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.

264667 lines
7.8MB

  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_Config.h *********/
  30. #ifndef __JUCE_CONFIG_JUCEHEADER__
  31. #define __JUCE_CONFIG_JUCEHEADER__
  32. /*
  33. This file contains macros that enable/disable various JUCE features.
  34. */
  35. /** The name of the namespace that all Juce classes and functions will be
  36. put inside. If this is not defined, no namespace will be used.
  37. */
  38. #ifndef JUCE_NAMESPACE
  39. #define JUCE_NAMESPACE juce
  40. #endif
  41. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  42. but if you define this value, you can override this can force it to be true or
  43. false.
  44. */
  45. #ifndef JUCE_FORCE_DEBUG
  46. //#define JUCE_FORCE_DEBUG 1
  47. #endif
  48. /** If this flag is enabled, the the jassert and jassertfalse macros will
  49. always use Logger::writeToLog() to write a message when an assertion happens.
  50. Enabling it will also leave this turned on in release builds. When it's disabled,
  51. however, the jassert and jassertfalse macros will not be compiled in a
  52. release build.
  53. @see jassert, jassertfalse, Logger
  54. */
  55. #ifndef JUCE_LOG_ASSERTIONS
  56. // #define JUCE_LOG_ASSERTIONS 1
  57. #endif
  58. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  59. which the ASIOAudioIODevice class can't be built. See the comments in the
  60. ASIOAudioIODevice class's header file for more info about this.
  61. (This only affects a Win32 build)
  62. */
  63. #ifndef JUCE_ASIO
  64. #define JUCE_ASIO 1
  65. #endif
  66. /** Comment out this macro to disable the Windows WASAPI audio device type.
  67. */
  68. #ifndef JUCE_WASAPI
  69. // #define JUCE_WASAPI 1
  70. #endif
  71. /** Comment out this macro to disable the Windows WASAPI audio device type.
  72. */
  73. #ifndef JUCE_DIRECTSOUND
  74. #define JUCE_DIRECTSOUND 1
  75. #endif
  76. /** Comment out this macro to disable building of ALSA device support on Linux.
  77. */
  78. #ifndef JUCE_ALSA
  79. #define JUCE_ALSA 1
  80. #endif
  81. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  82. have the SDK installed.
  83. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  84. classes will be unavailable.
  85. On Windows, if you enable this, you'll need to have the QuickTime SDK
  86. installed, and its header files will need to be on your include path.
  87. */
  88. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  89. #define JUCE_QUICKTIME 1
  90. #endif
  91. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  92. have the appropriate headers and libraries available. If it's not enabled, the
  93. OpenGLComponent class will be unavailable.
  94. */
  95. #ifndef JUCE_OPENGL
  96. #define JUCE_OPENGL 1
  97. #endif
  98. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  99. If you're not going to need either of these formats, turn off the flags to
  100. avoid bloating your codebase with them.
  101. */
  102. #ifndef JUCE_USE_FLAC
  103. #define JUCE_USE_FLAC 1
  104. #endif
  105. #ifndef JUCE_USE_OGGVORBIS
  106. #define JUCE_USE_OGGVORBIS 1
  107. #endif
  108. /** This flag lets you enable support for CD-burning. You might want to disable
  109. it to build without the MS SDK under windows.
  110. */
  111. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  112. #define JUCE_USE_CDBURNER 1
  113. #endif
  114. /** Enabling this provides support for cameras, using the CameraDevice class
  115. */
  116. #if JUCE_QUICKTIME && ! defined (JUCE_USE_CAMERA)
  117. // #define JUCE_USE_CAMERA 1
  118. #endif
  119. /** Enabling this macro means that all regions that get repainted will have a coloured
  120. line drawn around them.
  121. This is handy if you're trying to optimise drawing, because it lets you easily see
  122. when anything is being repainted unnecessarily.
  123. */
  124. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  125. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  126. #endif
  127. /** Enable this under Linux to use Xinerama for multi-monitor support.
  128. */
  129. #ifndef JUCE_USE_XINERAMA
  130. #define JUCE_USE_XINERAMA 1
  131. #endif
  132. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  133. */
  134. #ifndef JUCE_USE_XSHM
  135. #define JUCE_USE_XSHM 1
  136. #endif
  137. /** Enabling this builds support for VST audio plugins.
  138. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  139. */
  140. #ifndef JUCE_PLUGINHOST_VST
  141. // #define JUCE_PLUGINHOST_VST 1
  142. #endif
  143. /** Enabling this builds support for AudioUnit audio plugins.
  144. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  145. */
  146. #ifndef JUCE_PLUGINHOST_AU
  147. // #define JUCE_PLUGINHOST_AU 1
  148. #endif
  149. /** Enabling this will avoid including any UI code in the build. This is handy for
  150. writing command-line utilities, e.g. on linux boxes which don't have some
  151. of the UI libraries installed.
  152. */
  153. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  154. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  155. #endif
  156. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  157. */
  158. #ifndef JUCE_WEB_BROWSER
  159. #define JUCE_WEB_BROWSER 1
  160. #endif
  161. /** Setting this allows the build to use old Carbon libraries that will be
  162. deprecated in newer versions of OSX. This is handy for some backwards-compatibility
  163. reasons.
  164. */
  165. #ifndef JUCE_SUPPORT_CARBON
  166. #define JUCE_SUPPORT_CARBON 1
  167. #endif
  168. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  169. codebase - you might need to use this if you're linking to some of these libraries
  170. yourself.
  171. */
  172. #ifndef JUCE_INCLUDE_ZLIB_CODE
  173. #define JUCE_INCLUDE_ZLIB_CODE 1
  174. #endif
  175. #ifndef JUCE_INCLUDE_FLAC_CODE
  176. #define JUCE_INCLUDE_FLAC_CODE 1
  177. #endif
  178. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  179. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  180. #endif
  181. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  182. #define JUCE_INCLUDE_PNGLIB_CODE 1
  183. #endif
  184. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  185. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  186. #endif
  187. /** Enable this to add extra memory-leak info to the new and delete operators.
  188. (Currently, this only affects Windows builds in debug mode).
  189. */
  190. #ifndef JUCE_CHECK_MEMORY_LEAKS
  191. #define JUCE_CHECK_MEMORY_LEAKS 1
  192. #endif
  193. /** Enable this to turn on juce's internal catching of exceptions.
  194. Turning it off will avoid any exception catching. With it on, all exceptions
  195. are passed to the JUCEApplication::unhandledException() callback for logging.
  196. */
  197. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  198. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  199. #endif
  200. /** If this macro is set, the Juce String class will use unicode as its
  201. internal representation. If it isn't set, it'll use ANSI.
  202. */
  203. #ifndef JUCE_STRINGS_ARE_UNICODE
  204. #define JUCE_STRINGS_ARE_UNICODE 1
  205. #endif
  206. #endif
  207. /********* End of inlined file: juce_Config.h *********/
  208. // FORCE_AMALGAMATOR_INCLUDE
  209. //==============================================================================
  210. #ifdef _WIN32
  211. /********* Start of inlined file: juce_win32_NativeIncludes.h *********/
  212. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  213. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  214. #ifndef STRICT
  215. #define STRICT 1
  216. #endif
  217. #undef WIN32_LEAN_AND_MEAN
  218. #define WIN32_LEAN_AND_MEAN 1
  219. #ifdef _MSC_VER
  220. #pragma warning (push)
  221. #pragma warning (disable : 4100 4201 4514 4312 4995)
  222. #endif
  223. #define _WIN32_WINNT 0x0500
  224. #define _UNICODE 1
  225. #define UNICODE 1
  226. #ifndef _WIN32_IE
  227. #define _WIN32_IE 0x0400
  228. #endif
  229. #include <windows.h>
  230. #include <windowsx.h>
  231. #include <commdlg.h>
  232. #include <shellapi.h>
  233. #include <mmsystem.h>
  234. #include <vfw.h>
  235. #include <tchar.h>
  236. #include <stddef.h>
  237. #include <ctime>
  238. #include <wininet.h>
  239. #include <nb30.h>
  240. #include <iphlpapi.h>
  241. #include <mapi.h>
  242. #include <float.h>
  243. #include <crtdbg.h>
  244. #include <process.h>
  245. #include <comutil.h>
  246. #include <Exdisp.h>
  247. #include <exdispid.h>
  248. #include <shlobj.h>
  249. #if JUCE_OPENGL
  250. #include <gl/gl.h>
  251. #endif
  252. #undef PACKED
  253. #if JUCE_ASIO
  254. /*
  255. This is very frustrating - we only need to use a handful of definitions from
  256. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  257. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  258. implementation...
  259. ..unfortunately that would break Steinberg's license agreement for use of
  260. their SDK, so I'm not allowed to do this.
  261. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  262. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  263. (see www.steinberg.net/Steinberg/Developers.asp).
  264. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  265. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  266. if you prefer). Make sure that your header search path will find the
  267. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  268. files are actually needed - so to simplify things, you could just copy
  269. these into your JUCE directory).
  270. If you're compiling and you get an error here because you don't have the
  271. ASIO SDK installed, you can disable ASIO support by commenting-out the
  272. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  273. */
  274. #include "iasiodrv.h"
  275. #endif
  276. #if JUCE_USE_CDBURNER
  277. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  278. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  279. flag in juce_Config.h to avoid these includes.
  280. */
  281. #include <imapi.h>
  282. #include <imapierror.h>
  283. #endif
  284. #if JUCE_USE_CAMERA
  285. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  286. Both of these files are provided in the normal Windows SDK, but some Microsoft plonker
  287. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK!
  288. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  289. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  290. .. which is a pathetic bodge, but a lot less hassle than installing the full DShow SDK.
  291. */
  292. #include <dshow.h>
  293. #include <qedit.h>
  294. #endif
  295. #if JUCE_WASAPI
  296. #include <MMReg.h>
  297. #include <mmdeviceapi.h>
  298. #include <Audioclient.h>
  299. #include <functiondiscoverykeys.h>
  300. #endif
  301. #if JUCE_QUICKTIME
  302. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  303. add its header directory to your include path.
  304. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  305. flag in juce_Config.h
  306. */
  307. #include <Movies.h>
  308. #include <QTML.h>
  309. #include <QuickTimeComponents.h>
  310. #include <MediaHandlers.h>
  311. #include <ImageCodec.h>
  312. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  313. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  314. your include search path to make these import statements work.
  315. */
  316. #import <QTOLibrary.dll>
  317. #import <QTOControl.dll>
  318. #endif
  319. #ifdef _MSC_VER
  320. #pragma warning (pop)
  321. #endif
  322. /** A simple COM smart pointer.
  323. Avoids having to include ATL just to get one of these.
  324. */
  325. template <class T>
  326. class ComSmartPtr
  327. {
  328. public:
  329. ComSmartPtr() throw() : p (0) {}
  330. ComSmartPtr (T* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  331. ComSmartPtr (const ComSmartPtr<T>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  332. ~ComSmartPtr() { if (p != 0) p->Release(); }
  333. operator T*() const throw() { return p; }
  334. T& operator*() const throw() { return *p; }
  335. T** operator&() throw() { return &p; }
  336. T* operator->() const throw() { return p; }
  337. T* operator= (T* const newP)
  338. {
  339. if (newP != 0)
  340. newP->AddRef();
  341. if (p != 0)
  342. p->Release();
  343. p = newP;
  344. return newP;
  345. }
  346. T* operator= (const ComSmartPtr<T>& newP) { return operator= (newP.p); }
  347. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext)
  348. {
  349. #ifndef __MINGW32__
  350. operator= (0);
  351. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof(T), (void**) &p);
  352. #else
  353. return S_FALSE;
  354. #endif
  355. }
  356. T* p;
  357. };
  358. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  359. /********* End of inlined file: juce_win32_NativeIncludes.h *********/
  360. #elif defined (LINUX)
  361. /********* Start of inlined file: juce_linux_NativeIncludes.h *********/
  362. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  363. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  364. /*
  365. This file wraps together all the linux-specific headers, so
  366. that we can include them all just once, and compile all our
  367. platform-specific stuff in one big lump, keeping it out of the
  368. way of the rest of the codebase.
  369. */
  370. #include <sched.h>
  371. #include <pthread.h>
  372. #include <sys/time.h>
  373. #include <errno.h>
  374. #include <sys/stat.h>
  375. #include <sys/dir.h>
  376. #include <sys/ptrace.h>
  377. #include <sys/vfs.h>
  378. #include <sys/wait.h>
  379. #include <fnmatch.h>
  380. #include <utime.h>
  381. #include <pwd.h>
  382. #include <fcntl.h>
  383. #include <dlfcn.h>
  384. #include <netdb.h>
  385. #include <arpa/inet.h>
  386. #include <netinet/in.h>
  387. #include <sys/types.h>
  388. #include <sys/ioctl.h>
  389. #include <sys/socket.h>
  390. #include <linux/if.h>
  391. #include <sys/sysinfo.h>
  392. #include <sys/file.h>
  393. #include <signal.h>
  394. /* Got a build error here? You'll need to install the freetype library...
  395. The name of the package to install is "libfreetype6-dev".
  396. */
  397. #include <ft2build.h>
  398. #include FT_FREETYPE_H
  399. #include <X11/Xlib.h>
  400. #include <X11/Xatom.h>
  401. #include <X11/Xresource.h>
  402. #include <X11/Xutil.h>
  403. #include <X11/Xmd.h>
  404. #include <X11/keysym.h>
  405. #include <X11/cursorfont.h>
  406. #if JUCE_USE_XINERAMA
  407. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  408. #include <X11/extensions/Xinerama.h>
  409. #endif
  410. #if JUCE_USE_XSHM
  411. #include <X11/extensions/XShm.h>
  412. #include <sys/shm.h>
  413. #include <sys/ipc.h>
  414. #endif
  415. #if JUCE_OPENGL
  416. /* Got an include error here?
  417. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  418. and "freeglut3-dev".
  419. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  420. want to disable it.
  421. */
  422. #include <GL/glx.h>
  423. #endif
  424. #undef KeyPress
  425. #if JUCE_ALSA
  426. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  427. not got your paths set up correctly to find its header files.
  428. The package you need to install to get ASLA support is "libasound2-dev".
  429. If you don't have the ALSA library and don't want to build Juce with audio support,
  430. just disable the JUCE_ALSA flag in juce_Config.h
  431. */
  432. #include <alsa/asoundlib.h>
  433. #endif
  434. #undef SIZEOF
  435. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  436. /********* End of inlined file: juce_linux_NativeIncludes.h *********/
  437. #else
  438. /********* Start of inlined file: juce_mac_NativeIncludes.h *********/
  439. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  440. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  441. /*
  442. This file wraps together all the mac-specific code, so that
  443. we can include all the native headers just once, and compile all our
  444. platform-specific stuff in one big lump, keeping it out of the way of
  445. the rest of the codebase.
  446. */
  447. #import <Cocoa/Cocoa.h>
  448. #import <CoreAudio/HostTime.h>
  449. #import <CoreAudio/AudioHardware.h>
  450. #import <CoreMIDI/MIDIServices.h>
  451. #import <QTKit/QTKit.h>
  452. #import <WebKit/WebKit.h>
  453. #import <DiscRecording/DiscRecording.h>
  454. #import <IOKit/IOKitLib.h>
  455. #import <IOKit/IOCFPlugIn.h>
  456. #import <IOKit/hid/IOHIDLib.h>
  457. #import <IOKit/hid/IOHIDKeys.h>
  458. #import <IOKit/network/IOEthernetInterface.h>
  459. #import <IOKit/network/IONetworkInterface.h>
  460. #import <IOKit/network/IOEthernetController.h>
  461. #import <IOKit/pwr_mgt/IOPMLib.h>
  462. #include <sys/sysctl.h>
  463. #include <sys/stat.h>
  464. #include <sys/dir.h>
  465. #include <sys/param.h>
  466. #include <sys/mount.h>
  467. #include <fnmatch.h>
  468. #include <utime.h>
  469. #include <dlfcn.h>
  470. #if MACOS_10_4_OR_EARLIER
  471. #include <GLUT/glut.h>
  472. typedef int NSInteger;
  473. typedef unsigned int NSUInteger;
  474. #endif
  475. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  476. /********* End of inlined file: juce_mac_NativeIncludes.h *********/
  477. #endif
  478. //==============================================================================
  479. #define DONT_SET_USING_JUCE_NAMESPACE 1
  480. #include "juce_amalgamated.h"
  481. #define NO_DUMMY_DECL
  482. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  483. #pragma warning (disable: 4309 4305)
  484. #endif
  485. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  486. BEGIN_JUCE_NAMESPACE
  487. /********* Start of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  488. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  489. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  490. /**
  491. Creates a floating carbon window that can be used to hold a carbon UI.
  492. This is a handy class that's designed to be inlined where needed, e.g.
  493. in the audio plugin hosting code.
  494. */
  495. class CarbonViewWrapperComponent : public Component,
  496. public ComponentMovementWatcher,
  497. public Timer
  498. {
  499. public:
  500. CarbonViewWrapperComponent()
  501. : ComponentMovementWatcher (this),
  502. wrapperWindow (0),
  503. embeddedView (0),
  504. recursiveResize (false)
  505. {
  506. }
  507. virtual ~CarbonViewWrapperComponent()
  508. {
  509. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  510. }
  511. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  512. virtual void removeView (HIViewRef embeddedView) = 0;
  513. virtual void mouseDown (int x, int y) {}
  514. virtual void paint() {}
  515. virtual bool getEmbeddedViewSize (int& w, int& h)
  516. {
  517. if (embeddedView == 0)
  518. return false;
  519. HIRect bounds;
  520. HIViewGetBounds (embeddedView, &bounds);
  521. w = jmax (1, roundFloatToInt (bounds.size.width));
  522. h = jmax (1, roundFloatToInt (bounds.size.height));
  523. return true;
  524. }
  525. void createWindow()
  526. {
  527. if (wrapperWindow == 0)
  528. {
  529. Rect r;
  530. r.left = getScreenX();
  531. r.top = getScreenY();
  532. r.right = r.left + getWidth();
  533. r.bottom = r.top + getHeight();
  534. CreateNewWindow (kDocumentWindowClass,
  535. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  536. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  537. &r, &wrapperWindow);
  538. jassert (wrapperWindow != 0);
  539. if (wrapperWindow == 0)
  540. return;
  541. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  542. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  543. [ownerWindow addChildWindow: carbonWindow
  544. ordered: NSWindowAbove];
  545. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  546. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  547. { kEventClassWindow, kEventWindowHandleDeactivate } };
  548. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  549. InstallWindowEventHandler (wrapperWindow, upp,
  550. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  551. windowEventTypes, this, &eventHandlerRef);
  552. setOurSizeToEmbeddedViewSize();
  553. setEmbeddedWindowToOurSize();
  554. creationTime = Time::getCurrentTime();
  555. }
  556. }
  557. void deleteWindow()
  558. {
  559. removeView (embeddedView);
  560. embeddedView = 0;
  561. if (wrapperWindow != 0)
  562. {
  563. RemoveEventHandler (eventHandlerRef);
  564. DisposeWindow (wrapperWindow);
  565. wrapperWindow = 0;
  566. }
  567. }
  568. void setOurSizeToEmbeddedViewSize()
  569. {
  570. int w, h;
  571. if (getEmbeddedViewSize (w, h))
  572. {
  573. if (w != getWidth() || h != getHeight())
  574. {
  575. startTimer (50);
  576. setSize (w, h);
  577. if (getParentComponent() != 0)
  578. getParentComponent()->setSize (w, h);
  579. }
  580. else
  581. {
  582. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  583. }
  584. }
  585. else
  586. {
  587. stopTimer();
  588. }
  589. }
  590. void setEmbeddedWindowToOurSize()
  591. {
  592. if (! recursiveResize)
  593. {
  594. recursiveResize = true;
  595. if (embeddedView != 0)
  596. {
  597. HIRect r;
  598. r.origin.x = 0;
  599. r.origin.y = 0;
  600. r.size.width = (float) getWidth();
  601. r.size.height = (float) getHeight();
  602. HIViewSetFrame (embeddedView, &r);
  603. }
  604. if (wrapperWindow != 0)
  605. {
  606. Rect wr;
  607. wr.left = getScreenX();
  608. wr.top = getScreenY();
  609. wr.right = wr.left + getWidth();
  610. wr.bottom = wr.top + getHeight();
  611. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  612. ShowWindow (wrapperWindow);
  613. }
  614. recursiveResize = false;
  615. }
  616. }
  617. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  618. {
  619. setEmbeddedWindowToOurSize();
  620. }
  621. void componentPeerChanged()
  622. {
  623. deleteWindow();
  624. createWindow();
  625. }
  626. void componentVisibilityChanged (Component&)
  627. {
  628. if (isShowing())
  629. createWindow();
  630. else
  631. deleteWindow();
  632. setEmbeddedWindowToOurSize();
  633. }
  634. void timerCallback()
  635. {
  636. setOurSizeToEmbeddedViewSize();
  637. // To avoid strange overpainting problems when the UI is first opened, we'll
  638. // repaint it a few times during the first second that it's on-screen..
  639. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  640. HIViewSetNeedsDisplay (embeddedView, true);
  641. }
  642. OSStatus carbonEventHandler (EventHandlerCallRef nextHandlerRef,
  643. EventRef event)
  644. {
  645. switch (GetEventKind (event))
  646. {
  647. case kEventWindowHandleDeactivate:
  648. ActivateWindow (wrapperWindow, TRUE);
  649. break;
  650. case kEventWindowGetClickActivation:
  651. {
  652. getTopLevelComponent()->toFront (false);
  653. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  654. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  655. sizeof (ClickActivationResult), &howToHandleClick);
  656. HIViewSetNeedsDisplay (embeddedView, true);
  657. }
  658. break;
  659. }
  660. return noErr;
  661. }
  662. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  663. EventRef event, void* userData)
  664. {
  665. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  666. }
  667. protected:
  668. WindowRef wrapperWindow;
  669. HIViewRef embeddedView;
  670. bool recursiveResize;
  671. Time creationTime;
  672. EventHandlerRef eventHandlerRef;
  673. };
  674. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  675. /********* End of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  676. END_JUCE_NAMESPACE
  677. #endif
  678. #define JUCE_AMALGAMATED_TEMPLATE 1
  679. //==============================================================================
  680. /********* Start of inlined file: juce_FileLogger.cpp *********/
  681. BEGIN_JUCE_NAMESPACE
  682. FileLogger::FileLogger (const File& logFile_,
  683. const String& welcomeMessage,
  684. const int maxInitialFileSizeBytes)
  685. : logFile (logFile_)
  686. {
  687. if (maxInitialFileSizeBytes >= 0)
  688. trimFileSize (maxInitialFileSizeBytes);
  689. if (! logFile_.exists())
  690. {
  691. // do this so that the parent directories get created..
  692. logFile_.create();
  693. }
  694. logStream = logFile_.createOutputStream (256);
  695. jassert (logStream != 0);
  696. String welcome;
  697. welcome << "\r\n**********************************************************\r\n"
  698. << welcomeMessage
  699. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  700. << "\r\n";
  701. logMessage (welcome);
  702. }
  703. FileLogger::~FileLogger()
  704. {
  705. deleteAndZero (logStream);
  706. }
  707. void FileLogger::logMessage (const String& message)
  708. {
  709. if (logStream != 0)
  710. {
  711. Logger::outputDebugString (message);
  712. const ScopedLock sl (logLock);
  713. (*logStream) << message << T("\r\n");
  714. logStream->flush();
  715. }
  716. }
  717. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  718. {
  719. if (maxFileSizeBytes <= 0)
  720. {
  721. logFile.deleteFile();
  722. }
  723. else
  724. {
  725. const int64 fileSize = logFile.getSize();
  726. if (fileSize > maxFileSizeBytes)
  727. {
  728. FileInputStream* const in = logFile.createInputStream();
  729. jassert (in != 0);
  730. if (in != 0)
  731. {
  732. in->setPosition (fileSize - maxFileSizeBytes);
  733. String content;
  734. {
  735. MemoryBlock contentToSave;
  736. contentToSave.setSize (maxFileSizeBytes + 4);
  737. contentToSave.fillWith (0);
  738. in->read (contentToSave.getData(), maxFileSizeBytes);
  739. delete in;
  740. content = contentToSave.toString();
  741. }
  742. int newStart = 0;
  743. while (newStart < fileSize
  744. && content[newStart] != '\n'
  745. && content[newStart] != '\r')
  746. ++newStart;
  747. logFile.deleteFile();
  748. logFile.appendText (content.substring (newStart), false, false);
  749. }
  750. }
  751. }
  752. }
  753. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  754. const String& logFileName,
  755. const String& welcomeMessage,
  756. const int maxInitialFileSizeBytes)
  757. {
  758. #if JUCE_MAC
  759. File logFile ("~/Library/Logs");
  760. logFile = logFile.getChildFile (logFileName);
  761. #else
  762. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  763. if (logFile.isDirectory())
  764. {
  765. logFile = logFile.getChildFile (logFileSubDirectoryName)
  766. .getChildFile (logFileName);
  767. }
  768. #endif
  769. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  770. }
  771. END_JUCE_NAMESPACE
  772. /********* End of inlined file: juce_FileLogger.cpp *********/
  773. /********* Start of inlined file: juce_Logger.cpp *********/
  774. BEGIN_JUCE_NAMESPACE
  775. Logger::Logger()
  776. {
  777. }
  778. Logger::~Logger()
  779. {
  780. }
  781. static Logger* currentLogger = 0;
  782. void Logger::setCurrentLogger (Logger* const newLogger,
  783. const bool deleteOldLogger)
  784. {
  785. Logger* const oldLogger = currentLogger;
  786. currentLogger = newLogger;
  787. if (deleteOldLogger && (oldLogger != 0))
  788. delete oldLogger;
  789. }
  790. void Logger::writeToLog (const String& message)
  791. {
  792. if (currentLogger != 0)
  793. currentLogger->logMessage (message);
  794. else
  795. outputDebugString (message);
  796. }
  797. #if JUCE_LOG_ASSERTIONS
  798. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  799. {
  800. String m ("JUCE Assertion failure in ");
  801. m << filename << ", line " << lineNum;
  802. Logger::writeToLog (m);
  803. }
  804. #endif
  805. END_JUCE_NAMESPACE
  806. /********* End of inlined file: juce_Logger.cpp *********/
  807. /********* Start of inlined file: juce_Random.cpp *********/
  808. BEGIN_JUCE_NAMESPACE
  809. Random::Random (const int64 seedValue) throw()
  810. : seed (seedValue)
  811. {
  812. }
  813. Random::~Random() throw()
  814. {
  815. }
  816. void Random::setSeed (const int64 newSeed) throw()
  817. {
  818. seed = newSeed;
  819. }
  820. void Random::setSeedRandomly()
  821. {
  822. Random r1 (Time::getMillisecondCounter());
  823. Random r2 (Time::getHighResolutionTicks());
  824. Random r3 (Time::getHighResolutionTicksPerSecond());
  825. Random r4 (Time::currentTimeMillis());
  826. setSeed (nextInt64() ^ r1.nextInt64() ^ r2.nextInt64()
  827. ^ r3.nextInt64() ^ r4.nextInt64());
  828. }
  829. int Random::nextInt() throw()
  830. {
  831. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  832. return (int) (seed >> 16);
  833. }
  834. int Random::nextInt (const int maxValue) throw()
  835. {
  836. jassert (maxValue > 0);
  837. return (nextInt() & 0x7fffffff) % maxValue;
  838. }
  839. int64 Random::nextInt64() throw()
  840. {
  841. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  842. }
  843. bool Random::nextBool() throw()
  844. {
  845. return (nextInt() & 0x80000000) != 0;
  846. }
  847. float Random::nextFloat() throw()
  848. {
  849. return ((uint32) nextInt()) / (float) 0xffffffff;
  850. }
  851. double Random::nextDouble() throw()
  852. {
  853. return ((uint32) nextInt()) / (double) 0xffffffff;
  854. }
  855. const BitArray Random::nextLargeNumber (const BitArray& maximumValue) throw()
  856. {
  857. BitArray n;
  858. do
  859. {
  860. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  861. }
  862. while (n.compare (maximumValue) >= 0);
  863. return n;
  864. }
  865. void Random::fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw()
  866. {
  867. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  868. while ((startBit & 31) != 0 && numBits > 0)
  869. {
  870. arrayToChange.setBit (startBit++, nextBool());
  871. --numBits;
  872. }
  873. while (numBits >= 32)
  874. {
  875. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  876. startBit += 32;
  877. numBits -= 32;
  878. }
  879. while (--numBits >= 0)
  880. arrayToChange.setBit (startBit + numBits, nextBool());
  881. }
  882. Random& Random::getSystemRandom() throw()
  883. {
  884. static Random sysRand (1);
  885. return sysRand;
  886. }
  887. END_JUCE_NAMESPACE
  888. /********* End of inlined file: juce_Random.cpp *********/
  889. /********* Start of inlined file: juce_RelativeTime.cpp *********/
  890. BEGIN_JUCE_NAMESPACE
  891. RelativeTime::RelativeTime (const double seconds_) throw()
  892. : seconds (seconds_)
  893. {
  894. }
  895. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  896. : seconds (other.seconds)
  897. {
  898. }
  899. RelativeTime::~RelativeTime() throw()
  900. {
  901. }
  902. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  903. {
  904. return RelativeTime (milliseconds * 0.001);
  905. }
  906. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  907. {
  908. return RelativeTime (milliseconds * 0.001);
  909. }
  910. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  911. {
  912. return RelativeTime (numberOfMinutes * 60.0);
  913. }
  914. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  915. {
  916. return RelativeTime (numberOfHours * (60.0 * 60.0));
  917. }
  918. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  919. {
  920. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  921. }
  922. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  923. {
  924. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  925. }
  926. int64 RelativeTime::inMilliseconds() const throw()
  927. {
  928. return (int64)(seconds * 1000.0);
  929. }
  930. double RelativeTime::inMinutes() const throw()
  931. {
  932. return seconds / 60.0;
  933. }
  934. double RelativeTime::inHours() const throw()
  935. {
  936. return seconds / (60.0 * 60.0);
  937. }
  938. double RelativeTime::inDays() const throw()
  939. {
  940. return seconds / (60.0 * 60.0 * 24.0);
  941. }
  942. double RelativeTime::inWeeks() const throw()
  943. {
  944. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  945. }
  946. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  947. {
  948. if (seconds < 0.001 && seconds > -0.001)
  949. return returnValueForZeroTime;
  950. String result;
  951. if (seconds < 0)
  952. result = T("-");
  953. int fieldsShown = 0;
  954. int n = abs ((int) inWeeks());
  955. if (n > 0)
  956. {
  957. result << n << ((n == 1) ? TRANS(" week ")
  958. : TRANS(" weeks "));
  959. ++fieldsShown;
  960. }
  961. n = abs ((int) inDays()) % 7;
  962. if (n > 0)
  963. {
  964. result << n << ((n == 1) ? TRANS(" day ")
  965. : TRANS(" days "));
  966. ++fieldsShown;
  967. }
  968. if (fieldsShown < 2)
  969. {
  970. n = abs ((int) inHours()) % 24;
  971. if (n > 0)
  972. {
  973. result << n << ((n == 1) ? TRANS(" hr ")
  974. : TRANS(" hrs "));
  975. ++fieldsShown;
  976. }
  977. if (fieldsShown < 2)
  978. {
  979. n = abs ((int) inMinutes()) % 60;
  980. if (n > 0)
  981. {
  982. result << n << ((n == 1) ? TRANS(" min ")
  983. : TRANS(" mins "));
  984. ++fieldsShown;
  985. }
  986. if (fieldsShown < 2)
  987. {
  988. n = abs ((int) inSeconds()) % 60;
  989. if (n > 0)
  990. {
  991. result << n << ((n == 1) ? TRANS(" sec ")
  992. : TRANS(" secs "));
  993. ++fieldsShown;
  994. }
  995. if (fieldsShown < 1)
  996. {
  997. n = abs ((int) inMilliseconds()) % 1000;
  998. if (n > 0)
  999. {
  1000. result << n << TRANS(" ms");
  1001. ++fieldsShown;
  1002. }
  1003. }
  1004. }
  1005. }
  1006. }
  1007. return result.trimEnd();
  1008. }
  1009. const RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1010. {
  1011. seconds = other.seconds;
  1012. return *this;
  1013. }
  1014. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1015. {
  1016. return seconds == other.seconds;
  1017. }
  1018. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1019. {
  1020. return seconds != other.seconds;
  1021. }
  1022. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1023. {
  1024. return seconds > other.seconds;
  1025. }
  1026. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1027. {
  1028. return seconds < other.seconds;
  1029. }
  1030. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1031. {
  1032. return seconds >= other.seconds;
  1033. }
  1034. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1035. {
  1036. return seconds <= other.seconds;
  1037. }
  1038. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1039. {
  1040. return RelativeTime (seconds + timeToAdd.seconds);
  1041. }
  1042. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1043. {
  1044. return RelativeTime (seconds - timeToSubtract.seconds);
  1045. }
  1046. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1047. {
  1048. return RelativeTime (seconds + secondsToAdd);
  1049. }
  1050. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1051. {
  1052. return RelativeTime (seconds - secondsToSubtract);
  1053. }
  1054. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1055. {
  1056. seconds += timeToAdd.seconds;
  1057. return *this;
  1058. }
  1059. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1060. {
  1061. seconds -= timeToSubtract.seconds;
  1062. return *this;
  1063. }
  1064. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1065. {
  1066. seconds += secondsToAdd;
  1067. return *this;
  1068. }
  1069. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1070. {
  1071. seconds -= secondsToSubtract;
  1072. return *this;
  1073. }
  1074. END_JUCE_NAMESPACE
  1075. /********* End of inlined file: juce_RelativeTime.cpp *********/
  1076. /********* Start of inlined file: juce_SystemStats.cpp *********/
  1077. BEGIN_JUCE_NAMESPACE
  1078. void juce_initialiseStrings();
  1079. const String SystemStats::getJUCEVersion() throw()
  1080. {
  1081. return "JUCE v" + String (JUCE_MAJOR_VERSION) + "." + String (JUCE_MINOR_VERSION);
  1082. }
  1083. static bool juceInitialisedNonGUI = false;
  1084. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1085. {
  1086. if (! juceInitialisedNonGUI)
  1087. {
  1088. #if JUCE_MAC
  1089. const ScopedAutoReleasePool pool;
  1090. #endif
  1091. #ifdef JUCE_DEBUG
  1092. // Some simple test code to keep an eye on things and make sure these functions
  1093. // work ok on all platforms. Let me know if any of these assertions fail!
  1094. int n = 1;
  1095. atomicIncrement (n);
  1096. jassert (atomicIncrementAndReturn (n) == 3);
  1097. atomicDecrement (n);
  1098. jassert (atomicDecrementAndReturn (n) == 1);
  1099. jassert (swapByteOrder ((uint32) 0x11223344) == 0x44332211);
  1100. // quick test to make sure the run-time lib doesn't crash on freeing a null-pointer.
  1101. SystemStats* nullPointer = 0;
  1102. juce_free (nullPointer);
  1103. delete[] nullPointer;
  1104. delete nullPointer;
  1105. #endif
  1106. // Now the real initialisation..
  1107. juceInitialisedNonGUI = true;
  1108. DBG (SystemStats::getJUCEVersion());
  1109. Random::getSystemRandom().setSeedRandomly(); // (calling this more than once improves its randomness)
  1110. juce_initialiseStrings();
  1111. SystemStats::initialiseStats();
  1112. Random::getSystemRandom().setSeedRandomly(); // (calling this more than once improves its randomness)
  1113. }
  1114. }
  1115. #if JUCE_WIN32
  1116. // This is imported from the sockets code..
  1117. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1118. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1119. #endif
  1120. #if JUCE_DEBUG
  1121. extern void juce_CheckForDanglingStreams();
  1122. #endif
  1123. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1124. {
  1125. if (juceInitialisedNonGUI)
  1126. {
  1127. #if JUCE_MAC
  1128. const ScopedAutoReleasePool pool;
  1129. #endif
  1130. #if JUCE_WIN32
  1131. // need to shut down sockets if they were used..
  1132. if (juce_CloseWin32SocketLib != 0)
  1133. (*juce_CloseWin32SocketLib)();
  1134. #endif
  1135. LocalisedStrings::setCurrentMappings (0);
  1136. Thread::stopAllThreads (3000);
  1137. #if JUCE_DEBUG
  1138. juce_CheckForDanglingStreams();
  1139. #endif
  1140. juceInitialisedNonGUI = false;
  1141. }
  1142. }
  1143. #ifdef JUCE_DLL
  1144. void* juce_Malloc (const int size)
  1145. {
  1146. return malloc (size);
  1147. }
  1148. void* juce_Calloc (const int size)
  1149. {
  1150. return calloc (1, size);
  1151. }
  1152. void* juce_Realloc (void* const block, const int size)
  1153. {
  1154. return realloc (block, size);
  1155. }
  1156. void juce_Free (void* const block)
  1157. {
  1158. free (block);
  1159. }
  1160. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1161. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1162. {
  1163. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1164. }
  1165. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1166. {
  1167. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1168. }
  1169. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1170. {
  1171. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1172. }
  1173. void juce_DebugFree (void* const block)
  1174. {
  1175. _free_dbg (block, _NORMAL_BLOCK);
  1176. }
  1177. #endif
  1178. #endif
  1179. END_JUCE_NAMESPACE
  1180. /********* End of inlined file: juce_SystemStats.cpp *********/
  1181. /********* Start of inlined file: juce_Time.cpp *********/
  1182. #ifdef _MSC_VER
  1183. #pragma warning (disable: 4514)
  1184. #pragma warning (push)
  1185. #endif
  1186. #ifndef JUCE_WIN32
  1187. #include <sys/time.h>
  1188. #else
  1189. #include <ctime>
  1190. #endif
  1191. #include <sys/timeb.h>
  1192. BEGIN_JUCE_NAMESPACE
  1193. #ifdef _MSC_VER
  1194. #pragma warning (pop)
  1195. #ifdef _INC_TIME_INL
  1196. #define USE_NEW_SECURE_TIME_FNS
  1197. #endif
  1198. #endif
  1199. static void millisToLocal (const int64 millis, struct tm& result) throw()
  1200. {
  1201. const int64 seconds = millis / 1000;
  1202. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1203. {
  1204. // use extended maths for dates beyond 1970 to 2037..
  1205. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1206. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1207. const int days = (int) (jdm / literal64bit (86400));
  1208. const int a = 32044 + days;
  1209. const int b = (4 * a + 3) / 146097;
  1210. const int c = a - (b * 146097) / 4;
  1211. const int d = (4 * c + 3) / 1461;
  1212. const int e = c - (d * 1461) / 4;
  1213. const int m = (5 * e + 2) / 153;
  1214. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1215. result.tm_mon = m + 2 - 12 * (m / 10);
  1216. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1217. result.tm_wday = (days + 1) % 7;
  1218. result.tm_yday = -1;
  1219. int t = (int) (jdm % literal64bit (86400));
  1220. result.tm_hour = t / 3600;
  1221. t %= 3600;
  1222. result.tm_min = t / 60;
  1223. result.tm_sec = t % 60;
  1224. result.tm_isdst = -1;
  1225. }
  1226. else
  1227. {
  1228. time_t now = (time_t) (seconds);
  1229. #if JUCE_WIN32
  1230. #ifdef USE_NEW_SECURE_TIME_FNS
  1231. if (now >= 0 && now <= 0x793406fff)
  1232. localtime_s (&result, &now);
  1233. else
  1234. zeromem (&result, sizeof (result));
  1235. #else
  1236. result = *localtime (&now);
  1237. #endif
  1238. #else
  1239. // more thread-safe
  1240. localtime_r (&now, &result);
  1241. #endif
  1242. }
  1243. }
  1244. Time::Time() throw()
  1245. : millisSinceEpoch (0)
  1246. {
  1247. }
  1248. Time::Time (const Time& other) throw()
  1249. : millisSinceEpoch (other.millisSinceEpoch)
  1250. {
  1251. }
  1252. Time::Time (const int64 ms) throw()
  1253. : millisSinceEpoch (ms)
  1254. {
  1255. }
  1256. Time::Time (const int year,
  1257. const int month,
  1258. const int day,
  1259. const int hours,
  1260. const int minutes,
  1261. const int seconds,
  1262. const int milliseconds,
  1263. const bool useLocalTime) throw()
  1264. {
  1265. jassert (year > 100); // year must be a 4-digit version
  1266. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1267. {
  1268. // use extended maths for dates beyond 1970 to 2037..
  1269. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1270. : 0;
  1271. const int a = (13 - month) / 12;
  1272. const int y = year + 4800 - a;
  1273. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1274. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1275. - 32045;
  1276. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1277. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1278. + milliseconds;
  1279. }
  1280. else
  1281. {
  1282. struct tm t;
  1283. t.tm_year = year - 1900;
  1284. t.tm_mon = month;
  1285. t.tm_mday = day;
  1286. t.tm_hour = hours;
  1287. t.tm_min = minutes;
  1288. t.tm_sec = seconds;
  1289. t.tm_isdst = -1;
  1290. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1291. if (millisSinceEpoch < 0)
  1292. millisSinceEpoch = 0;
  1293. else
  1294. millisSinceEpoch += milliseconds;
  1295. }
  1296. }
  1297. Time::~Time() throw()
  1298. {
  1299. }
  1300. const Time& Time::operator= (const Time& other) throw()
  1301. {
  1302. millisSinceEpoch = other.millisSinceEpoch;
  1303. return *this;
  1304. }
  1305. int64 Time::currentTimeMillis() throw()
  1306. {
  1307. static uint32 lastCounterResult = 0xffffffff;
  1308. static int64 correction = 0;
  1309. const uint32 now = getMillisecondCounter();
  1310. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1311. if (now < lastCounterResult)
  1312. {
  1313. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1314. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1315. {
  1316. // get the time once using normal library calls, and store the difference needed to
  1317. // turn the millisecond counter into a real time.
  1318. #if JUCE_WIN32
  1319. struct _timeb t;
  1320. #ifdef USE_NEW_SECURE_TIME_FNS
  1321. _ftime_s (&t);
  1322. #else
  1323. _ftime (&t);
  1324. #endif
  1325. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1326. #else
  1327. struct timeval tv;
  1328. struct timezone tz;
  1329. gettimeofday (&tv, &tz);
  1330. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1331. #endif
  1332. }
  1333. }
  1334. lastCounterResult = now;
  1335. return correction + now;
  1336. }
  1337. uint32 juce_millisecondsSinceStartup() throw();
  1338. static uint32 lastMSCounterValue = 0;
  1339. uint32 Time::getMillisecondCounter() throw()
  1340. {
  1341. const uint32 now = juce_millisecondsSinceStartup();
  1342. if (now < lastMSCounterValue)
  1343. {
  1344. // in multi-threaded apps this might be called concurrently, so
  1345. // make sure that our last counter value only increases and doesn't
  1346. // go backwards..
  1347. if (now < lastMSCounterValue - 1000)
  1348. lastMSCounterValue = now;
  1349. }
  1350. else
  1351. {
  1352. lastMSCounterValue = now;
  1353. }
  1354. return now;
  1355. }
  1356. uint32 Time::getApproximateMillisecondCounter() throw()
  1357. {
  1358. jassert (lastMSCounterValue != 0);
  1359. return lastMSCounterValue;
  1360. }
  1361. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1362. {
  1363. for (;;)
  1364. {
  1365. const uint32 now = getMillisecondCounter();
  1366. if (now >= targetTime)
  1367. break;
  1368. const int toWait = targetTime - now;
  1369. if (toWait > 2)
  1370. {
  1371. Thread::sleep (jmin (20, toWait >> 1));
  1372. }
  1373. else
  1374. {
  1375. // xxx should consider using mutex_pause on the mac as it apparently
  1376. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1377. for (int i = 10; --i >= 0;)
  1378. Thread::yield();
  1379. }
  1380. }
  1381. }
  1382. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1383. {
  1384. return ticks / (double) getHighResolutionTicksPerSecond();
  1385. }
  1386. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1387. {
  1388. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1389. }
  1390. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1391. {
  1392. return Time (currentTimeMillis());
  1393. }
  1394. const String Time::toString (const bool includeDate,
  1395. const bool includeTime,
  1396. const bool includeSeconds,
  1397. const bool use24HourClock) const throw()
  1398. {
  1399. String result;
  1400. if (includeDate)
  1401. {
  1402. result << getDayOfMonth() << ' '
  1403. << getMonthName (true) << ' '
  1404. << getYear();
  1405. if (includeTime)
  1406. result << ' ';
  1407. }
  1408. if (includeTime)
  1409. {
  1410. if (includeSeconds)
  1411. {
  1412. result += String::formatted (T("%d:%02d:%02d "),
  1413. (use24HourClock) ? getHours()
  1414. : getHoursInAmPmFormat(),
  1415. getMinutes(),
  1416. getSeconds());
  1417. }
  1418. else
  1419. {
  1420. result += String::formatted (T("%d.%02d"),
  1421. (use24HourClock) ? getHours()
  1422. : getHoursInAmPmFormat(),
  1423. getMinutes());
  1424. }
  1425. if (! use24HourClock)
  1426. result << (isAfternoon() ? "pm" : "am");
  1427. }
  1428. return result.trimEnd();
  1429. }
  1430. const String Time::formatted (const tchar* const format) const throw()
  1431. {
  1432. tchar buffer[80];
  1433. struct tm t;
  1434. millisToLocal (millisSinceEpoch, t);
  1435. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  1436. {
  1437. int bufferSize = 128;
  1438. for (;;)
  1439. {
  1440. MemoryBlock mb (bufferSize * sizeof (tchar));
  1441. tchar* const b = (tchar*) mb.getData();
  1442. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  1443. return String (b);
  1444. bufferSize += 128;
  1445. }
  1446. }
  1447. return String (buffer);
  1448. }
  1449. int Time::getYear() const throw()
  1450. {
  1451. struct tm t;
  1452. millisToLocal (millisSinceEpoch, t);
  1453. return t.tm_year + 1900;
  1454. }
  1455. int Time::getMonth() const throw()
  1456. {
  1457. struct tm t;
  1458. millisToLocal (millisSinceEpoch, t);
  1459. return t.tm_mon;
  1460. }
  1461. int Time::getDayOfMonth() const throw()
  1462. {
  1463. struct tm t;
  1464. millisToLocal (millisSinceEpoch, t);
  1465. return t.tm_mday;
  1466. }
  1467. int Time::getDayOfWeek() const throw()
  1468. {
  1469. struct tm t;
  1470. millisToLocal (millisSinceEpoch, t);
  1471. return t.tm_wday;
  1472. }
  1473. int Time::getHours() const throw()
  1474. {
  1475. struct tm t;
  1476. millisToLocal (millisSinceEpoch, t);
  1477. return t.tm_hour;
  1478. }
  1479. int Time::getHoursInAmPmFormat() const throw()
  1480. {
  1481. const int hours = getHours();
  1482. if (hours == 0)
  1483. return 12;
  1484. else if (hours <= 12)
  1485. return hours;
  1486. else
  1487. return hours - 12;
  1488. }
  1489. bool Time::isAfternoon() const throw()
  1490. {
  1491. return getHours() >= 12;
  1492. }
  1493. static int extendedModulo (const int64 value, const int modulo) throw()
  1494. {
  1495. return (int) (value >= 0 ? (value % modulo)
  1496. : (value - ((value / modulo) + 1) * modulo));
  1497. }
  1498. int Time::getMinutes() const throw()
  1499. {
  1500. struct tm t;
  1501. millisToLocal (millisSinceEpoch, t);
  1502. return t.tm_min;
  1503. }
  1504. int Time::getSeconds() const throw()
  1505. {
  1506. return extendedModulo (millisSinceEpoch / 1000, 60);
  1507. }
  1508. int Time::getMilliseconds() const throw()
  1509. {
  1510. return extendedModulo (millisSinceEpoch, 1000);
  1511. }
  1512. bool Time::isDaylightSavingTime() const throw()
  1513. {
  1514. struct tm t;
  1515. millisToLocal (millisSinceEpoch, t);
  1516. return t.tm_isdst != 0;
  1517. }
  1518. const String Time::getTimeZone() const throw()
  1519. {
  1520. String zone[2];
  1521. #if JUCE_WIN32
  1522. _tzset();
  1523. #ifdef USE_NEW_SECURE_TIME_FNS
  1524. {
  1525. char name [128];
  1526. size_t length;
  1527. for (int i = 0; i < 2; ++i)
  1528. {
  1529. zeromem (name, sizeof (name));
  1530. _get_tzname (&length, name, 127, i);
  1531. zone[i] = name;
  1532. }
  1533. }
  1534. #else
  1535. const char** const zonePtr = (const char**) _tzname;
  1536. zone[0] = zonePtr[0];
  1537. zone[1] = zonePtr[1];
  1538. #endif
  1539. #else
  1540. tzset();
  1541. const char** const zonePtr = (const char**) tzname;
  1542. zone[0] = zonePtr[0];
  1543. zone[1] = zonePtr[1];
  1544. #endif
  1545. if (isDaylightSavingTime())
  1546. {
  1547. zone[0] = zone[1];
  1548. if (zone[0].length() > 3
  1549. && zone[0].containsIgnoreCase (T("daylight"))
  1550. && zone[0].contains (T("GMT")))
  1551. zone[0] = "BST";
  1552. }
  1553. return zone[0].substring (0, 3);
  1554. }
  1555. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1556. {
  1557. return getMonthName (getMonth(), threeLetterVersion);
  1558. }
  1559. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1560. {
  1561. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1562. }
  1563. const String Time::getMonthName (int monthNumber,
  1564. const bool threeLetterVersion) throw()
  1565. {
  1566. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1567. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1568. monthNumber %= 12;
  1569. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1570. : longMonthNames [monthNumber]);
  1571. }
  1572. const String Time::getWeekdayName (int day,
  1573. const bool threeLetterVersion) throw()
  1574. {
  1575. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1576. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1577. day %= 7;
  1578. return TRANS (threeLetterVersion ? shortDayNames [day]
  1579. : longDayNames [day]);
  1580. }
  1581. END_JUCE_NAMESPACE
  1582. /********* End of inlined file: juce_Time.cpp *********/
  1583. /********* Start of inlined file: juce_BitArray.cpp *********/
  1584. BEGIN_JUCE_NAMESPACE
  1585. BitArray::BitArray() throw()
  1586. : numValues (4),
  1587. highestBit (-1),
  1588. negative (false)
  1589. {
  1590. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1591. }
  1592. BitArray::BitArray (const int value) throw()
  1593. : numValues (4),
  1594. highestBit (31),
  1595. negative (value < 0)
  1596. {
  1597. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1598. values[0] = abs (value);
  1599. highestBit = getHighestBit();
  1600. }
  1601. BitArray::BitArray (int64 value) throw()
  1602. : numValues (4),
  1603. highestBit (63),
  1604. negative (value < 0)
  1605. {
  1606. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1607. if (value < 0)
  1608. value = -value;
  1609. values[0] = (unsigned int) value;
  1610. values[1] = (unsigned int) (value >> 32);
  1611. highestBit = getHighestBit();
  1612. }
  1613. BitArray::BitArray (const unsigned int value) throw()
  1614. : numValues (4),
  1615. highestBit (31),
  1616. negative (false)
  1617. {
  1618. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1619. values[0] = value;
  1620. highestBit = getHighestBit();
  1621. }
  1622. BitArray::BitArray (const BitArray& other) throw()
  1623. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1624. highestBit (other.getHighestBit()),
  1625. negative (other.negative)
  1626. {
  1627. const int bytes = sizeof (unsigned int) * (numValues + 1);
  1628. values = (unsigned int*) juce_malloc (bytes);
  1629. memcpy (values, other.values, bytes);
  1630. }
  1631. BitArray::~BitArray() throw()
  1632. {
  1633. juce_free (values);
  1634. }
  1635. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1636. {
  1637. if (this != &other)
  1638. {
  1639. juce_free (values);
  1640. highestBit = other.getHighestBit();
  1641. numValues = jmax (4, (highestBit >> 5) + 1);
  1642. negative = other.negative;
  1643. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1644. values = (unsigned int*)juce_malloc (memSize);
  1645. memcpy (values, other.values, memSize);
  1646. }
  1647. return *this;
  1648. }
  1649. // result == 0 = the same
  1650. // result < 0 = this number is smaller
  1651. // result > 0 = this number is bigger
  1652. int BitArray::compare (const BitArray& other) const throw()
  1653. {
  1654. if (isNegative() == other.isNegative())
  1655. {
  1656. const int absComp = compareAbsolute (other);
  1657. return isNegative() ? -absComp : absComp;
  1658. }
  1659. else
  1660. {
  1661. return isNegative() ? -1 : 1;
  1662. }
  1663. }
  1664. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1665. {
  1666. const int h1 = getHighestBit();
  1667. const int h2 = other.getHighestBit();
  1668. if (h1 > h2)
  1669. return 1;
  1670. else if (h1 < h2)
  1671. return -1;
  1672. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1673. if (values[i] != other.values[i])
  1674. return (values[i] > other.values[i]) ? 1 : -1;
  1675. return 0;
  1676. }
  1677. bool BitArray::operator== (const BitArray& other) const throw()
  1678. {
  1679. return compare (other) == 0;
  1680. }
  1681. bool BitArray::operator!= (const BitArray& other) const throw()
  1682. {
  1683. return compare (other) != 0;
  1684. }
  1685. bool BitArray::operator[] (const int bit) const throw()
  1686. {
  1687. return bit >= 0 && bit <= highestBit
  1688. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1689. }
  1690. bool BitArray::isEmpty() const throw()
  1691. {
  1692. return getHighestBit() < 0;
  1693. }
  1694. void BitArray::clear() throw()
  1695. {
  1696. if (numValues > 16)
  1697. {
  1698. juce_free (values);
  1699. numValues = 4;
  1700. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1701. }
  1702. else
  1703. {
  1704. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1705. }
  1706. highestBit = -1;
  1707. negative = false;
  1708. }
  1709. void BitArray::setBit (const int bit) throw()
  1710. {
  1711. if (bit >= 0)
  1712. {
  1713. if (bit > highestBit)
  1714. {
  1715. ensureSize (bit >> 5);
  1716. highestBit = bit;
  1717. }
  1718. values [bit >> 5] |= (1 << (bit & 31));
  1719. }
  1720. }
  1721. void BitArray::setBit (const int bit,
  1722. const bool shouldBeSet) throw()
  1723. {
  1724. if (shouldBeSet)
  1725. setBit (bit);
  1726. else
  1727. clearBit (bit);
  1728. }
  1729. void BitArray::clearBit (const int bit) throw()
  1730. {
  1731. if (bit >= 0 && bit <= highestBit)
  1732. values [bit >> 5] &= ~(1 << (bit & 31));
  1733. }
  1734. void BitArray::setRange (int startBit,
  1735. int numBits,
  1736. const bool shouldBeSet) throw()
  1737. {
  1738. while (--numBits >= 0)
  1739. setBit (startBit++, shouldBeSet);
  1740. }
  1741. void BitArray::insertBit (const int bit,
  1742. const bool shouldBeSet) throw()
  1743. {
  1744. if (bit >= 0)
  1745. shiftBits (1, bit);
  1746. setBit (bit, shouldBeSet);
  1747. }
  1748. void BitArray::andWith (const BitArray& other) throw()
  1749. {
  1750. // this operation will only work with the absolute values
  1751. jassert (isNegative() == other.isNegative());
  1752. int n = numValues;
  1753. while (n > other.numValues)
  1754. values[--n] = 0;
  1755. while (--n >= 0)
  1756. values[n] &= other.values[n];
  1757. if (other.highestBit < highestBit)
  1758. highestBit = other.highestBit;
  1759. highestBit = getHighestBit();
  1760. }
  1761. void BitArray::orWith (const BitArray& other) throw()
  1762. {
  1763. if (other.highestBit < 0)
  1764. return;
  1765. // this operation will only work with the absolute values
  1766. jassert (isNegative() == other.isNegative());
  1767. ensureSize (other.highestBit >> 5);
  1768. int n = (other.highestBit >> 5) + 1;
  1769. while (--n >= 0)
  1770. values[n] |= other.values[n];
  1771. if (other.highestBit > highestBit)
  1772. highestBit = other.highestBit;
  1773. highestBit = getHighestBit();
  1774. }
  1775. void BitArray::xorWith (const BitArray& other) throw()
  1776. {
  1777. if (other.highestBit < 0)
  1778. return;
  1779. // this operation will only work with the absolute values
  1780. jassert (isNegative() == other.isNegative());
  1781. ensureSize (other.highestBit >> 5);
  1782. int n = (other.highestBit >> 5) + 1;
  1783. while (--n >= 0)
  1784. values[n] ^= other.values[n];
  1785. if (other.highestBit > highestBit)
  1786. highestBit = other.highestBit;
  1787. highestBit = getHighestBit();
  1788. }
  1789. void BitArray::add (const BitArray& other) throw()
  1790. {
  1791. if (other.isNegative())
  1792. {
  1793. BitArray o (other);
  1794. o.negate();
  1795. subtract (o);
  1796. return;
  1797. }
  1798. if (isNegative())
  1799. {
  1800. if (compareAbsolute (other) < 0)
  1801. {
  1802. BitArray temp (*this);
  1803. temp.negate();
  1804. *this = other;
  1805. subtract (temp);
  1806. }
  1807. else
  1808. {
  1809. negate();
  1810. subtract (other);
  1811. negate();
  1812. }
  1813. return;
  1814. }
  1815. if (other.highestBit > highestBit)
  1816. highestBit = other.highestBit;
  1817. ++highestBit;
  1818. const int numInts = (highestBit >> 5) + 1;
  1819. ensureSize (numInts);
  1820. int64 remainder = 0;
  1821. for (int i = 0; i <= numInts; ++i)
  1822. {
  1823. if (i < numValues)
  1824. remainder += values[i];
  1825. if (i < other.numValues)
  1826. remainder += other.values[i];
  1827. values[i] = (unsigned int) remainder;
  1828. remainder >>= 32;
  1829. }
  1830. jassert (remainder == 0);
  1831. highestBit = getHighestBit();
  1832. }
  1833. void BitArray::subtract (const BitArray& other) throw()
  1834. {
  1835. if (other.isNegative())
  1836. {
  1837. BitArray o (other);
  1838. o.negate();
  1839. add (o);
  1840. return;
  1841. }
  1842. if (! isNegative())
  1843. {
  1844. if (compareAbsolute (other) < 0)
  1845. {
  1846. BitArray temp (*this);
  1847. *this = other;
  1848. subtract (temp);
  1849. negate();
  1850. return;
  1851. }
  1852. }
  1853. else
  1854. {
  1855. negate();
  1856. add (other);
  1857. negate();
  1858. return;
  1859. }
  1860. const int numInts = (highestBit >> 5) + 1;
  1861. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1862. int64 amountToSubtract = 0;
  1863. for (int i = 0; i <= numInts; ++i)
  1864. {
  1865. if (i <= maxOtherInts)
  1866. amountToSubtract += (int64)other.values[i];
  1867. if (values[i] >= amountToSubtract)
  1868. {
  1869. values[i] = (unsigned int) (values[i] - amountToSubtract);
  1870. amountToSubtract = 0;
  1871. }
  1872. else
  1873. {
  1874. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  1875. values[i] = (unsigned int) n;
  1876. amountToSubtract = 1;
  1877. }
  1878. }
  1879. }
  1880. void BitArray::multiplyBy (const BitArray& other) throw()
  1881. {
  1882. BitArray total;
  1883. highestBit = getHighestBit();
  1884. const bool wasNegative = isNegative();
  1885. setNegative (false);
  1886. for (int i = 0; i <= highestBit; ++i)
  1887. {
  1888. if (operator[](i))
  1889. {
  1890. BitArray n (other);
  1891. n.setNegative (false);
  1892. n.shiftBits (i);
  1893. total.add (n);
  1894. }
  1895. }
  1896. *this = total;
  1897. negative = wasNegative ^ other.isNegative();
  1898. }
  1899. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  1900. {
  1901. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  1902. const int divHB = divisor.getHighestBit();
  1903. const int ourHB = getHighestBit();
  1904. if (divHB < 0 || ourHB < 0)
  1905. {
  1906. // division by zero
  1907. remainder.clear();
  1908. clear();
  1909. }
  1910. else
  1911. {
  1912. remainder = *this;
  1913. remainder.setNegative (false);
  1914. const bool wasNegative = isNegative();
  1915. clear();
  1916. BitArray temp (divisor);
  1917. temp.setNegative (false);
  1918. int leftShift = ourHB - divHB;
  1919. temp.shiftBits (leftShift);
  1920. while (leftShift >= 0)
  1921. {
  1922. if (remainder.compareAbsolute (temp) >= 0)
  1923. {
  1924. remainder.subtract (temp);
  1925. setBit (leftShift);
  1926. }
  1927. if (--leftShift >= 0)
  1928. temp.shiftBits (-1);
  1929. }
  1930. negative = wasNegative ^ divisor.isNegative();
  1931. remainder.setNegative (wasNegative);
  1932. }
  1933. }
  1934. void BitArray::modulo (const BitArray& divisor) throw()
  1935. {
  1936. BitArray remainder;
  1937. divideBy (divisor, remainder);
  1938. *this = remainder;
  1939. }
  1940. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  1941. {
  1942. while (! m->isEmpty())
  1943. {
  1944. if (n->compareAbsolute (*m) > 0)
  1945. swapVariables (m, n);
  1946. m->subtract (*n);
  1947. }
  1948. return *n;
  1949. }
  1950. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  1951. {
  1952. BitArray m (*this);
  1953. while (! n.isEmpty())
  1954. {
  1955. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  1956. return simpleGCD (&m, &n);
  1957. BitArray temp1 (m), temp2;
  1958. temp1.divideBy (n, temp2);
  1959. m = n;
  1960. n = temp2;
  1961. }
  1962. return m;
  1963. }
  1964. void BitArray::exponentModulo (const BitArray& exponent,
  1965. const BitArray& modulus) throw()
  1966. {
  1967. BitArray exp (exponent);
  1968. exp.modulo (modulus);
  1969. BitArray value (*this);
  1970. value.modulo (modulus);
  1971. clear();
  1972. setBit (0);
  1973. while (! exp.isEmpty())
  1974. {
  1975. if (exp [0])
  1976. {
  1977. multiplyBy (value);
  1978. this->modulo (modulus);
  1979. }
  1980. value.multiplyBy (value);
  1981. value.modulo (modulus);
  1982. exp.shiftBits (-1);
  1983. }
  1984. }
  1985. void BitArray::inverseModulo (const BitArray& modulus) throw()
  1986. {
  1987. const BitArray one (1);
  1988. if (modulus == one || modulus.isNegative())
  1989. {
  1990. clear();
  1991. return;
  1992. }
  1993. if (isNegative() || compareAbsolute (modulus) >= 0)
  1994. this->modulo (modulus);
  1995. if (*this == one)
  1996. return;
  1997. if (! (*this)[0])
  1998. {
  1999. // not invertible
  2000. clear();
  2001. return;
  2002. }
  2003. BitArray a1 (modulus);
  2004. BitArray a2 (*this);
  2005. BitArray b1 (modulus);
  2006. BitArray b2 (1);
  2007. while (a2 != one)
  2008. {
  2009. BitArray temp1, temp2, multiplier (a1);
  2010. multiplier.divideBy (a2, temp1);
  2011. temp1 = a2;
  2012. temp1.multiplyBy (multiplier);
  2013. temp2 = a1;
  2014. temp2.subtract (temp1);
  2015. a1 = a2;
  2016. a2 = temp2;
  2017. temp1 = b2;
  2018. temp1.multiplyBy (multiplier);
  2019. temp2 = b1;
  2020. temp2.subtract (temp1);
  2021. b1 = b2;
  2022. b2 = temp2;
  2023. }
  2024. while (b2.isNegative())
  2025. b2.add (modulus);
  2026. b2.modulo (modulus);
  2027. *this = b2;
  2028. }
  2029. void BitArray::shiftBits (int bits, const int startBit) throw()
  2030. {
  2031. if (highestBit < 0)
  2032. return;
  2033. if (startBit > 0)
  2034. {
  2035. if (bits < 0)
  2036. {
  2037. // right shift
  2038. for (int i = startBit; i <= highestBit; ++i)
  2039. setBit (i, operator[] (i - bits));
  2040. highestBit = getHighestBit();
  2041. }
  2042. else if (bits > 0)
  2043. {
  2044. // left shift
  2045. for (int i = highestBit + 1; --i >= startBit;)
  2046. setBit (i + bits, operator[] (i));
  2047. while (--bits >= 0)
  2048. clearBit (bits + startBit);
  2049. }
  2050. }
  2051. else
  2052. {
  2053. if (bits < 0)
  2054. {
  2055. // right shift
  2056. bits = -bits;
  2057. if (bits > highestBit)
  2058. {
  2059. clear();
  2060. }
  2061. else
  2062. {
  2063. const int wordsToMove = bits >> 5;
  2064. int top = 1 + (highestBit >> 5) - wordsToMove;
  2065. highestBit -= bits;
  2066. if (wordsToMove > 0)
  2067. {
  2068. int i;
  2069. for (i = 0; i < top; ++i)
  2070. values [i] = values [i + wordsToMove];
  2071. for (i = 0; i < wordsToMove; ++i)
  2072. values [top + i] = 0;
  2073. bits &= 31;
  2074. }
  2075. if (bits != 0)
  2076. {
  2077. const int invBits = 32 - bits;
  2078. --top;
  2079. for (int i = 0; i < top; ++i)
  2080. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2081. values[top] = (values[top] >> bits);
  2082. }
  2083. highestBit = getHighestBit();
  2084. }
  2085. }
  2086. else if (bits > 0)
  2087. {
  2088. // left shift
  2089. ensureSize (((highestBit + bits) >> 5) + 1);
  2090. const int wordsToMove = bits >> 5;
  2091. int top = 1 + (highestBit >> 5);
  2092. highestBit += bits;
  2093. if (wordsToMove > 0)
  2094. {
  2095. int i;
  2096. for (i = top; --i >= 0;)
  2097. values [i + wordsToMove] = values [i];
  2098. for (i = 0; i < wordsToMove; ++i)
  2099. values [i] = 0;
  2100. bits &= 31;
  2101. }
  2102. if (bits != 0)
  2103. {
  2104. const int invBits = 32 - bits;
  2105. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2106. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2107. values [wordsToMove] = values [wordsToMove] << bits;
  2108. }
  2109. highestBit = getHighestBit();
  2110. }
  2111. }
  2112. }
  2113. const BitArray BitArray::getBitRange (int startBit, int numBits) const throw()
  2114. {
  2115. BitArray r;
  2116. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2117. r.ensureSize (numBits >> 5);
  2118. r.highestBit = numBits;
  2119. int i = 0;
  2120. while (numBits > 0)
  2121. {
  2122. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2123. numBits -= 32;
  2124. startBit += 32;
  2125. }
  2126. r.highestBit = r.getHighestBit();
  2127. return r;
  2128. }
  2129. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2130. {
  2131. if (numBits > 32)
  2132. {
  2133. jassertfalse // use getBitRange() if you need more than 32 bits..
  2134. numBits = 32;
  2135. }
  2136. numBits = jmin (numBits, highestBit + 1 - startBit);
  2137. if (numBits <= 0)
  2138. return 0;
  2139. const int pos = startBit >> 5;
  2140. const int offset = startBit & 31;
  2141. const int endSpace = 32 - numBits;
  2142. uint32 n = ((uint32) values [pos]) >> offset;
  2143. if (offset > endSpace)
  2144. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2145. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2146. }
  2147. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  2148. {
  2149. if (numBits > 32)
  2150. {
  2151. jassertfalse
  2152. numBits = 32;
  2153. }
  2154. for (int i = 0; i < numBits; ++i)
  2155. {
  2156. setBit (startBit + i, (valueToSet & 1) != 0);
  2157. valueToSet >>= 1;
  2158. }
  2159. }
  2160. bool BitArray::isNegative() const throw()
  2161. {
  2162. return negative && ! isEmpty();
  2163. }
  2164. void BitArray::setNegative (const bool neg) throw()
  2165. {
  2166. negative = neg;
  2167. }
  2168. void BitArray::negate() throw()
  2169. {
  2170. negative = (! negative) && ! isEmpty();
  2171. }
  2172. int BitArray::countNumberOfSetBits() const throw()
  2173. {
  2174. int total = 0;
  2175. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2176. {
  2177. unsigned int n = values[i];
  2178. if (n == 0xffffffff)
  2179. {
  2180. total += 32;
  2181. }
  2182. else
  2183. {
  2184. while (n != 0)
  2185. {
  2186. total += (n & 1);
  2187. n >>= 1;
  2188. }
  2189. }
  2190. }
  2191. return total;
  2192. }
  2193. int BitArray::getHighestBit() const throw()
  2194. {
  2195. for (int i = highestBit + 1; --i >= 0;)
  2196. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2197. return i;
  2198. return -1;
  2199. }
  2200. int BitArray::findNextSetBit (int i) const throw()
  2201. {
  2202. for (; i <= highestBit; ++i)
  2203. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2204. return i;
  2205. return -1;
  2206. }
  2207. int BitArray::findNextClearBit (int i) const throw()
  2208. {
  2209. for (; i <= highestBit; ++i)
  2210. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2211. break;
  2212. return i;
  2213. }
  2214. void BitArray::ensureSize (const int numVals) throw()
  2215. {
  2216. if (numVals + 2 >= numValues)
  2217. {
  2218. int oldSize = numValues;
  2219. numValues = ((numVals + 2) * 3) / 2;
  2220. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  2221. while (oldSize < numValues)
  2222. values [oldSize++] = 0;
  2223. }
  2224. }
  2225. const String BitArray::toString (const int base, const int minimumNumCharacters) const throw()
  2226. {
  2227. String s;
  2228. BitArray v (*this);
  2229. if (base == 2 || base == 8 || base == 16)
  2230. {
  2231. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2232. static const tchar* const hexDigits = T("0123456789abcdef");
  2233. for (;;)
  2234. {
  2235. const int remainder = v.getBitRangeAsInt (0, bits);
  2236. v.shiftBits (-bits);
  2237. if (remainder == 0 && v.isEmpty())
  2238. break;
  2239. s = String::charToString (hexDigits [remainder]) + s;
  2240. }
  2241. }
  2242. else if (base == 10)
  2243. {
  2244. const BitArray ten (10);
  2245. BitArray remainder;
  2246. for (;;)
  2247. {
  2248. v.divideBy (ten, remainder);
  2249. if (remainder.isEmpty() && v.isEmpty())
  2250. break;
  2251. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2252. }
  2253. }
  2254. else
  2255. {
  2256. jassertfalse // can't do the specified base
  2257. return String::empty;
  2258. }
  2259. const int length = s.length();
  2260. if (length < minimumNumCharacters)
  2261. s = String::repeatedString (T("0"), minimumNumCharacters - length);
  2262. return isNegative() ? T("-") + s : s;
  2263. }
  2264. void BitArray::parseString (const String& text,
  2265. const int base) throw()
  2266. {
  2267. clear();
  2268. const tchar* t = (const tchar*) text;
  2269. if (base == 2 || base == 8 || base == 16)
  2270. {
  2271. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2272. for (;;)
  2273. {
  2274. const tchar c = *t++;
  2275. const int digit = CharacterFunctions::getHexDigitValue (c);
  2276. if (((unsigned int) digit) < (unsigned int) base)
  2277. {
  2278. shiftBits (bits);
  2279. add (digit);
  2280. }
  2281. else if (c == 0)
  2282. {
  2283. break;
  2284. }
  2285. }
  2286. }
  2287. else if (base == 10)
  2288. {
  2289. const BitArray ten ((unsigned int) 10);
  2290. for (;;)
  2291. {
  2292. const tchar c = *t++;
  2293. if (c >= T('0') && c <= T('9'))
  2294. {
  2295. multiplyBy (ten);
  2296. add ((int) (c - T('0')));
  2297. }
  2298. else if (c == 0)
  2299. {
  2300. break;
  2301. }
  2302. }
  2303. }
  2304. setNegative (text.trimStart().startsWithChar (T('-')));
  2305. }
  2306. const MemoryBlock BitArray::toMemoryBlock() const throw()
  2307. {
  2308. const int numBytes = (getHighestBit() + 8) >> 3;
  2309. MemoryBlock mb (numBytes);
  2310. for (int i = 0; i < numBytes; ++i)
  2311. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2312. return mb;
  2313. }
  2314. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  2315. {
  2316. clear();
  2317. for (int i = data.getSize(); --i >= 0;)
  2318. this->setBitRangeAsInt (i << 3, 8, data [i]);
  2319. }
  2320. END_JUCE_NAMESPACE
  2321. /********* End of inlined file: juce_BitArray.cpp *********/
  2322. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  2323. BEGIN_JUCE_NAMESPACE
  2324. MemoryBlock::MemoryBlock() throw()
  2325. : data (0),
  2326. size (0)
  2327. {
  2328. }
  2329. MemoryBlock::MemoryBlock (const int initialSize,
  2330. const bool initialiseToZero) throw()
  2331. {
  2332. if (initialSize > 0)
  2333. {
  2334. size = initialSize;
  2335. if (initialiseToZero)
  2336. data = (char*) juce_calloc (initialSize);
  2337. else
  2338. data = (char*) juce_malloc (initialSize);
  2339. }
  2340. else
  2341. {
  2342. data = 0;
  2343. size = 0;
  2344. }
  2345. }
  2346. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2347. : data (0),
  2348. size (other.size)
  2349. {
  2350. if (size > 0)
  2351. {
  2352. jassert (other.data != 0);
  2353. data = (char*) juce_malloc (size);
  2354. memcpy (data, other.data, size);
  2355. }
  2356. }
  2357. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2358. const int sizeInBytes) throw()
  2359. : data (0),
  2360. size (jmax (0, sizeInBytes))
  2361. {
  2362. jassert (sizeInBytes >= 0);
  2363. if (size > 0)
  2364. {
  2365. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2366. data = (char*) juce_malloc (size);
  2367. if (dataToInitialiseFrom != 0)
  2368. memcpy (data, dataToInitialiseFrom, size);
  2369. }
  2370. }
  2371. MemoryBlock::~MemoryBlock() throw()
  2372. {
  2373. jassert (size >= 0); // should never happen
  2374. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2375. juce_free (data);
  2376. }
  2377. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2378. {
  2379. if (this != &other)
  2380. {
  2381. setSize (other.size, false);
  2382. memcpy (data, other.data, size);
  2383. }
  2384. return *this;
  2385. }
  2386. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2387. {
  2388. return (size == other.size)
  2389. && (memcmp (data, other.data, size) == 0);
  2390. }
  2391. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2392. {
  2393. return ! operator== (other);
  2394. }
  2395. // this will resize the block to this size
  2396. void MemoryBlock::setSize (const int newSize,
  2397. const bool initialiseToZero) throw()
  2398. {
  2399. if (size != newSize)
  2400. {
  2401. if (newSize <= 0)
  2402. {
  2403. juce_free (data);
  2404. data = 0;
  2405. size = 0;
  2406. }
  2407. else
  2408. {
  2409. if (data != 0)
  2410. {
  2411. data = (char*) juce_realloc (data, newSize);
  2412. if (initialiseToZero && (newSize > size))
  2413. zeromem (data + size, newSize - size);
  2414. }
  2415. else
  2416. {
  2417. if (initialiseToZero)
  2418. data = (char*) juce_calloc (newSize);
  2419. else
  2420. data = (char*) juce_malloc (newSize);
  2421. }
  2422. size = newSize;
  2423. }
  2424. }
  2425. }
  2426. void MemoryBlock::ensureSize (const int minimumSize,
  2427. const bool initialiseToZero) throw()
  2428. {
  2429. if (size < minimumSize)
  2430. setSize (minimumSize, initialiseToZero);
  2431. }
  2432. void MemoryBlock::fillWith (const uint8 value) throw()
  2433. {
  2434. memset (data, (int) value, size);
  2435. }
  2436. void MemoryBlock::append (const void* const srcData,
  2437. const int numBytes) throw()
  2438. {
  2439. if (numBytes > 0)
  2440. {
  2441. const int oldSize = size;
  2442. setSize (size + numBytes);
  2443. memcpy (data + oldSize, srcData, numBytes);
  2444. }
  2445. }
  2446. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  2447. {
  2448. const char* d = (const char*) src;
  2449. if (offset < 0)
  2450. {
  2451. d -= offset;
  2452. num -= offset;
  2453. offset = 0;
  2454. }
  2455. if (offset + num > size)
  2456. num = size - offset;
  2457. if (num > 0)
  2458. memcpy (data + offset, d, num);
  2459. }
  2460. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  2461. {
  2462. char* d = (char*) dst;
  2463. if (offset < 0)
  2464. {
  2465. zeromem (d, -offset);
  2466. d -= offset;
  2467. num += offset;
  2468. offset = 0;
  2469. }
  2470. if (offset + num > size)
  2471. {
  2472. const int newNum = size - offset;
  2473. zeromem (d + newNum, num - newNum);
  2474. num = newNum;
  2475. }
  2476. if (num > 0)
  2477. memcpy (d, data + offset, num);
  2478. }
  2479. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  2480. {
  2481. if (startByte < 0)
  2482. {
  2483. numBytesToRemove += startByte;
  2484. startByte = 0;
  2485. }
  2486. if (startByte + numBytesToRemove >= size)
  2487. {
  2488. setSize (startByte);
  2489. }
  2490. else if (numBytesToRemove > 0)
  2491. {
  2492. memmove (data + startByte,
  2493. data + startByte + numBytesToRemove,
  2494. size - (startByte + numBytesToRemove));
  2495. setSize (size - numBytesToRemove);
  2496. }
  2497. }
  2498. const String MemoryBlock::toString() const throw()
  2499. {
  2500. return String (data, size);
  2501. }
  2502. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  2503. {
  2504. int res = 0;
  2505. int byte = bitRangeStart >> 3;
  2506. int offsetInByte = bitRangeStart & 7;
  2507. int bitsSoFar = 0;
  2508. while (numBits > 0 && byte < size)
  2509. {
  2510. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2511. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2512. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2513. bitsSoFar += bitsThisTime;
  2514. numBits -= bitsThisTime;
  2515. ++byte;
  2516. offsetInByte = 0;
  2517. }
  2518. return res;
  2519. }
  2520. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  2521. {
  2522. int byte = bitRangeStart >> 3;
  2523. int offsetInByte = bitRangeStart & 7;
  2524. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2525. while (numBits > 0 && byte < size)
  2526. {
  2527. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2528. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  2529. const unsigned int tempBits = bitsToSet << offsetInByte;
  2530. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  2531. ++byte;
  2532. numBits -= bitsThisTime;
  2533. bitsToSet >>= bitsThisTime;
  2534. mask >>= bitsThisTime;
  2535. offsetInByte = 0;
  2536. }
  2537. }
  2538. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2539. {
  2540. ensureSize (hex.length() >> 1);
  2541. char* dest = data;
  2542. int i = 0;
  2543. for (;;)
  2544. {
  2545. int byte = 0;
  2546. for (int loop = 2; --loop >= 0;)
  2547. {
  2548. byte <<= 4;
  2549. for (;;)
  2550. {
  2551. const tchar c = hex [i++];
  2552. if (c >= T('0') && c <= T('9'))
  2553. {
  2554. byte |= c - T('0');
  2555. break;
  2556. }
  2557. else if (c >= T('a') && c <= T('z'))
  2558. {
  2559. byte |= c - (T('a') - 10);
  2560. break;
  2561. }
  2562. else if (c >= T('A') && c <= T('Z'))
  2563. {
  2564. byte |= c - (T('A') - 10);
  2565. break;
  2566. }
  2567. else if (c == 0)
  2568. {
  2569. setSize ((int) (dest - data));
  2570. return;
  2571. }
  2572. }
  2573. }
  2574. *dest++ = (char) byte;
  2575. }
  2576. }
  2577. static const char* const encodingTable
  2578. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2579. const String MemoryBlock::toBase64Encoding() const throw()
  2580. {
  2581. const int numChars = ((size << 3) + 5) / 6;
  2582. String destString (size); // store the length, followed by a '.', and then the data.
  2583. const int initialLen = destString.length();
  2584. destString.preallocateStorage (initialLen + 2 + numChars);
  2585. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  2586. *d++ = T('.');
  2587. for (int i = 0; i < numChars; ++i)
  2588. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2589. *d++ = 0;
  2590. return destString;
  2591. }
  2592. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2593. {
  2594. const int startPos = s.indexOfChar (T('.')) + 1;
  2595. if (startPos <= 0)
  2596. return false;
  2597. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2598. setSize (numBytesNeeded, true);
  2599. const int numChars = s.length() - startPos;
  2600. const tchar* const srcChars = ((const tchar*) s) + startPos;
  2601. for (int i = 0; i < numChars; ++i)
  2602. {
  2603. const char c = (char) srcChars[i];
  2604. for (int j = 0; j < 64; ++j)
  2605. {
  2606. if (encodingTable[j] == c)
  2607. {
  2608. setBitRange (i * 6, 6, j);
  2609. break;
  2610. }
  2611. }
  2612. }
  2613. return true;
  2614. }
  2615. END_JUCE_NAMESPACE
  2616. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2617. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2618. BEGIN_JUCE_NAMESPACE
  2619. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2620. : properties (ignoreCaseOfKeyNames),
  2621. fallbackProperties (0),
  2622. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2623. {
  2624. }
  2625. PropertySet::PropertySet (const PropertySet& other) throw()
  2626. : properties (other.properties),
  2627. fallbackProperties (other.fallbackProperties),
  2628. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2629. {
  2630. }
  2631. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2632. {
  2633. properties = other.properties;
  2634. fallbackProperties = other.fallbackProperties;
  2635. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2636. propertyChanged();
  2637. return *this;
  2638. }
  2639. PropertySet::~PropertySet()
  2640. {
  2641. }
  2642. void PropertySet::clear()
  2643. {
  2644. const ScopedLock sl (lock);
  2645. if (properties.size() > 0)
  2646. {
  2647. properties.clear();
  2648. propertyChanged();
  2649. }
  2650. }
  2651. const String PropertySet::getValue (const String& keyName,
  2652. const String& defaultValue) const throw()
  2653. {
  2654. const ScopedLock sl (lock);
  2655. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2656. if (index >= 0)
  2657. return properties.getAllValues() [index];
  2658. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2659. : defaultValue;
  2660. }
  2661. int PropertySet::getIntValue (const String& keyName,
  2662. const int defaultValue) const throw()
  2663. {
  2664. const ScopedLock sl (lock);
  2665. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2666. if (index >= 0)
  2667. return properties.getAllValues() [index].getIntValue();
  2668. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2669. : defaultValue;
  2670. }
  2671. double PropertySet::getDoubleValue (const String& keyName,
  2672. const double defaultValue) const throw()
  2673. {
  2674. const ScopedLock sl (lock);
  2675. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2676. if (index >= 0)
  2677. return properties.getAllValues()[index].getDoubleValue();
  2678. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2679. : defaultValue;
  2680. }
  2681. bool PropertySet::getBoolValue (const String& keyName,
  2682. const bool defaultValue) const throw()
  2683. {
  2684. const ScopedLock sl (lock);
  2685. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2686. if (index >= 0)
  2687. return properties.getAllValues() [index].getIntValue() != 0;
  2688. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2689. : defaultValue;
  2690. }
  2691. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2692. {
  2693. XmlDocument doc (getValue (keyName));
  2694. return doc.getDocumentElement();
  2695. }
  2696. void PropertySet::setValue (const String& keyName,
  2697. const String& value) throw()
  2698. {
  2699. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2700. if (keyName.isNotEmpty())
  2701. {
  2702. const ScopedLock sl (lock);
  2703. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2704. if (index < 0 || properties.getAllValues() [index] != value)
  2705. {
  2706. properties.set (keyName, value);
  2707. propertyChanged();
  2708. }
  2709. }
  2710. }
  2711. void PropertySet::removeValue (const String& keyName) throw()
  2712. {
  2713. if (keyName.isNotEmpty())
  2714. {
  2715. const ScopedLock sl (lock);
  2716. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2717. if (index >= 0)
  2718. {
  2719. properties.remove (keyName);
  2720. propertyChanged();
  2721. }
  2722. }
  2723. }
  2724. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2725. {
  2726. setValue (keyName, String (value));
  2727. }
  2728. void PropertySet::setValue (const String& keyName, const int value) throw()
  2729. {
  2730. setValue (keyName, String (value));
  2731. }
  2732. void PropertySet::setValue (const String& keyName, const double value) throw()
  2733. {
  2734. setValue (keyName, String (value));
  2735. }
  2736. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2737. {
  2738. setValue (keyName, String ((value) ? T("1") : T("0")));
  2739. }
  2740. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2741. {
  2742. setValue (keyName, (xml == 0) ? String::empty
  2743. : xml->createDocument (String::empty, true));
  2744. }
  2745. bool PropertySet::containsKey (const String& keyName) const throw()
  2746. {
  2747. const ScopedLock sl (lock);
  2748. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2749. }
  2750. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2751. {
  2752. const ScopedLock sl (lock);
  2753. fallbackProperties = fallbackProperties_;
  2754. }
  2755. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2756. {
  2757. const ScopedLock sl (lock);
  2758. XmlElement* const xml = new XmlElement (nodeName);
  2759. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2760. {
  2761. XmlElement* const e = new XmlElement (T("VALUE"));
  2762. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2763. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2764. xml->addChildElement (e);
  2765. }
  2766. return xml;
  2767. }
  2768. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2769. {
  2770. const ScopedLock sl (lock);
  2771. clear();
  2772. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2773. {
  2774. if (e->hasAttribute (T("name"))
  2775. && e->hasAttribute (T("val")))
  2776. {
  2777. properties.set (e->getStringAttribute (T("name")),
  2778. e->getStringAttribute (T("val")));
  2779. }
  2780. }
  2781. if (properties.size() > 0)
  2782. propertyChanged();
  2783. }
  2784. void PropertySet::propertyChanged()
  2785. {
  2786. }
  2787. END_JUCE_NAMESPACE
  2788. /********* End of inlined file: juce_PropertySet.cpp *********/
  2789. /********* Start of inlined file: juce_Variant.cpp *********/
  2790. BEGIN_JUCE_NAMESPACE
  2791. var::var() throw()
  2792. : type (voidType)
  2793. {
  2794. value.doubleValue = 0;
  2795. }
  2796. void var::releaseValue() throw()
  2797. {
  2798. if (type == stringType)
  2799. delete value.stringValue;
  2800. else if (type == objectType && value.objectValue != 0)
  2801. value.objectValue->decReferenceCount();
  2802. }
  2803. var::~var()
  2804. {
  2805. releaseValue();
  2806. }
  2807. var::var (const var& valueToCopy) throw()
  2808. : type (valueToCopy.type),
  2809. value (valueToCopy.value)
  2810. {
  2811. if (type == stringType)
  2812. value.stringValue = new String (*(value.stringValue));
  2813. else if (type == objectType && value.objectValue != 0)
  2814. value.objectValue->incReferenceCount();
  2815. }
  2816. var::var (const int value_) throw()
  2817. : type (intType)
  2818. {
  2819. value.intValue = value_;
  2820. }
  2821. var::var (const bool value_) throw()
  2822. : type (boolType)
  2823. {
  2824. value.boolValue = value_;
  2825. }
  2826. var::var (const double value_) throw()
  2827. : type (doubleType)
  2828. {
  2829. value.doubleValue = value_;
  2830. }
  2831. var::var (const String& value_) throw()
  2832. : type (stringType)
  2833. {
  2834. value.stringValue = new String (value_);
  2835. }
  2836. var::var (const char* const value_) throw()
  2837. : type (stringType)
  2838. {
  2839. value.stringValue = new String (value_);
  2840. }
  2841. var::var (const juce_wchar* const value_) throw()
  2842. : type (stringType)
  2843. {
  2844. value.stringValue = new String (value_);
  2845. }
  2846. var::var (DynamicObject* const object) throw()
  2847. : type (objectType)
  2848. {
  2849. value.objectValue = object;
  2850. if (object != 0)
  2851. object->incReferenceCount();
  2852. }
  2853. var::var (MethodFunction method_) throw()
  2854. : type (methodType)
  2855. {
  2856. value.methodValue = method_;
  2857. }
  2858. const var& var::operator= (const var& valueToCopy) throw()
  2859. {
  2860. if (this != &valueToCopy)
  2861. {
  2862. if (type == stringType)
  2863. delete value.stringValue;
  2864. DynamicObject* const oldObject = getObject();
  2865. type = valueToCopy.type;
  2866. value = valueToCopy.value;
  2867. if (type == stringType)
  2868. value.stringValue = new String (*(value.stringValue));
  2869. else if (type == objectType && value.objectValue != 0)
  2870. value.objectValue->incReferenceCount();
  2871. if (oldObject != 0)
  2872. oldObject->decReferenceCount();
  2873. }
  2874. return *this;
  2875. }
  2876. const var& var::operator= (const int value_) throw()
  2877. {
  2878. releaseValue();
  2879. type = intType;
  2880. value.intValue = value_;
  2881. return *this;
  2882. }
  2883. const var& var::operator= (const bool value_) throw()
  2884. {
  2885. releaseValue();
  2886. type = boolType;
  2887. value.boolValue = value_;
  2888. return *this;
  2889. }
  2890. const var& var::operator= (const double value_) throw()
  2891. {
  2892. releaseValue();
  2893. type = doubleType;
  2894. value.doubleValue = value_;
  2895. return *this;
  2896. }
  2897. const var& var::operator= (const char* const value_) throw()
  2898. {
  2899. releaseValue();
  2900. type = stringType;
  2901. value.stringValue = new String (value_);
  2902. return *this;
  2903. }
  2904. const var& var::operator= (const juce_wchar* const value_) throw()
  2905. {
  2906. releaseValue();
  2907. type = stringType;
  2908. value.stringValue = new String (value_);
  2909. return *this;
  2910. }
  2911. const var& var::operator= (const String& value_) throw()
  2912. {
  2913. releaseValue();
  2914. type = stringType;
  2915. value.stringValue = new String (value_);
  2916. return *this;
  2917. }
  2918. const var& var::operator= (DynamicObject* const value_) throw()
  2919. {
  2920. value_->incReferenceCount();
  2921. releaseValue();
  2922. type = objectType;
  2923. value.objectValue = value_;
  2924. return *this;
  2925. }
  2926. const var& var::operator= (MethodFunction method_) throw()
  2927. {
  2928. releaseValue();
  2929. type = doubleType;
  2930. value.methodValue = method_;
  2931. return *this;
  2932. }
  2933. var::operator int() const throw()
  2934. {
  2935. switch (type)
  2936. {
  2937. case voidType:
  2938. case objectType: break;
  2939. case intType: return value.intValue;
  2940. case boolType: return value.boolValue ? 1 : 0;
  2941. case doubleType: return (int) value.doubleValue;
  2942. case stringType: return value.stringValue->getIntValue();
  2943. default: jassertfalse; break;
  2944. }
  2945. return 0;
  2946. }
  2947. var::operator bool() const throw()
  2948. {
  2949. switch (type)
  2950. {
  2951. case voidType: break;
  2952. case objectType: return value.objectValue != 0;
  2953. case intType: return value.intValue != 0;
  2954. case boolType: return value.boolValue;
  2955. case doubleType: return value.doubleValue != 0;
  2956. case stringType: return value.stringValue->getIntValue() != 0
  2957. || value.stringValue->trim().equalsIgnoreCase (T("true"))
  2958. || value.stringValue->trim().equalsIgnoreCase (T("yes"));
  2959. default: jassertfalse; break;
  2960. }
  2961. return false;
  2962. }
  2963. var::operator double() const throw()
  2964. {
  2965. switch (type)
  2966. {
  2967. case voidType:
  2968. case objectType: break;
  2969. case intType: return value.intValue;
  2970. case boolType: return value.boolValue ? 1.0 : 0.0;
  2971. case doubleType: return value.doubleValue;
  2972. case stringType: return value.stringValue->getDoubleValue();
  2973. default: jassertfalse; break;
  2974. }
  2975. return 0;
  2976. }
  2977. const String var::toString() const throw()
  2978. {
  2979. switch (type)
  2980. {
  2981. case voidType:
  2982. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  2983. case intType: return String (value.intValue);
  2984. case boolType: return value.boolValue ? T("1") : T("0");
  2985. case doubleType: return String (value.doubleValue);
  2986. case stringType: return *(value.stringValue);
  2987. default: jassertfalse; break;
  2988. }
  2989. return String::empty;
  2990. }
  2991. var::operator const String() const throw()
  2992. {
  2993. return toString();
  2994. }
  2995. DynamicObject* var::getObject() const throw()
  2996. {
  2997. return type == objectType ? value.objectValue : 0;
  2998. }
  2999. const var var::operator[] (const var::identifier& propertyName) const throw()
  3000. {
  3001. if (type == objectType && value.objectValue != 0)
  3002. return value.objectValue->getProperty (propertyName);
  3003. return var();
  3004. }
  3005. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  3006. {
  3007. if (type == objectType && value.objectValue != 0)
  3008. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3009. return var();
  3010. }
  3011. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3012. {
  3013. if (isMethod())
  3014. {
  3015. DynamicObject* const target = targetObject.getObject();
  3016. if (target != 0)
  3017. return (target->*(value.methodValue)) (arguments, numArguments);
  3018. }
  3019. return var();
  3020. }
  3021. const var var::call (const var::identifier& method) const
  3022. {
  3023. return invoke (method, 0, 0);
  3024. }
  3025. const var var::call (const var::identifier& method, const var& arg1) const
  3026. {
  3027. return invoke (method, &arg1, 1);
  3028. }
  3029. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3030. {
  3031. var args[] = { arg1, arg2 };
  3032. return invoke (method, args, 2);
  3033. }
  3034. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3035. {
  3036. var args[] = { arg1, arg2, arg3 };
  3037. return invoke (method, args, 3);
  3038. }
  3039. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3040. {
  3041. var args[] = { arg1, arg2, arg3, arg4 };
  3042. return invoke (method, args, 4);
  3043. }
  3044. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3045. {
  3046. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3047. return invoke (method, args, 5);
  3048. }
  3049. var::identifier::identifier (const String& name_) throw()
  3050. : name (name_),
  3051. hashCode (name_.hashCode())
  3052. {
  3053. }
  3054. var::identifier::identifier (const char* const name_) throw()
  3055. : name (name_),
  3056. hashCode (name.hashCode())
  3057. {
  3058. }
  3059. var::identifier::~identifier() throw()
  3060. {
  3061. }
  3062. DynamicObject::DynamicObject()
  3063. {
  3064. }
  3065. DynamicObject::~DynamicObject()
  3066. {
  3067. }
  3068. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3069. {
  3070. const int index = propertyIds.indexOf (propertyName.hashCode);
  3071. return index >= 0 && ! propertyValues.getUnchecked (index)->isMethod();
  3072. }
  3073. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3074. {
  3075. const int index = propertyIds.indexOf (propertyName.hashCode);
  3076. if (index >= 0)
  3077. return *propertyValues.getUnchecked (index);
  3078. return var();
  3079. }
  3080. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3081. {
  3082. const int index = propertyIds.indexOf (propertyName.hashCode);
  3083. if (index >= 0)
  3084. {
  3085. propertyValues.set (index, new var (newValue));
  3086. }
  3087. else
  3088. {
  3089. propertyIds.add (propertyName.hashCode);
  3090. propertyValues.add (new var (newValue));
  3091. }
  3092. }
  3093. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3094. {
  3095. const int index = propertyIds.indexOf (propertyName.hashCode);
  3096. if (index >= 0)
  3097. {
  3098. propertyIds.remove (index);
  3099. propertyValues.remove (index);
  3100. }
  3101. }
  3102. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3103. {
  3104. return getProperty (methodName).isMethod();
  3105. }
  3106. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3107. const var* parameters,
  3108. int numParameters)
  3109. {
  3110. return getProperty (methodName).invoke (this, parameters, numParameters);
  3111. }
  3112. void DynamicObject::setMethod (const var::identifier& name,
  3113. var::MethodFunction methodFunction)
  3114. {
  3115. setProperty (name, methodFunction);
  3116. }
  3117. void DynamicObject::clear()
  3118. {
  3119. propertyIds.clear();
  3120. propertyValues.clear();
  3121. }
  3122. END_JUCE_NAMESPACE
  3123. /********* End of inlined file: juce_Variant.cpp *********/
  3124. /********* Start of inlined file: juce_BlowFish.cpp *********/
  3125. BEGIN_JUCE_NAMESPACE
  3126. static const uint32 initialPValues [18] =
  3127. {
  3128. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  3129. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3130. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  3131. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3132. 0x9216d5d9, 0x8979fb1b
  3133. };
  3134. static const uint32 initialSValues [4 * 256] =
  3135. {
  3136. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  3137. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3138. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  3139. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3140. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  3141. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3142. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  3143. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3144. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  3145. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3146. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  3147. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3148. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  3149. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3150. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  3151. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3152. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  3153. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3154. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  3155. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3156. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  3157. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3158. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  3159. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3160. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  3161. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3162. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  3163. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3164. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  3165. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3166. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  3167. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3168. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  3169. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3170. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  3171. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3172. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  3173. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3174. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  3175. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3176. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  3177. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3178. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  3179. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3180. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  3181. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3182. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  3183. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3184. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  3185. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3186. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  3187. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3188. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  3189. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3190. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  3191. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3192. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  3193. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3194. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  3195. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3196. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  3197. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3198. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  3199. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3200. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  3201. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3202. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  3203. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3204. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  3205. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3206. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  3207. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3208. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  3209. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3210. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  3211. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3212. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  3213. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3214. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  3215. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3216. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  3217. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3218. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  3219. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3220. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  3221. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3222. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  3223. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3224. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  3225. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3226. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  3227. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3228. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  3229. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3230. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  3231. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3232. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  3233. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3234. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  3235. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3236. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  3237. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3238. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  3239. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3240. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  3241. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3242. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  3243. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3244. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  3245. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3246. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  3247. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3248. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  3249. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3250. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  3251. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3252. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  3253. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3254. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  3255. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3256. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  3257. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3258. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  3259. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3260. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  3261. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3262. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  3263. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3264. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  3265. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3266. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  3267. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3268. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  3269. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3270. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  3271. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3272. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  3273. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3274. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  3275. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3276. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  3277. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3278. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  3279. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3280. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  3281. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3282. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  3283. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3284. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  3285. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3286. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  3287. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3288. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  3289. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3290. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  3291. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3292. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  3293. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3294. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  3295. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3296. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  3297. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3298. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  3299. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3300. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  3301. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3302. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  3303. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3304. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  3305. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3306. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  3307. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3308. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  3309. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3310. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  3311. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3312. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  3313. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3314. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  3315. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3316. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  3317. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3318. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  3319. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3320. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  3321. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3322. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  3323. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3324. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  3325. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3326. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  3327. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3328. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  3329. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3330. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  3331. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3332. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  3333. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3334. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  3335. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3336. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  3337. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3338. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  3339. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3340. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  3341. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3342. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  3343. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3344. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  3345. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3346. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  3347. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3348. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  3349. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3350. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  3351. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3352. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  3353. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3354. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  3355. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3356. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  3357. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3358. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  3359. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3360. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  3361. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3362. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  3363. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3364. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  3365. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3366. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  3367. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3368. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  3369. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3370. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  3371. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3372. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  3373. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3374. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  3375. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3376. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  3377. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3378. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  3379. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3380. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  3381. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3382. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  3383. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3384. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  3385. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3386. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  3387. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3388. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  3389. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3390. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  3391. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3392. };
  3393. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  3394. {
  3395. memcpy (p, initialPValues, sizeof (p));
  3396. int i, j;
  3397. for (i = 4; --i >= 0;)
  3398. {
  3399. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3400. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3401. }
  3402. j = 0;
  3403. for (i = 0; i < 18; ++i)
  3404. {
  3405. uint32 d = 0;
  3406. for (int k = 0; k < 4; ++k)
  3407. {
  3408. d = (d << 8) | keyData[j];
  3409. if (++j >= keyBytes)
  3410. j = 0;
  3411. }
  3412. p[i] = initialPValues[i] ^ d;
  3413. }
  3414. uint32 l = 0, r = 0;
  3415. for (i = 0; i < 18; i += 2)
  3416. {
  3417. encrypt (l, r);
  3418. p[i] = l;
  3419. p[i + 1] = r;
  3420. }
  3421. for (i = 0; i < 4; ++i)
  3422. {
  3423. for (j = 0; j < 256; j += 2)
  3424. {
  3425. encrypt (l, r);
  3426. s[i][j] = l;
  3427. s[i][j + 1] = r;
  3428. }
  3429. }
  3430. }
  3431. BlowFish::BlowFish (const BlowFish& other)
  3432. {
  3433. for (int i = 4; --i >= 0;)
  3434. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3435. operator= (other);
  3436. }
  3437. const BlowFish& BlowFish::operator= (const BlowFish& other)
  3438. {
  3439. memcpy (p, other.p, sizeof (p));
  3440. for (int i = 4; --i >= 0;)
  3441. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3442. return *this;
  3443. }
  3444. BlowFish::~BlowFish()
  3445. {
  3446. for (int i = 4; --i >= 0;)
  3447. juce_free (s[i]);
  3448. }
  3449. uint32 BlowFish::F (uint32 x) const
  3450. {
  3451. uint16 a, b, c, d;
  3452. uint32 y;
  3453. d = (uint16) (x & 0xff);
  3454. x >>= 8;
  3455. c = (uint16) (x & 0xff);
  3456. x >>= 8;
  3457. b = (uint16) (x & 0xff);
  3458. x >>= 8;
  3459. a = (uint16) (x & 0xff);
  3460. y = s[0][a] + s[1][b];
  3461. y = y ^ s[2][c];
  3462. y = y + s[3][d];
  3463. return y;
  3464. }
  3465. void BlowFish::encrypt (uint32& data1,
  3466. uint32& data2) const
  3467. {
  3468. uint32 l = data1;
  3469. uint32 r = data2;
  3470. for (int i = 0; i < 16; ++i)
  3471. {
  3472. l = l ^ p[i];
  3473. r = F (l) ^ r;
  3474. const uint32 temp = l;
  3475. l = r;
  3476. r = temp;
  3477. }
  3478. const uint32 temp = l;
  3479. l = r;
  3480. r = temp;
  3481. r = r ^ p[16];
  3482. l = l ^ p[17];
  3483. data1 = l;
  3484. data2 = r;
  3485. }
  3486. void BlowFish::decrypt (uint32& data1,
  3487. uint32& data2) const
  3488. {
  3489. uint32 l = data1;
  3490. uint32 r = data2;
  3491. for (int i = 17; i > 1; --i)
  3492. {
  3493. l =l ^ p[i];
  3494. r = F (l) ^ r;
  3495. const uint32 temp = l;
  3496. l = r;
  3497. r = temp;
  3498. }
  3499. const uint32 temp = l;
  3500. l = r;
  3501. r = temp;
  3502. r = r ^ p[1];
  3503. l = l ^ p[0];
  3504. data1 = l;
  3505. data2 = r;
  3506. }
  3507. END_JUCE_NAMESPACE
  3508. /********* End of inlined file: juce_BlowFish.cpp *********/
  3509. /********* Start of inlined file: juce_MD5.cpp *********/
  3510. BEGIN_JUCE_NAMESPACE
  3511. MD5::MD5()
  3512. {
  3513. zeromem (result, sizeof (result));
  3514. }
  3515. MD5::MD5 (const MD5& other)
  3516. {
  3517. memcpy (result, other.result, sizeof (result));
  3518. }
  3519. const MD5& MD5::operator= (const MD5& other)
  3520. {
  3521. memcpy (result, other.result, sizeof (result));
  3522. return *this;
  3523. }
  3524. MD5::MD5 (const MemoryBlock& data)
  3525. {
  3526. ProcessContext context;
  3527. context.processBlock ((const uint8*) data.getData(), data.getSize());
  3528. context.finish (result);
  3529. }
  3530. MD5::MD5 (const char* data, const int numBytes)
  3531. {
  3532. ProcessContext context;
  3533. context.processBlock ((const uint8*) data, numBytes);
  3534. context.finish (result);
  3535. }
  3536. MD5::MD5 (const String& text)
  3537. {
  3538. ProcessContext context;
  3539. const int len = text.length();
  3540. const juce_wchar* const t = text;
  3541. for (int i = 0; i < len; ++i)
  3542. {
  3543. // force the string into integer-sized unicode characters, to try to make it
  3544. // get the same results on all platforms + compilers.
  3545. uint32 unicodeChar = (uint32) t[i];
  3546. swapIfBigEndian (unicodeChar);
  3547. context.processBlock ((const uint8*) &unicodeChar,
  3548. sizeof (unicodeChar));
  3549. }
  3550. context.finish (result);
  3551. }
  3552. void MD5::processStream (InputStream& input, int numBytesToRead)
  3553. {
  3554. ProcessContext context;
  3555. if (numBytesToRead < 0)
  3556. numBytesToRead = INT_MAX;
  3557. while (numBytesToRead > 0)
  3558. {
  3559. char tempBuffer [512];
  3560. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  3561. if (bytesRead <= 0)
  3562. break;
  3563. numBytesToRead -= bytesRead;
  3564. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  3565. }
  3566. context.finish (result);
  3567. }
  3568. MD5::MD5 (InputStream& input, int numBytesToRead)
  3569. {
  3570. processStream (input, numBytesToRead);
  3571. }
  3572. MD5::MD5 (const File& file)
  3573. {
  3574. FileInputStream* const fin = file.createInputStream();
  3575. if (fin != 0)
  3576. {
  3577. processStream (*fin, -1);
  3578. delete fin;
  3579. }
  3580. else
  3581. {
  3582. zeromem (result, sizeof (result));
  3583. }
  3584. }
  3585. MD5::~MD5()
  3586. {
  3587. }
  3588. MD5::ProcessContext::ProcessContext()
  3589. {
  3590. state[0] = 0x67452301;
  3591. state[1] = 0xefcdab89;
  3592. state[2] = 0x98badcfe;
  3593. state[3] = 0x10325476;
  3594. count[0] = 0;
  3595. count[1] = 0;
  3596. }
  3597. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  3598. {
  3599. int bufferPos = ((count[0] >> 3) & 0x3F);
  3600. count[0] += (dataSize << 3);
  3601. if (count[0] < ((uint32) dataSize << 3))
  3602. count[1]++;
  3603. count[1] += (dataSize >> 29);
  3604. const int spaceLeft = 64 - bufferPos;
  3605. int i = 0;
  3606. if (dataSize >= spaceLeft)
  3607. {
  3608. memcpy (buffer + bufferPos, data, spaceLeft);
  3609. transform (buffer);
  3610. i = spaceLeft;
  3611. while (i < dataSize - 63)
  3612. {
  3613. transform (data + i);
  3614. i += 64;
  3615. }
  3616. bufferPos = 0;
  3617. }
  3618. memcpy (buffer + bufferPos, data + i, dataSize - i);
  3619. }
  3620. static void encode (uint8* const output,
  3621. const uint32* const input,
  3622. const int numBytes)
  3623. {
  3624. uint32* const o = (uint32*) output;
  3625. for (int i = 0; i < (numBytes >> 2); ++i)
  3626. o[i] = swapIfBigEndian (input [i]);
  3627. }
  3628. static void decode (uint32* const output,
  3629. const uint8* const input,
  3630. const int numBytes)
  3631. {
  3632. for (int i = 0; i < (numBytes >> 2); ++i)
  3633. output[i] = littleEndianInt ((const char*) input + (i << 2));
  3634. }
  3635. void MD5::ProcessContext::finish (uint8* const result)
  3636. {
  3637. unsigned char encodedLength[8];
  3638. encode (encodedLength, count, 8);
  3639. // Pad out to 56 mod 64.
  3640. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3641. const int paddingLength = (index < 56) ? (56 - index)
  3642. : (120 - index);
  3643. uint8 paddingBuffer [64];
  3644. zeromem (paddingBuffer, paddingLength);
  3645. paddingBuffer [0] = 0x80;
  3646. processBlock (paddingBuffer, paddingLength);
  3647. processBlock (encodedLength, 8);
  3648. encode (result, state, 16);
  3649. zeromem (buffer, sizeof (buffer));
  3650. }
  3651. #define S11 7
  3652. #define S12 12
  3653. #define S13 17
  3654. #define S14 22
  3655. #define S21 5
  3656. #define S22 9
  3657. #define S23 14
  3658. #define S24 20
  3659. #define S31 4
  3660. #define S32 11
  3661. #define S33 16
  3662. #define S34 23
  3663. #define S41 6
  3664. #define S42 10
  3665. #define S43 15
  3666. #define S44 21
  3667. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  3668. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  3669. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  3670. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  3671. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  3672. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3673. {
  3674. a += F (b, c, d) + x + ac;
  3675. a = rotateLeft (a, s) + b;
  3676. }
  3677. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3678. {
  3679. a += G (b, c, d) + x + ac;
  3680. a = rotateLeft (a, s) + b;
  3681. }
  3682. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3683. {
  3684. a += H (b, c, d) + x + ac;
  3685. a = rotateLeft (a, s) + b;
  3686. }
  3687. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3688. {
  3689. a += I (b, c, d) + x + ac;
  3690. a = rotateLeft (a, s) + b;
  3691. }
  3692. void MD5::ProcessContext::transform (const uint8* const buffer)
  3693. {
  3694. uint32 a = state[0];
  3695. uint32 b = state[1];
  3696. uint32 c = state[2];
  3697. uint32 d = state[3];
  3698. uint32 x[16];
  3699. decode (x, buffer, 64);
  3700. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  3701. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  3702. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  3703. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  3704. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  3705. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  3706. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  3707. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  3708. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  3709. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  3710. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  3711. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  3712. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  3713. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  3714. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  3715. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  3716. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  3717. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  3718. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  3719. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  3720. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  3721. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  3722. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  3723. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  3724. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  3725. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  3726. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  3727. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  3728. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  3729. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  3730. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  3731. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  3732. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  3733. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  3734. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  3735. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  3736. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  3737. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  3738. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  3739. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  3740. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  3741. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  3742. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  3743. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  3744. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  3745. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  3746. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  3747. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  3748. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  3749. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  3750. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  3751. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  3752. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  3753. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  3754. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  3755. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  3756. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  3757. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  3758. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  3759. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  3760. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  3761. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  3762. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  3763. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  3764. state[0] += a;
  3765. state[1] += b;
  3766. state[2] += c;
  3767. state[3] += d;
  3768. zeromem (x, sizeof (x));
  3769. }
  3770. const MemoryBlock MD5::getRawChecksumData() const
  3771. {
  3772. return MemoryBlock (result, 16);
  3773. }
  3774. const String MD5::toHexString() const
  3775. {
  3776. return String::toHexString (result, 16, 0);
  3777. }
  3778. bool MD5::operator== (const MD5& other) const
  3779. {
  3780. return memcmp (result, other.result, 16) == 0;
  3781. }
  3782. bool MD5::operator!= (const MD5& other) const
  3783. {
  3784. return ! operator== (other);
  3785. }
  3786. END_JUCE_NAMESPACE
  3787. /********* End of inlined file: juce_MD5.cpp *********/
  3788. /********* Start of inlined file: juce_Primes.cpp *********/
  3789. BEGIN_JUCE_NAMESPACE
  3790. static void createSmallSieve (const int numBits, BitArray& result) throw()
  3791. {
  3792. result.setBit (numBits);
  3793. result.clearBit (numBits); // to enlarge the array
  3794. result.setBit (0);
  3795. int n = 2;
  3796. do
  3797. {
  3798. for (int i = n + n; i < numBits; i += n)
  3799. result.setBit (i);
  3800. n = result.findNextClearBit (n + 1);
  3801. }
  3802. while (n <= (numBits >> 1));
  3803. }
  3804. static void bigSieve (const BitArray& base,
  3805. const int numBits,
  3806. BitArray& result,
  3807. const BitArray& smallSieve,
  3808. const int smallSieveSize) throw()
  3809. {
  3810. jassert (! base[0]); // must be even!
  3811. result.setBit (numBits);
  3812. result.clearBit (numBits); // to enlarge the array
  3813. int index = smallSieve.findNextClearBit (0);
  3814. do
  3815. {
  3816. const int prime = (index << 1) + 1;
  3817. BitArray r (base);
  3818. BitArray remainder;
  3819. r.divideBy (prime, remainder);
  3820. int i = prime - remainder.getBitRangeAsInt (0, 32);
  3821. if (r.isEmpty())
  3822. i += prime;
  3823. if ((i & 1) == 0)
  3824. i += prime;
  3825. i = (i - 1) >> 1;
  3826. while (i < numBits)
  3827. {
  3828. result.setBit (i);
  3829. i += prime;
  3830. }
  3831. index = smallSieve.findNextClearBit (index + 1);
  3832. }
  3833. while (index < smallSieveSize);
  3834. }
  3835. static bool findCandidate (const BitArray& base,
  3836. const BitArray& sieve,
  3837. const int numBits,
  3838. BitArray& result,
  3839. const int certainty) throw()
  3840. {
  3841. for (int i = 0; i < numBits; ++i)
  3842. {
  3843. if (! sieve[i])
  3844. {
  3845. result = base;
  3846. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  3847. if (Primes::isProbablyPrime (result, certainty))
  3848. return true;
  3849. }
  3850. }
  3851. return false;
  3852. }
  3853. const BitArray Primes::createProbablePrime (const int bitLength,
  3854. const int certainty,
  3855. const int* randomSeeds,
  3856. int numRandomSeeds) throw()
  3857. {
  3858. int defaultSeeds [16];
  3859. if (numRandomSeeds <= 0)
  3860. {
  3861. randomSeeds = defaultSeeds;
  3862. numRandomSeeds = numElementsInArray (defaultSeeds);
  3863. Random r (0);
  3864. for (int j = 10; --j >= 0;)
  3865. {
  3866. r.setSeedRandomly();
  3867. for (int i = numRandomSeeds; --i >= 0;)
  3868. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  3869. }
  3870. }
  3871. BitArray smallSieve;
  3872. const int smallSieveSize = 15000;
  3873. createSmallSieve (smallSieveSize, smallSieve);
  3874. BitArray p;
  3875. for (int i = numRandomSeeds; --i >= 0;)
  3876. {
  3877. BitArray p2;
  3878. Random r (randomSeeds[i]);
  3879. r.fillBitsRandomly (p2, 0, bitLength);
  3880. p.xorWith (p2);
  3881. }
  3882. p.setBit (bitLength - 1);
  3883. p.clearBit (0);
  3884. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  3885. while (p.getHighestBit() < bitLength)
  3886. {
  3887. p.add (2 * searchLen);
  3888. BitArray sieve;
  3889. bigSieve (p, searchLen, sieve,
  3890. smallSieve, smallSieveSize);
  3891. BitArray candidate;
  3892. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  3893. return candidate;
  3894. }
  3895. jassertfalse
  3896. return BitArray();
  3897. }
  3898. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  3899. {
  3900. const BitArray one (1);
  3901. const BitArray two (2);
  3902. BitArray nMinusOne (n);
  3903. nMinusOne.subtract (one);
  3904. BitArray d (nMinusOne);
  3905. const int s = d.findNextSetBit (0);
  3906. d.shiftBits (-s);
  3907. BitArray smallPrimes;
  3908. int numBitsInSmallPrimes = 0;
  3909. for (;;)
  3910. {
  3911. numBitsInSmallPrimes += 256;
  3912. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  3913. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  3914. if (numPrimesFound > iterations + 1)
  3915. break;
  3916. }
  3917. int smallPrime = 2;
  3918. while (--iterations >= 0)
  3919. {
  3920. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  3921. BitArray r (smallPrime);
  3922. //r.createRandomNumber (nMinusOne);
  3923. r.exponentModulo (d, n);
  3924. if (! (r == one || r == nMinusOne))
  3925. {
  3926. for (int j = 0; j < s; ++j)
  3927. {
  3928. r.exponentModulo (two, n);
  3929. if (r == nMinusOne)
  3930. break;
  3931. }
  3932. if (r != nMinusOne)
  3933. return false;
  3934. }
  3935. }
  3936. return true;
  3937. }
  3938. bool Primes::isProbablyPrime (const BitArray& number,
  3939. const int certainty) throw()
  3940. {
  3941. if (! number[0])
  3942. return false;
  3943. if (number.getHighestBit() <= 10)
  3944. {
  3945. const int num = number.getBitRangeAsInt (0, 10);
  3946. for (int i = num / 2; --i > 1;)
  3947. if (num % i == 0)
  3948. return false;
  3949. return true;
  3950. }
  3951. else
  3952. {
  3953. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  3954. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  3955. return false;
  3956. return passesMillerRabin (number, certainty);
  3957. }
  3958. }
  3959. END_JUCE_NAMESPACE
  3960. /********* End of inlined file: juce_Primes.cpp *********/
  3961. /********* Start of inlined file: juce_RSAKey.cpp *********/
  3962. BEGIN_JUCE_NAMESPACE
  3963. RSAKey::RSAKey() throw()
  3964. {
  3965. }
  3966. RSAKey::RSAKey (const String& s) throw()
  3967. {
  3968. if (s.containsChar (T(',')))
  3969. {
  3970. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  3971. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  3972. }
  3973. else
  3974. {
  3975. // the string needs to be two hex numbers, comma-separated..
  3976. jassertfalse;
  3977. }
  3978. }
  3979. RSAKey::~RSAKey() throw()
  3980. {
  3981. }
  3982. const String RSAKey::toString() const throw()
  3983. {
  3984. return part1.toString (16) + T(",") + part2.toString (16);
  3985. }
  3986. bool RSAKey::applyToValue (BitArray& value) const throw()
  3987. {
  3988. if (part1.isEmpty() || part2.isEmpty()
  3989. || value.compare (0) <= 0)
  3990. {
  3991. jassertfalse // using an uninitialised key
  3992. value.clear();
  3993. return false;
  3994. }
  3995. BitArray result;
  3996. while (! value.isEmpty())
  3997. {
  3998. result.multiplyBy (part2);
  3999. BitArray remainder;
  4000. value.divideBy (part2, remainder);
  4001. remainder.exponentModulo (part1, part2);
  4002. result.add (remainder);
  4003. }
  4004. value = result;
  4005. return true;
  4006. }
  4007. static const BitArray findBestCommonDivisor (const BitArray& p,
  4008. const BitArray& q) throw()
  4009. {
  4010. const BitArray one (1);
  4011. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4012. // are fast to divide + multiply
  4013. for (int i = 2; i <= 65536; i *= 2)
  4014. {
  4015. const BitArray e (1 + i);
  4016. if (e.findGreatestCommonDivisor (p) == one
  4017. && e.findGreatestCommonDivisor (q) == one)
  4018. {
  4019. return e;
  4020. }
  4021. }
  4022. BitArray e (4);
  4023. while (! (e.findGreatestCommonDivisor (p) == one
  4024. && e.findGreatestCommonDivisor (q) == one))
  4025. {
  4026. e.add (one);
  4027. }
  4028. return e;
  4029. }
  4030. void RSAKey::createKeyPair (RSAKey& publicKey,
  4031. RSAKey& privateKey,
  4032. const int numBits,
  4033. const int* randomSeeds,
  4034. const int numRandomSeeds) throw()
  4035. {
  4036. jassert (numBits > 16); // not much point using less than this..
  4037. BitArray p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4038. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4039. BitArray n (p);
  4040. n.multiplyBy (q); // n = pq
  4041. const BitArray one (1);
  4042. p.subtract (one);
  4043. q.subtract (one);
  4044. BitArray m (p);
  4045. m.multiplyBy (q); // m = (p - 1)(q - 1)
  4046. const BitArray e (findBestCommonDivisor (p, q));
  4047. BitArray d (e);
  4048. d.inverseModulo (m);
  4049. publicKey.part1 = e;
  4050. publicKey.part2 = n;
  4051. privateKey.part1 = d;
  4052. privateKey.part2 = n;
  4053. }
  4054. END_JUCE_NAMESPACE
  4055. /********* End of inlined file: juce_RSAKey.cpp *********/
  4056. /********* Start of inlined file: juce_InputStream.cpp *********/
  4057. BEGIN_JUCE_NAMESPACE
  4058. char InputStream::readByte()
  4059. {
  4060. char temp = 0;
  4061. read (&temp, 1);
  4062. return temp;
  4063. }
  4064. bool InputStream::readBool()
  4065. {
  4066. return readByte() != 0;
  4067. }
  4068. short InputStream::readShort()
  4069. {
  4070. char temp [2];
  4071. if (read (temp, 2) == 2)
  4072. return (short) littleEndianShort (temp);
  4073. else
  4074. return 0;
  4075. }
  4076. short InputStream::readShortBigEndian()
  4077. {
  4078. char temp [2];
  4079. if (read (temp, 2) == 2)
  4080. return (short) bigEndianShort (temp);
  4081. else
  4082. return 0;
  4083. }
  4084. int InputStream::readInt()
  4085. {
  4086. char temp [4];
  4087. if (read (temp, 4) == 4)
  4088. return (int) littleEndianInt (temp);
  4089. else
  4090. return 0;
  4091. }
  4092. int InputStream::readIntBigEndian()
  4093. {
  4094. char temp [4];
  4095. if (read (temp, 4) == 4)
  4096. return (int) bigEndianInt (temp);
  4097. else
  4098. return 0;
  4099. }
  4100. int InputStream::readCompressedInt()
  4101. {
  4102. int num = 0;
  4103. if (! isExhausted())
  4104. {
  4105. unsigned char numBytes = readByte();
  4106. const bool negative = (numBytes & 0x80) != 0;
  4107. numBytes &= 0x7f;
  4108. if (numBytes <= 4)
  4109. {
  4110. if (read (&num, numBytes) != numBytes)
  4111. return 0;
  4112. if (negative)
  4113. num = -num;
  4114. }
  4115. }
  4116. return num;
  4117. }
  4118. int64 InputStream::readInt64()
  4119. {
  4120. char temp [8];
  4121. if (read (temp, 8) == 8)
  4122. return (int64) swapIfBigEndian (*(uint64*)temp);
  4123. else
  4124. return 0;
  4125. }
  4126. int64 InputStream::readInt64BigEndian()
  4127. {
  4128. char temp [8];
  4129. if (read (temp, 8) == 8)
  4130. return (int64) swapIfLittleEndian (*(uint64*)temp);
  4131. else
  4132. return 0;
  4133. }
  4134. float InputStream::readFloat()
  4135. {
  4136. union { int asInt; float asFloat; } n;
  4137. n.asInt = readInt();
  4138. return n.asFloat;
  4139. }
  4140. float InputStream::readFloatBigEndian()
  4141. {
  4142. union { int asInt; float asFloat; } n;
  4143. n.asInt = readIntBigEndian();
  4144. return n.asFloat;
  4145. }
  4146. double InputStream::readDouble()
  4147. {
  4148. union { int64 asInt; double asDouble; } n;
  4149. n.asInt = readInt64();
  4150. return n.asDouble;
  4151. }
  4152. double InputStream::readDoubleBigEndian()
  4153. {
  4154. union { int64 asInt; double asDouble; } n;
  4155. n.asInt = readInt64BigEndian();
  4156. return n.asDouble;
  4157. }
  4158. const String InputStream::readString()
  4159. {
  4160. const int tempBufferSize = 256;
  4161. uint8 temp [tempBufferSize];
  4162. int i = 0;
  4163. while ((temp [i++] = readByte()) != 0)
  4164. {
  4165. if (i == tempBufferSize)
  4166. {
  4167. // too big for our quick buffer, so read it in blocks..
  4168. String result (String::fromUTF8 (temp, i));
  4169. i = 0;
  4170. for (;;)
  4171. {
  4172. if ((temp [i++] = readByte()) == 0)
  4173. {
  4174. result += String::fromUTF8 (temp, i - 1);
  4175. break;
  4176. }
  4177. else if (i == tempBufferSize)
  4178. {
  4179. result += String::fromUTF8 (temp, i);
  4180. i = 0;
  4181. }
  4182. }
  4183. return result;
  4184. }
  4185. }
  4186. return String::fromUTF8 (temp, i - 1);
  4187. }
  4188. const String InputStream::readNextLine()
  4189. {
  4190. String s;
  4191. const int maxChars = 256;
  4192. tchar buffer [maxChars];
  4193. int charsInBuffer = 0;
  4194. while (! isExhausted())
  4195. {
  4196. const uint8 c = readByte();
  4197. const int64 lastPos = getPosition();
  4198. if (c == '\n')
  4199. {
  4200. break;
  4201. }
  4202. else if (c == '\r')
  4203. {
  4204. if (readByte() != '\n')
  4205. setPosition (lastPos);
  4206. break;
  4207. }
  4208. buffer [charsInBuffer++] = c;
  4209. if (charsInBuffer == maxChars)
  4210. {
  4211. s.append (buffer, maxChars);
  4212. charsInBuffer = 0;
  4213. }
  4214. }
  4215. if (charsInBuffer > 0)
  4216. s.append (buffer, charsInBuffer);
  4217. return s;
  4218. }
  4219. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  4220. int numBytes)
  4221. {
  4222. const int64 totalLength = getTotalLength();
  4223. if (totalLength >= 0)
  4224. {
  4225. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4226. totalLength - getPosition());
  4227. if (numBytes < 0)
  4228. numBytes = totalBytesRemaining;
  4229. else if (numBytes > 0)
  4230. numBytes = jmin (numBytes, totalBytesRemaining);
  4231. else
  4232. return 0;
  4233. }
  4234. const int originalBlockSize = block.getSize();
  4235. int totalBytesRead = 0;
  4236. if (numBytes > 0)
  4237. {
  4238. // know how many bytes we want, so we can resize the block first..
  4239. block.setSize (originalBlockSize + numBytes, false);
  4240. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  4241. }
  4242. else
  4243. {
  4244. // read until end of stram..
  4245. const int chunkSize = 32768;
  4246. for (;;)
  4247. {
  4248. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4249. const int bytesJustIn = read (((char*) block.getData())
  4250. + originalBlockSize
  4251. + totalBytesRead,
  4252. chunkSize);
  4253. if (bytesJustIn == 0)
  4254. break;
  4255. totalBytesRead += bytesJustIn;
  4256. }
  4257. }
  4258. // trim off any excess left at the end
  4259. block.setSize (originalBlockSize + totalBytesRead, false);
  4260. return totalBytesRead;
  4261. }
  4262. const String InputStream::readEntireStreamAsString()
  4263. {
  4264. MemoryBlock mb;
  4265. const int size = readIntoMemoryBlock (mb);
  4266. return String::createStringFromData ((const char*) mb.getData(), size);
  4267. }
  4268. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4269. {
  4270. if (numBytesToSkip > 0)
  4271. {
  4272. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4273. MemoryBlock temp (skipBufferSize);
  4274. while ((numBytesToSkip > 0) && ! isExhausted())
  4275. {
  4276. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4277. }
  4278. }
  4279. }
  4280. END_JUCE_NAMESPACE
  4281. /********* End of inlined file: juce_InputStream.cpp *********/
  4282. /********* Start of inlined file: juce_OutputStream.cpp *********/
  4283. BEGIN_JUCE_NAMESPACE
  4284. #if JUCE_DEBUG
  4285. static CriticalSection activeStreamLock;
  4286. static VoidArray activeStreams;
  4287. void juce_CheckForDanglingStreams()
  4288. {
  4289. /*
  4290. It's always a bad idea to leak any object, but if you're leaking output
  4291. streams, then there's a good chance that you're failing to flush a file
  4292. to disk properly, which could result in corrupted data and other similar
  4293. nastiness..
  4294. */
  4295. jassert (activeStreams.size() == 0);
  4296. };
  4297. #endif
  4298. OutputStream::OutputStream() throw()
  4299. {
  4300. #if JUCE_DEBUG
  4301. activeStreamLock.enter();
  4302. activeStreams.add (this);
  4303. activeStreamLock.exit();
  4304. #endif
  4305. }
  4306. OutputStream::~OutputStream()
  4307. {
  4308. #if JUCE_DEBUG
  4309. activeStreamLock.enter();
  4310. activeStreams.removeValue (this);
  4311. activeStreamLock.exit();
  4312. #endif
  4313. }
  4314. void OutputStream::writeBool (bool b)
  4315. {
  4316. writeByte ((b) ? (char) 1
  4317. : (char) 0);
  4318. }
  4319. void OutputStream::writeByte (char byte)
  4320. {
  4321. write (&byte, 1);
  4322. }
  4323. void OutputStream::writeShort (short value)
  4324. {
  4325. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  4326. write (&v, 2);
  4327. }
  4328. void OutputStream::writeShortBigEndian (short value)
  4329. {
  4330. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  4331. write (&v, 2);
  4332. }
  4333. void OutputStream::writeInt (int value)
  4334. {
  4335. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  4336. write (&v, 4);
  4337. }
  4338. void OutputStream::writeIntBigEndian (int value)
  4339. {
  4340. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  4341. write (&v, 4);
  4342. }
  4343. void OutputStream::writeCompressedInt (int value)
  4344. {
  4345. unsigned int un = (value < 0) ? (unsigned int) -value
  4346. : (unsigned int) value;
  4347. unsigned int tn = un;
  4348. int numSigBytes = 0;
  4349. do
  4350. {
  4351. tn >>= 8;
  4352. numSigBytes++;
  4353. } while (tn & 0xff);
  4354. if (value < 0)
  4355. numSigBytes |= 0x80;
  4356. writeByte ((char) numSigBytes);
  4357. write (&un, numSigBytes);
  4358. }
  4359. void OutputStream::writeInt64 (int64 value)
  4360. {
  4361. const uint64 v = swapIfBigEndian ((uint64) value);
  4362. write (&v, 8);
  4363. }
  4364. void OutputStream::writeInt64BigEndian (int64 value)
  4365. {
  4366. const uint64 v = swapIfLittleEndian ((uint64) value);
  4367. write (&v, 8);
  4368. }
  4369. void OutputStream::writeFloat (float value)
  4370. {
  4371. union { int asInt; float asFloat; } n;
  4372. n.asFloat = value;
  4373. writeInt (n.asInt);
  4374. }
  4375. void OutputStream::writeFloatBigEndian (float value)
  4376. {
  4377. union { int asInt; float asFloat; } n;
  4378. n.asFloat = value;
  4379. writeIntBigEndian (n.asInt);
  4380. }
  4381. void OutputStream::writeDouble (double value)
  4382. {
  4383. union { int64 asInt; double asDouble; } n;
  4384. n.asDouble = value;
  4385. writeInt64 (n.asInt);
  4386. }
  4387. void OutputStream::writeDoubleBigEndian (double value)
  4388. {
  4389. union { int64 asInt; double asDouble; } n;
  4390. n.asDouble = value;
  4391. writeInt64BigEndian (n.asInt);
  4392. }
  4393. void OutputStream::writeString (const String& text)
  4394. {
  4395. const int numBytes = text.copyToUTF8 (0);
  4396. uint8* const temp = (uint8*) juce_malloc (numBytes);
  4397. text.copyToUTF8 (temp);
  4398. write (temp, numBytes); // (numBytes includes the terminating null).
  4399. juce_free (temp);
  4400. }
  4401. void OutputStream::printf (const char* pf, ...)
  4402. {
  4403. unsigned int bufSize = 256;
  4404. char* buf = (char*) juce_malloc (bufSize);
  4405. for (;;)
  4406. {
  4407. va_list list;
  4408. va_start (list, pf);
  4409. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  4410. va_end (list);
  4411. if (num > 0)
  4412. {
  4413. write (buf, num);
  4414. break;
  4415. }
  4416. else if (num == 0)
  4417. {
  4418. break;
  4419. }
  4420. juce_free (buf);
  4421. bufSize += 256;
  4422. buf = (char*) juce_malloc (bufSize);
  4423. }
  4424. juce_free (buf);
  4425. }
  4426. OutputStream& OutputStream::operator<< (const int number)
  4427. {
  4428. const String s (number);
  4429. write ((const char*) s, s.length());
  4430. return *this;
  4431. }
  4432. OutputStream& OutputStream::operator<< (const double number)
  4433. {
  4434. const String s (number);
  4435. write ((const char*) s, s.length());
  4436. return *this;
  4437. }
  4438. OutputStream& OutputStream::operator<< (const char character)
  4439. {
  4440. writeByte (character);
  4441. return *this;
  4442. }
  4443. OutputStream& OutputStream::operator<< (const char* const text)
  4444. {
  4445. write (text, (int) strlen (text));
  4446. return *this;
  4447. }
  4448. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  4449. {
  4450. const String s (text);
  4451. write ((const char*) s, s.length());
  4452. return *this;
  4453. }
  4454. OutputStream& OutputStream::operator<< (const String& text)
  4455. {
  4456. write ((const char*) text,
  4457. text.length());
  4458. return *this;
  4459. }
  4460. void OutputStream::writeText (const String& text,
  4461. const bool asUnicode,
  4462. const bool writeUnicodeHeaderBytes)
  4463. {
  4464. if (asUnicode)
  4465. {
  4466. if (writeUnicodeHeaderBytes)
  4467. write ("\x0ff\x0fe", 2);
  4468. const juce_wchar* src = (const juce_wchar*) text;
  4469. bool lastCharWasReturn = false;
  4470. while (*src != 0)
  4471. {
  4472. if (*src == L'\n' && ! lastCharWasReturn)
  4473. writeShort ((short) L'\r');
  4474. lastCharWasReturn = (*src == L'\r');
  4475. writeShort ((short) *src++);
  4476. }
  4477. }
  4478. else
  4479. {
  4480. const char* src = (const char*) text;
  4481. const char* t = src;
  4482. for (;;)
  4483. {
  4484. if (*t == '\n')
  4485. {
  4486. if (t > src)
  4487. write (src, (int) (t - src));
  4488. write ("\r\n", 2);
  4489. src = t + 1;
  4490. }
  4491. else if (*t == '\r')
  4492. {
  4493. if (t[1] == '\n')
  4494. ++t;
  4495. }
  4496. else if (*t == 0)
  4497. {
  4498. if (t > src)
  4499. write (src, (int) (t - src));
  4500. break;
  4501. }
  4502. ++t;
  4503. }
  4504. }
  4505. }
  4506. int OutputStream::writeFromInputStream (InputStream& source,
  4507. int numBytesToWrite)
  4508. {
  4509. if (numBytesToWrite < 0)
  4510. numBytesToWrite = 0x7fffffff;
  4511. int numWritten = 0;
  4512. while (numBytesToWrite > 0 && ! source.isExhausted())
  4513. {
  4514. char buffer [8192];
  4515. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  4516. if (num == 0)
  4517. break;
  4518. write (buffer, num);
  4519. numBytesToWrite -= num;
  4520. numWritten += num;
  4521. }
  4522. return numWritten;
  4523. }
  4524. END_JUCE_NAMESPACE
  4525. /********* End of inlined file: juce_OutputStream.cpp *********/
  4526. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  4527. BEGIN_JUCE_NAMESPACE
  4528. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4529. bool* isDirectory, bool* isHidden, int64* fileSize,
  4530. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4531. bool juce_findFileNext (void* handle, String& resultFile,
  4532. bool* isDirectory, bool* isHidden, int64* fileSize,
  4533. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4534. void juce_findFileClose (void* handle) throw();
  4535. DirectoryIterator::DirectoryIterator (const File& directory,
  4536. bool isRecursive,
  4537. const String& wc,
  4538. const int whatToLookFor_) throw()
  4539. : wildCard (wc),
  4540. index (-1),
  4541. whatToLookFor (whatToLookFor_),
  4542. subIterator (0)
  4543. {
  4544. // you have to specify the type of files you're looking for!
  4545. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4546. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4547. String path (directory.getFullPathName());
  4548. if (! path.endsWithChar (File::separator))
  4549. path += File::separator;
  4550. String filename;
  4551. bool isDirectory, isHidden;
  4552. void* const handle = juce_findFileStart (path,
  4553. isRecursive ? T("*") : wc,
  4554. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  4555. if (handle != 0)
  4556. {
  4557. do
  4558. {
  4559. if (! filename.containsOnly (T(".")))
  4560. {
  4561. bool addToList = false;
  4562. if (isDirectory)
  4563. {
  4564. if (isRecursive
  4565. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  4566. || ! isHidden))
  4567. {
  4568. dirsFound.add (new File (path + filename, 0));
  4569. }
  4570. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  4571. }
  4572. else
  4573. {
  4574. addToList = (whatToLookFor_ & File::findFiles) != 0;
  4575. }
  4576. // if it's recursive, we're not relying on the OS iterator
  4577. // to do the wildcard match, so do it now..
  4578. if (isRecursive && addToList)
  4579. addToList = filename.matchesWildcard (wc, true);
  4580. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  4581. addToList = ! isHidden;
  4582. if (addToList)
  4583. filesFound.add (new File (path + filename, 0));
  4584. }
  4585. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4586. juce_findFileClose (handle);
  4587. }
  4588. }
  4589. DirectoryIterator::~DirectoryIterator() throw()
  4590. {
  4591. if (subIterator != 0)
  4592. delete subIterator;
  4593. }
  4594. bool DirectoryIterator::next() throw()
  4595. {
  4596. if (subIterator != 0)
  4597. {
  4598. if (subIterator->next())
  4599. return true;
  4600. deleteAndZero (subIterator);
  4601. }
  4602. if (index >= filesFound.size() + dirsFound.size() - 1)
  4603. return false;
  4604. ++index;
  4605. if (index >= filesFound.size())
  4606. {
  4607. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  4608. true, wildCard, whatToLookFor);
  4609. return next();
  4610. }
  4611. return true;
  4612. }
  4613. const File DirectoryIterator::getFile() const throw()
  4614. {
  4615. if (subIterator != 0)
  4616. return subIterator->getFile();
  4617. const File* const f = filesFound [index];
  4618. return (f != 0) ? *f
  4619. : File::nonexistent;
  4620. }
  4621. float DirectoryIterator::getEstimatedProgress() const throw()
  4622. {
  4623. if (filesFound.size() + dirsFound.size() == 0)
  4624. {
  4625. return 0.0f;
  4626. }
  4627. else
  4628. {
  4629. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4630. : (float) index;
  4631. return detailedIndex / (filesFound.size() + dirsFound.size());
  4632. }
  4633. }
  4634. END_JUCE_NAMESPACE
  4635. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  4636. /********* Start of inlined file: juce_File.cpp *********/
  4637. #ifdef _MSC_VER
  4638. #pragma warning (disable: 4514)
  4639. #pragma warning (push)
  4640. #endif
  4641. #ifndef JUCE_WIN32
  4642. #include <pwd.h>
  4643. #endif
  4644. BEGIN_JUCE_NAMESPACE
  4645. #ifdef _MSC_VER
  4646. #pragma warning (pop)
  4647. #endif
  4648. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4649. void juce_fileClose (void* handle) throw();
  4650. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4651. int64 juce_fileGetPosition (void* handle) throw();
  4652. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4653. void juce_fileFlush (void* handle) throw();
  4654. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  4655. bool juce_isDirectory (const String& fileName) throw();
  4656. int64 juce_getFileSize (const String& fileName) throw();
  4657. bool juce_canWriteToFile (const String& fileName) throw();
  4658. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  4659. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  4660. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  4661. bool juce_deleteFile (const String& fileName) throw();
  4662. bool juce_copyFile (const String& source, const String& dest) throw();
  4663. bool juce_moveFile (const String& source, const String& dest) throw();
  4664. // this must also create all paths involved in the directory.
  4665. void juce_createDirectory (const String& fileName) throw();
  4666. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  4667. const StringArray juce_getFileSystemRoots() throw();
  4668. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  4669. // starts a directory search operation with a wildcard, returning a handle for
  4670. // use in calls to juce_findFileNext.
  4671. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  4672. // the other pointers, if non-null, are set based on the properties of the file.
  4673. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4674. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  4675. Time* creationTime, bool* isReadOnly) throw();
  4676. // returns false when no more files are found
  4677. bool juce_findFileNext (void* handle, String& resultFile,
  4678. bool* isDirectory, bool* isHidden, int64* fileSize,
  4679. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4680. void juce_findFileClose (void* handle) throw();
  4681. static const String juce_addTrailingSeparator (const String& path) throw()
  4682. {
  4683. return path.endsWithChar (File::separator) ? path
  4684. : path + File::separator;
  4685. }
  4686. static const String parseAbsolutePath (String path) throw()
  4687. {
  4688. if (path.isEmpty())
  4689. return String::empty;
  4690. #if JUCE_WIN32
  4691. // Windows..
  4692. path = path.replaceCharacter (T('/'), T('\\'));
  4693. if (path.startsWithChar (File::separator))
  4694. {
  4695. if (path[1] != File::separator)
  4696. {
  4697. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  4698. // Windows, because it needs a drive letter, which in this case
  4699. // we'll take from the CWD.. but this is a bit of an assumption that
  4700. // could be wrong..
  4701. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4702. }
  4703. }
  4704. else if (path.indexOfChar (T(':')) < 0)
  4705. {
  4706. if (path.isEmpty())
  4707. return String::empty;
  4708. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4709. // we don't know what directory to put it in.
  4710. // Here we'll assume it's in the CWD, but this might not be what was
  4711. // intended..
  4712. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4713. }
  4714. #else
  4715. // Mac or Linux..
  4716. path = path.replaceCharacter (T('\\'), T('/'));
  4717. if (path.startsWithChar (T('~')))
  4718. {
  4719. const char* homeDir = 0;
  4720. if (path[1] == File::separator || path[1] == 0)
  4721. {
  4722. // expand a name of the form "~/abc"
  4723. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4724. + path.substring (1);
  4725. }
  4726. else
  4727. {
  4728. // expand a name of type "~dave/abc"
  4729. const String userName (path.substring (1)
  4730. .upToFirstOccurrenceOf (T("/"), false, false));
  4731. struct passwd* const pw = getpwnam (userName);
  4732. if (pw != 0)
  4733. {
  4734. String home (homeDir);
  4735. if (home.endsWithChar (File::separator))
  4736. home [home.length() - 1] = 0;
  4737. path = String (pw->pw_dir)
  4738. + path.substring (userName.length());
  4739. }
  4740. }
  4741. }
  4742. else if (! path.startsWithChar (File::separator))
  4743. {
  4744. while (path.startsWith (T("./")))
  4745. path = path.substring (2);
  4746. if (path.isEmpty())
  4747. return String::empty;
  4748. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4749. // we don't know what directory to put it in.
  4750. // Here we'll assume it's in the CWD, but this might not be what was
  4751. // intended..
  4752. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4753. }
  4754. #endif
  4755. int len = path.length();
  4756. while (--len > 0 && path [len] == File::separator)
  4757. path [len] = 0;
  4758. return path;
  4759. }
  4760. const File File::nonexistent;
  4761. File::File (const String& fullPathName) throw()
  4762. : fullPath (parseAbsolutePath (fullPathName))
  4763. {
  4764. }
  4765. File::File (const String& path, int) throw()
  4766. : fullPath (path)
  4767. {
  4768. }
  4769. File::File (const File& other) throw()
  4770. : fullPath (other.fullPath)
  4771. {
  4772. }
  4773. const File& File::operator= (const String& newPath) throw()
  4774. {
  4775. fullPath = parseAbsolutePath (newPath);
  4776. return *this;
  4777. }
  4778. const File& File::operator= (const File& other) throw()
  4779. {
  4780. fullPath = other.fullPath;
  4781. return *this;
  4782. }
  4783. #if JUCE_LINUX
  4784. #define NAMES_ARE_CASE_SENSITIVE 1
  4785. #endif
  4786. bool File::areFileNamesCaseSensitive()
  4787. {
  4788. #if NAMES_ARE_CASE_SENSITIVE
  4789. return true;
  4790. #else
  4791. return false;
  4792. #endif
  4793. }
  4794. bool File::operator== (const File& other) const throw()
  4795. {
  4796. // case-insensitive on Windows, but not on linux.
  4797. #if NAMES_ARE_CASE_SENSITIVE
  4798. return fullPath == other.fullPath;
  4799. #else
  4800. return fullPath.equalsIgnoreCase (other.fullPath);
  4801. #endif
  4802. }
  4803. bool File::operator!= (const File& other) const throw()
  4804. {
  4805. return ! operator== (other);
  4806. }
  4807. bool File::exists() const throw()
  4808. {
  4809. return juce_fileExists (fullPath, false);
  4810. }
  4811. bool File::existsAsFile() const throw()
  4812. {
  4813. return juce_fileExists (fullPath, true);
  4814. }
  4815. bool File::isDirectory() const throw()
  4816. {
  4817. return juce_isDirectory (fullPath);
  4818. }
  4819. bool File::hasWriteAccess() const throw()
  4820. {
  4821. if (exists())
  4822. return juce_canWriteToFile (fullPath);
  4823. #ifndef JUCE_WIN32
  4824. else if ((! isDirectory()) && fullPath.containsChar (separator))
  4825. return getParentDirectory().hasWriteAccess();
  4826. else
  4827. return false;
  4828. #else
  4829. // on windows, it seems that even read-only directories can still be written into,
  4830. // so checking the parent directory's permissions would return the wrong result..
  4831. else
  4832. return true;
  4833. #endif
  4834. }
  4835. bool File::setReadOnly (const bool shouldBeReadOnly,
  4836. const bool applyRecursively) const throw()
  4837. {
  4838. bool worked = true;
  4839. if (applyRecursively && isDirectory())
  4840. {
  4841. OwnedArray <File> subFiles;
  4842. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4843. for (int i = subFiles.size(); --i >= 0;)
  4844. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  4845. }
  4846. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  4847. }
  4848. bool File::deleteFile() const throw()
  4849. {
  4850. return (! exists())
  4851. || juce_deleteFile (fullPath);
  4852. }
  4853. bool File::deleteRecursively() const throw()
  4854. {
  4855. bool worked = true;
  4856. if (isDirectory())
  4857. {
  4858. OwnedArray<File> subFiles;
  4859. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4860. for (int i = subFiles.size(); --i >= 0;)
  4861. worked = subFiles[i]->deleteRecursively() && worked;
  4862. }
  4863. return deleteFile() && worked;
  4864. }
  4865. bool File::moveFileTo (const File& newFile) const throw()
  4866. {
  4867. if (newFile.fullPath == fullPath)
  4868. return true;
  4869. #if ! NAMES_ARE_CASE_SENSITIVE
  4870. if (*this != newFile)
  4871. #endif
  4872. if (! newFile.deleteFile())
  4873. return false;
  4874. return juce_moveFile (fullPath, newFile.fullPath);
  4875. }
  4876. bool File::copyFileTo (const File& newFile) const throw()
  4877. {
  4878. if (*this == newFile)
  4879. return true;
  4880. if (! newFile.deleteFile())
  4881. return false;
  4882. return juce_copyFile (fullPath, newFile.fullPath);
  4883. }
  4884. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  4885. {
  4886. if (isDirectory() && newDirectory.createDirectory())
  4887. {
  4888. OwnedArray<File> subFiles;
  4889. findChildFiles (subFiles, File::findFiles, false);
  4890. int i;
  4891. for (i = 0; i < subFiles.size(); ++i)
  4892. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  4893. return false;
  4894. subFiles.clear();
  4895. findChildFiles (subFiles, File::findDirectories, false);
  4896. for (i = 0; i < subFiles.size(); ++i)
  4897. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  4898. return false;
  4899. return true;
  4900. }
  4901. return false;
  4902. }
  4903. const String File::getPathUpToLastSlash() const throw()
  4904. {
  4905. const int lastSlash = fullPath.lastIndexOfChar (separator);
  4906. if (lastSlash > 0)
  4907. return fullPath.substring (0, lastSlash);
  4908. else if (lastSlash == 0)
  4909. return separatorString;
  4910. else
  4911. return fullPath;
  4912. }
  4913. const File File::getParentDirectory() const throw()
  4914. {
  4915. return File (getPathUpToLastSlash());
  4916. }
  4917. const String File::getFileName() const throw()
  4918. {
  4919. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  4920. }
  4921. int File::hashCode() const throw()
  4922. {
  4923. return fullPath.hashCode();
  4924. }
  4925. int64 File::hashCode64() const throw()
  4926. {
  4927. return fullPath.hashCode64();
  4928. }
  4929. const String File::getFileNameWithoutExtension() const throw()
  4930. {
  4931. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  4932. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  4933. if (lastDot > lastSlash)
  4934. return fullPath.substring (lastSlash, lastDot);
  4935. else
  4936. return fullPath.substring (lastSlash);
  4937. }
  4938. bool File::isAChildOf (const File& potentialParent) const throw()
  4939. {
  4940. const String ourPath (getPathUpToLastSlash());
  4941. #if NAMES_ARE_CASE_SENSITIVE
  4942. if (potentialParent.fullPath == ourPath)
  4943. #else
  4944. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  4945. #endif
  4946. {
  4947. return true;
  4948. }
  4949. else if (potentialParent.fullPath.length() >= ourPath.length())
  4950. {
  4951. return false;
  4952. }
  4953. else
  4954. {
  4955. return getParentDirectory().isAChildOf (potentialParent);
  4956. }
  4957. }
  4958. bool File::isAbsolutePath (const String& path) throw()
  4959. {
  4960. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  4961. #if JUCE_WIN32
  4962. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  4963. #else
  4964. || path.startsWithChar (T('~'));
  4965. #endif
  4966. }
  4967. const File File::getChildFile (String relativePath) const throw()
  4968. {
  4969. if (isAbsolutePath (relativePath))
  4970. {
  4971. // the path is really absolute..
  4972. return File (relativePath);
  4973. }
  4974. else
  4975. {
  4976. // it's relative, so remove any ../ or ./ bits at the start.
  4977. String path (fullPath);
  4978. if (relativePath[0] == T('.'))
  4979. {
  4980. #if JUCE_WIN32
  4981. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  4982. #else
  4983. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  4984. #endif
  4985. while (relativePath[0] == T('.'))
  4986. {
  4987. if (relativePath[1] == T('.'))
  4988. {
  4989. if (relativePath [2] == 0 || relativePath[2] == separator)
  4990. {
  4991. const int lastSlash = path.lastIndexOfChar (separator);
  4992. if (lastSlash >= 0)
  4993. path = path.substring (0, lastSlash);
  4994. relativePath = relativePath.substring (3);
  4995. }
  4996. else
  4997. {
  4998. break;
  4999. }
  5000. }
  5001. else if (relativePath[1] == separator)
  5002. {
  5003. relativePath = relativePath.substring (2);
  5004. }
  5005. else
  5006. {
  5007. break;
  5008. }
  5009. }
  5010. }
  5011. return File (juce_addTrailingSeparator (path) + relativePath);
  5012. }
  5013. }
  5014. const File File::getSiblingFile (const String& fileName) const throw()
  5015. {
  5016. return getParentDirectory().getChildFile (fileName);
  5017. }
  5018. int64 File::getSize() const throw()
  5019. {
  5020. return juce_getFileSize (fullPath);
  5021. }
  5022. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5023. {
  5024. if (bytes == 1)
  5025. {
  5026. return "1 byte";
  5027. }
  5028. else if (bytes < 1024)
  5029. {
  5030. return String ((int) bytes) + " bytes";
  5031. }
  5032. else if (bytes < 1024 * 1024)
  5033. {
  5034. return String (bytes / 1024.0, 1) + " KB";
  5035. }
  5036. else if (bytes < 1024 * 1024 * 1024)
  5037. {
  5038. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5039. }
  5040. else
  5041. {
  5042. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5043. }
  5044. }
  5045. bool File::create() const throw()
  5046. {
  5047. if (! exists())
  5048. {
  5049. const File parentDir (getParentDirectory());
  5050. if (parentDir == *this || ! parentDir.createDirectory())
  5051. return false;
  5052. void* const fh = juce_fileOpen (fullPath, true);
  5053. if (fh == 0)
  5054. return false;
  5055. juce_fileClose (fh);
  5056. }
  5057. return true;
  5058. }
  5059. bool File::createDirectory() const throw()
  5060. {
  5061. if (! isDirectory())
  5062. {
  5063. const File parentDir (getParentDirectory());
  5064. if (parentDir == *this || ! parentDir.createDirectory())
  5065. return false;
  5066. String dir (fullPath);
  5067. while (dir.endsWithChar (separator))
  5068. dir [dir.length() - 1] = 0;
  5069. juce_createDirectory (dir);
  5070. return isDirectory();
  5071. }
  5072. return true;
  5073. }
  5074. const Time File::getCreationTime() const throw()
  5075. {
  5076. int64 m, a, c;
  5077. juce_getFileTimes (fullPath, m, a, c);
  5078. return Time (c);
  5079. }
  5080. bool File::setCreationTime (const Time& t) const throw()
  5081. {
  5082. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  5083. }
  5084. const Time File::getLastModificationTime() const throw()
  5085. {
  5086. int64 m, a, c;
  5087. juce_getFileTimes (fullPath, m, a, c);
  5088. return Time (m);
  5089. }
  5090. bool File::setLastModificationTime (const Time& t) const throw()
  5091. {
  5092. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  5093. }
  5094. const Time File::getLastAccessTime() const throw()
  5095. {
  5096. int64 m, a, c;
  5097. juce_getFileTimes (fullPath, m, a, c);
  5098. return Time (a);
  5099. }
  5100. bool File::setLastAccessTime (const Time& t) const throw()
  5101. {
  5102. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  5103. }
  5104. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  5105. {
  5106. if (! existsAsFile())
  5107. return false;
  5108. FileInputStream in (*this);
  5109. return getSize() == in.readIntoMemoryBlock (destBlock);
  5110. }
  5111. const String File::loadFileAsString() const throw()
  5112. {
  5113. if (! existsAsFile())
  5114. return String::empty;
  5115. FileInputStream in (*this);
  5116. return in.readEntireStreamAsString();
  5117. }
  5118. static inline bool fileTypeMatches (const int whatToLookFor,
  5119. const bool isDir,
  5120. const bool isHidden)
  5121. {
  5122. return (whatToLookFor & (isDir ? File::findDirectories
  5123. : File::findFiles)) != 0
  5124. && ((! isHidden)
  5125. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5126. }
  5127. int File::findChildFiles (OwnedArray<File>& results,
  5128. const int whatToLookFor,
  5129. const bool searchRecursively,
  5130. const String& wildCardPattern) const throw()
  5131. {
  5132. // you have to specify the type of files you're looking for!
  5133. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5134. int total = 0;
  5135. // find child files or directories in this directory first..
  5136. if (isDirectory())
  5137. {
  5138. const String path (juce_addTrailingSeparator (fullPath));
  5139. String filename;
  5140. bool isDirectory, isHidden;
  5141. void* const handle = juce_findFileStart (path,
  5142. wildCardPattern,
  5143. filename,
  5144. &isDirectory, &isHidden,
  5145. 0, 0, 0, 0);
  5146. if (handle != 0)
  5147. {
  5148. do
  5149. {
  5150. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5151. && ! filename.containsOnly (T(".")))
  5152. {
  5153. results.add (new File (path + filename, 0));
  5154. ++total;
  5155. }
  5156. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5157. juce_findFileClose (handle);
  5158. }
  5159. }
  5160. else
  5161. {
  5162. // trying to search for files inside a non-directory?
  5163. //jassertfalse
  5164. }
  5165. // and recurse down if required.
  5166. if (searchRecursively)
  5167. {
  5168. OwnedArray <File> subDirectories;
  5169. findChildFiles (subDirectories, File::findDirectories, false);
  5170. for (int i = 0; i < subDirectories.size(); ++i)
  5171. {
  5172. total += subDirectories.getUnchecked(i)
  5173. ->findChildFiles (results,
  5174. whatToLookFor,
  5175. true,
  5176. wildCardPattern);
  5177. }
  5178. }
  5179. return total;
  5180. }
  5181. int File::getNumberOfChildFiles (const int whatToLookFor,
  5182. const String& wildCardPattern) const throw()
  5183. {
  5184. // you have to specify the type of files you're looking for!
  5185. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5186. int count = 0;
  5187. if (isDirectory())
  5188. {
  5189. String filename;
  5190. bool isDirectory, isHidden;
  5191. void* const handle = juce_findFileStart (fullPath,
  5192. wildCardPattern,
  5193. filename,
  5194. &isDirectory, &isHidden,
  5195. 0, 0, 0, 0);
  5196. if (handle != 0)
  5197. {
  5198. do
  5199. {
  5200. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5201. && ! filename.containsOnly (T(".")))
  5202. {
  5203. ++count;
  5204. }
  5205. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5206. juce_findFileClose (handle);
  5207. }
  5208. }
  5209. else
  5210. {
  5211. // trying to search for files inside a non-directory?
  5212. jassertfalse
  5213. }
  5214. return count;
  5215. }
  5216. bool File::containsSubDirectories() const throw()
  5217. {
  5218. bool result = false;
  5219. if (isDirectory())
  5220. {
  5221. String filename;
  5222. bool isDirectory, isHidden;
  5223. void* const handle = juce_findFileStart (juce_addTrailingSeparator (fullPath),
  5224. T("*"), filename,
  5225. &isDirectory, &isHidden, 0, 0, 0, 0);
  5226. if (handle != 0)
  5227. {
  5228. do
  5229. {
  5230. if (isDirectory)
  5231. {
  5232. result = true;
  5233. break;
  5234. }
  5235. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5236. juce_findFileClose (handle);
  5237. }
  5238. }
  5239. return result;
  5240. }
  5241. const File File::getNonexistentChildFile (const String& prefix_,
  5242. const String& suffix,
  5243. bool putNumbersInBrackets) const throw()
  5244. {
  5245. File f (getChildFile (prefix_ + suffix));
  5246. if (f.exists())
  5247. {
  5248. int num = 2;
  5249. String prefix (prefix_);
  5250. // remove any bracketed numbers that may already be on the end..
  5251. if (prefix.trim().endsWithChar (T(')')))
  5252. {
  5253. putNumbersInBrackets = true;
  5254. const int openBracks = prefix.lastIndexOfChar (T('('));
  5255. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  5256. if (openBracks > 0
  5257. && closeBracks > openBracks
  5258. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  5259. {
  5260. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5261. prefix = prefix.substring (0, openBracks);
  5262. }
  5263. }
  5264. // also use brackets if it ends in a digit.
  5265. putNumbersInBrackets = putNumbersInBrackets
  5266. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5267. do
  5268. {
  5269. if (putNumbersInBrackets)
  5270. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  5271. else
  5272. f = getChildFile (prefix + String (num++) + suffix);
  5273. } while (f.exists());
  5274. }
  5275. return f;
  5276. }
  5277. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  5278. {
  5279. if (exists())
  5280. {
  5281. return getParentDirectory()
  5282. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5283. getFileExtension(),
  5284. putNumbersInBrackets);
  5285. }
  5286. else
  5287. {
  5288. return *this;
  5289. }
  5290. }
  5291. const String File::getFileExtension() const throw()
  5292. {
  5293. String ext;
  5294. if (! isDirectory())
  5295. {
  5296. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  5297. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5298. ext = fullPath.substring (indexOfDot);
  5299. }
  5300. return ext;
  5301. }
  5302. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  5303. {
  5304. if (possibleSuffix.isEmpty())
  5305. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  5306. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5307. {
  5308. if (possibleSuffix.startsWithChar (T('.')))
  5309. return true;
  5310. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5311. if (dotPos >= 0)
  5312. return fullPath [dotPos] == T('.');
  5313. }
  5314. return false;
  5315. }
  5316. const File File::withFileExtension (const String& newExtension) const throw()
  5317. {
  5318. if (fullPath.isEmpty())
  5319. return File::nonexistent;
  5320. String filePart (getFileName());
  5321. int i = filePart.lastIndexOfChar (T('.'));
  5322. if (i < 0)
  5323. i = filePart.length();
  5324. String newExt (newExtension);
  5325. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  5326. newExt = T(".") + newExt;
  5327. return getSiblingFile (filePart.substring (0, i) + newExt);
  5328. }
  5329. bool File::startAsProcess (const String& parameters) const throw()
  5330. {
  5331. return exists()
  5332. && juce_launchFile (fullPath, parameters);
  5333. }
  5334. FileInputStream* File::createInputStream() const throw()
  5335. {
  5336. if (existsAsFile())
  5337. return new FileInputStream (*this);
  5338. else
  5339. return 0;
  5340. }
  5341. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  5342. {
  5343. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  5344. if (out->failedToOpen())
  5345. {
  5346. delete out;
  5347. return 0;
  5348. }
  5349. else
  5350. {
  5351. return out;
  5352. }
  5353. }
  5354. bool File::appendData (const void* const dataToAppend,
  5355. const int numberOfBytes) const throw()
  5356. {
  5357. if (numberOfBytes > 0)
  5358. {
  5359. FileOutputStream* const out = createOutputStream();
  5360. if (out == 0)
  5361. return false;
  5362. out->write (dataToAppend, numberOfBytes);
  5363. delete out;
  5364. }
  5365. return true;
  5366. }
  5367. bool File::replaceWithData (const void* const dataToWrite,
  5368. const int numberOfBytes) const throw()
  5369. {
  5370. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5371. if (numberOfBytes <= 0)
  5372. return deleteFile();
  5373. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5374. if (tempFile.appendData (dataToWrite, numberOfBytes)
  5375. && tempFile.moveFileTo (*this))
  5376. {
  5377. return true;
  5378. }
  5379. tempFile.deleteFile();
  5380. return false;
  5381. }
  5382. bool File::appendText (const String& text,
  5383. const bool asUnicode,
  5384. const bool writeUnicodeHeaderBytes) const throw()
  5385. {
  5386. FileOutputStream* const out = createOutputStream();
  5387. if (out != 0)
  5388. {
  5389. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5390. delete out;
  5391. return true;
  5392. }
  5393. return false;
  5394. }
  5395. bool File::printf (const tchar* pf, ...) const throw()
  5396. {
  5397. va_list list;
  5398. va_start (list, pf);
  5399. String text;
  5400. text.vprintf (pf, list);
  5401. return appendData ((const char*) text, text.length());
  5402. }
  5403. bool File::replaceWithText (const String& textToWrite,
  5404. const bool asUnicode,
  5405. const bool writeUnicodeHeaderBytes) const throw()
  5406. {
  5407. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5408. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  5409. && tempFile.moveFileTo (*this))
  5410. {
  5411. return true;
  5412. }
  5413. tempFile.deleteFile();
  5414. return false;
  5415. }
  5416. const String File::createLegalPathName (const String& original) throw()
  5417. {
  5418. String s (original);
  5419. String start;
  5420. if (s[1] == T(':'))
  5421. {
  5422. start = s.substring (0, 2);
  5423. s = s.substring (2);
  5424. }
  5425. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  5426. .substring (0, 1024);
  5427. }
  5428. const String File::createLegalFileName (const String& original) throw()
  5429. {
  5430. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  5431. const int maxLength = 128; // only the length of the filename, not the whole path
  5432. const int len = s.length();
  5433. if (len > maxLength)
  5434. {
  5435. const int lastDot = s.lastIndexOfChar (T('.'));
  5436. if (lastDot > jmax (0, len - 12))
  5437. {
  5438. s = s.substring (0, maxLength - (len - lastDot))
  5439. + s.substring (lastDot);
  5440. }
  5441. else
  5442. {
  5443. s = s.substring (0, maxLength);
  5444. }
  5445. }
  5446. return s;
  5447. }
  5448. const String File::getRelativePathFrom (const File& dir) const throw()
  5449. {
  5450. String thisPath (fullPath);
  5451. {
  5452. int len = thisPath.length();
  5453. while (--len >= 0 && thisPath [len] == File::separator)
  5454. thisPath [len] = 0;
  5455. }
  5456. String dirPath (juce_addTrailingSeparator ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  5457. : dir.fullPath));
  5458. const int len = jmin (thisPath.length(), dirPath.length());
  5459. int commonBitLength = 0;
  5460. for (int i = 0; i < len; ++i)
  5461. {
  5462. #if NAMES_ARE_CASE_SENSITIVE
  5463. if (thisPath[i] != dirPath[i])
  5464. #else
  5465. if (CharacterFunctions::toLowerCase (thisPath[i])
  5466. != CharacterFunctions::toLowerCase (dirPath[i]))
  5467. #endif
  5468. {
  5469. break;
  5470. }
  5471. ++commonBitLength;
  5472. }
  5473. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5474. --commonBitLength;
  5475. // if the only common bit is the root, then just return the full path..
  5476. if (commonBitLength <= 0
  5477. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5478. return fullPath;
  5479. thisPath = thisPath.substring (commonBitLength);
  5480. dirPath = dirPath.substring (commonBitLength);
  5481. while (dirPath.isNotEmpty())
  5482. {
  5483. #if JUCE_WIN32
  5484. thisPath = T("..\\") + thisPath;
  5485. #else
  5486. thisPath = T("../") + thisPath;
  5487. #endif
  5488. const int sep = dirPath.indexOfChar (separator);
  5489. if (sep >= 0)
  5490. dirPath = dirPath.substring (sep + 1);
  5491. else
  5492. dirPath = String::empty;
  5493. }
  5494. return thisPath;
  5495. }
  5496. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  5497. {
  5498. const StringArray roots (juce_getFileSystemRoots());
  5499. for (int i = 0; i < roots.size(); ++i)
  5500. destArray.add (new File (roots[i]));
  5501. }
  5502. const String File::getVolumeLabel() const throw()
  5503. {
  5504. int serialNum;
  5505. return juce_getVolumeLabel (fullPath, serialNum);
  5506. }
  5507. int File::getVolumeSerialNumber() const throw()
  5508. {
  5509. int serialNum;
  5510. juce_getVolumeLabel (fullPath, serialNum);
  5511. return serialNum;
  5512. }
  5513. const File File::createTempFile (const String& fileNameEnding) throw()
  5514. {
  5515. String tempName (T("temp"));
  5516. static int tempNum = 0;
  5517. tempName << tempNum++ << fileNameEnding;
  5518. const File tempFile (getSpecialLocation (tempDirectory)
  5519. .getChildFile (tempName));
  5520. if (tempFile.exists())
  5521. return createTempFile (fileNameEnding);
  5522. else
  5523. return tempFile;
  5524. }
  5525. END_JUCE_NAMESPACE
  5526. /********* End of inlined file: juce_File.cpp *********/
  5527. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  5528. BEGIN_JUCE_NAMESPACE
  5529. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5530. void juce_fileClose (void* handle) throw();
  5531. int juce_fileRead (void* handle, void* buffer, int size) throw();
  5532. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5533. FileInputStream::FileInputStream (const File& f)
  5534. : file (f),
  5535. currentPosition (0),
  5536. needToSeek (true)
  5537. {
  5538. totalSize = f.getSize();
  5539. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  5540. }
  5541. FileInputStream::~FileInputStream()
  5542. {
  5543. juce_fileClose (fileHandle);
  5544. }
  5545. int64 FileInputStream::getTotalLength()
  5546. {
  5547. return totalSize;
  5548. }
  5549. int FileInputStream::read (void* buffer, int bytesToRead)
  5550. {
  5551. int num = 0;
  5552. if (needToSeek)
  5553. {
  5554. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5555. return 0;
  5556. needToSeek = false;
  5557. }
  5558. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5559. currentPosition += num;
  5560. return num;
  5561. }
  5562. bool FileInputStream::isExhausted()
  5563. {
  5564. return currentPosition >= totalSize;
  5565. }
  5566. int64 FileInputStream::getPosition()
  5567. {
  5568. return currentPosition;
  5569. }
  5570. bool FileInputStream::setPosition (int64 pos)
  5571. {
  5572. pos = jlimit ((int64) 0, totalSize, pos);
  5573. needToSeek |= (currentPosition != pos);
  5574. currentPosition = pos;
  5575. return true;
  5576. }
  5577. END_JUCE_NAMESPACE
  5578. /********* End of inlined file: juce_FileInputStream.cpp *********/
  5579. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  5580. BEGIN_JUCE_NAMESPACE
  5581. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5582. void juce_fileClose (void* handle) throw();
  5583. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  5584. void juce_fileFlush (void* handle) throw();
  5585. int64 juce_fileGetPosition (void* handle) throw();
  5586. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5587. FileOutputStream::FileOutputStream (const File& f,
  5588. const int bufferSize_)
  5589. : file (f),
  5590. bufferSize (bufferSize_),
  5591. bytesInBuffer (0)
  5592. {
  5593. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  5594. if (fileHandle != 0)
  5595. {
  5596. currentPosition = juce_fileGetPosition (fileHandle);
  5597. if (currentPosition < 0)
  5598. {
  5599. jassertfalse
  5600. juce_fileClose (fileHandle);
  5601. fileHandle = 0;
  5602. }
  5603. }
  5604. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  5605. }
  5606. FileOutputStream::~FileOutputStream()
  5607. {
  5608. flush();
  5609. juce_fileClose (fileHandle);
  5610. juce_free (buffer);
  5611. }
  5612. int64 FileOutputStream::getPosition()
  5613. {
  5614. return currentPosition;
  5615. }
  5616. bool FileOutputStream::setPosition (int64 newPosition)
  5617. {
  5618. if (newPosition != currentPosition)
  5619. {
  5620. flush();
  5621. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5622. }
  5623. return newPosition == currentPosition;
  5624. }
  5625. void FileOutputStream::flush()
  5626. {
  5627. if (bytesInBuffer > 0)
  5628. {
  5629. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5630. bytesInBuffer = 0;
  5631. }
  5632. juce_fileFlush (fileHandle);
  5633. }
  5634. bool FileOutputStream::write (const void* const src, const int numBytes)
  5635. {
  5636. if (bytesInBuffer + numBytes < bufferSize)
  5637. {
  5638. memcpy (buffer + bytesInBuffer, src, numBytes);
  5639. bytesInBuffer += numBytes;
  5640. currentPosition += numBytes;
  5641. }
  5642. else
  5643. {
  5644. if (bytesInBuffer > 0)
  5645. {
  5646. // flush the reservoir
  5647. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5648. bytesInBuffer = 0;
  5649. if (! wroteOk)
  5650. return false;
  5651. }
  5652. if (numBytes < bufferSize)
  5653. {
  5654. memcpy (buffer + bytesInBuffer, src, numBytes);
  5655. bytesInBuffer += numBytes;
  5656. currentPosition += numBytes;
  5657. }
  5658. else
  5659. {
  5660. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5661. currentPosition += bytesWritten;
  5662. return bytesWritten == numBytes;
  5663. }
  5664. }
  5665. return true;
  5666. }
  5667. END_JUCE_NAMESPACE
  5668. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  5669. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  5670. BEGIN_JUCE_NAMESPACE
  5671. FileSearchPath::FileSearchPath()
  5672. {
  5673. }
  5674. FileSearchPath::FileSearchPath (const String& path)
  5675. {
  5676. init (path);
  5677. }
  5678. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5679. : directories (other.directories)
  5680. {
  5681. }
  5682. FileSearchPath::~FileSearchPath()
  5683. {
  5684. }
  5685. const FileSearchPath& FileSearchPath::operator= (const String& path)
  5686. {
  5687. init (path);
  5688. return *this;
  5689. }
  5690. void FileSearchPath::init (const String& path)
  5691. {
  5692. directories.clear();
  5693. directories.addTokens (path, T(";"), T("\""));
  5694. directories.trim();
  5695. directories.removeEmptyStrings();
  5696. for (int i = directories.size(); --i >= 0;)
  5697. directories.set (i, directories[i].unquoted());
  5698. }
  5699. int FileSearchPath::getNumPaths() const
  5700. {
  5701. return directories.size();
  5702. }
  5703. const File FileSearchPath::operator[] (const int index) const
  5704. {
  5705. return File (directories [index]);
  5706. }
  5707. const String FileSearchPath::toString() const
  5708. {
  5709. StringArray directories2 (directories);
  5710. for (int i = directories2.size(); --i >= 0;)
  5711. if (directories2[i].containsChar (T(';')))
  5712. directories2.set (i, directories2[i].quoted());
  5713. return directories2.joinIntoString (T(";"));
  5714. }
  5715. void FileSearchPath::add (const File& dir, const int insertIndex)
  5716. {
  5717. directories.insert (insertIndex, dir.getFullPathName());
  5718. }
  5719. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5720. {
  5721. for (int i = 0; i < directories.size(); ++i)
  5722. if (File (directories[i]) == dir)
  5723. return;
  5724. add (dir);
  5725. }
  5726. void FileSearchPath::remove (const int index)
  5727. {
  5728. directories.remove (index);
  5729. }
  5730. void FileSearchPath::addPath (const FileSearchPath& other)
  5731. {
  5732. for (int i = 0; i < other.getNumPaths(); ++i)
  5733. addIfNotAlreadyThere (other[i]);
  5734. }
  5735. void FileSearchPath::removeRedundantPaths()
  5736. {
  5737. for (int i = directories.size(); --i >= 0;)
  5738. {
  5739. const File d1 (directories[i]);
  5740. for (int j = directories.size(); --j >= 0;)
  5741. {
  5742. const File d2 (directories[j]);
  5743. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5744. {
  5745. directories.remove (i);
  5746. break;
  5747. }
  5748. }
  5749. }
  5750. }
  5751. void FileSearchPath::removeNonExistentPaths()
  5752. {
  5753. for (int i = directories.size(); --i >= 0;)
  5754. if (! File (directories[i]).isDirectory())
  5755. directories.remove (i);
  5756. }
  5757. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  5758. const int whatToLookFor,
  5759. const bool searchRecursively,
  5760. const String& wildCardPattern) const
  5761. {
  5762. int total = 0;
  5763. for (int i = 0; i < directories.size(); ++i)
  5764. total += operator[] (i).findChildFiles (results,
  5765. whatToLookFor,
  5766. searchRecursively,
  5767. wildCardPattern);
  5768. return total;
  5769. }
  5770. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5771. const bool checkRecursively) const
  5772. {
  5773. for (int i = directories.size(); --i >= 0;)
  5774. {
  5775. const File d (directories[i]);
  5776. if (checkRecursively)
  5777. {
  5778. if (fileToCheck.isAChildOf (d))
  5779. return true;
  5780. }
  5781. else
  5782. {
  5783. if (fileToCheck.getParentDirectory() == d)
  5784. return true;
  5785. }
  5786. }
  5787. return false;
  5788. }
  5789. END_JUCE_NAMESPACE
  5790. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  5791. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  5792. BEGIN_JUCE_NAMESPACE
  5793. NamedPipe::NamedPipe()
  5794. : internal (0)
  5795. {
  5796. }
  5797. NamedPipe::~NamedPipe()
  5798. {
  5799. close();
  5800. }
  5801. bool NamedPipe::openExisting (const String& pipeName)
  5802. {
  5803. currentPipeName = pipeName;
  5804. return openInternal (pipeName, false);
  5805. }
  5806. bool NamedPipe::createNewPipe (const String& pipeName)
  5807. {
  5808. currentPipeName = pipeName;
  5809. return openInternal (pipeName, true);
  5810. }
  5811. bool NamedPipe::isOpen() const throw()
  5812. {
  5813. return internal != 0;
  5814. }
  5815. const String NamedPipe::getName() const throw()
  5816. {
  5817. return currentPipeName;
  5818. }
  5819. // other methods for this class are implemented in the platform-specific files
  5820. END_JUCE_NAMESPACE
  5821. /********* End of inlined file: juce_NamedPipe.cpp *********/
  5822. /********* Start of inlined file: juce_Socket.cpp *********/
  5823. #ifdef _WIN32
  5824. #include <winsock2.h>
  5825. #ifdef _MSC_VER
  5826. #pragma warning (disable : 4127 4389 4018)
  5827. #endif
  5828. #else
  5829. #if defined (LINUX) || defined (__linux__)
  5830. #include <sys/types.h>
  5831. #include <sys/socket.h>
  5832. #include <sys/errno.h>
  5833. #include <unistd.h>
  5834. #include <netinet/in.h>
  5835. #else
  5836. #if MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4
  5837. #include <CoreServices/CoreServices.h>
  5838. #endif
  5839. #endif
  5840. #include <fcntl.h>
  5841. #include <netdb.h>
  5842. #include <arpa/inet.h>
  5843. #include <netinet/tcp.h>
  5844. #endif
  5845. BEGIN_JUCE_NAMESPACE
  5846. #if JUCE_WIN32
  5847. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5848. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5849. static void initWin32Sockets()
  5850. {
  5851. static CriticalSection lock;
  5852. const ScopedLock sl (lock);
  5853. if (juce_CloseWin32SocketLib == 0)
  5854. {
  5855. WSADATA wsaData;
  5856. const WORD wVersionRequested = MAKEWORD (1, 1);
  5857. WSAStartup (wVersionRequested, &wsaData);
  5858. juce_CloseWin32SocketLib = &WSACleanup;
  5859. }
  5860. }
  5861. #endif
  5862. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5863. {
  5864. const int sndBufSize = 65536;
  5865. const int rcvBufSize = 65536;
  5866. const int one = 1;
  5867. return handle > 0
  5868. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5869. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5870. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5871. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5872. }
  5873. static bool bindSocketToPort (const int handle, const int port) throw()
  5874. {
  5875. if (handle <= 0 || port <= 0)
  5876. return false;
  5877. struct sockaddr_in servTmpAddr;
  5878. zerostruct (servTmpAddr);
  5879. servTmpAddr.sin_family = PF_INET;
  5880. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5881. servTmpAddr.sin_port = htons ((uint16) port);
  5882. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5883. }
  5884. static int readSocket (const int handle,
  5885. void* const destBuffer, const int maxBytesToRead,
  5886. bool volatile& connected,
  5887. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5888. {
  5889. int bytesRead = 0;
  5890. while (bytesRead < maxBytesToRead)
  5891. {
  5892. int bytesThisTime;
  5893. #if JUCE_WIN32
  5894. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5895. #else
  5896. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5897. && errno == EINTR
  5898. && connected)
  5899. {
  5900. }
  5901. #endif
  5902. if (bytesThisTime <= 0 || ! connected)
  5903. {
  5904. if (bytesRead == 0)
  5905. bytesRead = -1;
  5906. break;
  5907. }
  5908. bytesRead += bytesThisTime;
  5909. if (! blockUntilSpecifiedAmountHasArrived)
  5910. break;
  5911. }
  5912. return bytesRead;
  5913. }
  5914. static int waitForReadiness (const int handle, const bool forReading,
  5915. const int timeoutMsecs) throw()
  5916. {
  5917. struct timeval timeout;
  5918. struct timeval* timeoutp;
  5919. if (timeoutMsecs >= 0)
  5920. {
  5921. timeout.tv_sec = timeoutMsecs / 1000;
  5922. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  5923. timeoutp = &timeout;
  5924. }
  5925. else
  5926. {
  5927. timeoutp = 0;
  5928. }
  5929. fd_set rset, wset;
  5930. FD_ZERO (&rset);
  5931. FD_SET (handle, &rset);
  5932. FD_ZERO (&wset);
  5933. FD_SET (handle, &wset);
  5934. fd_set* const prset = forReading ? &rset : 0;
  5935. fd_set* const pwset = forReading ? 0 : &wset;
  5936. #if JUCE_WIN32
  5937. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  5938. return -1;
  5939. #else
  5940. {
  5941. int result;
  5942. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  5943. && errno == EINTR)
  5944. {
  5945. }
  5946. if (result < 0)
  5947. return -1;
  5948. }
  5949. #endif
  5950. {
  5951. int opt;
  5952. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  5953. socklen_t len = sizeof (opt);
  5954. #else
  5955. int len = sizeof (opt);
  5956. #endif
  5957. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  5958. || opt != 0)
  5959. return -1;
  5960. }
  5961. if ((forReading && FD_ISSET (handle, &rset))
  5962. || ((! forReading) && FD_ISSET (handle, &wset)))
  5963. return 1;
  5964. return 0;
  5965. }
  5966. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  5967. {
  5968. #if JUCE_WIN32
  5969. u_long nonBlocking = shouldBlock ? 0 : 1;
  5970. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  5971. return false;
  5972. #else
  5973. int socketFlags = fcntl (handle, F_GETFL, 0);
  5974. if (socketFlags == -1)
  5975. return false;
  5976. if (shouldBlock)
  5977. socketFlags &= ~O_NONBLOCK;
  5978. else
  5979. socketFlags |= O_NONBLOCK;
  5980. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  5981. return false;
  5982. #endif
  5983. return true;
  5984. }
  5985. static bool connectSocket (int volatile& handle,
  5986. const bool isDatagram,
  5987. void** serverAddress,
  5988. const String& hostName,
  5989. const int portNumber,
  5990. const int timeOutMillisecs) throw()
  5991. {
  5992. struct hostent* const hostEnt = gethostbyname (hostName);
  5993. if (hostEnt == 0)
  5994. return false;
  5995. struct in_addr targetAddress;
  5996. memcpy (&targetAddress.s_addr,
  5997. *(hostEnt->h_addr_list),
  5998. sizeof (targetAddress.s_addr));
  5999. struct sockaddr_in servTmpAddr;
  6000. zerostruct (servTmpAddr);
  6001. servTmpAddr.sin_family = PF_INET;
  6002. servTmpAddr.sin_addr = targetAddress;
  6003. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6004. if (handle < 0)
  6005. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6006. if (handle < 0)
  6007. return false;
  6008. if (isDatagram)
  6009. {
  6010. *serverAddress = new struct sockaddr_in();
  6011. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6012. return true;
  6013. }
  6014. setSocketBlockingState (handle, false);
  6015. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6016. if (result < 0)
  6017. {
  6018. #if JUCE_WIN32
  6019. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6020. #else
  6021. if (errno == EINPROGRESS)
  6022. #endif
  6023. {
  6024. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6025. {
  6026. setSocketBlockingState (handle, true);
  6027. return false;
  6028. }
  6029. }
  6030. }
  6031. setSocketBlockingState (handle, true);
  6032. resetSocketOptions (handle, false, false);
  6033. return true;
  6034. }
  6035. StreamingSocket::StreamingSocket()
  6036. : portNumber (0),
  6037. handle (-1),
  6038. connected (false),
  6039. isListener (false)
  6040. {
  6041. #if JUCE_WIN32
  6042. initWin32Sockets();
  6043. #endif
  6044. }
  6045. StreamingSocket::StreamingSocket (const String& hostName_,
  6046. const int portNumber_,
  6047. const int handle_)
  6048. : hostName (hostName_),
  6049. portNumber (portNumber_),
  6050. handle (handle_),
  6051. connected (true),
  6052. isListener (false)
  6053. {
  6054. #if JUCE_WIN32
  6055. initWin32Sockets();
  6056. #endif
  6057. resetSocketOptions (handle_, false, false);
  6058. }
  6059. StreamingSocket::~StreamingSocket()
  6060. {
  6061. close();
  6062. }
  6063. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6064. {
  6065. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6066. : -1;
  6067. }
  6068. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6069. {
  6070. if (isListener || ! connected)
  6071. return -1;
  6072. #if JUCE_WIN32
  6073. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6074. #else
  6075. int result;
  6076. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6077. && errno == EINTR)
  6078. {
  6079. }
  6080. return result;
  6081. #endif
  6082. }
  6083. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6084. const int timeoutMsecs) const
  6085. {
  6086. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6087. : -1;
  6088. }
  6089. bool StreamingSocket::bindToPort (const int port)
  6090. {
  6091. return bindSocketToPort (handle, port);
  6092. }
  6093. bool StreamingSocket::connect (const String& remoteHostName,
  6094. const int remotePortNumber,
  6095. const int timeOutMillisecs)
  6096. {
  6097. if (isListener)
  6098. {
  6099. jassertfalse // a listener socket can't connect to another one!
  6100. return false;
  6101. }
  6102. if (connected)
  6103. close();
  6104. hostName = remoteHostName;
  6105. portNumber = remotePortNumber;
  6106. isListener = false;
  6107. connected = connectSocket (handle, false, 0, remoteHostName,
  6108. remotePortNumber, timeOutMillisecs);
  6109. if (! (connected && resetSocketOptions (handle, false, false)))
  6110. {
  6111. close();
  6112. return false;
  6113. }
  6114. return true;
  6115. }
  6116. void StreamingSocket::close()
  6117. {
  6118. #if JUCE_WIN32
  6119. closesocket (handle);
  6120. connected = false;
  6121. #else
  6122. if (connected)
  6123. {
  6124. connected = false;
  6125. if (isListener)
  6126. {
  6127. // need to do this to interrupt the accept() function..
  6128. StreamingSocket temp;
  6129. temp.connect ("localhost", portNumber, 1000);
  6130. }
  6131. }
  6132. ::close (handle);
  6133. #endif
  6134. hostName = String::empty;
  6135. portNumber = 0;
  6136. handle = -1;
  6137. isListener = false;
  6138. }
  6139. bool StreamingSocket::createListener (const int newPortNumber)
  6140. {
  6141. if (connected)
  6142. close();
  6143. hostName = "listener";
  6144. portNumber = newPortNumber;
  6145. isListener = true;
  6146. struct sockaddr_in servTmpAddr;
  6147. zerostruct (servTmpAddr);
  6148. servTmpAddr.sin_family = PF_INET;
  6149. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6150. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6151. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6152. if (handle < 0)
  6153. return false;
  6154. const int reuse = 1;
  6155. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6156. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6157. || listen (handle, SOMAXCONN) < 0)
  6158. {
  6159. close();
  6160. return false;
  6161. }
  6162. connected = true;
  6163. return true;
  6164. }
  6165. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6166. {
  6167. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6168. // prepare this socket as a listener.
  6169. if (connected && isListener)
  6170. {
  6171. struct sockaddr address;
  6172. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  6173. socklen_t len = sizeof (sockaddr);
  6174. #else
  6175. int len = sizeof (sockaddr);
  6176. #endif
  6177. const int newSocket = (int) accept (handle, &address, &len);
  6178. if (newSocket >= 0 && connected)
  6179. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6180. portNumber, newSocket);
  6181. }
  6182. return 0;
  6183. }
  6184. bool StreamingSocket::isLocal() const throw()
  6185. {
  6186. return hostName == T("127.0.0.1");
  6187. }
  6188. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6189. : portNumber (0),
  6190. handle (-1),
  6191. connected (true),
  6192. allowBroadcast (allowBroadcast_),
  6193. serverAddress (0)
  6194. {
  6195. #if JUCE_WIN32
  6196. initWin32Sockets();
  6197. #endif
  6198. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6199. bindToPort (localPortNumber);
  6200. }
  6201. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6202. const int handle_, const int localPortNumber)
  6203. : hostName (hostName_),
  6204. portNumber (portNumber_),
  6205. handle (handle_),
  6206. connected (true),
  6207. allowBroadcast (false),
  6208. serverAddress (0)
  6209. {
  6210. #if JUCE_WIN32
  6211. initWin32Sockets();
  6212. #endif
  6213. resetSocketOptions (handle_, true, allowBroadcast);
  6214. bindToPort (localPortNumber);
  6215. }
  6216. DatagramSocket::~DatagramSocket()
  6217. {
  6218. close();
  6219. delete ((struct sockaddr_in*) serverAddress);
  6220. serverAddress = 0;
  6221. }
  6222. void DatagramSocket::close()
  6223. {
  6224. #if JUCE_WIN32
  6225. closesocket (handle);
  6226. connected = false;
  6227. #else
  6228. connected = false;
  6229. ::close (handle);
  6230. #endif
  6231. hostName = String::empty;
  6232. portNumber = 0;
  6233. handle = -1;
  6234. }
  6235. bool DatagramSocket::bindToPort (const int port)
  6236. {
  6237. return bindSocketToPort (handle, port);
  6238. }
  6239. bool DatagramSocket::connect (const String& remoteHostName,
  6240. const int remotePortNumber,
  6241. const int timeOutMillisecs)
  6242. {
  6243. if (connected)
  6244. close();
  6245. hostName = remoteHostName;
  6246. portNumber = remotePortNumber;
  6247. connected = connectSocket (handle, true, &serverAddress,
  6248. remoteHostName, remotePortNumber,
  6249. timeOutMillisecs);
  6250. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6251. {
  6252. close();
  6253. return false;
  6254. }
  6255. return true;
  6256. }
  6257. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6258. {
  6259. struct sockaddr address;
  6260. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  6261. socklen_t len = sizeof (sockaddr);
  6262. #else
  6263. int len = sizeof (sockaddr);
  6264. #endif
  6265. while (waitUntilReady (true, -1) == 1)
  6266. {
  6267. char buf[1];
  6268. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6269. {
  6270. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6271. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6272. -1, -1);
  6273. }
  6274. }
  6275. return 0;
  6276. }
  6277. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6278. const int timeoutMsecs) const
  6279. {
  6280. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6281. : -1;
  6282. }
  6283. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6284. {
  6285. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6286. : -1;
  6287. }
  6288. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6289. {
  6290. // You need to call connect() first to set the server address..
  6291. jassert (serverAddress != 0 && connected);
  6292. return connected ? sendto (handle, (const char*) sourceBuffer,
  6293. numBytesToWrite, 0,
  6294. (const struct sockaddr*) serverAddress,
  6295. sizeof (struct sockaddr_in))
  6296. : -1;
  6297. }
  6298. bool DatagramSocket::isLocal() const throw()
  6299. {
  6300. return hostName == T("127.0.0.1");
  6301. }
  6302. END_JUCE_NAMESPACE
  6303. /********* End of inlined file: juce_Socket.cpp *********/
  6304. /********* Start of inlined file: juce_URL.cpp *********/
  6305. BEGIN_JUCE_NAMESPACE
  6306. URL::URL() throw()
  6307. {
  6308. }
  6309. URL::URL (const String& url_)
  6310. : url (url_)
  6311. {
  6312. int i = url.indexOfChar (T('?'));
  6313. if (i >= 0)
  6314. {
  6315. do
  6316. {
  6317. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  6318. const int equalsPos = url.indexOfChar (i + 1, T('='));
  6319. if (equalsPos > i + 1)
  6320. {
  6321. if (nextAmp < 0)
  6322. {
  6323. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6324. removeEscapeChars (url.substring (equalsPos + 1)));
  6325. }
  6326. else if (nextAmp > 0 && equalsPos < nextAmp)
  6327. {
  6328. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6329. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6330. }
  6331. }
  6332. i = nextAmp;
  6333. }
  6334. while (i >= 0);
  6335. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  6336. }
  6337. }
  6338. URL::URL (const URL& other)
  6339. : url (other.url),
  6340. postData (other.postData),
  6341. parameters (other.parameters),
  6342. filesToUpload (other.filesToUpload),
  6343. mimeTypes (other.mimeTypes)
  6344. {
  6345. }
  6346. const URL& URL::operator= (const URL& other)
  6347. {
  6348. url = other.url;
  6349. postData = other.postData;
  6350. parameters = other.parameters;
  6351. filesToUpload = other.filesToUpload;
  6352. mimeTypes = other.mimeTypes;
  6353. return *this;
  6354. }
  6355. URL::~URL() throw()
  6356. {
  6357. }
  6358. static const String getMangledParameters (const StringPairArray& parameters)
  6359. {
  6360. String p;
  6361. for (int i = 0; i < parameters.size(); ++i)
  6362. {
  6363. if (i > 0)
  6364. p += T("&");
  6365. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6366. << T("=")
  6367. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6368. }
  6369. return p;
  6370. }
  6371. const String URL::toString (const bool includeGetParameters) const
  6372. {
  6373. if (includeGetParameters && parameters.size() > 0)
  6374. return url + T("?") + getMangledParameters (parameters);
  6375. else
  6376. return url;
  6377. }
  6378. bool URL::isWellFormed() const
  6379. {
  6380. //xxx TODO
  6381. return url.isNotEmpty();
  6382. }
  6383. static int findStartOfDomain (const String& url)
  6384. {
  6385. int i = 0;
  6386. while (CharacterFunctions::isLetterOrDigit (url[i])
  6387. || CharacterFunctions::indexOfChar (T("+-."), url[i], false) >= 0)
  6388. ++i;
  6389. return url[i] == T(':') ? i + 1 : 0;
  6390. }
  6391. const String URL::getDomain() const
  6392. {
  6393. int start = findStartOfDomain (url);
  6394. while (url[start] == T('/'))
  6395. ++start;
  6396. const int end1 = url.indexOfChar (start, T('/'));
  6397. const int end2 = url.indexOfChar (start, T(':'));
  6398. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6399. : jmin (end1, end2);
  6400. return url.substring (start, end);
  6401. }
  6402. const String URL::getSubPath() const
  6403. {
  6404. int start = findStartOfDomain (url);
  6405. while (url[start] == T('/'))
  6406. ++start;
  6407. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6408. return startOfPath <= 0 ? String::empty
  6409. : url.substring (startOfPath);
  6410. }
  6411. const String URL::getScheme() const
  6412. {
  6413. return url.substring (0, findStartOfDomain (url) - 1);
  6414. }
  6415. const URL URL::withNewSubPath (const String& newPath) const
  6416. {
  6417. int start = findStartOfDomain (url);
  6418. while (url[start] == T('/'))
  6419. ++start;
  6420. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6421. URL u (*this);
  6422. if (startOfPath > 0)
  6423. u.url = url.substring (0, startOfPath);
  6424. if (! u.url.endsWithChar (T('/')))
  6425. u.url << '/';
  6426. if (newPath.startsWithChar (T('/')))
  6427. u.url << newPath.substring (1);
  6428. else
  6429. u.url << newPath;
  6430. return u;
  6431. }
  6432. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6433. {
  6434. if (possibleURL.startsWithIgnoreCase (T("http:"))
  6435. || possibleURL.startsWithIgnoreCase (T("ftp:")))
  6436. return true;
  6437. if (possibleURL.startsWithIgnoreCase (T("file:"))
  6438. || possibleURL.containsChar (T('@'))
  6439. || possibleURL.endsWithChar (T('.'))
  6440. || (! possibleURL.containsChar (T('.'))))
  6441. return false;
  6442. if (possibleURL.startsWithIgnoreCase (T("www."))
  6443. && possibleURL.substring (5).containsChar (T('.')))
  6444. return true;
  6445. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6446. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6447. if ((possibleURL + T("/")).containsIgnoreCase (T(".") + String (commonTLDs[i]) + T("/")))
  6448. return true;
  6449. return false;
  6450. }
  6451. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6452. {
  6453. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  6454. return atSign > 0
  6455. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  6456. && (! possibleEmailAddress.endsWithChar (T('.')));
  6457. }
  6458. void* juce_openInternetFile (const String& url,
  6459. const String& headers,
  6460. const MemoryBlock& optionalPostData,
  6461. const bool isPost,
  6462. URL::OpenStreamProgressCallback* callback,
  6463. void* callbackContext,
  6464. int timeOutMs);
  6465. void juce_closeInternetFile (void* handle);
  6466. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6467. int juce_seekInInternetFile (void* handle, int newPosition);
  6468. int64 juce_getInternetFileContentLength (void* handle);
  6469. class WebInputStream : public InputStream
  6470. {
  6471. public:
  6472. WebInputStream (const URL& url,
  6473. const bool isPost_,
  6474. URL::OpenStreamProgressCallback* const progressCallback_,
  6475. void* const progressCallbackContext_,
  6476. const String& extraHeaders,
  6477. int timeOutMs_)
  6478. : position (0),
  6479. finished (false),
  6480. isPost (isPost_),
  6481. progressCallback (progressCallback_),
  6482. progressCallbackContext (progressCallbackContext_),
  6483. timeOutMs (timeOutMs_)
  6484. {
  6485. server = url.toString (! isPost);
  6486. if (isPost_)
  6487. createHeadersAndPostData (url);
  6488. headers += extraHeaders;
  6489. if (! headers.endsWithChar (T('\n')))
  6490. headers << "\r\n";
  6491. handle = juce_openInternetFile (server, headers, postData, isPost,
  6492. progressCallback_, progressCallbackContext_,
  6493. timeOutMs);
  6494. }
  6495. ~WebInputStream()
  6496. {
  6497. juce_closeInternetFile (handle);
  6498. }
  6499. bool isError() const throw()
  6500. {
  6501. return handle == 0;
  6502. }
  6503. int64 getTotalLength()
  6504. {
  6505. return juce_getInternetFileContentLength (handle);
  6506. }
  6507. bool isExhausted()
  6508. {
  6509. return finished;
  6510. }
  6511. int read (void* dest, int bytes)
  6512. {
  6513. if (finished || isError())
  6514. {
  6515. return 0;
  6516. }
  6517. else
  6518. {
  6519. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6520. position += bytesRead;
  6521. if (bytesRead == 0)
  6522. finished = true;
  6523. return bytesRead;
  6524. }
  6525. }
  6526. int64 getPosition()
  6527. {
  6528. return position;
  6529. }
  6530. bool setPosition (int64 wantedPos)
  6531. {
  6532. if (wantedPos != position)
  6533. {
  6534. finished = false;
  6535. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6536. if (actualPos == wantedPos)
  6537. {
  6538. position = wantedPos;
  6539. }
  6540. else
  6541. {
  6542. if (wantedPos < position)
  6543. {
  6544. juce_closeInternetFile (handle);
  6545. position = 0;
  6546. finished = false;
  6547. handle = juce_openInternetFile (server, headers, postData, isPost,
  6548. progressCallback, progressCallbackContext,
  6549. timeOutMs);
  6550. }
  6551. skipNextBytes (wantedPos - position);
  6552. }
  6553. }
  6554. return true;
  6555. }
  6556. juce_UseDebuggingNewOperator
  6557. private:
  6558. String server, headers;
  6559. MemoryBlock postData;
  6560. int64 position;
  6561. bool finished;
  6562. const bool isPost;
  6563. void* handle;
  6564. URL::OpenStreamProgressCallback* const progressCallback;
  6565. void* const progressCallbackContext;
  6566. const int timeOutMs;
  6567. void createHeadersAndPostData (const URL& url)
  6568. {
  6569. if (url.getFilesToUpload().size() > 0)
  6570. {
  6571. // need to upload some files, so do it as multi-part...
  6572. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6573. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6574. appendUTF8ToPostData ("--" + boundary);
  6575. int i;
  6576. for (i = 0; i < url.getParameters().size(); ++i)
  6577. {
  6578. String s;
  6579. s << "\r\nContent-Disposition: form-data; name=\""
  6580. << url.getParameters().getAllKeys() [i]
  6581. << "\"\r\n\r\n"
  6582. << url.getParameters().getAllValues() [i]
  6583. << "\r\n--"
  6584. << boundary;
  6585. appendUTF8ToPostData (s);
  6586. }
  6587. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6588. {
  6589. const File f (url.getFilesToUpload().getAllValues() [i]);
  6590. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6591. String s;
  6592. s << "\r\nContent-Disposition: form-data; name=\""
  6593. << paramName
  6594. << "\"; filename=\""
  6595. << f.getFileName()
  6596. << "\"\r\n";
  6597. const String mimeType (url.getMimeTypesOfUploadFiles()
  6598. .getValue (paramName, String::empty));
  6599. if (mimeType.isNotEmpty())
  6600. s << "Content-Type: " << mimeType << "\r\n";
  6601. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  6602. appendUTF8ToPostData (s);
  6603. f.loadFileAsData (postData);
  6604. s = "\r\n--" + boundary;
  6605. appendUTF8ToPostData (s);
  6606. }
  6607. appendUTF8ToPostData ("--\r\n");
  6608. }
  6609. else
  6610. {
  6611. appendUTF8ToPostData (getMangledParameters (url.getParameters()));
  6612. appendUTF8ToPostData (url.getPostData());
  6613. // just a short text attachment, so use simple url encoding..
  6614. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6615. + String (postData.getSize())
  6616. + "\r\n";
  6617. }
  6618. }
  6619. void appendUTF8ToPostData (const String& text) throw()
  6620. {
  6621. postData.append (text.toUTF8(),
  6622. (int) strlen (text.toUTF8()));
  6623. }
  6624. WebInputStream (const WebInputStream&);
  6625. const WebInputStream& operator= (const WebInputStream&);
  6626. };
  6627. InputStream* URL::createInputStream (const bool usePostCommand,
  6628. OpenStreamProgressCallback* const progressCallback,
  6629. void* const progressCallbackContext,
  6630. const String& extraHeaders,
  6631. const int timeOutMs) const
  6632. {
  6633. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  6634. progressCallback, progressCallbackContext,
  6635. extraHeaders,
  6636. timeOutMs);
  6637. if (wi->isError())
  6638. {
  6639. delete wi;
  6640. wi = 0;
  6641. }
  6642. return wi;
  6643. }
  6644. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6645. const bool usePostCommand) const
  6646. {
  6647. InputStream* const in = createInputStream (usePostCommand);
  6648. if (in != 0)
  6649. {
  6650. in->readIntoMemoryBlock (destData, -1);
  6651. delete in;
  6652. return true;
  6653. }
  6654. return false;
  6655. }
  6656. const String URL::readEntireTextStream (const bool usePostCommand) const
  6657. {
  6658. String result;
  6659. InputStream* const in = createInputStream (usePostCommand);
  6660. if (in != 0)
  6661. {
  6662. result = in->readEntireStreamAsString();
  6663. delete in;
  6664. }
  6665. return result;
  6666. }
  6667. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6668. {
  6669. XmlDocument doc (readEntireTextStream (usePostCommand));
  6670. return doc.getDocumentElement();
  6671. }
  6672. const URL URL::withParameter (const String& parameterName,
  6673. const String& parameterValue) const
  6674. {
  6675. URL u (*this);
  6676. u.parameters.set (parameterName, parameterValue);
  6677. return u;
  6678. }
  6679. const URL URL::withFileToUpload (const String& parameterName,
  6680. const File& fileToUpload,
  6681. const String& mimeType) const
  6682. {
  6683. URL u (*this);
  6684. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6685. u.mimeTypes.set (parameterName, mimeType);
  6686. return u;
  6687. }
  6688. const URL URL::withPOSTData (const String& postData_) const
  6689. {
  6690. URL u (*this);
  6691. u.postData = postData_;
  6692. return u;
  6693. }
  6694. const StringPairArray& URL::getParameters() const throw()
  6695. {
  6696. return parameters;
  6697. }
  6698. const StringPairArray& URL::getFilesToUpload() const throw()
  6699. {
  6700. return filesToUpload;
  6701. }
  6702. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  6703. {
  6704. return mimeTypes;
  6705. }
  6706. const String URL::removeEscapeChars (const String& s)
  6707. {
  6708. const int len = s.length();
  6709. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  6710. uint8* r = resultUTF8;
  6711. for (int i = 0; i < len; ++i)
  6712. {
  6713. char c = (char) s[i];
  6714. if (c == 0)
  6715. break;
  6716. if (c == '+')
  6717. {
  6718. c = ' ';
  6719. }
  6720. else if (c == '%')
  6721. {
  6722. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  6723. i += 2;
  6724. }
  6725. *r++ = c;
  6726. }
  6727. const String stringResult (String::fromUTF8 (resultUTF8));
  6728. juce_free (resultUTF8);
  6729. return stringResult;
  6730. }
  6731. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6732. {
  6733. String result;
  6734. result.preallocateStorage (s.length() + 8);
  6735. const char* utf8 = s.toUTF8();
  6736. const char* legalChars = isParameter ? "_-.*!'()"
  6737. : "_-$.*!'(),";
  6738. while (*utf8 != 0)
  6739. {
  6740. const char c = *utf8++;
  6741. if (CharacterFunctions::isLetterOrDigit (c)
  6742. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6743. {
  6744. result << c;
  6745. }
  6746. else
  6747. {
  6748. const int v = (int) (uint8) c;
  6749. if (v < 0x10)
  6750. result << T("%0");
  6751. else
  6752. result << T('%');
  6753. result << String::toHexString (v);
  6754. }
  6755. }
  6756. return result;
  6757. }
  6758. extern bool juce_launchFile (const String& fileName,
  6759. const String& parameters) throw();
  6760. bool URL::launchInDefaultBrowser() const
  6761. {
  6762. String u (toString (true));
  6763. if (u.contains (T("@")) && ! u.contains (T(":")))
  6764. u = "mailto:" + u;
  6765. return juce_launchFile (u, String::empty);
  6766. }
  6767. END_JUCE_NAMESPACE
  6768. /********* End of inlined file: juce_URL.cpp *********/
  6769. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  6770. BEGIN_JUCE_NAMESPACE
  6771. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6772. const int bufferSize_,
  6773. const bool deleteSourceWhenDestroyed_) throw()
  6774. : source (source_),
  6775. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  6776. bufferSize (jmax (256, bufferSize_)),
  6777. position (source_->getPosition()),
  6778. lastReadPos (0),
  6779. bufferOverlap (128)
  6780. {
  6781. const int sourceSize = (int) source_->getTotalLength();
  6782. if (sourceSize >= 0)
  6783. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6784. bufferStart = position;
  6785. buffer = (char*) juce_malloc (bufferSize);
  6786. }
  6787. BufferedInputStream::~BufferedInputStream() throw()
  6788. {
  6789. if (deleteSourceWhenDestroyed)
  6790. delete source;
  6791. juce_free (buffer);
  6792. }
  6793. int64 BufferedInputStream::getTotalLength()
  6794. {
  6795. return source->getTotalLength();
  6796. }
  6797. int64 BufferedInputStream::getPosition()
  6798. {
  6799. return position;
  6800. }
  6801. bool BufferedInputStream::setPosition (int64 newPosition)
  6802. {
  6803. position = jmax ((int64) 0, newPosition);
  6804. return true;
  6805. }
  6806. bool BufferedInputStream::isExhausted()
  6807. {
  6808. return (position >= lastReadPos)
  6809. && source->isExhausted();
  6810. }
  6811. void BufferedInputStream::ensureBuffered()
  6812. {
  6813. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6814. if (position < bufferStart || position >= bufferEndOverlap)
  6815. {
  6816. int bytesRead;
  6817. if (position < lastReadPos
  6818. && position >= bufferEndOverlap
  6819. && position >= bufferStart)
  6820. {
  6821. const int bytesToKeep = (int) (lastReadPos - position);
  6822. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  6823. bufferStart = position;
  6824. bytesRead = source->read (buffer + bytesToKeep,
  6825. bufferSize - bytesToKeep);
  6826. lastReadPos += bytesRead;
  6827. bytesRead += bytesToKeep;
  6828. }
  6829. else
  6830. {
  6831. bufferStart = position;
  6832. source->setPosition (bufferStart);
  6833. bytesRead = source->read (buffer, bufferSize);
  6834. lastReadPos = bufferStart + bytesRead;
  6835. }
  6836. while (bytesRead < bufferSize)
  6837. buffer [bytesRead++] = 0;
  6838. }
  6839. }
  6840. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6841. {
  6842. if (position >= bufferStart
  6843. && position + maxBytesToRead <= lastReadPos)
  6844. {
  6845. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  6846. position += maxBytesToRead;
  6847. return maxBytesToRead;
  6848. }
  6849. else
  6850. {
  6851. if (position < bufferStart || position >= lastReadPos)
  6852. ensureBuffered();
  6853. int bytesRead = 0;
  6854. while (maxBytesToRead > 0)
  6855. {
  6856. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6857. if (bytesAvailable > 0)
  6858. {
  6859. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  6860. maxBytesToRead -= bytesAvailable;
  6861. bytesRead += bytesAvailable;
  6862. position += bytesAvailable;
  6863. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  6864. }
  6865. const int64 oldLastReadPos = lastReadPos;
  6866. ensureBuffered();
  6867. if (oldLastReadPos == lastReadPos)
  6868. break; // if ensureBuffered() failed to read any more data, bail out
  6869. if (isExhausted())
  6870. break;
  6871. }
  6872. return bytesRead;
  6873. }
  6874. }
  6875. const String BufferedInputStream::readString()
  6876. {
  6877. if (position >= bufferStart
  6878. && position < lastReadPos)
  6879. {
  6880. const int maxChars = (int) (lastReadPos - position);
  6881. const char* const src = buffer + (position - bufferStart);
  6882. for (int i = 0; i < maxChars; ++i)
  6883. {
  6884. if (src[i] == 0)
  6885. {
  6886. position += i + 1;
  6887. return String::fromUTF8 ((const uint8*) src, i);
  6888. }
  6889. }
  6890. }
  6891. return InputStream::readString();
  6892. }
  6893. END_JUCE_NAMESPACE
  6894. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  6895. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  6896. BEGIN_JUCE_NAMESPACE
  6897. FileInputSource::FileInputSource (const File& file_) throw()
  6898. : file (file_)
  6899. {
  6900. }
  6901. FileInputSource::~FileInputSource()
  6902. {
  6903. }
  6904. InputStream* FileInputSource::createInputStream()
  6905. {
  6906. return file.createInputStream();
  6907. }
  6908. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6909. {
  6910. return file.getSiblingFile (relatedItemPath).createInputStream();
  6911. }
  6912. int64 FileInputSource::hashCode() const
  6913. {
  6914. return file.hashCode();
  6915. }
  6916. END_JUCE_NAMESPACE
  6917. /********* End of inlined file: juce_FileInputSource.cpp *********/
  6918. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  6919. BEGIN_JUCE_NAMESPACE
  6920. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6921. const int sourceDataSize,
  6922. const bool keepInternalCopy) throw()
  6923. : data ((const char*) sourceData),
  6924. dataSize (sourceDataSize),
  6925. position (0)
  6926. {
  6927. if (keepInternalCopy)
  6928. {
  6929. internalCopy.append (data, sourceDataSize);
  6930. data = (const char*) internalCopy.getData();
  6931. }
  6932. }
  6933. MemoryInputStream::~MemoryInputStream() throw()
  6934. {
  6935. }
  6936. int64 MemoryInputStream::getTotalLength()
  6937. {
  6938. return dataSize;
  6939. }
  6940. int MemoryInputStream::read (void* buffer, int howMany)
  6941. {
  6942. const int num = jmin (howMany, dataSize - position);
  6943. memcpy (buffer, data + position, num);
  6944. position += num;
  6945. return num;
  6946. }
  6947. bool MemoryInputStream::isExhausted()
  6948. {
  6949. return (position >= dataSize);
  6950. }
  6951. bool MemoryInputStream::setPosition (int64 pos)
  6952. {
  6953. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  6954. return true;
  6955. }
  6956. int64 MemoryInputStream::getPosition()
  6957. {
  6958. return position;
  6959. }
  6960. END_JUCE_NAMESPACE
  6961. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  6962. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  6963. BEGIN_JUCE_NAMESPACE
  6964. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  6965. const int blockSizeToIncreaseBy,
  6966. MemoryBlock* const memoryBlockToWriteTo) throw()
  6967. : data (memoryBlockToWriteTo),
  6968. position (0),
  6969. size (0),
  6970. blockSize (jmax (16, blockSizeToIncreaseBy)),
  6971. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  6972. {
  6973. if (memoryBlockToWriteTo == 0)
  6974. data = new MemoryBlock (initialSize);
  6975. else
  6976. memoryBlockToWriteTo->setSize (initialSize, false);
  6977. }
  6978. MemoryOutputStream::~MemoryOutputStream() throw()
  6979. {
  6980. if (ownsMemoryBlock)
  6981. delete data;
  6982. else
  6983. flush();
  6984. }
  6985. void MemoryOutputStream::flush()
  6986. {
  6987. if (! ownsMemoryBlock)
  6988. data->setSize (size, false);
  6989. }
  6990. void MemoryOutputStream::reset() throw()
  6991. {
  6992. position = 0;
  6993. size = 0;
  6994. }
  6995. bool MemoryOutputStream::write (const void* buffer, int howMany)
  6996. {
  6997. if (howMany > 0)
  6998. {
  6999. int storageNeeded = position + howMany;
  7000. if (storageNeeded >= data->getSize())
  7001. {
  7002. // if we need more space, increase the block by at least 10%..
  7003. storageNeeded += jmax (blockSize, storageNeeded / 10);
  7004. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  7005. data->ensureSize (storageNeeded);
  7006. }
  7007. data->copyFrom (buffer, position, howMany);
  7008. position += howMany;
  7009. size = jmax (size, position);
  7010. }
  7011. return true;
  7012. }
  7013. const char* MemoryOutputStream::getData() throw()
  7014. {
  7015. if (data->getSize() > size)
  7016. ((char*) data->getData()) [size] = 0;
  7017. return (const char*) data->getData();
  7018. }
  7019. int MemoryOutputStream::getDataSize() const throw()
  7020. {
  7021. return size;
  7022. }
  7023. int64 MemoryOutputStream::getPosition()
  7024. {
  7025. return position;
  7026. }
  7027. bool MemoryOutputStream::setPosition (int64 newPosition)
  7028. {
  7029. if (newPosition <= size)
  7030. {
  7031. // ok to seek backwards
  7032. position = jlimit (0, size, (int) newPosition);
  7033. return true;
  7034. }
  7035. else
  7036. {
  7037. // trying to make it bigger isn't a good thing to do..
  7038. return false;
  7039. }
  7040. }
  7041. END_JUCE_NAMESPACE
  7042. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  7043. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  7044. BEGIN_JUCE_NAMESPACE
  7045. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7046. const int64 startPositionInSourceStream_,
  7047. const int64 lengthOfSourceStream_,
  7048. const bool deleteSourceWhenDestroyed_) throw()
  7049. : source (sourceStream),
  7050. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  7051. startPositionInSourceStream (startPositionInSourceStream_),
  7052. lengthOfSourceStream (lengthOfSourceStream_)
  7053. {
  7054. setPosition (0);
  7055. }
  7056. SubregionStream::~SubregionStream() throw()
  7057. {
  7058. if (deleteSourceWhenDestroyed)
  7059. delete source;
  7060. }
  7061. int64 SubregionStream::getTotalLength()
  7062. {
  7063. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7064. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7065. : srcLen;
  7066. }
  7067. int64 SubregionStream::getPosition()
  7068. {
  7069. return source->getPosition() - startPositionInSourceStream;
  7070. }
  7071. bool SubregionStream::setPosition (int64 newPosition)
  7072. {
  7073. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7074. }
  7075. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7076. {
  7077. if (lengthOfSourceStream < 0)
  7078. {
  7079. return source->read (destBuffer, maxBytesToRead);
  7080. }
  7081. else
  7082. {
  7083. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7084. if (maxBytesToRead <= 0)
  7085. return 0;
  7086. return source->read (destBuffer, maxBytesToRead);
  7087. }
  7088. }
  7089. bool SubregionStream::isExhausted()
  7090. {
  7091. if (lengthOfSourceStream >= 0)
  7092. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7093. else
  7094. return source->isExhausted();
  7095. }
  7096. END_JUCE_NAMESPACE
  7097. /********* End of inlined file: juce_SubregionStream.cpp *********/
  7098. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  7099. BEGIN_JUCE_NAMESPACE
  7100. PerformanceCounter::PerformanceCounter (const String& name_,
  7101. int runsPerPrintout,
  7102. const File& loggingFile)
  7103. : name (name_),
  7104. numRuns (0),
  7105. runsPerPrint (runsPerPrintout),
  7106. totalTime (0),
  7107. outputFile (loggingFile)
  7108. {
  7109. if (outputFile != File::nonexistent)
  7110. {
  7111. String s ("**** Counter for \"");
  7112. s << name_ << "\" started at: "
  7113. << Time::getCurrentTime().toString (true, true)
  7114. << "\r\n";
  7115. outputFile.appendText (s, false, false);
  7116. }
  7117. }
  7118. PerformanceCounter::~PerformanceCounter()
  7119. {
  7120. printStatistics();
  7121. }
  7122. void PerformanceCounter::start()
  7123. {
  7124. started = Time::getHighResolutionTicks();
  7125. }
  7126. void PerformanceCounter::stop()
  7127. {
  7128. const int64 now = Time::getHighResolutionTicks();
  7129. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7130. if (++numRuns == runsPerPrint)
  7131. printStatistics();
  7132. }
  7133. void PerformanceCounter::printStatistics()
  7134. {
  7135. if (numRuns > 0)
  7136. {
  7137. String s ("Performance count for \"");
  7138. s << name << "\" - average over " << numRuns << " run(s) = ";
  7139. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7140. if (micros > 10000)
  7141. s << (micros/1000) << " millisecs";
  7142. else
  7143. s << micros << " microsecs";
  7144. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7145. Logger::outputDebugString (s);
  7146. s << "\r\n";
  7147. if (outputFile != File::nonexistent)
  7148. outputFile.appendText (s, false, false);
  7149. numRuns = 0;
  7150. totalTime = 0;
  7151. }
  7152. }
  7153. END_JUCE_NAMESPACE
  7154. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  7155. /********* Start of inlined file: juce_Uuid.cpp *********/
  7156. BEGIN_JUCE_NAMESPACE
  7157. Uuid::Uuid()
  7158. {
  7159. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7160. // to make it very very unlikely that two UUIDs will ever be the same..
  7161. static int64 macAddresses[2];
  7162. static bool hasCheckedMacAddresses = false;
  7163. if (! hasCheckedMacAddresses)
  7164. {
  7165. hasCheckedMacAddresses = true;
  7166. SystemStats::getMACAddresses (macAddresses, 2);
  7167. }
  7168. value.asInt64[0] = macAddresses[0];
  7169. value.asInt64[1] = macAddresses[1];
  7170. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7171. // whose seed will carry over between calls to this method.
  7172. Random r (macAddresses[0] ^ macAddresses[1]
  7173. ^ Random::getSystemRandom().nextInt64());
  7174. for (int i = 4; --i >= 0;)
  7175. {
  7176. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7177. value.asInt[i] ^= r.nextInt();
  7178. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7179. }
  7180. }
  7181. Uuid::~Uuid() throw()
  7182. {
  7183. }
  7184. Uuid::Uuid (const Uuid& other)
  7185. : value (other.value)
  7186. {
  7187. }
  7188. Uuid& Uuid::operator= (const Uuid& other)
  7189. {
  7190. if (this != &other)
  7191. value = other.value;
  7192. return *this;
  7193. }
  7194. bool Uuid::operator== (const Uuid& other) const
  7195. {
  7196. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  7197. }
  7198. bool Uuid::operator!= (const Uuid& other) const
  7199. {
  7200. return ! operator== (other);
  7201. }
  7202. bool Uuid::isNull() const throw()
  7203. {
  7204. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7205. }
  7206. const String Uuid::toString() const
  7207. {
  7208. return String::toHexString (value.asBytes, 16, 0);
  7209. }
  7210. Uuid::Uuid (const String& uuidString)
  7211. {
  7212. operator= (uuidString);
  7213. }
  7214. Uuid& Uuid::operator= (const String& uuidString)
  7215. {
  7216. int destIndex = 0;
  7217. int i = 0;
  7218. for (;;)
  7219. {
  7220. int byte = 0;
  7221. for (int loop = 2; --loop >= 0;)
  7222. {
  7223. byte <<= 4;
  7224. for (;;)
  7225. {
  7226. const tchar c = uuidString [i++];
  7227. if (c >= T('0') && c <= T('9'))
  7228. {
  7229. byte |= c - T('0');
  7230. break;
  7231. }
  7232. else if (c >= T('a') && c <= T('z'))
  7233. {
  7234. byte |= c - (T('a') - 10);
  7235. break;
  7236. }
  7237. else if (c >= T('A') && c <= T('Z'))
  7238. {
  7239. byte |= c - (T('A') - 10);
  7240. break;
  7241. }
  7242. else if (c == 0)
  7243. {
  7244. while (destIndex < 16)
  7245. value.asBytes [destIndex++] = 0;
  7246. return *this;
  7247. }
  7248. }
  7249. }
  7250. value.asBytes [destIndex++] = (uint8) byte;
  7251. }
  7252. }
  7253. Uuid::Uuid (const uint8* const rawData)
  7254. {
  7255. operator= (rawData);
  7256. }
  7257. Uuid& Uuid::operator= (const uint8* const rawData)
  7258. {
  7259. if (rawData != 0)
  7260. memcpy (value.asBytes, rawData, 16);
  7261. else
  7262. zeromem (value.asBytes, 16);
  7263. return *this;
  7264. }
  7265. END_JUCE_NAMESPACE
  7266. /********* End of inlined file: juce_Uuid.cpp *********/
  7267. /********* Start of inlined file: juce_ZipFile.cpp *********/
  7268. BEGIN_JUCE_NAMESPACE
  7269. struct ZipEntryInfo
  7270. {
  7271. ZipFile::ZipEntry entry;
  7272. int streamOffset;
  7273. int compressedSize;
  7274. bool compressed;
  7275. };
  7276. class ZipInputStream : public InputStream
  7277. {
  7278. public:
  7279. ZipInputStream (ZipFile& file_,
  7280. ZipEntryInfo& zei) throw()
  7281. : file (file_),
  7282. zipEntryInfo (zei),
  7283. pos (0),
  7284. headerSize (0),
  7285. inputStream (0)
  7286. {
  7287. inputStream = file_.inputStream;
  7288. if (file_.inputSource != 0)
  7289. {
  7290. inputStream = file.inputSource->createInputStream();
  7291. }
  7292. else
  7293. {
  7294. #ifdef JUCE_DEBUG
  7295. file_.numOpenStreams++;
  7296. #endif
  7297. }
  7298. char buffer [30];
  7299. if (inputStream != 0
  7300. && inputStream->setPosition (zei.streamOffset)
  7301. && inputStream->read (buffer, 30) == 30
  7302. && littleEndianInt (buffer) == 0x04034b50)
  7303. {
  7304. headerSize = 30 + littleEndianShort (buffer + 26)
  7305. + littleEndianShort (buffer + 28);
  7306. }
  7307. }
  7308. ~ZipInputStream() throw()
  7309. {
  7310. #ifdef JUCE_DEBUG
  7311. if (inputStream != 0 && inputStream == file.inputStream)
  7312. file.numOpenStreams--;
  7313. #endif
  7314. if (inputStream != file.inputStream)
  7315. delete inputStream;
  7316. }
  7317. int64 getTotalLength() throw()
  7318. {
  7319. return zipEntryInfo.compressedSize;
  7320. }
  7321. int read (void* buffer, int howMany) throw()
  7322. {
  7323. if (headerSize <= 0)
  7324. return 0;
  7325. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7326. if (inputStream == 0)
  7327. return 0;
  7328. int num;
  7329. if (inputStream == file.inputStream)
  7330. {
  7331. const ScopedLock sl (file.lock);
  7332. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7333. num = inputStream->read (buffer, howMany);
  7334. }
  7335. else
  7336. {
  7337. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7338. num = inputStream->read (buffer, howMany);
  7339. }
  7340. pos += num;
  7341. return num;
  7342. }
  7343. bool isExhausted() throw()
  7344. {
  7345. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7346. }
  7347. int64 getPosition() throw()
  7348. {
  7349. return pos;
  7350. }
  7351. bool setPosition (int64 newPos) throw()
  7352. {
  7353. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7354. return true;
  7355. }
  7356. private:
  7357. ZipFile& file;
  7358. ZipEntryInfo zipEntryInfo;
  7359. int64 pos;
  7360. int headerSize;
  7361. InputStream* inputStream;
  7362. ZipInputStream (const ZipInputStream&);
  7363. const ZipInputStream& operator= (const ZipInputStream&);
  7364. };
  7365. ZipFile::ZipFile (InputStream* const source_,
  7366. const bool deleteStreamWhenDestroyed_) throw()
  7367. : inputStream (source_),
  7368. inputSource (0),
  7369. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  7370. #ifdef JUCE_DEBUG
  7371. , numOpenStreams (0)
  7372. #endif
  7373. {
  7374. init();
  7375. }
  7376. ZipFile::ZipFile (const File& file)
  7377. : inputStream (0),
  7378. deleteStreamWhenDestroyed (false)
  7379. #ifdef JUCE_DEBUG
  7380. , numOpenStreams (0)
  7381. #endif
  7382. {
  7383. inputSource = new FileInputSource (file);
  7384. init();
  7385. }
  7386. ZipFile::ZipFile (InputSource* const inputSource_)
  7387. : inputStream (0),
  7388. inputSource (inputSource_),
  7389. deleteStreamWhenDestroyed (false)
  7390. #ifdef JUCE_DEBUG
  7391. , numOpenStreams (0)
  7392. #endif
  7393. {
  7394. init();
  7395. }
  7396. ZipFile::~ZipFile() throw()
  7397. {
  7398. for (int i = entries.size(); --i >= 0;)
  7399. {
  7400. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  7401. delete zei;
  7402. }
  7403. if (deleteStreamWhenDestroyed)
  7404. delete inputStream;
  7405. delete inputSource;
  7406. #ifdef JUCE_DEBUG
  7407. // If you hit this assertion, it means you've created a stream to read
  7408. // one of the items in the zipfile, but you've forgotten to delete that
  7409. // stream object before deleting the file.. Streams can't be kept open
  7410. // after the file is deleted because they need to share the input
  7411. // stream that the file uses to read itself.
  7412. jassert (numOpenStreams == 0);
  7413. #endif
  7414. }
  7415. int ZipFile::getNumEntries() const throw()
  7416. {
  7417. return entries.size();
  7418. }
  7419. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7420. {
  7421. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  7422. return (zei != 0) ? &(zei->entry)
  7423. : 0;
  7424. }
  7425. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7426. {
  7427. for (int i = 0; i < entries.size(); ++i)
  7428. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  7429. return i;
  7430. return -1;
  7431. }
  7432. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7433. {
  7434. return getEntry (getIndexOfFileName (fileName));
  7435. }
  7436. InputStream* ZipFile::createStreamForEntry (const int index)
  7437. {
  7438. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  7439. InputStream* stream = 0;
  7440. if (zei != 0)
  7441. {
  7442. stream = new ZipInputStream (*this, *zei);
  7443. if (zei->compressed)
  7444. {
  7445. stream = new GZIPDecompressorInputStream (stream, true, true,
  7446. zei->entry.uncompressedSize);
  7447. // (much faster to unzip in big blocks using a buffer..)
  7448. stream = new BufferedInputStream (stream, 32768, true);
  7449. }
  7450. }
  7451. return stream;
  7452. }
  7453. class ZipFilenameComparator
  7454. {
  7455. public:
  7456. static int compareElements (const void* const first, const void* const second) throw()
  7457. {
  7458. return ((const ZipEntryInfo*) first)->entry.filename
  7459. .compare (((const ZipEntryInfo*) second)->entry.filename);
  7460. }
  7461. };
  7462. void ZipFile::sortEntriesByFilename()
  7463. {
  7464. ZipFilenameComparator sorter;
  7465. entries.sort (sorter);
  7466. }
  7467. void ZipFile::init()
  7468. {
  7469. InputStream* in = inputStream;
  7470. bool deleteInput = false;
  7471. if (inputSource != 0)
  7472. {
  7473. deleteInput = true;
  7474. in = inputSource->createInputStream();
  7475. }
  7476. if (in != 0)
  7477. {
  7478. numEntries = 0;
  7479. int pos = findEndOfZipEntryTable (in);
  7480. if (pos >= 0 && pos < in->getTotalLength())
  7481. {
  7482. const int size = (int) (in->getTotalLength() - pos);
  7483. in->setPosition (pos);
  7484. MemoryBlock headerData;
  7485. if (in->readIntoMemoryBlock (headerData, size) == size)
  7486. {
  7487. pos = 0;
  7488. for (int i = 0; i < numEntries; ++i)
  7489. {
  7490. if (pos + 46 > size)
  7491. break;
  7492. const char* const buffer = ((const char*) headerData.getData()) + pos;
  7493. const int fileNameLen = littleEndianShort (buffer + 28);
  7494. if (pos + 46 + fileNameLen > size)
  7495. break;
  7496. ZipEntryInfo* const zei = new ZipEntryInfo();
  7497. zei->entry.filename = String (buffer + 46, fileNameLen);
  7498. const int time = littleEndianShort (buffer + 12);
  7499. const int date = littleEndianShort (buffer + 14);
  7500. const int year = 1980 + (date >> 9);
  7501. const int month = ((date >> 5) & 15) - 1;
  7502. const int day = date & 31;
  7503. const int hours = time >> 11;
  7504. const int minutes = (time >> 5) & 63;
  7505. const int seconds = (time & 31) << 1;
  7506. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7507. zei->compressed = littleEndianShort (buffer + 10) != 0;
  7508. zei->compressedSize = littleEndianInt (buffer + 20);
  7509. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  7510. zei->streamOffset = littleEndianInt (buffer + 42);
  7511. entries.add (zei);
  7512. pos += 46 + fileNameLen
  7513. + littleEndianShort (buffer + 30)
  7514. + littleEndianShort (buffer + 32);
  7515. }
  7516. }
  7517. }
  7518. if (deleteInput)
  7519. delete in;
  7520. }
  7521. }
  7522. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  7523. {
  7524. BufferedInputStream in (input, 8192, false);
  7525. in.setPosition (in.getTotalLength());
  7526. int64 pos = in.getPosition();
  7527. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7528. char buffer [32];
  7529. zeromem (buffer, sizeof (buffer));
  7530. while (pos > lowestPos)
  7531. {
  7532. in.setPosition (pos - 22);
  7533. pos = in.getPosition();
  7534. memcpy (buffer + 22, buffer, 4);
  7535. if (in.read (buffer, 22) != 22)
  7536. return 0;
  7537. for (int i = 0; i < 22; ++i)
  7538. {
  7539. if (littleEndianInt (buffer + i) == 0x06054b50)
  7540. {
  7541. in.setPosition (pos + i);
  7542. in.read (buffer, 22);
  7543. numEntries = littleEndianShort (buffer + 10);
  7544. return littleEndianInt (buffer + 16);
  7545. }
  7546. }
  7547. }
  7548. return 0;
  7549. }
  7550. void ZipFile::uncompressTo (const File& targetDirectory,
  7551. const bool shouldOverwriteFiles)
  7552. {
  7553. for (int i = 0; i < entries.size(); ++i)
  7554. {
  7555. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  7556. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  7557. if (zei.entry.filename.endsWithChar (T('/')))
  7558. {
  7559. targetFile.createDirectory(); // (entry is a directory, not a file)
  7560. }
  7561. else
  7562. {
  7563. InputStream* const in = createStreamForEntry (i);
  7564. if (in != 0)
  7565. {
  7566. if (shouldOverwriteFiles)
  7567. targetFile.deleteFile();
  7568. if ((! targetFile.exists())
  7569. && targetFile.getParentDirectory().createDirectory())
  7570. {
  7571. FileOutputStream* const out = targetFile.createOutputStream();
  7572. if (out != 0)
  7573. {
  7574. out->writeFromInputStream (*in, -1);
  7575. delete out;
  7576. targetFile.setCreationTime (zei.entry.fileTime);
  7577. targetFile.setLastModificationTime (zei.entry.fileTime);
  7578. targetFile.setLastAccessTime (zei.entry.fileTime);
  7579. }
  7580. }
  7581. delete in;
  7582. }
  7583. }
  7584. }
  7585. }
  7586. END_JUCE_NAMESPACE
  7587. /********* End of inlined file: juce_ZipFile.cpp *********/
  7588. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  7589. #ifdef _MSC_VER
  7590. #pragma warning (disable: 4514 4996)
  7591. #pragma warning (push)
  7592. #endif
  7593. #include <cwctype>
  7594. #include <cctype>
  7595. #include <ctime>
  7596. #ifdef _MSC_VER
  7597. #pragma warning (pop)
  7598. #endif
  7599. BEGIN_JUCE_NAMESPACE
  7600. int CharacterFunctions::length (const char* const s) throw()
  7601. {
  7602. return (int) strlen (s);
  7603. }
  7604. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7605. {
  7606. return (int) wcslen (s);
  7607. }
  7608. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7609. {
  7610. strncpy (dest, src, maxChars);
  7611. }
  7612. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7613. {
  7614. wcsncpy (dest, src, maxChars);
  7615. }
  7616. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7617. {
  7618. mbstowcs (dest, src, maxChars);
  7619. }
  7620. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7621. {
  7622. wcstombs (dest, src, maxChars);
  7623. }
  7624. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7625. {
  7626. return (int) wcstombs (0, src, 0);
  7627. }
  7628. void CharacterFunctions::append (char* dest, const char* src) throw()
  7629. {
  7630. strcat (dest, src);
  7631. }
  7632. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7633. {
  7634. wcscat (dest, src);
  7635. }
  7636. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7637. {
  7638. return strcmp (s1, s2);
  7639. }
  7640. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7641. {
  7642. jassert (s1 != 0 && s2 != 0);
  7643. return wcscmp (s1, s2);
  7644. }
  7645. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7646. {
  7647. jassert (s1 != 0 && s2 != 0);
  7648. return strncmp (s1, s2, maxChars);
  7649. }
  7650. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7651. {
  7652. jassert (s1 != 0 && s2 != 0);
  7653. return wcsncmp (s1, s2, maxChars);
  7654. }
  7655. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7656. {
  7657. jassert (s1 != 0 && s2 != 0);
  7658. #if JUCE_WIN32
  7659. return stricmp (s1, s2);
  7660. #else
  7661. return strcasecmp (s1, s2);
  7662. #endif
  7663. }
  7664. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7665. {
  7666. jassert (s1 != 0 && s2 != 0);
  7667. #if JUCE_WIN32
  7668. return _wcsicmp (s1, s2);
  7669. #else
  7670. for (;;)
  7671. {
  7672. if (*s1 != *s2)
  7673. {
  7674. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7675. if (diff != 0)
  7676. return diff < 0 ? -1 : 1;
  7677. }
  7678. else if (*s1 == 0)
  7679. break;
  7680. ++s1;
  7681. ++s2;
  7682. }
  7683. return 0;
  7684. #endif
  7685. }
  7686. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7687. {
  7688. jassert (s1 != 0 && s2 != 0);
  7689. #if JUCE_WIN32
  7690. return strnicmp (s1, s2, maxChars);
  7691. #else
  7692. return strncasecmp (s1, s2, maxChars);
  7693. #endif
  7694. }
  7695. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7696. {
  7697. jassert (s1 != 0 && s2 != 0);
  7698. #if JUCE_WIN32
  7699. return _wcsnicmp (s1, s2, maxChars);
  7700. #else
  7701. while (--maxChars >= 0)
  7702. {
  7703. if (*s1 != *s2)
  7704. {
  7705. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7706. if (diff != 0)
  7707. return diff < 0 ? -1 : 1;
  7708. }
  7709. else if (*s1 == 0)
  7710. break;
  7711. ++s1;
  7712. ++s2;
  7713. }
  7714. return 0;
  7715. #endif
  7716. }
  7717. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7718. {
  7719. return strstr (haystack, needle);
  7720. }
  7721. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7722. {
  7723. return wcsstr (haystack, needle);
  7724. }
  7725. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7726. {
  7727. if (haystack != 0)
  7728. {
  7729. int i = 0;
  7730. if (ignoreCase)
  7731. {
  7732. const char n1 = toLowerCase (needle);
  7733. const char n2 = toUpperCase (needle);
  7734. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7735. {
  7736. while (haystack[i] != 0)
  7737. {
  7738. if (haystack[i] == n1 || haystack[i] == n2)
  7739. return i;
  7740. ++i;
  7741. }
  7742. return -1;
  7743. }
  7744. jassert (n1 == needle);
  7745. }
  7746. while (haystack[i] != 0)
  7747. {
  7748. if (haystack[i] == needle)
  7749. return i;
  7750. ++i;
  7751. }
  7752. }
  7753. return -1;
  7754. }
  7755. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7756. {
  7757. if (haystack != 0)
  7758. {
  7759. int i = 0;
  7760. if (ignoreCase)
  7761. {
  7762. const juce_wchar n1 = toLowerCase (needle);
  7763. const juce_wchar n2 = toUpperCase (needle);
  7764. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7765. {
  7766. while (haystack[i] != 0)
  7767. {
  7768. if (haystack[i] == n1 || haystack[i] == n2)
  7769. return i;
  7770. ++i;
  7771. }
  7772. return -1;
  7773. }
  7774. jassert (n1 == needle);
  7775. }
  7776. while (haystack[i] != 0)
  7777. {
  7778. if (haystack[i] == needle)
  7779. return i;
  7780. ++i;
  7781. }
  7782. }
  7783. return -1;
  7784. }
  7785. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7786. {
  7787. jassert (haystack != 0);
  7788. int i = 0;
  7789. while (haystack[i] != 0)
  7790. {
  7791. if (haystack[i] == needle)
  7792. return i;
  7793. ++i;
  7794. }
  7795. return -1;
  7796. }
  7797. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7798. {
  7799. jassert (haystack != 0);
  7800. int i = 0;
  7801. while (haystack[i] != 0)
  7802. {
  7803. if (haystack[i] == needle)
  7804. return i;
  7805. ++i;
  7806. }
  7807. return -1;
  7808. }
  7809. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7810. {
  7811. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7812. }
  7813. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7814. {
  7815. if (allowedChars == 0)
  7816. return 0;
  7817. int i = 0;
  7818. for (;;)
  7819. {
  7820. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7821. break;
  7822. ++i;
  7823. }
  7824. return i;
  7825. }
  7826. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7827. {
  7828. return (int) strftime (dest, maxChars, format, tm);
  7829. }
  7830. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7831. {
  7832. return (int) wcsftime (dest, maxChars, format, tm);
  7833. }
  7834. int CharacterFunctions::getIntValue (const char* const s) throw()
  7835. {
  7836. return atoi (s);
  7837. }
  7838. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7839. {
  7840. #if JUCE_WIN32
  7841. return _wtoi (s);
  7842. #else
  7843. int v = 0;
  7844. while (isWhitespace (*s))
  7845. ++s;
  7846. const bool isNeg = *s == T('-');
  7847. if (isNeg)
  7848. ++s;
  7849. for (;;)
  7850. {
  7851. const wchar_t c = *s++;
  7852. if (c >= T('0') && c <= T('9'))
  7853. v = v * 10 + (int) (c - T('0'));
  7854. else
  7855. break;
  7856. }
  7857. return isNeg ? -v : v;
  7858. #endif
  7859. }
  7860. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7861. {
  7862. #if JUCE_LINUX
  7863. return atoll (s);
  7864. #elif defined (JUCE_WIN32)
  7865. return _atoi64 (s);
  7866. #else
  7867. int64 v = 0;
  7868. while (isWhitespace (*s))
  7869. ++s;
  7870. const bool isNeg = *s == T('-');
  7871. if (isNeg)
  7872. ++s;
  7873. for (;;)
  7874. {
  7875. const char c = *s++;
  7876. if (c >= '0' && c <= '9')
  7877. v = v * 10 + (int64) (c - '0');
  7878. else
  7879. break;
  7880. }
  7881. return isNeg ? -v : v;
  7882. #endif
  7883. }
  7884. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7885. {
  7886. #if JUCE_WIN32
  7887. return _wtoi64 (s);
  7888. #else
  7889. int64 v = 0;
  7890. while (isWhitespace (*s))
  7891. ++s;
  7892. const bool isNeg = *s == T('-');
  7893. if (isNeg)
  7894. ++s;
  7895. for (;;)
  7896. {
  7897. const juce_wchar c = *s++;
  7898. if (c >= T('0') && c <= T('9'))
  7899. v = v * 10 + (int64) (c - T('0'));
  7900. else
  7901. break;
  7902. }
  7903. return isNeg ? -v : v;
  7904. #endif
  7905. }
  7906. static double juce_mulexp10 (const double value, int exponent) throw()
  7907. {
  7908. if (exponent == 0)
  7909. return value;
  7910. if (value == 0)
  7911. return 0;
  7912. const bool negative = (exponent < 0);
  7913. if (negative)
  7914. exponent = -exponent;
  7915. double result = 1.0, power = 10.0;
  7916. for (int bit = 1; exponent != 0; bit <<= 1)
  7917. {
  7918. if ((exponent & bit) != 0)
  7919. {
  7920. exponent ^= bit;
  7921. result *= power;
  7922. if (exponent == 0)
  7923. break;
  7924. }
  7925. power *= power;
  7926. }
  7927. return negative ? (value / result) : (value * result);
  7928. }
  7929. template <class CharType>
  7930. double juce_atof (const CharType* const original) throw()
  7931. {
  7932. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7933. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7934. int exponent = 0, decPointIndex = 0, digit = 0;
  7935. int lastDigit = 0, numSignificantDigits = 0;
  7936. bool isNegative = false, digitsFound = false;
  7937. const int maxSignificantDigits = 15 + 2;
  7938. const CharType* s = original;
  7939. while (CharacterFunctions::isWhitespace (*s))
  7940. ++s;
  7941. switch (*s)
  7942. {
  7943. case '-': isNegative = true; // fall-through..
  7944. case '+': ++s;
  7945. }
  7946. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  7947. return atof (String (original)); // Let the c library deal with NAN and INF
  7948. for (;;)
  7949. {
  7950. if (CharacterFunctions::isDigit (*s))
  7951. {
  7952. lastDigit = digit;
  7953. digit = *s++ - '0';
  7954. digitsFound = true;
  7955. if (decPointIndex != 0)
  7956. exponentAdjustment[1]++;
  7957. if (numSignificantDigits == 0 && digit == 0)
  7958. continue;
  7959. if (++numSignificantDigits > maxSignificantDigits)
  7960. {
  7961. if (digit > 5)
  7962. ++accumulator [decPointIndex];
  7963. else if (digit == 5 && (lastDigit & 1) != 0)
  7964. ++accumulator [decPointIndex];
  7965. if (decPointIndex > 0)
  7966. exponentAdjustment[1]--;
  7967. else
  7968. exponentAdjustment[0]++;
  7969. while (CharacterFunctions::isDigit (*s))
  7970. {
  7971. ++s;
  7972. if (decPointIndex == 0)
  7973. exponentAdjustment[0]++;
  7974. }
  7975. }
  7976. else
  7977. {
  7978. const double maxAccumulatorValue = (double) ((UINT_MAX - 9) / 10);
  7979. if (accumulator [decPointIndex] > maxAccumulatorValue)
  7980. {
  7981. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  7982. + accumulator [decPointIndex];
  7983. accumulator [decPointIndex] = 0;
  7984. exponentAccumulator [decPointIndex] = 0;
  7985. }
  7986. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  7987. exponentAccumulator [decPointIndex]++;
  7988. }
  7989. }
  7990. else if (decPointIndex == 0 && *s == '.')
  7991. {
  7992. ++s;
  7993. decPointIndex = 1;
  7994. if (numSignificantDigits > maxSignificantDigits)
  7995. {
  7996. while (CharacterFunctions::isDigit (*s))
  7997. ++s;
  7998. break;
  7999. }
  8000. }
  8001. else
  8002. {
  8003. break;
  8004. }
  8005. }
  8006. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8007. if (decPointIndex != 0)
  8008. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8009. if ((*s == 'e' || *s == 'E') && digitsFound)
  8010. {
  8011. bool negativeExponent = false;
  8012. switch (*++s)
  8013. {
  8014. case '-': negativeExponent = true; // fall-through..
  8015. case '+': ++s;
  8016. }
  8017. while (CharacterFunctions::isDigit (*s))
  8018. exponent = (exponent * 10) + (*s++ - '0');
  8019. if (negativeExponent)
  8020. exponent = -exponent;
  8021. }
  8022. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8023. if (decPointIndex != 0)
  8024. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8025. return isNegative ? -r : r;
  8026. }
  8027. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8028. {
  8029. return juce_atof <char> (s);
  8030. }
  8031. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8032. {
  8033. return juce_atof <juce_wchar> (s);
  8034. }
  8035. char CharacterFunctions::toUpperCase (const char character) throw()
  8036. {
  8037. return (char) toupper (character);
  8038. }
  8039. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8040. {
  8041. return towupper (character);
  8042. }
  8043. void CharacterFunctions::toUpperCase (char* s) throw()
  8044. {
  8045. #if JUCE_WIN32
  8046. strupr (s);
  8047. #else
  8048. while (*s != 0)
  8049. {
  8050. *s = toUpperCase (*s);
  8051. ++s;
  8052. }
  8053. #endif
  8054. }
  8055. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8056. {
  8057. #if JUCE_WIN32
  8058. _wcsupr (s);
  8059. #else
  8060. while (*s != 0)
  8061. {
  8062. *s = toUpperCase (*s);
  8063. ++s;
  8064. }
  8065. #endif
  8066. }
  8067. bool CharacterFunctions::isUpperCase (const char character) throw()
  8068. {
  8069. return isupper (character) != 0;
  8070. }
  8071. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8072. {
  8073. #if JUCE_WIN32
  8074. return iswupper (character) != 0;
  8075. #else
  8076. return toLowerCase (character) != character;
  8077. #endif
  8078. }
  8079. char CharacterFunctions::toLowerCase (const char character) throw()
  8080. {
  8081. return (char) tolower (character);
  8082. }
  8083. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8084. {
  8085. return towlower (character);
  8086. }
  8087. void CharacterFunctions::toLowerCase (char* s) throw()
  8088. {
  8089. #if JUCE_WIN32
  8090. strlwr (s);
  8091. #else
  8092. while (*s != 0)
  8093. {
  8094. *s = toLowerCase (*s);
  8095. ++s;
  8096. }
  8097. #endif
  8098. }
  8099. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8100. {
  8101. #if JUCE_WIN32
  8102. _wcslwr (s);
  8103. #else
  8104. while (*s != 0)
  8105. {
  8106. *s = toLowerCase (*s);
  8107. ++s;
  8108. }
  8109. #endif
  8110. }
  8111. bool CharacterFunctions::isLowerCase (const char character) throw()
  8112. {
  8113. return islower (character) != 0;
  8114. }
  8115. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8116. {
  8117. #if JUCE_WIN32
  8118. return iswlower (character) != 0;
  8119. #else
  8120. return toUpperCase (character) != character;
  8121. #endif
  8122. }
  8123. bool CharacterFunctions::isWhitespace (const char character) throw()
  8124. {
  8125. return character == T(' ') || (character <= 13 && character >= 9);
  8126. }
  8127. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8128. {
  8129. return iswspace (character) != 0;
  8130. }
  8131. bool CharacterFunctions::isDigit (const char character) throw()
  8132. {
  8133. return (character >= '0' && character <= '9');
  8134. }
  8135. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8136. {
  8137. return iswdigit (character) != 0;
  8138. }
  8139. bool CharacterFunctions::isLetter (const char character) throw()
  8140. {
  8141. return (character >= 'a' && character <= 'z')
  8142. || (character >= 'A' && character <= 'Z');
  8143. }
  8144. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8145. {
  8146. return iswalpha (character) != 0;
  8147. }
  8148. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8149. {
  8150. return (character >= 'a' && character <= 'z')
  8151. || (character >= 'A' && character <= 'Z')
  8152. || (character >= '0' && character <= '9');
  8153. }
  8154. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8155. {
  8156. return iswalnum (character) != 0;
  8157. }
  8158. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  8159. {
  8160. if (digit >= T('0') && digit <= T('9'))
  8161. return digit - T('0');
  8162. else if (digit >= T('a') && digit <= T('f'))
  8163. return digit - (T('a') - 10);
  8164. else if (digit >= T('A') && digit <= T('F'))
  8165. return digit - (T('A') - 10);
  8166. return -1;
  8167. }
  8168. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  8169. {
  8170. va_list list;
  8171. va_start (list, format);
  8172. return vprintf (dest, maxLength, format, list);
  8173. }
  8174. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  8175. {
  8176. va_list list;
  8177. va_start (list, format);
  8178. return vprintf (dest, maxLength, format, list);
  8179. }
  8180. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  8181. {
  8182. #if JUCE_WIN32
  8183. return (int) _vsnprintf (dest, maxLength, format, args);
  8184. #else
  8185. return (int) vsnprintf (dest, maxLength, format, args);
  8186. #endif
  8187. }
  8188. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  8189. {
  8190. #if MACOS_10_3_OR_EARLIER
  8191. const String formatTemp (format);
  8192. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  8193. String temp ((char*) dest);
  8194. temp.copyToBuffer (dest, num);
  8195. dest [num] = 0;
  8196. return (int) num;
  8197. #elif defined (JUCE_WIN32)
  8198. return (int) _vsnwprintf (dest, maxLength, format, args);
  8199. #else
  8200. return (int) vswprintf (dest, maxLength, format, args);
  8201. #endif
  8202. }
  8203. END_JUCE_NAMESPACE
  8204. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  8205. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  8206. BEGIN_JUCE_NAMESPACE
  8207. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  8208. {
  8209. loadFromText (fileContents);
  8210. }
  8211. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  8212. {
  8213. loadFromText (fileToLoad.loadFileAsString());
  8214. }
  8215. LocalisedStrings::~LocalisedStrings() throw()
  8216. {
  8217. }
  8218. const String LocalisedStrings::translate (const String& text) const throw()
  8219. {
  8220. return translations.getValue (text, text);
  8221. }
  8222. static int findCloseQuote (const String& text, int startPos) throw()
  8223. {
  8224. tchar lastChar = 0;
  8225. for (;;)
  8226. {
  8227. const tchar c = text [startPos];
  8228. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  8229. break;
  8230. lastChar = c;
  8231. ++startPos;
  8232. }
  8233. return startPos;
  8234. }
  8235. static const String unescapeString (const String& s) throw()
  8236. {
  8237. return s.replace (T("\\\""), T("\""))
  8238. .replace (T("\\\'"), T("\'"))
  8239. .replace (T("\\t"), T("\t"))
  8240. .replace (T("\\r"), T("\r"))
  8241. .replace (T("\\n"), T("\n"));
  8242. }
  8243. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  8244. {
  8245. StringArray lines;
  8246. lines.addLines (fileContents);
  8247. for (int i = 0; i < lines.size(); ++i)
  8248. {
  8249. String line (lines[i].trim());
  8250. if (line.startsWithChar (T('"')))
  8251. {
  8252. int closeQuote = findCloseQuote (line, 1);
  8253. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8254. if (originalText.isNotEmpty())
  8255. {
  8256. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8257. closeQuote = findCloseQuote (line, openingQuote + 1);
  8258. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8259. if (newText.isNotEmpty())
  8260. translations.set (originalText, newText);
  8261. }
  8262. }
  8263. else if (line.startsWithIgnoreCase (T("language:")))
  8264. {
  8265. languageName = line.substring (9).trim();
  8266. }
  8267. else if (line.startsWithIgnoreCase (T("countries:")))
  8268. {
  8269. countryCodes.addTokens (line.substring (10).trim(), true);
  8270. countryCodes.trim();
  8271. countryCodes.removeEmptyStrings();
  8272. }
  8273. }
  8274. }
  8275. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase) throw()
  8276. {
  8277. translations.setIgnoresCase (shouldIgnoreCase);
  8278. }
  8279. static CriticalSection currentMappingsLock;
  8280. static LocalisedStrings* currentMappings = 0;
  8281. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  8282. {
  8283. const ScopedLock sl (currentMappingsLock);
  8284. delete currentMappings;
  8285. currentMappings = newTranslations;
  8286. }
  8287. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  8288. {
  8289. return currentMappings;
  8290. }
  8291. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  8292. {
  8293. const ScopedLock sl (currentMappingsLock);
  8294. if (currentMappings != 0)
  8295. return currentMappings->translate (text);
  8296. return text;
  8297. }
  8298. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  8299. {
  8300. return translateWithCurrentMappings (String (text));
  8301. }
  8302. END_JUCE_NAMESPACE
  8303. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  8304. /********* Start of inlined file: juce_String.cpp *********/
  8305. #ifdef _MSC_VER
  8306. #pragma warning (disable: 4514)
  8307. #pragma warning (push)
  8308. #endif
  8309. #include <locale>
  8310. #if JUCE_MSVC
  8311. #include <float.h>
  8312. #endif
  8313. BEGIN_JUCE_NAMESPACE
  8314. #ifdef _MSC_VER
  8315. #pragma warning (pop)
  8316. #endif
  8317. static const char* const emptyCharString = "\0\0\0\0JUCE";
  8318. static const int safeEmptyStringRefCount = 0x3fffffff;
  8319. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  8320. static tchar decimalPoint = T('.');
  8321. void juce_initialiseStrings()
  8322. {
  8323. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  8324. }
  8325. void String::deleteInternal() throw()
  8326. {
  8327. if (atomicDecrementAndReturn (text->refCount) == 0)
  8328. juce_free (text);
  8329. }
  8330. void String::createInternal (const int numChars) throw()
  8331. {
  8332. jassert (numChars > 0);
  8333. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8334. + numChars * sizeof (tchar));
  8335. text->refCount = 1;
  8336. text->allocatedNumChars = numChars;
  8337. text->text[0] = 0;
  8338. }
  8339. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  8340. {
  8341. jassert (*(textEnd - 1) == 0); // must have a null terminator
  8342. const int numChars = (int) (textEnd - t);
  8343. createInternal (numChars - 1);
  8344. memcpy (text->text, t, numChars * sizeof (tchar));
  8345. }
  8346. void String::appendInternal (const tchar* const newText,
  8347. const int numExtraChars) throw()
  8348. {
  8349. if (numExtraChars > 0)
  8350. {
  8351. const int oldLen = CharacterFunctions::length (text->text);
  8352. const int newTotalLen = oldLen + numExtraChars;
  8353. if (text->refCount > 1)
  8354. {
  8355. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  8356. InternalRefCountedStringHolder* const newTextHolder
  8357. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8358. + newTotalLen * sizeof (tchar));
  8359. newTextHolder->refCount = 1;
  8360. newTextHolder->allocatedNumChars = newTotalLen;
  8361. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  8362. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8363. InternalRefCountedStringHolder* const old = text;
  8364. text = newTextHolder;
  8365. if (atomicDecrementAndReturn (old->refCount) == 0)
  8366. juce_free (old);
  8367. }
  8368. else
  8369. {
  8370. // no other strings using it, so just expand it if needed..
  8371. if (newTotalLen > text->allocatedNumChars)
  8372. {
  8373. text = (InternalRefCountedStringHolder*)
  8374. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8375. + newTotalLen * sizeof (tchar));
  8376. text->allocatedNumChars = newTotalLen;
  8377. }
  8378. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8379. }
  8380. text->text [newTotalLen] = 0;
  8381. }
  8382. }
  8383. void String::dupeInternalIfMultiplyReferenced() throw()
  8384. {
  8385. if (text->refCount > 1)
  8386. {
  8387. InternalRefCountedStringHolder* const old = text;
  8388. const int len = old->allocatedNumChars;
  8389. InternalRefCountedStringHolder* const newTextHolder
  8390. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8391. + len * sizeof (tchar));
  8392. newTextHolder->refCount = 1;
  8393. newTextHolder->allocatedNumChars = len;
  8394. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  8395. text = newTextHolder;
  8396. if (atomicDecrementAndReturn (old->refCount) == 0)
  8397. juce_free (old);
  8398. }
  8399. }
  8400. const String String::empty;
  8401. String::String() throw()
  8402. : text (&emptyString)
  8403. {
  8404. }
  8405. String::String (const String& other) throw()
  8406. : text (other.text)
  8407. {
  8408. atomicIncrement (text->refCount);
  8409. }
  8410. String::String (const int numChars,
  8411. const int /*dummyVariable*/) throw()
  8412. {
  8413. createInternal (numChars);
  8414. }
  8415. String::String (const char* const t) throw()
  8416. {
  8417. if (t != 0 && *t != 0)
  8418. {
  8419. const int len = CharacterFunctions::length (t);
  8420. createInternal (len);
  8421. #if JUCE_STRINGS_ARE_UNICODE
  8422. CharacterFunctions::copy (text->text, t, len + 1);
  8423. #else
  8424. memcpy (text->text, t, len + 1);
  8425. #endif
  8426. }
  8427. else
  8428. {
  8429. text = &emptyString;
  8430. emptyString.refCount = safeEmptyStringRefCount;
  8431. }
  8432. }
  8433. String::String (const juce_wchar* const t) throw()
  8434. {
  8435. if (t != 0 && *t != 0)
  8436. {
  8437. #if JUCE_STRINGS_ARE_UNICODE
  8438. const int len = CharacterFunctions::length (t);
  8439. createInternal (len);
  8440. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  8441. #else
  8442. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  8443. createInternal (len);
  8444. CharacterFunctions::copy (text->text, t, len + 1);
  8445. #endif
  8446. }
  8447. else
  8448. {
  8449. text = &emptyString;
  8450. emptyString.refCount = safeEmptyStringRefCount;
  8451. }
  8452. }
  8453. String::String (const char* const t,
  8454. const int maxChars) throw()
  8455. {
  8456. int i;
  8457. for (i = 0; i < maxChars; ++i)
  8458. if (t[i] == 0)
  8459. break;
  8460. if (i > 0)
  8461. {
  8462. createInternal (i);
  8463. #if JUCE_STRINGS_ARE_UNICODE
  8464. CharacterFunctions::copy (text->text, t, i);
  8465. #else
  8466. memcpy (text->text, t, i);
  8467. #endif
  8468. text->text [i] = 0;
  8469. }
  8470. else
  8471. {
  8472. text = &emptyString;
  8473. emptyString.refCount = safeEmptyStringRefCount;
  8474. }
  8475. }
  8476. String::String (const juce_wchar* const t,
  8477. const int maxChars) throw()
  8478. {
  8479. int i;
  8480. for (i = 0; i < maxChars; ++i)
  8481. if (t[i] == 0)
  8482. break;
  8483. if (i > 0)
  8484. {
  8485. createInternal (i);
  8486. #if JUCE_STRINGS_ARE_UNICODE
  8487. memcpy (text->text, t, i * sizeof (tchar));
  8488. #else
  8489. CharacterFunctions::copy (text->text, t, i);
  8490. #endif
  8491. text->text [i] = 0;
  8492. }
  8493. else
  8494. {
  8495. text = &emptyString;
  8496. emptyString.refCount = safeEmptyStringRefCount;
  8497. }
  8498. }
  8499. const String String::charToString (const tchar character) throw()
  8500. {
  8501. tchar temp[2];
  8502. temp[0] = character;
  8503. temp[1] = 0;
  8504. return String (temp);
  8505. }
  8506. // pass in a pointer to the END of a buffer..
  8507. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  8508. {
  8509. *--t = 0;
  8510. int64 v = (n >= 0) ? n : -n;
  8511. do
  8512. {
  8513. *--t = (tchar) (T('0') + (int) (v % 10));
  8514. v /= 10;
  8515. } while (v > 0);
  8516. if (n < 0)
  8517. *--t = T('-');
  8518. return t;
  8519. }
  8520. static tchar* intToCharString (tchar* t, const int n) throw()
  8521. {
  8522. if (n == (int) 0x80000000) // (would cause an overflow)
  8523. return int64ToCharString (t, n);
  8524. *--t = 0;
  8525. int v = abs (n);
  8526. do
  8527. {
  8528. *--t = (tchar) (T('0') + (v % 10));
  8529. v /= 10;
  8530. } while (v > 0);
  8531. if (n < 0)
  8532. *--t = T('-');
  8533. return t;
  8534. }
  8535. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  8536. {
  8537. *--t = 0;
  8538. do
  8539. {
  8540. *--t = (tchar) (T('0') + (v % 10));
  8541. v /= 10;
  8542. } while (v > 0);
  8543. return t;
  8544. }
  8545. String::String (const int number) throw()
  8546. {
  8547. tchar buffer [16];
  8548. tchar* const end = buffer + 16;
  8549. createInternal (intToCharString (end, number), end);
  8550. }
  8551. String::String (const unsigned int number) throw()
  8552. {
  8553. tchar buffer [16];
  8554. tchar* const end = buffer + 16;
  8555. createInternal (uintToCharString (end, number), end);
  8556. }
  8557. String::String (const short number) throw()
  8558. {
  8559. tchar buffer [16];
  8560. tchar* const end = buffer + 16;
  8561. createInternal (intToCharString (end, (int) number), end);
  8562. }
  8563. String::String (const unsigned short number) throw()
  8564. {
  8565. tchar buffer [16];
  8566. tchar* const end = buffer + 16;
  8567. createInternal (uintToCharString (end, (unsigned int) number), end);
  8568. }
  8569. String::String (const int64 number) throw()
  8570. {
  8571. tchar buffer [32];
  8572. tchar* const end = buffer + 32;
  8573. createInternal (int64ToCharString (end, number), end);
  8574. }
  8575. String::String (const uint64 number) throw()
  8576. {
  8577. tchar buffer [32];
  8578. tchar* const end = buffer + 32;
  8579. tchar* t = end;
  8580. *--t = 0;
  8581. int64 v = number;
  8582. do
  8583. {
  8584. *--t = (tchar) (T('0') + (int) (v % 10));
  8585. v /= 10;
  8586. } while (v > 0);
  8587. createInternal (t, end);
  8588. }
  8589. // a double-to-string routine that actually uses the number of dec. places you asked for
  8590. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  8591. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  8592. {
  8593. const int bufSize = 80;
  8594. tchar buffer [bufSize];
  8595. int len;
  8596. tchar* t;
  8597. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8598. {
  8599. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  8600. t = buffer + bufSize;
  8601. *--t = (tchar) 0;
  8602. while (numDecPlaces >= 0 || v > 0)
  8603. {
  8604. if (numDecPlaces == 0)
  8605. *--t = decimalPoint;
  8606. *--t = (tchar) (T('0') + (v % 10));
  8607. v /= 10;
  8608. --numDecPlaces;
  8609. }
  8610. if (n < 0)
  8611. *--t = T('-');
  8612. len = (int) ((buffer + bufSize) - t);
  8613. }
  8614. else
  8615. {
  8616. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  8617. t = buffer;
  8618. }
  8619. if (len > 1)
  8620. {
  8621. jassert (len < numElementsInArray (buffer));
  8622. createInternal (len - 1);
  8623. memcpy (text->text, t, len * sizeof (tchar));
  8624. }
  8625. else
  8626. {
  8627. jassert (*t == 0);
  8628. text = &emptyString;
  8629. emptyString.refCount = safeEmptyStringRefCount;
  8630. }
  8631. }
  8632. String::String (const float number,
  8633. const int numberOfDecimalPlaces) throw()
  8634. {
  8635. doubleToStringWithDecPlaces ((double) number,
  8636. numberOfDecimalPlaces);
  8637. }
  8638. String::String (const double number,
  8639. const int numberOfDecimalPlaces) throw()
  8640. {
  8641. doubleToStringWithDecPlaces (number,
  8642. numberOfDecimalPlaces);
  8643. }
  8644. String::~String() throw()
  8645. {
  8646. emptyString.refCount = safeEmptyStringRefCount;
  8647. if (atomicDecrementAndReturn (text->refCount) == 0)
  8648. juce_free (text);
  8649. }
  8650. void String::preallocateStorage (const int numChars) throw()
  8651. {
  8652. if (numChars > text->allocatedNumChars)
  8653. {
  8654. dupeInternalIfMultiplyReferenced();
  8655. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8656. + numChars * sizeof (tchar));
  8657. text->allocatedNumChars = numChars;
  8658. }
  8659. }
  8660. #if JUCE_STRINGS_ARE_UNICODE
  8661. String::operator const char*() const throw()
  8662. {
  8663. if (isEmpty())
  8664. {
  8665. return (const char*) emptyCharString;
  8666. }
  8667. else
  8668. {
  8669. String* const mutableThis = const_cast <String*> (this);
  8670. mutableThis->dupeInternalIfMultiplyReferenced();
  8671. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  8672. mutableThis->text = (InternalRefCountedStringHolder*)
  8673. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8674. + (len * sizeof (juce_wchar) + len));
  8675. char* otherCopy = (char*) (text->text + len);
  8676. --len;
  8677. CharacterFunctions::copy (otherCopy, text->text, len);
  8678. otherCopy [len] = 0;
  8679. return otherCopy;
  8680. }
  8681. }
  8682. #else
  8683. String::operator const juce_wchar*() const throw()
  8684. {
  8685. if (isEmpty())
  8686. {
  8687. return (const juce_wchar*) emptyCharString;
  8688. }
  8689. else
  8690. {
  8691. String* const mutableThis = const_cast <String*> (this);
  8692. mutableThis->dupeInternalIfMultiplyReferenced();
  8693. int len = CharacterFunctions::length (text->text) + 1;
  8694. mutableThis->text = (InternalRefCountedStringHolder*)
  8695. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8696. + (len * sizeof (juce_wchar) + len));
  8697. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  8698. --len;
  8699. CharacterFunctions::copy (otherCopy, text->text, len);
  8700. otherCopy [len] = 0;
  8701. return otherCopy;
  8702. }
  8703. }
  8704. #endif
  8705. void String::copyToBuffer (char* const destBuffer,
  8706. const int bufferSizeBytes) const throw()
  8707. {
  8708. #if JUCE_STRINGS_ARE_UNICODE
  8709. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  8710. CharacterFunctions::copy (destBuffer, text->text, len);
  8711. #else
  8712. const int len = jmin (bufferSizeBytes, length());
  8713. memcpy (destBuffer, text->text, len * sizeof (tchar));
  8714. #endif
  8715. destBuffer [len] = 0;
  8716. }
  8717. void String::copyToBuffer (juce_wchar* const destBuffer,
  8718. const int maxCharsToCopy) const throw()
  8719. {
  8720. const int len = jmin (maxCharsToCopy, length());
  8721. #if JUCE_STRINGS_ARE_UNICODE
  8722. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  8723. #else
  8724. CharacterFunctions::copy (destBuffer, text->text, len);
  8725. #endif
  8726. destBuffer [len] = 0;
  8727. }
  8728. int String::length() const throw()
  8729. {
  8730. return CharacterFunctions::length (text->text);
  8731. }
  8732. int String::hashCode() const throw()
  8733. {
  8734. const tchar* t = text->text;
  8735. int result = 0;
  8736. while (*t != (tchar) 0)
  8737. result = 31 * result + *t++;
  8738. return result;
  8739. }
  8740. int64 String::hashCode64() const throw()
  8741. {
  8742. const tchar* t = text->text;
  8743. int64 result = 0;
  8744. while (*t != (tchar) 0)
  8745. result = 101 * result + *t++;
  8746. return result;
  8747. }
  8748. const String& String::operator= (const tchar* const otherText) throw()
  8749. {
  8750. if (otherText != 0 && *otherText != 0)
  8751. {
  8752. const int otherLen = CharacterFunctions::length (otherText);
  8753. if (otherLen > 0)
  8754. {
  8755. // avoid resizing the memory block if the string is
  8756. // shrinking..
  8757. if (text->refCount > 1
  8758. || otherLen > text->allocatedNumChars
  8759. || otherLen <= (text->allocatedNumChars >> 1))
  8760. {
  8761. deleteInternal();
  8762. createInternal (otherLen);
  8763. }
  8764. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  8765. return *this;
  8766. }
  8767. }
  8768. deleteInternal();
  8769. text = &emptyString;
  8770. emptyString.refCount = safeEmptyStringRefCount;
  8771. return *this;
  8772. }
  8773. const String& String::operator= (const String& other) throw()
  8774. {
  8775. if (this != &other)
  8776. {
  8777. atomicIncrement (other.text->refCount);
  8778. if (atomicDecrementAndReturn (text->refCount) == 0)
  8779. juce_free (text);
  8780. text = other.text;
  8781. }
  8782. return *this;
  8783. }
  8784. bool String::operator== (const String& other) const throw()
  8785. {
  8786. return text == other.text
  8787. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  8788. }
  8789. bool String::operator== (const tchar* const t) const throw()
  8790. {
  8791. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  8792. : isEmpty();
  8793. }
  8794. bool String::equalsIgnoreCase (const tchar* t) const throw()
  8795. {
  8796. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  8797. : isEmpty();
  8798. }
  8799. bool String::equalsIgnoreCase (const String& other) const throw()
  8800. {
  8801. return text == other.text
  8802. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  8803. }
  8804. bool String::operator!= (const String& other) const throw()
  8805. {
  8806. return text != other.text
  8807. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  8808. }
  8809. bool String::operator!= (const tchar* const t) const throw()
  8810. {
  8811. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  8812. : isNotEmpty();
  8813. }
  8814. bool String::operator> (const String& other) const throw()
  8815. {
  8816. return compare (other) > 0;
  8817. }
  8818. bool String::operator< (const tchar* const other) const throw()
  8819. {
  8820. return compare (other) < 0;
  8821. }
  8822. bool String::operator>= (const String& other) const throw()
  8823. {
  8824. return compare (other) >= 0;
  8825. }
  8826. bool String::operator<= (const tchar* const other) const throw()
  8827. {
  8828. return compare (other) <= 0;
  8829. }
  8830. int String::compare (const tchar* const other) const throw()
  8831. {
  8832. return other != 0 ? CharacterFunctions::compare (text->text, other)
  8833. : isEmpty();
  8834. }
  8835. int String::compareIgnoreCase (const tchar* const other) const throw()
  8836. {
  8837. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  8838. : isEmpty();
  8839. }
  8840. int String::compareLexicographically (const tchar* other) const throw()
  8841. {
  8842. if (other == 0)
  8843. return isEmpty();
  8844. const tchar* s1 = text->text;
  8845. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8846. ++s1;
  8847. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  8848. ++other;
  8849. return CharacterFunctions::compareIgnoreCase (s1, other);
  8850. }
  8851. const String String::operator+ (const String& other) const throw()
  8852. {
  8853. if (*(other.text->text) == 0)
  8854. return *this;
  8855. if (isEmpty())
  8856. return other;
  8857. const int len = CharacterFunctions::length (text->text);
  8858. const int otherLen = CharacterFunctions::length (other.text->text);
  8859. String result (len + otherLen, (int) 0);
  8860. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8861. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  8862. result.text->text [len + otherLen] = 0;
  8863. return result;
  8864. }
  8865. const String String::operator+ (const tchar* const textToAppend) const throw()
  8866. {
  8867. if (textToAppend == 0 || *textToAppend == 0)
  8868. return *this;
  8869. const int len = CharacterFunctions::length (text->text);
  8870. const int otherLen = CharacterFunctions::length (textToAppend);
  8871. String result (len + otherLen, (int) 0);
  8872. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8873. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  8874. result.text->text [len + otherLen] = 0;
  8875. return result;
  8876. }
  8877. const String String::operator+ (const tchar characterToAppend) const throw()
  8878. {
  8879. if (characterToAppend == 0)
  8880. return *this;
  8881. const int len = CharacterFunctions::length (text->text);
  8882. String result ((int) (len + 1), (int) 0);
  8883. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8884. result.text->text[len] = characterToAppend;
  8885. result.text->text[len + 1] = 0;
  8886. return result;
  8887. }
  8888. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  8889. const String& string2) throw()
  8890. {
  8891. String s (string1);
  8892. s += string2;
  8893. return s;
  8894. }
  8895. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  8896. const String& string2) throw()
  8897. {
  8898. String s (string1);
  8899. s += string2;
  8900. return s;
  8901. }
  8902. const String& String::operator+= (const tchar* const t) throw()
  8903. {
  8904. if (t != 0)
  8905. appendInternal (t, CharacterFunctions::length (t));
  8906. return *this;
  8907. }
  8908. const String& String::operator+= (const String& other) throw()
  8909. {
  8910. if (isEmpty())
  8911. operator= (other);
  8912. else
  8913. appendInternal (other.text->text,
  8914. CharacterFunctions::length (other.text->text));
  8915. return *this;
  8916. }
  8917. const String& String::operator+= (const char ch) throw()
  8918. {
  8919. char asString[2];
  8920. asString[0] = ch;
  8921. asString[1] = 0;
  8922. #if JUCE_STRINGS_ARE_UNICODE
  8923. operator+= (String (asString));
  8924. #else
  8925. appendInternal (asString, 1);
  8926. #endif
  8927. return *this;
  8928. }
  8929. const String& String::operator+= (const juce_wchar ch) throw()
  8930. {
  8931. juce_wchar asString[2];
  8932. asString[0] = ch;
  8933. asString[1] = 0;
  8934. #if JUCE_STRINGS_ARE_UNICODE
  8935. appendInternal (asString, 1);
  8936. #else
  8937. operator+= (String (asString));
  8938. #endif
  8939. return *this;
  8940. }
  8941. void String::append (const tchar* const other,
  8942. const int howMany) throw()
  8943. {
  8944. if (howMany > 0)
  8945. {
  8946. int i;
  8947. for (i = 0; i < howMany; ++i)
  8948. if (other[i] == 0)
  8949. break;
  8950. appendInternal (other, i);
  8951. }
  8952. }
  8953. String& String::operator<< (const int number) throw()
  8954. {
  8955. tchar buffer [64];
  8956. tchar* const end = buffer + 64;
  8957. const tchar* const t = intToCharString (end, number);
  8958. appendInternal (t, (int) (end - t) - 1);
  8959. return *this;
  8960. }
  8961. String& String::operator<< (const unsigned int number) throw()
  8962. {
  8963. tchar buffer [64];
  8964. tchar* const end = buffer + 64;
  8965. const tchar* const t = uintToCharString (end, number);
  8966. appendInternal (t, (int) (end - t) - 1);
  8967. return *this;
  8968. }
  8969. String& String::operator<< (const short number) throw()
  8970. {
  8971. tchar buffer [64];
  8972. tchar* const end = buffer + 64;
  8973. const tchar* const t = intToCharString (end, (int) number);
  8974. appendInternal (t, (int) (end - t) - 1);
  8975. return *this;
  8976. }
  8977. String& String::operator<< (const double number) throw()
  8978. {
  8979. operator+= (String (number));
  8980. return *this;
  8981. }
  8982. String& String::operator<< (const float number) throw()
  8983. {
  8984. operator+= (String (number));
  8985. return *this;
  8986. }
  8987. String& String::operator<< (const char character) throw()
  8988. {
  8989. operator+= (character);
  8990. return *this;
  8991. }
  8992. String& String::operator<< (const juce_wchar character) throw()
  8993. {
  8994. operator+= (character);
  8995. return *this;
  8996. }
  8997. String& String::operator<< (const char* const t) throw()
  8998. {
  8999. #if JUCE_STRINGS_ARE_UNICODE
  9000. operator+= (String (t));
  9001. #else
  9002. operator+= (t);
  9003. #endif
  9004. return *this;
  9005. }
  9006. String& String::operator<< (const juce_wchar* const t) throw()
  9007. {
  9008. #if JUCE_STRINGS_ARE_UNICODE
  9009. operator+= (t);
  9010. #else
  9011. operator+= (String (t));
  9012. #endif
  9013. return *this;
  9014. }
  9015. String& String::operator<< (const String& t) throw()
  9016. {
  9017. operator+= (t);
  9018. return *this;
  9019. }
  9020. int String::indexOfChar (const tchar character) const throw()
  9021. {
  9022. const tchar* t = text->text;
  9023. for (;;)
  9024. {
  9025. if (*t == character)
  9026. return (int) (t - text->text);
  9027. if (*t++ == 0)
  9028. return -1;
  9029. }
  9030. }
  9031. int String::lastIndexOfChar (const tchar character) const throw()
  9032. {
  9033. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9034. if (text->text[i] == character)
  9035. return i;
  9036. return -1;
  9037. }
  9038. int String::indexOf (const tchar* const t) const throw()
  9039. {
  9040. const tchar* const r = CharacterFunctions::find (text->text, t);
  9041. return (r == 0) ? -1
  9042. : (int) (r - text->text);
  9043. }
  9044. int String::indexOfChar (const int startIndex,
  9045. const tchar character) const throw()
  9046. {
  9047. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  9048. return -1;
  9049. const tchar* t = text->text + jmax (0, startIndex);
  9050. for (;;)
  9051. {
  9052. if (*t == character)
  9053. return (int) (t - text->text);
  9054. if (*t++ == 0)
  9055. return -1;
  9056. }
  9057. }
  9058. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  9059. const int startIndex,
  9060. const bool ignoreCase) const throw()
  9061. {
  9062. if (charactersToLookFor == 0
  9063. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  9064. return -1;
  9065. const tchar* t = text->text + jmax (0, startIndex);
  9066. while (*t != 0)
  9067. {
  9068. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  9069. return (int) (t - text->text);
  9070. ++t;
  9071. }
  9072. return -1;
  9073. }
  9074. int String::indexOf (const int startIndex,
  9075. const tchar* const other) const throw()
  9076. {
  9077. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  9078. return -1;
  9079. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  9080. other);
  9081. return (found == 0) ? -1
  9082. : (int) (found - text->text);
  9083. }
  9084. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  9085. {
  9086. if (other != 0 && *other != 0)
  9087. {
  9088. const int len = CharacterFunctions::length (other);
  9089. const int end = CharacterFunctions::length (text->text) - len;
  9090. for (int i = 0; i <= end; ++i)
  9091. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  9092. return i;
  9093. }
  9094. return -1;
  9095. }
  9096. int String::indexOfIgnoreCase (const int startIndex,
  9097. const tchar* const other) const throw()
  9098. {
  9099. if (other != 0 && *other != 0)
  9100. {
  9101. const int len = CharacterFunctions::length (other);
  9102. const int end = length() - len;
  9103. for (int i = jmax (0, startIndex); i <= end; ++i)
  9104. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  9105. return i;
  9106. }
  9107. return -1;
  9108. }
  9109. int String::lastIndexOf (const tchar* const other) const throw()
  9110. {
  9111. if (other != 0 && *other != 0)
  9112. {
  9113. const int len = CharacterFunctions::length (other);
  9114. int i = length() - len;
  9115. if (i >= 0)
  9116. {
  9117. const tchar* n = text->text + i;
  9118. while (i >= 0)
  9119. {
  9120. if (CharacterFunctions::compare (n--, other, len) == 0)
  9121. return i;
  9122. --i;
  9123. }
  9124. }
  9125. }
  9126. return -1;
  9127. }
  9128. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  9129. {
  9130. if (other != 0 && *other != 0)
  9131. {
  9132. const int len = CharacterFunctions::length (other);
  9133. int i = length() - len;
  9134. if (i >= 0)
  9135. {
  9136. const tchar* n = text->text + i;
  9137. while (i >= 0)
  9138. {
  9139. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  9140. return i;
  9141. --i;
  9142. }
  9143. }
  9144. }
  9145. return -1;
  9146. }
  9147. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  9148. const bool ignoreCase) const throw()
  9149. {
  9150. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9151. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  9152. return i;
  9153. return -1;
  9154. }
  9155. bool String::contains (const tchar* const other) const throw()
  9156. {
  9157. return indexOf (other) >= 0;
  9158. }
  9159. bool String::containsChar (const tchar character) const throw()
  9160. {
  9161. return indexOfChar (character) >= 0;
  9162. }
  9163. bool String::containsIgnoreCase (const tchar* const t) const throw()
  9164. {
  9165. return indexOfIgnoreCase (t) >= 0;
  9166. }
  9167. int String::indexOfWholeWord (const tchar* const word) const throw()
  9168. {
  9169. if (word != 0 && *word != 0)
  9170. {
  9171. const int wordLen = CharacterFunctions::length (word);
  9172. const int end = length() - wordLen;
  9173. const tchar* t = text->text;
  9174. for (int i = 0; i <= end; ++i)
  9175. {
  9176. if (CharacterFunctions::compare (t, word, wordLen) == 0
  9177. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9178. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9179. {
  9180. return i;
  9181. }
  9182. ++t;
  9183. }
  9184. }
  9185. return -1;
  9186. }
  9187. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  9188. {
  9189. if (word != 0 && *word != 0)
  9190. {
  9191. const int wordLen = CharacterFunctions::length (word);
  9192. const int end = length() - wordLen;
  9193. const tchar* t = text->text;
  9194. for (int i = 0; i <= end; ++i)
  9195. {
  9196. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  9197. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9198. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9199. {
  9200. return i;
  9201. }
  9202. ++t;
  9203. }
  9204. }
  9205. return -1;
  9206. }
  9207. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  9208. {
  9209. return indexOfWholeWord (wordToLookFor) >= 0;
  9210. }
  9211. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  9212. {
  9213. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9214. }
  9215. static int indexOfMatch (const tchar* const wildcard,
  9216. const tchar* const test,
  9217. const bool ignoreCase) throw()
  9218. {
  9219. int start = 0;
  9220. while (test [start] != 0)
  9221. {
  9222. int i = 0;
  9223. for (;;)
  9224. {
  9225. const tchar wc = wildcard [i];
  9226. const tchar c = test [i + start];
  9227. if (wc == c
  9228. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9229. || (wc == T('?') && c != 0))
  9230. {
  9231. if (wc == 0)
  9232. return start;
  9233. ++i;
  9234. }
  9235. else
  9236. {
  9237. if (wc == T('*') && (wildcard [i + 1] == 0
  9238. || indexOfMatch (wildcard + i + 1,
  9239. test + start + i,
  9240. ignoreCase) >= 0))
  9241. {
  9242. return start;
  9243. }
  9244. break;
  9245. }
  9246. }
  9247. ++start;
  9248. }
  9249. return -1;
  9250. }
  9251. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  9252. {
  9253. int i = 0;
  9254. for (;;)
  9255. {
  9256. const tchar wc = wildcard [i];
  9257. const tchar c = text->text [i];
  9258. if (wc == c
  9259. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9260. || (wc == T('?') && c != 0))
  9261. {
  9262. if (wc == 0)
  9263. return true;
  9264. ++i;
  9265. }
  9266. else
  9267. {
  9268. return wc == T('*') && (wildcard [i + 1] == 0
  9269. || indexOfMatch (wildcard + i + 1,
  9270. text->text + i,
  9271. ignoreCase) >= 0);
  9272. }
  9273. }
  9274. }
  9275. void String::printf (const tchar* const pf, ...) throw()
  9276. {
  9277. va_list list;
  9278. va_start (list, pf);
  9279. vprintf (pf, list);
  9280. }
  9281. const String String::formatted (const tchar* const pf, ...) throw()
  9282. {
  9283. va_list list;
  9284. va_start (list, pf);
  9285. String result;
  9286. result.vprintf (pf, list);
  9287. return result;
  9288. }
  9289. void String::vprintf (const tchar* const pf, va_list& args) throw()
  9290. {
  9291. tchar stackBuf [256];
  9292. unsigned int bufSize = 256;
  9293. tchar* buf = stackBuf;
  9294. deleteInternal();
  9295. do
  9296. {
  9297. #if JUCE_LINUX && JUCE_64BIT
  9298. va_list tempArgs;
  9299. va_copy (tempArgs, args);
  9300. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  9301. va_end (tempArgs);
  9302. #else
  9303. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  9304. #endif
  9305. if (num > 0)
  9306. {
  9307. createInternal (num);
  9308. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  9309. break;
  9310. }
  9311. else if (num == 0)
  9312. {
  9313. text = &emptyString;
  9314. emptyString.refCount = safeEmptyStringRefCount;
  9315. break;
  9316. }
  9317. if (buf != stackBuf)
  9318. juce_free (buf);
  9319. bufSize += 256;
  9320. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  9321. }
  9322. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  9323. // returns -1 because of an error rather than because it needs more space.
  9324. if (buf != stackBuf)
  9325. juce_free (buf);
  9326. }
  9327. const String String::repeatedString (const tchar* const stringToRepeat,
  9328. int numberOfTimesToRepeat) throw()
  9329. {
  9330. const int len = CharacterFunctions::length (stringToRepeat);
  9331. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  9332. tchar* n = result.text->text;
  9333. n[0] = 0;
  9334. while (--numberOfTimesToRepeat >= 0)
  9335. {
  9336. CharacterFunctions::append (n, stringToRepeat);
  9337. n += len;
  9338. }
  9339. return result;
  9340. }
  9341. const String String::replaceSection (int index,
  9342. int numCharsToReplace,
  9343. const tchar* const stringToInsert) const throw()
  9344. {
  9345. if (index < 0)
  9346. {
  9347. // a negative index to replace from?
  9348. jassertfalse
  9349. index = 0;
  9350. }
  9351. if (numCharsToReplace < 0)
  9352. {
  9353. // replacing a negative number of characters?
  9354. numCharsToReplace = 0;
  9355. jassertfalse;
  9356. }
  9357. const int len = length();
  9358. if (index + numCharsToReplace > len)
  9359. {
  9360. if (index > len)
  9361. {
  9362. // replacing beyond the end of the string?
  9363. index = len;
  9364. jassertfalse
  9365. }
  9366. numCharsToReplace = len - index;
  9367. }
  9368. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  9369. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9370. if (newTotalLen <= 0)
  9371. return String::empty;
  9372. String result (newTotalLen, (int) 0);
  9373. memcpy (result.text->text,
  9374. text->text,
  9375. index * sizeof (tchar));
  9376. if (newStringLen > 0)
  9377. memcpy (result.text->text + index,
  9378. stringToInsert,
  9379. newStringLen * sizeof (tchar));
  9380. const int endStringLen = newTotalLen - (index + newStringLen);
  9381. if (endStringLen > 0)
  9382. memcpy (result.text->text + (index + newStringLen),
  9383. text->text + (index + numCharsToReplace),
  9384. endStringLen * sizeof (tchar));
  9385. result.text->text [newTotalLen] = 0;
  9386. return result;
  9387. }
  9388. const String String::replace (const tchar* const stringToReplace,
  9389. const tchar* const stringToInsert,
  9390. const bool ignoreCase) const throw()
  9391. {
  9392. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  9393. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  9394. int i = 0;
  9395. String result (*this);
  9396. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9397. : result.indexOf (i, stringToReplace))) >= 0)
  9398. {
  9399. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9400. i += stringToInsertLen;
  9401. }
  9402. return result;
  9403. }
  9404. const String String::replaceCharacter (const tchar charToReplace,
  9405. const tchar charToInsert) const throw()
  9406. {
  9407. const int index = indexOfChar (charToReplace);
  9408. if (index < 0)
  9409. return *this;
  9410. String result (*this);
  9411. result.dupeInternalIfMultiplyReferenced();
  9412. tchar* t = result.text->text + index;
  9413. while (*t != 0)
  9414. {
  9415. if (*t == charToReplace)
  9416. *t = charToInsert;
  9417. ++t;
  9418. }
  9419. return result;
  9420. }
  9421. const String String::replaceCharacters (const String& charactersToReplace,
  9422. const tchar* const charactersToInsertInstead) const throw()
  9423. {
  9424. String result (*this);
  9425. result.dupeInternalIfMultiplyReferenced();
  9426. tchar* t = result.text->text;
  9427. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  9428. // the two strings passed in are supposed to be the same length!
  9429. jassert (len2 == charactersToReplace.length());
  9430. while (*t != 0)
  9431. {
  9432. const int index = charactersToReplace.indexOfChar (*t);
  9433. if (((unsigned int) index) < (unsigned int) len2)
  9434. *t = charactersToInsertInstead [index];
  9435. ++t;
  9436. }
  9437. return result;
  9438. }
  9439. bool String::startsWith (const tchar* const other) const throw()
  9440. {
  9441. return other != 0
  9442. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  9443. }
  9444. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  9445. {
  9446. return other != 0
  9447. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  9448. }
  9449. bool String::startsWithChar (const tchar character) const throw()
  9450. {
  9451. jassert (character != 0); // strings can't contain a null character!
  9452. return text->text[0] == character;
  9453. }
  9454. bool String::endsWithChar (const tchar character) const throw()
  9455. {
  9456. jassert (character != 0); // strings can't contain a null character!
  9457. return text->text[0] != 0
  9458. && text->text [length() - 1] == character;
  9459. }
  9460. bool String::endsWith (const tchar* const other) const throw()
  9461. {
  9462. if (other == 0)
  9463. return false;
  9464. const int thisLen = length();
  9465. const int otherLen = CharacterFunctions::length (other);
  9466. return thisLen >= otherLen
  9467. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  9468. }
  9469. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  9470. {
  9471. if (other == 0)
  9472. return false;
  9473. const int thisLen = length();
  9474. const int otherLen = CharacterFunctions::length (other);
  9475. return thisLen >= otherLen
  9476. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  9477. }
  9478. const String String::toUpperCase() const throw()
  9479. {
  9480. String result (*this);
  9481. result.dupeInternalIfMultiplyReferenced();
  9482. CharacterFunctions::toUpperCase (result.text->text);
  9483. return result;
  9484. }
  9485. const String String::toLowerCase() const throw()
  9486. {
  9487. String result (*this);
  9488. result.dupeInternalIfMultiplyReferenced();
  9489. CharacterFunctions::toLowerCase (result.text->text);
  9490. return result;
  9491. }
  9492. tchar& String::operator[] (const int index) throw()
  9493. {
  9494. jassert (((unsigned int) index) <= (unsigned int) length());
  9495. dupeInternalIfMultiplyReferenced();
  9496. return text->text [index];
  9497. }
  9498. tchar String::getLastCharacter() const throw()
  9499. {
  9500. return (isEmpty()) ? ((tchar) 0)
  9501. : text->text [CharacterFunctions::length (text->text) - 1];
  9502. }
  9503. const String String::substring (int start, int end) const throw()
  9504. {
  9505. if (start < 0)
  9506. start = 0;
  9507. else if (end <= start)
  9508. return empty;
  9509. int len = 0;
  9510. const tchar* const t = text->text;
  9511. while (len <= end && t [len] != 0)
  9512. ++len;
  9513. if (end >= len)
  9514. {
  9515. if (start == 0)
  9516. return *this;
  9517. end = len;
  9518. }
  9519. return String (text->text + start,
  9520. end - start);
  9521. }
  9522. const String String::substring (const int start) const throw()
  9523. {
  9524. if (start <= 0)
  9525. return *this;
  9526. const int len = CharacterFunctions::length (text->text);
  9527. if (start >= len)
  9528. return empty;
  9529. else
  9530. return String (text->text + start,
  9531. len - start);
  9532. }
  9533. const String String::dropLastCharacters (const int numberToDrop) const throw()
  9534. {
  9535. return String (text->text,
  9536. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  9537. }
  9538. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  9539. const bool includeSubString,
  9540. const bool ignoreCase) const throw()
  9541. {
  9542. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9543. : indexOf (sub);
  9544. if (i < 0)
  9545. return empty;
  9546. else
  9547. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9548. }
  9549. const String String::fromLastOccurrenceOf (const tchar* const sub,
  9550. const bool includeSubString,
  9551. const bool ignoreCase) const throw()
  9552. {
  9553. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9554. : lastIndexOf (sub);
  9555. if (i < 0)
  9556. return *this;
  9557. else
  9558. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9559. }
  9560. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  9561. const bool includeSubString,
  9562. const bool ignoreCase) const throw()
  9563. {
  9564. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9565. : indexOf (sub);
  9566. if (i < 0)
  9567. return *this;
  9568. else
  9569. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9570. }
  9571. const String String::upToLastOccurrenceOf (const tchar* const sub,
  9572. const bool includeSubString,
  9573. const bool ignoreCase) const throw()
  9574. {
  9575. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9576. : lastIndexOf (sub);
  9577. if (i < 0)
  9578. return *this;
  9579. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9580. }
  9581. bool String::isQuotedString() const throw()
  9582. {
  9583. const String trimmed (trimStart());
  9584. return trimmed[0] == T('"')
  9585. || trimmed[0] == T('\'');
  9586. }
  9587. const String String::unquoted() const throw()
  9588. {
  9589. String s (*this);
  9590. if (s[0] == T('"') || s[0] == T('\''))
  9591. s = s.substring (1);
  9592. const int lastCharIndex = s.length() - 1;
  9593. if (lastCharIndex >= 0
  9594. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  9595. s [lastCharIndex] = 0;
  9596. return s;
  9597. }
  9598. const String String::quoted (const tchar quoteCharacter) const throw()
  9599. {
  9600. if (isEmpty())
  9601. return charToString (quoteCharacter) + quoteCharacter;
  9602. String t (*this);
  9603. if (! t.startsWithChar (quoteCharacter))
  9604. t = charToString (quoteCharacter) + t;
  9605. if (! t.endsWithChar (quoteCharacter))
  9606. t += quoteCharacter;
  9607. return t;
  9608. }
  9609. const String String::trim() const throw()
  9610. {
  9611. if (isEmpty())
  9612. return empty;
  9613. int start = 0;
  9614. while (CharacterFunctions::isWhitespace (text->text [start]))
  9615. ++start;
  9616. const int len = CharacterFunctions::length (text->text);
  9617. int end = len - 1;
  9618. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  9619. --end;
  9620. ++end;
  9621. if (end <= start)
  9622. return empty;
  9623. else if (start > 0 || end < len)
  9624. return String (text->text + start, end - start);
  9625. else
  9626. return *this;
  9627. }
  9628. const String String::trimStart() const throw()
  9629. {
  9630. if (isEmpty())
  9631. return empty;
  9632. const tchar* t = text->text;
  9633. while (CharacterFunctions::isWhitespace (*t))
  9634. ++t;
  9635. if (t == text->text)
  9636. return *this;
  9637. else
  9638. return String (t);
  9639. }
  9640. const String String::trimEnd() const throw()
  9641. {
  9642. if (isEmpty())
  9643. return empty;
  9644. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  9645. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  9646. --endT;
  9647. return String (text->text, (int) (++endT - text->text));
  9648. }
  9649. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  9650. {
  9651. jassert (charactersToRetain != 0);
  9652. if (isEmpty())
  9653. return empty;
  9654. String result (text->allocatedNumChars, (int) 0);
  9655. tchar* dst = result.text->text;
  9656. const tchar* src = text->text;
  9657. while (*src != 0)
  9658. {
  9659. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  9660. *dst++ = *src;
  9661. ++src;
  9662. }
  9663. *dst = 0;
  9664. return result;
  9665. }
  9666. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  9667. {
  9668. jassert (charactersToRemove != 0);
  9669. if (isEmpty())
  9670. return empty;
  9671. String result (text->allocatedNumChars, (int) 0);
  9672. tchar* dst = result.text->text;
  9673. const tchar* src = text->text;
  9674. while (*src != 0)
  9675. {
  9676. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  9677. *dst++ = *src;
  9678. ++src;
  9679. }
  9680. *dst = 0;
  9681. return result;
  9682. }
  9683. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  9684. {
  9685. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  9686. }
  9687. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  9688. {
  9689. jassert (charactersToStopAt != 0);
  9690. const tchar* const t = text->text;
  9691. int i = 0;
  9692. while (t[i] != 0)
  9693. {
  9694. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  9695. return String (text->text, i);
  9696. ++i;
  9697. }
  9698. return empty;
  9699. }
  9700. bool String::containsOnly (const tchar* const chars) const throw()
  9701. {
  9702. jassert (chars != 0);
  9703. const tchar* t = text->text;
  9704. while (*t != 0)
  9705. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  9706. return false;
  9707. return true;
  9708. }
  9709. bool String::containsAnyOf (const tchar* const chars) const throw()
  9710. {
  9711. jassert (chars != 0);
  9712. const tchar* t = text->text;
  9713. while (*t != 0)
  9714. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  9715. return true;
  9716. return false;
  9717. }
  9718. bool String::containsNonWhitespaceChars() const throw()
  9719. {
  9720. const tchar* t = text->text;
  9721. while (*t != 0)
  9722. if (! CharacterFunctions::isWhitespace (*t++))
  9723. return true;
  9724. return false;
  9725. }
  9726. int String::getIntValue() const throw()
  9727. {
  9728. return CharacterFunctions::getIntValue (text->text);
  9729. }
  9730. int String::getTrailingIntValue() const throw()
  9731. {
  9732. int n = 0;
  9733. int mult = 1;
  9734. const tchar* t = text->text + length();
  9735. while (--t >= text->text)
  9736. {
  9737. const tchar c = *t;
  9738. if (! CharacterFunctions::isDigit (c))
  9739. {
  9740. if (c == T('-'))
  9741. n = -n;
  9742. break;
  9743. }
  9744. n += mult * (c - T('0'));
  9745. mult *= 10;
  9746. }
  9747. return n;
  9748. }
  9749. int64 String::getLargeIntValue() const throw()
  9750. {
  9751. return CharacterFunctions::getInt64Value (text->text);
  9752. }
  9753. float String::getFloatValue() const throw()
  9754. {
  9755. return (float) CharacterFunctions::getDoubleValue (text->text);
  9756. }
  9757. double String::getDoubleValue() const throw()
  9758. {
  9759. return CharacterFunctions::getDoubleValue (text->text);
  9760. }
  9761. static const tchar* const hexDigits = T("0123456789abcdef");
  9762. const String String::toHexString (const int number) throw()
  9763. {
  9764. tchar buffer[32];
  9765. tchar* const end = buffer + 32;
  9766. tchar* t = end;
  9767. *--t = 0;
  9768. unsigned int v = (unsigned int) number;
  9769. do
  9770. {
  9771. *--t = hexDigits [v & 15];
  9772. v >>= 4;
  9773. } while (v != 0);
  9774. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9775. }
  9776. const String String::toHexString (const int64 number) throw()
  9777. {
  9778. tchar buffer[32];
  9779. tchar* const end = buffer + 32;
  9780. tchar* t = end;
  9781. *--t = 0;
  9782. uint64 v = (uint64) number;
  9783. do
  9784. {
  9785. *--t = hexDigits [(int) (v & 15)];
  9786. v >>= 4;
  9787. } while (v != 0);
  9788. return String (t, (int) (((char*) end) - (char*) t));
  9789. }
  9790. const String String::toHexString (const short number) throw()
  9791. {
  9792. return toHexString ((int) (unsigned short) number);
  9793. }
  9794. const String String::toHexString (const unsigned char* data,
  9795. const int size,
  9796. const int groupSize) throw()
  9797. {
  9798. if (size <= 0)
  9799. return empty;
  9800. int numChars = (size * 2) + 2;
  9801. if (groupSize > 0)
  9802. numChars += size / groupSize;
  9803. String s (numChars, (int) 0);
  9804. tchar* d = s.text->text;
  9805. for (int i = 0; i < size; ++i)
  9806. {
  9807. *d++ = hexDigits [(*data) >> 4];
  9808. *d++ = hexDigits [(*data) & 0xf];
  9809. ++data;
  9810. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9811. *d++ = T(' ');
  9812. }
  9813. *d = 0;
  9814. return s;
  9815. }
  9816. int String::getHexValue32() const throw()
  9817. {
  9818. int result = 0;
  9819. const tchar* c = text->text;
  9820. for (;;)
  9821. {
  9822. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9823. if (hexValue >= 0)
  9824. result = (result << 4) | hexValue;
  9825. else if (*c == 0)
  9826. break;
  9827. ++c;
  9828. }
  9829. return result;
  9830. }
  9831. int64 String::getHexValue64() const throw()
  9832. {
  9833. int64 result = 0;
  9834. const tchar* c = text->text;
  9835. for (;;)
  9836. {
  9837. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9838. if (hexValue >= 0)
  9839. result = (result << 4) | hexValue;
  9840. else if (*c == 0)
  9841. break;
  9842. ++c;
  9843. }
  9844. return result;
  9845. }
  9846. const String String::createStringFromData (const void* const data_,
  9847. const int size) throw()
  9848. {
  9849. const char* const data = (const char*) data_;
  9850. if (size <= 0 || data == 0)
  9851. {
  9852. return empty;
  9853. }
  9854. else if (size < 2)
  9855. {
  9856. return charToString (data[0]);
  9857. }
  9858. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9859. || (data[0] == (char)-1 && data[1] == (char)-2))
  9860. {
  9861. // assume it's 16-bit unicode
  9862. const bool bigEndian = (data[0] == (char)-2);
  9863. const int numChars = size / 2 - 1;
  9864. String result;
  9865. result.preallocateStorage (numChars + 2);
  9866. const uint16* const src = (const uint16*) (data + 2);
  9867. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  9868. if (bigEndian)
  9869. {
  9870. for (int i = 0; i < numChars; ++i)
  9871. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  9872. }
  9873. else
  9874. {
  9875. for (int i = 0; i < numChars; ++i)
  9876. dst[i] = (tchar) swapIfBigEndian (src[i]);
  9877. }
  9878. dst [numChars] = 0;
  9879. return result;
  9880. }
  9881. else
  9882. {
  9883. return String::fromUTF8 ((const uint8*) data, size);
  9884. }
  9885. }
  9886. const char* String::toUTF8() const throw()
  9887. {
  9888. if (isEmpty())
  9889. {
  9890. return (const char*) emptyCharString;
  9891. }
  9892. else
  9893. {
  9894. String* const mutableThis = const_cast <String*> (this);
  9895. mutableThis->dupeInternalIfMultiplyReferenced();
  9896. const int currentLen = CharacterFunctions::length (text->text) + 1;
  9897. const int utf8BytesNeeded = copyToUTF8 (0);
  9898. mutableThis->text = (InternalRefCountedStringHolder*)
  9899. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  9900. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  9901. char* const otherCopy = (char*) (text->text + currentLen);
  9902. copyToUTF8 ((uint8*) otherCopy);
  9903. return otherCopy;
  9904. }
  9905. }
  9906. int String::copyToUTF8 (uint8* const buffer, const int maxBufferSizeBytes) const throw()
  9907. {
  9908. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9909. #if JUCE_STRINGS_ARE_UNICODE
  9910. int num = 0, index = 0;
  9911. for (;;)
  9912. {
  9913. const uint32 c = (uint32) text->text [index++];
  9914. if (c >= 0x80)
  9915. {
  9916. int numExtraBytes = 1;
  9917. if (c >= 0x800)
  9918. {
  9919. ++numExtraBytes;
  9920. if (c >= 0x10000)
  9921. {
  9922. ++numExtraBytes;
  9923. if (c >= 0x200000)
  9924. {
  9925. ++numExtraBytes;
  9926. if (c >= 0x4000000)
  9927. ++numExtraBytes;
  9928. }
  9929. }
  9930. }
  9931. if (buffer != 0)
  9932. {
  9933. if (num + numExtraBytes >= maxBufferSizeBytes)
  9934. {
  9935. buffer [num++] = 0;
  9936. break;
  9937. }
  9938. else
  9939. {
  9940. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9941. while (--numExtraBytes >= 0)
  9942. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9943. }
  9944. }
  9945. else
  9946. {
  9947. num += numExtraBytes + 1;
  9948. }
  9949. }
  9950. else
  9951. {
  9952. if (buffer != 0)
  9953. {
  9954. if (num + 1 >= maxBufferSizeBytes)
  9955. {
  9956. buffer [num++] = 0;
  9957. break;
  9958. }
  9959. buffer [num] = (uint8) c;
  9960. }
  9961. ++num;
  9962. }
  9963. if (c == 0)
  9964. break;
  9965. }
  9966. return num;
  9967. #else
  9968. const int numBytes = jmin (maxBufferSizeBytes, length() + 1);
  9969. if (buffer != 0)
  9970. copyToBuffer ((char*) buffer, maxBufferSizeBytes);
  9971. return numBytes;
  9972. #endif
  9973. }
  9974. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  9975. {
  9976. if (buffer == 0)
  9977. return empty;
  9978. if (bufferSizeBytes < 0)
  9979. bufferSizeBytes = INT_MAX;
  9980. int numBytes;
  9981. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  9982. if (buffer [numBytes] == 0)
  9983. break;
  9984. String result (numBytes + 1, 0);
  9985. tchar* dest = result.text->text;
  9986. int i = 0;
  9987. while (i < numBytes)
  9988. {
  9989. const uint8 c = buffer [i++];
  9990. if ((c & 0x80) != 0)
  9991. {
  9992. int mask = 0x7f;
  9993. int bit = 0x40;
  9994. int numExtraValues = 0;
  9995. while (bit != 0 && (c & bit) != 0)
  9996. {
  9997. bit >>= 1;
  9998. mask >>= 1;
  9999. ++numExtraValues;
  10000. }
  10001. int n = (c & mask);
  10002. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  10003. {
  10004. const uint8 c = buffer[i];
  10005. if ((c & 0xc0) != 0x80)
  10006. break;
  10007. n <<= 6;
  10008. n |= (c & 0x3f);
  10009. ++i;
  10010. }
  10011. *dest++ = (tchar) n;
  10012. }
  10013. else
  10014. {
  10015. *dest++ = (tchar) c;
  10016. }
  10017. }
  10018. *dest = 0;
  10019. return result;
  10020. }
  10021. END_JUCE_NAMESPACE
  10022. /********* End of inlined file: juce_String.cpp *********/
  10023. /********* Start of inlined file: juce_StringArray.cpp *********/
  10024. BEGIN_JUCE_NAMESPACE
  10025. StringArray::StringArray() throw()
  10026. {
  10027. }
  10028. StringArray::StringArray (const StringArray& other) throw()
  10029. {
  10030. addArray (other);
  10031. }
  10032. StringArray::StringArray (const juce_wchar** const strings,
  10033. const int numberOfStrings) throw()
  10034. {
  10035. for (int i = 0; i < numberOfStrings; ++i)
  10036. add (strings [i]);
  10037. }
  10038. StringArray::StringArray (const char** const strings,
  10039. const int numberOfStrings) throw()
  10040. {
  10041. for (int i = 0; i < numberOfStrings; ++i)
  10042. add (strings [i]);
  10043. }
  10044. StringArray::StringArray (const juce_wchar** const strings) throw()
  10045. {
  10046. int i = 0;
  10047. while (strings[i] != 0)
  10048. add (strings [i++]);
  10049. }
  10050. StringArray::StringArray (const char** const strings) throw()
  10051. {
  10052. int i = 0;
  10053. while (strings[i] != 0)
  10054. add (strings [i++]);
  10055. }
  10056. const StringArray& StringArray::operator= (const StringArray& other) throw()
  10057. {
  10058. if (this != &other)
  10059. {
  10060. clear();
  10061. addArray (other);
  10062. }
  10063. return *this;
  10064. }
  10065. StringArray::~StringArray() throw()
  10066. {
  10067. clear();
  10068. }
  10069. bool StringArray::operator== (const StringArray& other) const throw()
  10070. {
  10071. if (other.size() != size())
  10072. return false;
  10073. for (int i = size(); --i >= 0;)
  10074. {
  10075. if (*(String*) other.strings.getUnchecked(i)
  10076. != *(String*) strings.getUnchecked(i))
  10077. {
  10078. return false;
  10079. }
  10080. }
  10081. return true;
  10082. }
  10083. bool StringArray::operator!= (const StringArray& other) const throw()
  10084. {
  10085. return ! operator== (other);
  10086. }
  10087. void StringArray::clear() throw()
  10088. {
  10089. for (int i = size(); --i >= 0;)
  10090. {
  10091. String* const s = (String*) strings.getUnchecked(i);
  10092. delete s;
  10093. }
  10094. strings.clear();
  10095. }
  10096. const String& StringArray::operator[] (const int index) const throw()
  10097. {
  10098. if (((unsigned int) index) < (unsigned int) strings.size())
  10099. return *(const String*) (strings.getUnchecked (index));
  10100. return String::empty;
  10101. }
  10102. void StringArray::add (const String& newString) throw()
  10103. {
  10104. strings.add (new String (newString));
  10105. }
  10106. void StringArray::insert (const int index,
  10107. const String& newString) throw()
  10108. {
  10109. strings.insert (index, new String (newString));
  10110. }
  10111. void StringArray::addIfNotAlreadyThere (const String& newString,
  10112. const bool ignoreCase) throw()
  10113. {
  10114. if (! contains (newString, ignoreCase))
  10115. add (newString);
  10116. }
  10117. void StringArray::addArray (const StringArray& otherArray,
  10118. int startIndex,
  10119. int numElementsToAdd) throw()
  10120. {
  10121. if (startIndex < 0)
  10122. {
  10123. jassertfalse
  10124. startIndex = 0;
  10125. }
  10126. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10127. numElementsToAdd = otherArray.size() - startIndex;
  10128. while (--numElementsToAdd >= 0)
  10129. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  10130. }
  10131. void StringArray::set (const int index,
  10132. const String& newString) throw()
  10133. {
  10134. String* const s = (String*) strings [index];
  10135. if (s != 0)
  10136. {
  10137. *s = newString;
  10138. }
  10139. else if (index >= 0)
  10140. {
  10141. add (newString);
  10142. }
  10143. }
  10144. bool StringArray::contains (const String& stringToLookFor,
  10145. const bool ignoreCase) const throw()
  10146. {
  10147. if (ignoreCase)
  10148. {
  10149. for (int i = size(); --i >= 0;)
  10150. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  10151. return true;
  10152. }
  10153. else
  10154. {
  10155. for (int i = size(); --i >= 0;)
  10156. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  10157. return true;
  10158. }
  10159. return false;
  10160. }
  10161. int StringArray::indexOf (const String& stringToLookFor,
  10162. const bool ignoreCase,
  10163. int i) const throw()
  10164. {
  10165. if (i < 0)
  10166. i = 0;
  10167. const int numElements = size();
  10168. if (ignoreCase)
  10169. {
  10170. while (i < numElements)
  10171. {
  10172. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10173. return i;
  10174. ++i;
  10175. }
  10176. }
  10177. else
  10178. {
  10179. while (i < numElements)
  10180. {
  10181. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  10182. return i;
  10183. ++i;
  10184. }
  10185. }
  10186. return -1;
  10187. }
  10188. void StringArray::remove (const int index) throw()
  10189. {
  10190. String* const s = (String*) strings [index];
  10191. if (s != 0)
  10192. {
  10193. strings.remove (index);
  10194. delete s;
  10195. }
  10196. }
  10197. void StringArray::removeString (const String& stringToRemove,
  10198. const bool ignoreCase) throw()
  10199. {
  10200. if (ignoreCase)
  10201. {
  10202. for (int i = size(); --i >= 0;)
  10203. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10204. remove (i);
  10205. }
  10206. else
  10207. {
  10208. for (int i = size(); --i >= 0;)
  10209. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  10210. remove (i);
  10211. }
  10212. }
  10213. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  10214. {
  10215. if (removeWhitespaceStrings)
  10216. {
  10217. for (int i = size(); --i >= 0;)
  10218. if (! ((const String*) strings.getUnchecked(i))->containsNonWhitespaceChars())
  10219. remove (i);
  10220. }
  10221. else
  10222. {
  10223. for (int i = size(); --i >= 0;)
  10224. if (((const String*) strings.getUnchecked(i))->isEmpty())
  10225. remove (i);
  10226. }
  10227. }
  10228. void StringArray::trim() throw()
  10229. {
  10230. for (int i = size(); --i >= 0;)
  10231. {
  10232. String& s = *(String*) strings.getUnchecked(i);
  10233. s = s.trim();
  10234. }
  10235. }
  10236. class InternalStringArrayComparator
  10237. {
  10238. public:
  10239. static int compareElements (void* const first, void* const second) throw()
  10240. {
  10241. return ((const String*) first)->compare (*(const String*) second);
  10242. }
  10243. };
  10244. class InsensitiveInternalStringArrayComparator
  10245. {
  10246. public:
  10247. static int compareElements (void* const first, void* const second) throw()
  10248. {
  10249. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  10250. }
  10251. };
  10252. void StringArray::sort (const bool ignoreCase) throw()
  10253. {
  10254. if (ignoreCase)
  10255. {
  10256. InsensitiveInternalStringArrayComparator comp;
  10257. strings.sort (comp);
  10258. }
  10259. else
  10260. {
  10261. InternalStringArrayComparator comp;
  10262. strings.sort (comp);
  10263. }
  10264. }
  10265. void StringArray::move (const int currentIndex, int newIndex) throw()
  10266. {
  10267. strings.move (currentIndex, newIndex);
  10268. }
  10269. const String StringArray::joinIntoString (const String& separator,
  10270. int start,
  10271. int numberToJoin) const throw()
  10272. {
  10273. const int last = (numberToJoin < 0) ? size()
  10274. : jmin (size(), start + numberToJoin);
  10275. if (start < 0)
  10276. start = 0;
  10277. if (start >= last)
  10278. return String::empty;
  10279. if (start == last - 1)
  10280. return *(const String*) strings.getUnchecked (start);
  10281. const int separatorLen = separator.length();
  10282. int charsNeeded = separatorLen * (last - start - 1);
  10283. for (int i = start; i < last; ++i)
  10284. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  10285. String result;
  10286. result.preallocateStorage (charsNeeded);
  10287. tchar* dest = (tchar*) (const tchar*) result;
  10288. while (start < last)
  10289. {
  10290. const String& s = *(const String*) strings.getUnchecked (start);
  10291. const int len = s.length();
  10292. if (len > 0)
  10293. {
  10294. s.copyToBuffer (dest, len);
  10295. dest += len;
  10296. }
  10297. if (++start < last && separatorLen > 0)
  10298. {
  10299. separator.copyToBuffer (dest, separatorLen);
  10300. dest += separatorLen;
  10301. }
  10302. }
  10303. *dest = 0;
  10304. return result;
  10305. }
  10306. int StringArray::addTokens (const tchar* const text,
  10307. const bool preserveQuotedStrings) throw()
  10308. {
  10309. return addTokens (text,
  10310. T(" \n\r\t"),
  10311. preserveQuotedStrings ? T("\"") : 0);
  10312. }
  10313. int StringArray::addTokens (const tchar* const text,
  10314. const tchar* breakCharacters,
  10315. const tchar* quoteCharacters) throw()
  10316. {
  10317. int num = 0;
  10318. if (text != 0 && *text != 0)
  10319. {
  10320. if (breakCharacters == 0)
  10321. breakCharacters = T("");
  10322. if (quoteCharacters == 0)
  10323. quoteCharacters = T("");
  10324. bool insideQuotes = false;
  10325. tchar currentQuoteChar = 0;
  10326. int i = 0;
  10327. int tokenStart = 0;
  10328. for (;;)
  10329. {
  10330. const tchar c = text[i];
  10331. bool isBreak = (c == 0);
  10332. if (! (insideQuotes || isBreak))
  10333. {
  10334. const tchar* b = breakCharacters;
  10335. while (*b != 0)
  10336. {
  10337. if (*b++ == c)
  10338. {
  10339. isBreak = true;
  10340. break;
  10341. }
  10342. }
  10343. }
  10344. if (! isBreak)
  10345. {
  10346. bool isQuote = false;
  10347. const tchar* q = quoteCharacters;
  10348. while (*q != 0)
  10349. {
  10350. if (*q++ == c)
  10351. {
  10352. isQuote = true;
  10353. break;
  10354. }
  10355. }
  10356. if (isQuote)
  10357. {
  10358. if (insideQuotes)
  10359. {
  10360. // only break out of quotes-mode if we find a matching quote to the
  10361. // one that we opened with..
  10362. if (currentQuoteChar == c)
  10363. insideQuotes = false;
  10364. }
  10365. else
  10366. {
  10367. insideQuotes = true;
  10368. currentQuoteChar = c;
  10369. }
  10370. }
  10371. }
  10372. else
  10373. {
  10374. add (String (text + tokenStart, i - tokenStart));
  10375. ++num;
  10376. tokenStart = i + 1;
  10377. }
  10378. if (c == 0)
  10379. break;
  10380. ++i;
  10381. }
  10382. }
  10383. return num;
  10384. }
  10385. int StringArray::addLines (const tchar* text) throw()
  10386. {
  10387. int numLines = 0;
  10388. if (text != 0)
  10389. {
  10390. while (*text != 0)
  10391. {
  10392. const tchar* const startOfLine = text;
  10393. while (*text != 0)
  10394. {
  10395. if (*text == T('\r'))
  10396. {
  10397. ++text;
  10398. if (*text == T('\n'))
  10399. ++text;
  10400. break;
  10401. }
  10402. if (*text == T('\n'))
  10403. {
  10404. ++text;
  10405. break;
  10406. }
  10407. ++text;
  10408. }
  10409. const tchar* endOfLine = text;
  10410. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10411. --endOfLine;
  10412. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10413. --endOfLine;
  10414. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10415. ++numLines;
  10416. }
  10417. }
  10418. return numLines;
  10419. }
  10420. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  10421. {
  10422. for (int i = 0; i < size() - 1; ++i)
  10423. {
  10424. const String& s = *(String*) strings.getUnchecked(i);
  10425. int nextIndex = i + 1;
  10426. for (;;)
  10427. {
  10428. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10429. if (nextIndex < 0)
  10430. break;
  10431. remove (nextIndex);
  10432. }
  10433. }
  10434. }
  10435. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10436. const bool appendNumberToFirstInstance,
  10437. const tchar* const preNumberString,
  10438. const tchar* const postNumberString) throw()
  10439. {
  10440. for (int i = 0; i < size() - 1; ++i)
  10441. {
  10442. String& s = *(String*) strings.getUnchecked(i);
  10443. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10444. if (nextIndex >= 0)
  10445. {
  10446. const String original (s);
  10447. int number = 0;
  10448. if (appendNumberToFirstInstance)
  10449. s = original + preNumberString + String (++number) + postNumberString;
  10450. else
  10451. ++number;
  10452. while (nextIndex >= 0)
  10453. {
  10454. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10455. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10456. }
  10457. }
  10458. }
  10459. }
  10460. void StringArray::minimiseStorageOverheads() throw()
  10461. {
  10462. strings.minimiseStorageOverheads();
  10463. }
  10464. END_JUCE_NAMESPACE
  10465. /********* End of inlined file: juce_StringArray.cpp *********/
  10466. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  10467. BEGIN_JUCE_NAMESPACE
  10468. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  10469. : ignoreCase (ignoreCase_)
  10470. {
  10471. }
  10472. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  10473. : keys (other.keys),
  10474. values (other.values),
  10475. ignoreCase (other.ignoreCase)
  10476. {
  10477. }
  10478. StringPairArray::~StringPairArray() throw()
  10479. {
  10480. }
  10481. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  10482. {
  10483. keys = other.keys;
  10484. values = other.values;
  10485. return *this;
  10486. }
  10487. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  10488. {
  10489. for (int i = keys.size(); --i >= 0;)
  10490. if (other [keys[i]] != values[i])
  10491. return false;
  10492. return true;
  10493. }
  10494. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  10495. {
  10496. return ! operator== (other);
  10497. }
  10498. const String& StringPairArray::operator[] (const String& key) const throw()
  10499. {
  10500. return values [keys.indexOf (key, ignoreCase)];
  10501. }
  10502. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10503. {
  10504. const int i = keys.indexOf (key, ignoreCase);
  10505. if (i >= 0)
  10506. return values[i];
  10507. return defaultReturnValue;
  10508. }
  10509. void StringPairArray::set (const String& key,
  10510. const String& value) throw()
  10511. {
  10512. const int i = keys.indexOf (key, ignoreCase);
  10513. if (i >= 0)
  10514. {
  10515. values.set (i, value);
  10516. }
  10517. else
  10518. {
  10519. keys.add (key);
  10520. values.add (value);
  10521. }
  10522. }
  10523. void StringPairArray::addArray (const StringPairArray& other)
  10524. {
  10525. for (int i = 0; i < other.size(); ++i)
  10526. set (other.keys[i], other.values[i]);
  10527. }
  10528. void StringPairArray::clear() throw()
  10529. {
  10530. keys.clear();
  10531. values.clear();
  10532. }
  10533. void StringPairArray::remove (const String& key) throw()
  10534. {
  10535. remove (keys.indexOf (key, ignoreCase));
  10536. }
  10537. void StringPairArray::remove (const int index) throw()
  10538. {
  10539. keys.remove (index);
  10540. values.remove (index);
  10541. }
  10542. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase) throw()
  10543. {
  10544. ignoreCase = shouldIgnoreCase;
  10545. }
  10546. const String StringPairArray::getDescription() const
  10547. {
  10548. String s;
  10549. for (int i = 0; i < keys.size(); ++i)
  10550. {
  10551. s << keys[i] << T(" = ") << values[i];
  10552. if (i < keys.size())
  10553. s << T(", ");
  10554. }
  10555. return s;
  10556. }
  10557. void StringPairArray::minimiseStorageOverheads() throw()
  10558. {
  10559. keys.minimiseStorageOverheads();
  10560. values.minimiseStorageOverheads();
  10561. }
  10562. END_JUCE_NAMESPACE
  10563. /********* End of inlined file: juce_StringPairArray.cpp *********/
  10564. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  10565. BEGIN_JUCE_NAMESPACE
  10566. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  10567. {
  10568. return CharacterFunctions::isLetterOrDigit (c)
  10569. || c == T('_')
  10570. || c == T('-')
  10571. || c == T(':')
  10572. || c == T('.');
  10573. }
  10574. #define isXmlIdentifierChar(c) \
  10575. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  10576. XmlDocument::XmlDocument (const String& documentText) throw()
  10577. : originalText (documentText),
  10578. ignoreEmptyTextElements (true),
  10579. inputSource (0)
  10580. {
  10581. }
  10582. XmlDocument::XmlDocument (const File& file)
  10583. {
  10584. inputSource = new FileInputSource (file);
  10585. }
  10586. XmlDocument::~XmlDocument() throw()
  10587. {
  10588. delete inputSource;
  10589. }
  10590. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10591. {
  10592. if (inputSource != newSource)
  10593. {
  10594. delete inputSource;
  10595. inputSource = newSource;
  10596. }
  10597. }
  10598. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10599. {
  10600. ignoreEmptyTextElements = shouldBeIgnored;
  10601. }
  10602. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10603. {
  10604. String textToParse (originalText);
  10605. if (textToParse.isEmpty() && inputSource != 0)
  10606. {
  10607. InputStream* const in = inputSource->createInputStream();
  10608. if (in != 0)
  10609. {
  10610. MemoryBlock data;
  10611. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10612. delete in;
  10613. if (data.getSize() >= 2
  10614. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10615. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10616. {
  10617. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  10618. }
  10619. else
  10620. {
  10621. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  10622. }
  10623. if (! onlyReadOuterDocumentElement)
  10624. originalText = textToParse;
  10625. }
  10626. }
  10627. input = textToParse;
  10628. lastError = String::empty;
  10629. errorOccurred = false;
  10630. outOfData = false;
  10631. needToLoadDTD = true;
  10632. for (int i = 0; i < 128; ++i)
  10633. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  10634. if (textToParse.isEmpty())
  10635. {
  10636. lastError = "not enough input";
  10637. }
  10638. else
  10639. {
  10640. skipHeader();
  10641. if (input != 0)
  10642. {
  10643. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  10644. if (errorOccurred)
  10645. delete result;
  10646. else
  10647. return result;
  10648. }
  10649. else
  10650. {
  10651. lastError = "incorrect xml header";
  10652. }
  10653. }
  10654. return 0;
  10655. }
  10656. const String& XmlDocument::getLastParseError() const throw()
  10657. {
  10658. return lastError;
  10659. }
  10660. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  10661. {
  10662. lastError = desc;
  10663. errorOccurred = ! carryOn;
  10664. }
  10665. const String XmlDocument::getFileContents (const String& filename) const
  10666. {
  10667. String result;
  10668. if (inputSource != 0)
  10669. {
  10670. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  10671. if (in != 0)
  10672. {
  10673. result = in->readEntireStreamAsString();
  10674. delete in;
  10675. }
  10676. }
  10677. return result;
  10678. }
  10679. tchar XmlDocument::readNextChar() throw()
  10680. {
  10681. if (*input != 0)
  10682. {
  10683. return *input++;
  10684. }
  10685. else
  10686. {
  10687. outOfData = true;
  10688. return 0;
  10689. }
  10690. }
  10691. int XmlDocument::findNextTokenLength() throw()
  10692. {
  10693. int len = 0;
  10694. tchar c = *input;
  10695. while (isXmlIdentifierChar (c))
  10696. c = input [++len];
  10697. return len;
  10698. }
  10699. void XmlDocument::skipHeader() throw()
  10700. {
  10701. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10702. if (found != 0)
  10703. {
  10704. input = found;
  10705. input = CharacterFunctions::find (input, T("?>"));
  10706. if (input == 0)
  10707. return;
  10708. input += 2;
  10709. }
  10710. skipNextWhiteSpace();
  10711. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10712. if (docType == 0)
  10713. return;
  10714. input = docType + 9;
  10715. int n = 1;
  10716. while (n > 0)
  10717. {
  10718. const tchar c = readNextChar();
  10719. if (outOfData)
  10720. return;
  10721. if (c == T('<'))
  10722. ++n;
  10723. else if (c == T('>'))
  10724. --n;
  10725. }
  10726. docType += 9;
  10727. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10728. }
  10729. void XmlDocument::skipNextWhiteSpace() throw()
  10730. {
  10731. for (;;)
  10732. {
  10733. tchar c = *input;
  10734. while (CharacterFunctions::isWhitespace (c))
  10735. c = *++input;
  10736. if (c == 0)
  10737. {
  10738. outOfData = true;
  10739. break;
  10740. }
  10741. else if (c == T('<'))
  10742. {
  10743. if (input[1] == T('!')
  10744. && input[2] == T('-')
  10745. && input[3] == T('-'))
  10746. {
  10747. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10748. if (closeComment == 0)
  10749. {
  10750. outOfData = true;
  10751. break;
  10752. }
  10753. input = closeComment + 3;
  10754. continue;
  10755. }
  10756. else if (input[1] == T('?'))
  10757. {
  10758. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10759. if (closeBracket == 0)
  10760. {
  10761. outOfData = true;
  10762. break;
  10763. }
  10764. input = closeBracket + 2;
  10765. continue;
  10766. }
  10767. }
  10768. break;
  10769. }
  10770. }
  10771. void XmlDocument::readQuotedString (String& result) throw()
  10772. {
  10773. const tchar quote = readNextChar();
  10774. while (! outOfData)
  10775. {
  10776. const tchar character = readNextChar();
  10777. if (character == quote)
  10778. break;
  10779. if (character == T('&'))
  10780. {
  10781. --input;
  10782. readEntity (result);
  10783. }
  10784. else
  10785. {
  10786. --input;
  10787. const tchar* const start = input;
  10788. for (;;)
  10789. {
  10790. const tchar character = *input;
  10791. if (character == quote)
  10792. {
  10793. result.append (start, (int) (input - start));
  10794. ++input;
  10795. return;
  10796. }
  10797. else if (character == T('&'))
  10798. {
  10799. result.append (start, (int) (input - start));
  10800. break;
  10801. }
  10802. else if (character == 0)
  10803. {
  10804. outOfData = true;
  10805. setLastError ("unmatched quotes", false);
  10806. break;
  10807. }
  10808. ++input;
  10809. }
  10810. }
  10811. }
  10812. }
  10813. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  10814. {
  10815. XmlElement* node = 0;
  10816. skipNextWhiteSpace();
  10817. if (outOfData)
  10818. return 0;
  10819. input = CharacterFunctions::find (input, T("<"));
  10820. if (input != 0)
  10821. {
  10822. ++input;
  10823. int tagLen = findNextTokenLength();
  10824. if (tagLen == 0)
  10825. {
  10826. // no tag name - but allow for a gap after the '<' before giving an error
  10827. skipNextWhiteSpace();
  10828. tagLen = findNextTokenLength();
  10829. if (tagLen == 0)
  10830. {
  10831. setLastError ("tag name missing", false);
  10832. return node;
  10833. }
  10834. }
  10835. node = new XmlElement (input, tagLen);
  10836. input += tagLen;
  10837. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10838. // look for attributes
  10839. for (;;)
  10840. {
  10841. skipNextWhiteSpace();
  10842. const tchar c = *input;
  10843. // empty tag..
  10844. if (c == T('/') && input[1] == T('>'))
  10845. {
  10846. input += 2;
  10847. break;
  10848. }
  10849. // parse the guts of the element..
  10850. if (c == T('>'))
  10851. {
  10852. ++input;
  10853. skipNextWhiteSpace();
  10854. if (alsoParseSubElements)
  10855. readChildElements (node);
  10856. break;
  10857. }
  10858. // get an attribute..
  10859. if (isXmlIdentifierChar (c))
  10860. {
  10861. const int attNameLen = findNextTokenLength();
  10862. if (attNameLen > 0)
  10863. {
  10864. const tchar* attNameStart = input;
  10865. input += attNameLen;
  10866. skipNextWhiteSpace();
  10867. if (readNextChar() == T('='))
  10868. {
  10869. skipNextWhiteSpace();
  10870. const tchar c = *input;
  10871. if (c == T('"') || c == T('\''))
  10872. {
  10873. XmlElement::XmlAttributeNode* const newAtt
  10874. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10875. String::empty);
  10876. readQuotedString (newAtt->value);
  10877. if (lastAttribute == 0)
  10878. node->attributes = newAtt;
  10879. else
  10880. lastAttribute->next = newAtt;
  10881. lastAttribute = newAtt;
  10882. continue;
  10883. }
  10884. }
  10885. }
  10886. }
  10887. else
  10888. {
  10889. if (! outOfData)
  10890. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10891. }
  10892. break;
  10893. }
  10894. }
  10895. return node;
  10896. }
  10897. void XmlDocument::readChildElements (XmlElement* parent) throw()
  10898. {
  10899. XmlElement* lastChildNode = 0;
  10900. for (;;)
  10901. {
  10902. skipNextWhiteSpace();
  10903. if (outOfData)
  10904. {
  10905. setLastError ("unmatched tags", false);
  10906. break;
  10907. }
  10908. if (*input == T('<'))
  10909. {
  10910. if (input[1] == T('/'))
  10911. {
  10912. // our close tag..
  10913. input = CharacterFunctions::find (input, T(">"));
  10914. ++input;
  10915. break;
  10916. }
  10917. else if (input[1] == T('!')
  10918. && input[2] == T('[')
  10919. && input[3] == T('C')
  10920. && input[4] == T('D')
  10921. && input[5] == T('A')
  10922. && input[6] == T('T')
  10923. && input[7] == T('A')
  10924. && input[8] == T('['))
  10925. {
  10926. input += 9;
  10927. const tchar* const inputStart = input;
  10928. int len = 0;
  10929. for (;;)
  10930. {
  10931. if (*input == 0)
  10932. {
  10933. setLastError ("unterminated CDATA section", false);
  10934. outOfData = true;
  10935. break;
  10936. }
  10937. else if (input[0] == T(']')
  10938. && input[1] == T(']')
  10939. && input[2] == T('>'))
  10940. {
  10941. input += 3;
  10942. break;
  10943. }
  10944. ++input;
  10945. ++len;
  10946. }
  10947. XmlElement* const e = new XmlElement ((int) 0);
  10948. e->setText (String (inputStart, len));
  10949. if (lastChildNode != 0)
  10950. lastChildNode->nextElement = e;
  10951. else
  10952. parent->addChildElement (e);
  10953. lastChildNode = e;
  10954. }
  10955. else
  10956. {
  10957. // this is some other element, so parse and add it..
  10958. XmlElement* const n = readNextElement (true);
  10959. if (n != 0)
  10960. {
  10961. if (lastChildNode == 0)
  10962. parent->addChildElement (n);
  10963. else
  10964. lastChildNode->nextElement = n;
  10965. lastChildNode = n;
  10966. }
  10967. else
  10968. {
  10969. return;
  10970. }
  10971. }
  10972. }
  10973. else
  10974. {
  10975. // read character block..
  10976. XmlElement* const e = new XmlElement ((int)0);
  10977. if (lastChildNode != 0)
  10978. lastChildNode->nextElement = e;
  10979. else
  10980. parent->addChildElement (e);
  10981. lastChildNode = e;
  10982. String textElementContent;
  10983. for (;;)
  10984. {
  10985. const tchar c = *input;
  10986. if (c == T('<'))
  10987. break;
  10988. if (c == 0)
  10989. {
  10990. setLastError ("unmatched tags", false);
  10991. outOfData = true;
  10992. return;
  10993. }
  10994. if (c == T('&'))
  10995. {
  10996. String entity;
  10997. readEntity (entity);
  10998. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  10999. {
  11000. const tchar* const oldInput = input;
  11001. const bool oldOutOfData = outOfData;
  11002. input = (const tchar*) entity;
  11003. outOfData = false;
  11004. for (;;)
  11005. {
  11006. XmlElement* const n = readNextElement (true);
  11007. if (n == 0)
  11008. break;
  11009. if (lastChildNode == 0)
  11010. parent->addChildElement (n);
  11011. else
  11012. lastChildNode->nextElement = n;
  11013. lastChildNode = n;
  11014. }
  11015. input = oldInput;
  11016. outOfData = oldOutOfData;
  11017. }
  11018. else
  11019. {
  11020. textElementContent += entity;
  11021. }
  11022. }
  11023. else
  11024. {
  11025. const tchar* start = input;
  11026. int len = 0;
  11027. for (;;)
  11028. {
  11029. const tchar c = *input;
  11030. if (c == T('<') || c == T('&'))
  11031. {
  11032. break;
  11033. }
  11034. else if (c == 0)
  11035. {
  11036. setLastError ("unmatched tags", false);
  11037. outOfData = true;
  11038. return;
  11039. }
  11040. ++input;
  11041. ++len;
  11042. }
  11043. textElementContent.append (start, len);
  11044. }
  11045. }
  11046. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11047. : textElementContent.isNotEmpty())
  11048. e->setText (textElementContent);
  11049. }
  11050. }
  11051. }
  11052. void XmlDocument::readEntity (String& result) throw()
  11053. {
  11054. // skip over the ampersand
  11055. ++input;
  11056. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  11057. {
  11058. input += 4;
  11059. result += T("&");
  11060. }
  11061. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  11062. {
  11063. input += 5;
  11064. result += T("\"");
  11065. }
  11066. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  11067. {
  11068. input += 5;
  11069. result += T("\'");
  11070. }
  11071. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  11072. {
  11073. input += 3;
  11074. result += T("<");
  11075. }
  11076. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  11077. {
  11078. input += 3;
  11079. result += T(">");
  11080. }
  11081. else if (*input == T('#'))
  11082. {
  11083. int charCode = 0;
  11084. ++input;
  11085. if (*input == T('x') || *input == T('X'))
  11086. {
  11087. ++input;
  11088. int numChars = 0;
  11089. while (input[0] != T(';'))
  11090. {
  11091. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11092. if (hexValue < 0 || ++numChars > 8)
  11093. {
  11094. setLastError ("illegal escape sequence", true);
  11095. break;
  11096. }
  11097. charCode = (charCode << 4) | hexValue;
  11098. ++input;
  11099. }
  11100. ++input;
  11101. }
  11102. else if (input[0] >= T('0') && input[0] <= T('9'))
  11103. {
  11104. int numChars = 0;
  11105. while (input[0] != T(';'))
  11106. {
  11107. if (++numChars > 12)
  11108. {
  11109. setLastError ("illegal escape sequence", true);
  11110. break;
  11111. }
  11112. charCode = charCode * 10 + (input[0] - T('0'));
  11113. ++input;
  11114. }
  11115. ++input;
  11116. }
  11117. else
  11118. {
  11119. setLastError ("illegal escape sequence", true);
  11120. result += T("&");
  11121. return;
  11122. }
  11123. result << (tchar) charCode;
  11124. }
  11125. else
  11126. {
  11127. const tchar* const entityNameStart = input;
  11128. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  11129. if (closingSemiColon == 0)
  11130. {
  11131. outOfData = true;
  11132. result += T("&");
  11133. }
  11134. else
  11135. {
  11136. input = closingSemiColon + 1;
  11137. result += expandExternalEntity (String (entityNameStart,
  11138. (int) (closingSemiColon - entityNameStart)));
  11139. }
  11140. }
  11141. }
  11142. const String XmlDocument::expandEntity (const String& ent)
  11143. {
  11144. if (ent.equalsIgnoreCase (T("amp")))
  11145. {
  11146. return T("&");
  11147. }
  11148. else if (ent.equalsIgnoreCase (T("quot")))
  11149. {
  11150. return T("\"");
  11151. }
  11152. else if (ent.equalsIgnoreCase (T("apos")))
  11153. {
  11154. return T("\'");
  11155. }
  11156. else if (ent.equalsIgnoreCase (T("lt")))
  11157. {
  11158. return T("<");
  11159. }
  11160. else if (ent.equalsIgnoreCase (T("gt")))
  11161. {
  11162. return T(">");
  11163. }
  11164. else if (ent[0] == T('#'))
  11165. {
  11166. if (ent[1] == T('x') || ent[1] == T('X'))
  11167. {
  11168. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  11169. }
  11170. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  11171. {
  11172. return String::charToString ((tchar) ent.substring (1).getIntValue());
  11173. }
  11174. setLastError ("illegal escape sequence", false);
  11175. return T("&");
  11176. }
  11177. else
  11178. {
  11179. return expandExternalEntity (ent);
  11180. }
  11181. }
  11182. const String XmlDocument::expandExternalEntity (const String& entity)
  11183. {
  11184. if (needToLoadDTD)
  11185. {
  11186. if (dtdText.isNotEmpty())
  11187. {
  11188. while (dtdText.endsWithChar (T('>')))
  11189. dtdText = dtdText.dropLastCharacters (1);
  11190. tokenisedDTD.addTokens (dtdText, true);
  11191. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  11192. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11193. {
  11194. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11195. tokenisedDTD.clear();
  11196. tokenisedDTD.addTokens (getFileContents (fn), true);
  11197. }
  11198. else
  11199. {
  11200. tokenisedDTD.clear();
  11201. const int openBracket = dtdText.indexOfChar (T('['));
  11202. if (openBracket > 0)
  11203. {
  11204. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  11205. if (closeBracket > openBracket)
  11206. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11207. closeBracket), true);
  11208. }
  11209. }
  11210. for (int i = tokenisedDTD.size(); --i >= 0;)
  11211. {
  11212. if (tokenisedDTD[i].startsWithChar (T('%'))
  11213. && tokenisedDTD[i].endsWithChar (T(';')))
  11214. {
  11215. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11216. StringArray newToks;
  11217. newToks.addTokens (parsed, true);
  11218. tokenisedDTD.remove (i);
  11219. for (int j = newToks.size(); --j >= 0;)
  11220. tokenisedDTD.insert (i, newToks[j]);
  11221. }
  11222. }
  11223. }
  11224. needToLoadDTD = false;
  11225. }
  11226. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11227. {
  11228. if (tokenisedDTD[i] == entity)
  11229. {
  11230. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  11231. {
  11232. String ent (tokenisedDTD [i + 1]);
  11233. while (ent.endsWithChar (T('>')))
  11234. ent = ent.dropLastCharacters (1);
  11235. ent = ent.trim().unquoted();
  11236. // check for sub-entities..
  11237. int ampersand = ent.indexOfChar (T('&'));
  11238. while (ampersand >= 0)
  11239. {
  11240. const int semiColon = ent.indexOf (i + 1, T(";"));
  11241. if (semiColon < 0)
  11242. {
  11243. setLastError ("entity without terminating semi-colon", false);
  11244. break;
  11245. }
  11246. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11247. ent = ent.substring (0, ampersand)
  11248. + resolved
  11249. + ent.substring (semiColon + 1);
  11250. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  11251. }
  11252. return ent;
  11253. }
  11254. }
  11255. }
  11256. setLastError ("unknown entity", true);
  11257. return entity;
  11258. }
  11259. const String XmlDocument::getParameterEntity (const String& entity)
  11260. {
  11261. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11262. {
  11263. if (tokenisedDTD[i] == entity)
  11264. {
  11265. if (tokenisedDTD [i - 1] == T("%")
  11266. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  11267. {
  11268. String ent (tokenisedDTD [i + 1]);
  11269. while (ent.endsWithChar (T('>')))
  11270. ent = ent.dropLastCharacters (1);
  11271. if (ent.equalsIgnoreCase (T("system")))
  11272. {
  11273. String filename (tokenisedDTD [i + 2]);
  11274. while (filename.endsWithChar (T('>')))
  11275. filename = filename.dropLastCharacters (1);
  11276. return getFileContents (filename);
  11277. }
  11278. else
  11279. {
  11280. return ent.trim().unquoted();
  11281. }
  11282. }
  11283. }
  11284. }
  11285. return entity;
  11286. }
  11287. END_JUCE_NAMESPACE
  11288. /********* End of inlined file: juce_XmlDocument.cpp *********/
  11289. /********* Start of inlined file: juce_XmlElement.cpp *********/
  11290. BEGIN_JUCE_NAMESPACE
  11291. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11292. : name (other.name),
  11293. value (other.value),
  11294. next (0)
  11295. {
  11296. }
  11297. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  11298. const String& value_) throw()
  11299. : name (name_),
  11300. value (value_),
  11301. next (0)
  11302. {
  11303. }
  11304. XmlElement::XmlElement (const String& tagName_) throw()
  11305. : tagName (tagName_),
  11306. firstChildElement (0),
  11307. nextElement (0),
  11308. attributes (0)
  11309. {
  11310. // the tag name mustn't be empty, or it'll look like a text element!
  11311. jassert (tagName_.containsNonWhitespaceChars())
  11312. }
  11313. XmlElement::XmlElement (int /*dummy*/) throw()
  11314. : firstChildElement (0),
  11315. nextElement (0),
  11316. attributes (0)
  11317. {
  11318. }
  11319. XmlElement::XmlElement (const tchar* const tagName_,
  11320. const int nameLen) throw()
  11321. : tagName (tagName_, nameLen),
  11322. firstChildElement (0),
  11323. nextElement (0),
  11324. attributes (0)
  11325. {
  11326. }
  11327. XmlElement::XmlElement (const XmlElement& other) throw()
  11328. : tagName (other.tagName),
  11329. firstChildElement (0),
  11330. nextElement (0),
  11331. attributes (0)
  11332. {
  11333. copyChildrenAndAttributesFrom (other);
  11334. }
  11335. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11336. {
  11337. if (this != &other)
  11338. {
  11339. removeAllAttributes();
  11340. deleteAllChildElements();
  11341. tagName = other.tagName;
  11342. copyChildrenAndAttributesFrom (other);
  11343. }
  11344. return *this;
  11345. }
  11346. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11347. {
  11348. XmlElement* child = other.firstChildElement;
  11349. XmlElement* lastChild = 0;
  11350. while (child != 0)
  11351. {
  11352. XmlElement* const copiedChild = new XmlElement (*child);
  11353. if (lastChild != 0)
  11354. lastChild->nextElement = copiedChild;
  11355. else
  11356. firstChildElement = copiedChild;
  11357. lastChild = copiedChild;
  11358. child = child->nextElement;
  11359. }
  11360. const XmlAttributeNode* att = other.attributes;
  11361. XmlAttributeNode* lastAtt = 0;
  11362. while (att != 0)
  11363. {
  11364. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11365. if (lastAtt != 0)
  11366. lastAtt->next = newAtt;
  11367. else
  11368. attributes = newAtt;
  11369. lastAtt = newAtt;
  11370. att = att->next;
  11371. }
  11372. }
  11373. XmlElement::~XmlElement() throw()
  11374. {
  11375. XmlElement* child = firstChildElement;
  11376. while (child != 0)
  11377. {
  11378. XmlElement* const nextChild = child->nextElement;
  11379. delete child;
  11380. child = nextChild;
  11381. }
  11382. XmlAttributeNode* att = attributes;
  11383. while (att != 0)
  11384. {
  11385. XmlAttributeNode* const nextAtt = att->next;
  11386. delete att;
  11387. att = nextAtt;
  11388. }
  11389. }
  11390. static bool isLegalXmlChar (const juce_wchar character)
  11391. {
  11392. if ((character >= 'a' && character <= 'z')
  11393. || (character >= 'A' && character <= 'Z')
  11394. || (character >= '0' && character <= '9'))
  11395. return true;
  11396. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11397. do
  11398. {
  11399. if (((juce_wchar) (uint8) *t) == character)
  11400. return true;
  11401. }
  11402. while (*++t != 0);
  11403. return false;
  11404. }
  11405. static void escapeIllegalXmlChars (OutputStream& outputStream,
  11406. const String& text,
  11407. const bool changeNewLines) throw()
  11408. {
  11409. const juce_wchar* t = (const juce_wchar*) text;
  11410. for (;;)
  11411. {
  11412. const juce_wchar character = *t++;
  11413. if (character == 0)
  11414. {
  11415. break;
  11416. }
  11417. else if (isLegalXmlChar (character))
  11418. {
  11419. outputStream.writeByte ((char) character);
  11420. }
  11421. else
  11422. {
  11423. switch (character)
  11424. {
  11425. case '&':
  11426. outputStream.write ("&amp;", 5);
  11427. break;
  11428. case '"':
  11429. outputStream.write ("&quot;", 6);
  11430. break;
  11431. case '>':
  11432. outputStream.write ("&gt;", 4);
  11433. break;
  11434. case '<':
  11435. outputStream.write ("&lt;", 4);
  11436. break;
  11437. case '\n':
  11438. if (changeNewLines)
  11439. outputStream.write ("&#10;", 5);
  11440. else
  11441. outputStream.writeByte ((char) character);
  11442. break;
  11443. case '\r':
  11444. if (changeNewLines)
  11445. outputStream.write ("&#13;", 5);
  11446. else
  11447. outputStream.writeByte ((char) character);
  11448. break;
  11449. default:
  11450. {
  11451. String encoded (T("&#"));
  11452. encoded << String ((int) (unsigned int) character).trim()
  11453. << T(';');
  11454. outputStream.write ((const char*) encoded, encoded.length());
  11455. }
  11456. }
  11457. }
  11458. }
  11459. }
  11460. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  11461. {
  11462. if (numSpaces > 0)
  11463. {
  11464. const char* const blanks = " ";
  11465. const int blankSize = (int) sizeof (blanks) - 1;
  11466. while (numSpaces > blankSize)
  11467. {
  11468. out.write (blanks, blankSize);
  11469. numSpaces -= blankSize;
  11470. }
  11471. out.write (blanks, numSpaces);
  11472. }
  11473. }
  11474. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11475. const int indentationLevel,
  11476. const int lineWrapLength) const throw()
  11477. {
  11478. writeSpaces (outputStream, indentationLevel);
  11479. if (! isTextElement())
  11480. {
  11481. outputStream.writeByte ('<');
  11482. const int nameLen = tagName.length();
  11483. outputStream.write ((const char*) tagName, nameLen);
  11484. const int attIndent = indentationLevel + nameLen + 1;
  11485. int lineLen = 0;
  11486. const XmlAttributeNode* att = attributes;
  11487. while (att != 0)
  11488. {
  11489. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11490. {
  11491. outputStream.write ("\r\n", 2);
  11492. writeSpaces (outputStream, attIndent);
  11493. lineLen = 0;
  11494. }
  11495. const int attNameLen = att->name.length();
  11496. outputStream.writeByte (' ');
  11497. outputStream.write ((const char*) (att->name), attNameLen);
  11498. outputStream.write ("=\"", 2);
  11499. escapeIllegalXmlChars (outputStream, att->value, true);
  11500. outputStream.writeByte ('"');
  11501. lineLen += 4 + attNameLen + att->value.length();
  11502. att = att->next;
  11503. }
  11504. if (firstChildElement != 0)
  11505. {
  11506. XmlElement* child = firstChildElement;
  11507. if (child->nextElement == 0 && child->isTextElement())
  11508. {
  11509. outputStream.writeByte ('>');
  11510. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11511. }
  11512. else
  11513. {
  11514. if (indentationLevel >= 0)
  11515. outputStream.write (">\r\n", 3);
  11516. else
  11517. outputStream.writeByte ('>');
  11518. bool lastWasTextNode = false;
  11519. while (child != 0)
  11520. {
  11521. if (child->isTextElement())
  11522. {
  11523. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11524. writeSpaces (outputStream, indentationLevel + 2);
  11525. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11526. lastWasTextNode = true;
  11527. }
  11528. else
  11529. {
  11530. if (indentationLevel >= 0)
  11531. {
  11532. if (lastWasTextNode)
  11533. outputStream.write ("\r\n", 2);
  11534. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11535. }
  11536. else
  11537. {
  11538. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11539. }
  11540. lastWasTextNode = false;
  11541. }
  11542. child = child->nextElement;
  11543. }
  11544. if (indentationLevel >= 0)
  11545. {
  11546. if (lastWasTextNode)
  11547. outputStream.write ("\r\n", 2);
  11548. writeSpaces (outputStream, indentationLevel);
  11549. }
  11550. }
  11551. outputStream.write ("</", 2);
  11552. outputStream.write ((const char*) tagName, nameLen);
  11553. if (indentationLevel >= 0)
  11554. outputStream.write (">\r\n", 3);
  11555. else
  11556. outputStream.writeByte ('>');
  11557. }
  11558. else
  11559. {
  11560. if (indentationLevel >= 0)
  11561. outputStream.write ("/>\r\n", 4);
  11562. else
  11563. outputStream.write ("/>", 2);
  11564. }
  11565. }
  11566. else
  11567. {
  11568. if (indentationLevel >= 0)
  11569. writeSpaces (outputStream, indentationLevel + 2);
  11570. escapeIllegalXmlChars (outputStream, getText(), false);
  11571. }
  11572. }
  11573. const String XmlElement::createDocument (const String& dtd,
  11574. const bool allOnOneLine,
  11575. const bool includeXmlHeader,
  11576. const tchar* const encoding,
  11577. const int lineWrapLength) const throw()
  11578. {
  11579. String doc;
  11580. doc.preallocateStorage (1024);
  11581. if (includeXmlHeader)
  11582. {
  11583. doc << "<?xml version=\"1.0\" encoding=\""
  11584. << encoding;
  11585. if (allOnOneLine)
  11586. doc += "\"?> ";
  11587. else
  11588. doc += "\"?>\n\n";
  11589. }
  11590. if (dtd.isNotEmpty())
  11591. {
  11592. if (allOnOneLine)
  11593. doc << dtd << " ";
  11594. else
  11595. doc << dtd << "\r\n";
  11596. }
  11597. MemoryOutputStream mem (2048, 4096);
  11598. writeElementAsText (mem, allOnOneLine ? -1 : 0, lineWrapLength);
  11599. return doc + String (mem.getData(),
  11600. mem.getDataSize());
  11601. }
  11602. bool XmlElement::writeToFile (const File& f,
  11603. const String& dtd,
  11604. const tchar* const encoding,
  11605. const int lineWrapLength) const throw()
  11606. {
  11607. if (f.hasWriteAccess())
  11608. {
  11609. const File tempFile (f.getNonexistentSibling());
  11610. FileOutputStream* const out = tempFile.createOutputStream();
  11611. if (out != 0)
  11612. {
  11613. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  11614. << dtd << "\r\n";
  11615. writeElementAsText (*out, 0, lineWrapLength);
  11616. delete out;
  11617. if (tempFile.moveFileTo (f))
  11618. return true;
  11619. tempFile.deleteFile();
  11620. }
  11621. }
  11622. return false;
  11623. }
  11624. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  11625. {
  11626. #ifdef JUCE_DEBUG
  11627. // if debugging, check that the case is actually the same, because
  11628. // valid xml is case-sensitive, and although this lets it pass, it's
  11629. // better not to..
  11630. if (tagName.equalsIgnoreCase (tagNameWanted))
  11631. {
  11632. jassert (tagName == tagNameWanted);
  11633. return true;
  11634. }
  11635. else
  11636. {
  11637. return false;
  11638. }
  11639. #else
  11640. return tagName.equalsIgnoreCase (tagNameWanted);
  11641. #endif
  11642. }
  11643. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  11644. {
  11645. XmlElement* e = nextElement;
  11646. while (e != 0 && ! e->hasTagName (requiredTagName))
  11647. e = e->nextElement;
  11648. return e;
  11649. }
  11650. int XmlElement::getNumAttributes() const throw()
  11651. {
  11652. const XmlAttributeNode* att = attributes;
  11653. int count = 0;
  11654. while (att != 0)
  11655. {
  11656. att = att->next;
  11657. ++count;
  11658. }
  11659. return count;
  11660. }
  11661. const String& XmlElement::getAttributeName (const int index) const throw()
  11662. {
  11663. const XmlAttributeNode* att = attributes;
  11664. int count = 0;
  11665. while (att != 0)
  11666. {
  11667. if (count == index)
  11668. return att->name;
  11669. att = att->next;
  11670. ++count;
  11671. }
  11672. return String::empty;
  11673. }
  11674. const String& XmlElement::getAttributeValue (const int index) const throw()
  11675. {
  11676. const XmlAttributeNode* att = attributes;
  11677. int count = 0;
  11678. while (att != 0)
  11679. {
  11680. if (count == index)
  11681. return att->value;
  11682. att = att->next;
  11683. ++count;
  11684. }
  11685. return String::empty;
  11686. }
  11687. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  11688. {
  11689. const XmlAttributeNode* att = attributes;
  11690. while (att != 0)
  11691. {
  11692. if (att->name.equalsIgnoreCase (attributeName))
  11693. return true;
  11694. att = att->next;
  11695. }
  11696. return false;
  11697. }
  11698. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  11699. const tchar* const defaultReturnValue) const throw()
  11700. {
  11701. const XmlAttributeNode* att = attributes;
  11702. while (att != 0)
  11703. {
  11704. if (att->name.equalsIgnoreCase (attributeName))
  11705. return att->value;
  11706. att = att->next;
  11707. }
  11708. return defaultReturnValue;
  11709. }
  11710. int XmlElement::getIntAttribute (const tchar* const attributeName,
  11711. const int defaultReturnValue) const throw()
  11712. {
  11713. const XmlAttributeNode* att = attributes;
  11714. while (att != 0)
  11715. {
  11716. if (att->name.equalsIgnoreCase (attributeName))
  11717. return att->value.getIntValue();
  11718. att = att->next;
  11719. }
  11720. return defaultReturnValue;
  11721. }
  11722. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  11723. const double defaultReturnValue) const throw()
  11724. {
  11725. const XmlAttributeNode* att = attributes;
  11726. while (att != 0)
  11727. {
  11728. if (att->name.equalsIgnoreCase (attributeName))
  11729. return att->value.getDoubleValue();
  11730. att = att->next;
  11731. }
  11732. return defaultReturnValue;
  11733. }
  11734. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  11735. const bool defaultReturnValue) const throw()
  11736. {
  11737. const XmlAttributeNode* att = attributes;
  11738. while (att != 0)
  11739. {
  11740. if (att->name.equalsIgnoreCase (attributeName))
  11741. {
  11742. tchar firstChar = att->value[0];
  11743. if (CharacterFunctions::isWhitespace (firstChar))
  11744. firstChar = att->value.trimStart() [0];
  11745. return firstChar == T('1')
  11746. || firstChar == T('t')
  11747. || firstChar == T('y')
  11748. || firstChar == T('T')
  11749. || firstChar == T('Y');
  11750. }
  11751. att = att->next;
  11752. }
  11753. return defaultReturnValue;
  11754. }
  11755. bool XmlElement::compareAttribute (const tchar* const attributeName,
  11756. const tchar* const stringToCompareAgainst,
  11757. const bool ignoreCase) const throw()
  11758. {
  11759. const XmlAttributeNode* att = attributes;
  11760. while (att != 0)
  11761. {
  11762. if (att->name.equalsIgnoreCase (attributeName))
  11763. {
  11764. if (ignoreCase)
  11765. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11766. else
  11767. return att->value == stringToCompareAgainst;
  11768. }
  11769. att = att->next;
  11770. }
  11771. return false;
  11772. }
  11773. void XmlElement::setAttribute (const tchar* const attributeName,
  11774. const String& value) throw()
  11775. {
  11776. #ifdef JUCE_DEBUG
  11777. // check the identifier being passed in is legal..
  11778. const tchar* t = attributeName;
  11779. while (*t != 0)
  11780. {
  11781. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11782. || *t == T('_')
  11783. || *t == T('-')
  11784. || *t == T(':'));
  11785. ++t;
  11786. }
  11787. #endif
  11788. if (attributes == 0)
  11789. {
  11790. attributes = new XmlAttributeNode (attributeName, value);
  11791. }
  11792. else
  11793. {
  11794. XmlAttributeNode* att = attributes;
  11795. for (;;)
  11796. {
  11797. if (att->name.equalsIgnoreCase (attributeName))
  11798. {
  11799. att->value = value;
  11800. break;
  11801. }
  11802. else if (att->next == 0)
  11803. {
  11804. att->next = new XmlAttributeNode (attributeName, value);
  11805. break;
  11806. }
  11807. att = att->next;
  11808. }
  11809. }
  11810. }
  11811. void XmlElement::setAttribute (const tchar* const attributeName,
  11812. const tchar* const text) throw()
  11813. {
  11814. setAttribute (attributeName, String (text));
  11815. }
  11816. void XmlElement::setAttribute (const tchar* const attributeName,
  11817. const int number) throw()
  11818. {
  11819. setAttribute (attributeName, String (number));
  11820. }
  11821. void XmlElement::setAttribute (const tchar* const attributeName,
  11822. const double number) throw()
  11823. {
  11824. tchar buffer [40];
  11825. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  11826. setAttribute (attributeName, buffer);
  11827. }
  11828. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  11829. {
  11830. XmlAttributeNode* att = attributes;
  11831. XmlAttributeNode* lastAtt = 0;
  11832. while (att != 0)
  11833. {
  11834. if (att->name.equalsIgnoreCase (attributeName))
  11835. {
  11836. if (lastAtt == 0)
  11837. attributes = att->next;
  11838. else
  11839. lastAtt->next = att->next;
  11840. delete att;
  11841. break;
  11842. }
  11843. lastAtt = att;
  11844. att = att->next;
  11845. }
  11846. }
  11847. void XmlElement::removeAllAttributes() throw()
  11848. {
  11849. while (attributes != 0)
  11850. {
  11851. XmlAttributeNode* const nextAtt = attributes->next;
  11852. delete attributes;
  11853. attributes = nextAtt;
  11854. }
  11855. }
  11856. int XmlElement::getNumChildElements() const throw()
  11857. {
  11858. int count = 0;
  11859. const XmlElement* child = firstChildElement;
  11860. while (child != 0)
  11861. {
  11862. ++count;
  11863. child = child->nextElement;
  11864. }
  11865. return count;
  11866. }
  11867. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11868. {
  11869. int count = 0;
  11870. XmlElement* child = firstChildElement;
  11871. while (child != 0 && count < index)
  11872. {
  11873. child = child->nextElement;
  11874. ++count;
  11875. }
  11876. return child;
  11877. }
  11878. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  11879. {
  11880. XmlElement* child = firstChildElement;
  11881. while (child != 0)
  11882. {
  11883. if (child->hasTagName (childName))
  11884. break;
  11885. child = child->nextElement;
  11886. }
  11887. return child;
  11888. }
  11889. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11890. {
  11891. if (newNode != 0)
  11892. {
  11893. if (firstChildElement == 0)
  11894. {
  11895. firstChildElement = newNode;
  11896. }
  11897. else
  11898. {
  11899. XmlElement* child = firstChildElement;
  11900. while (child->nextElement != 0)
  11901. child = child->nextElement;
  11902. child->nextElement = newNode;
  11903. // if this is non-zero, then something's probably
  11904. // gone wrong..
  11905. jassert (newNode->nextElement == 0);
  11906. }
  11907. }
  11908. }
  11909. void XmlElement::insertChildElement (XmlElement* const newNode,
  11910. int indexToInsertAt) throw()
  11911. {
  11912. if (newNode != 0)
  11913. {
  11914. removeChildElement (newNode, false);
  11915. if (indexToInsertAt == 0)
  11916. {
  11917. newNode->nextElement = firstChildElement;
  11918. firstChildElement = newNode;
  11919. }
  11920. else
  11921. {
  11922. if (firstChildElement == 0)
  11923. {
  11924. firstChildElement = newNode;
  11925. }
  11926. else
  11927. {
  11928. if (indexToInsertAt < 0)
  11929. indexToInsertAt = INT_MAX;
  11930. XmlElement* child = firstChildElement;
  11931. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11932. child = child->nextElement;
  11933. newNode->nextElement = child->nextElement;
  11934. child->nextElement = newNode;
  11935. }
  11936. }
  11937. }
  11938. }
  11939. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11940. XmlElement* const newNode) throw()
  11941. {
  11942. if (newNode != 0)
  11943. {
  11944. XmlElement* child = firstChildElement;
  11945. XmlElement* previousNode = 0;
  11946. while (child != 0)
  11947. {
  11948. if (child == currentChildElement)
  11949. {
  11950. if (child != newNode)
  11951. {
  11952. if (previousNode == 0)
  11953. firstChildElement = newNode;
  11954. else
  11955. previousNode->nextElement = newNode;
  11956. newNode->nextElement = child->nextElement;
  11957. delete child;
  11958. }
  11959. return true;
  11960. }
  11961. previousNode = child;
  11962. child = child->nextElement;
  11963. }
  11964. }
  11965. return false;
  11966. }
  11967. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11968. const bool shouldDeleteTheChild) throw()
  11969. {
  11970. if (childToRemove != 0)
  11971. {
  11972. if (firstChildElement == childToRemove)
  11973. {
  11974. firstChildElement = childToRemove->nextElement;
  11975. childToRemove->nextElement = 0;
  11976. }
  11977. else
  11978. {
  11979. XmlElement* child = firstChildElement;
  11980. XmlElement* last = 0;
  11981. while (child != 0)
  11982. {
  11983. if (child == childToRemove)
  11984. {
  11985. if (last == 0)
  11986. firstChildElement = child->nextElement;
  11987. else
  11988. last->nextElement = child->nextElement;
  11989. childToRemove->nextElement = 0;
  11990. break;
  11991. }
  11992. last = child;
  11993. child = child->nextElement;
  11994. }
  11995. }
  11996. if (shouldDeleteTheChild)
  11997. delete childToRemove;
  11998. }
  11999. }
  12000. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12001. const bool ignoreOrderOfAttributes) const throw()
  12002. {
  12003. if (this != other)
  12004. {
  12005. if (other == 0 || tagName != other->tagName)
  12006. {
  12007. return false;
  12008. }
  12009. if (ignoreOrderOfAttributes)
  12010. {
  12011. int totalAtts = 0;
  12012. const XmlAttributeNode* att = attributes;
  12013. while (att != 0)
  12014. {
  12015. if (! other->compareAttribute (att->name, att->value))
  12016. return false;
  12017. att = att->next;
  12018. ++totalAtts;
  12019. }
  12020. if (totalAtts != other->getNumAttributes())
  12021. return false;
  12022. }
  12023. else
  12024. {
  12025. const XmlAttributeNode* thisAtt = attributes;
  12026. const XmlAttributeNode* otherAtt = other->attributes;
  12027. for (;;)
  12028. {
  12029. if (thisAtt == 0 || otherAtt == 0)
  12030. {
  12031. if (thisAtt == otherAtt) // both 0, so it's a match
  12032. break;
  12033. return false;
  12034. }
  12035. if (thisAtt->name != otherAtt->name
  12036. || thisAtt->value != otherAtt->value)
  12037. {
  12038. return false;
  12039. }
  12040. thisAtt = thisAtt->next;
  12041. otherAtt = otherAtt->next;
  12042. }
  12043. }
  12044. const XmlElement* thisChild = firstChildElement;
  12045. const XmlElement* otherChild = other->firstChildElement;
  12046. for (;;)
  12047. {
  12048. if (thisChild == 0 || otherChild == 0)
  12049. {
  12050. if (thisChild == otherChild) // both 0, so it's a match
  12051. break;
  12052. return false;
  12053. }
  12054. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12055. return false;
  12056. thisChild = thisChild->nextElement;
  12057. otherChild = otherChild->nextElement;
  12058. }
  12059. }
  12060. return true;
  12061. }
  12062. void XmlElement::deleteAllChildElements() throw()
  12063. {
  12064. while (firstChildElement != 0)
  12065. {
  12066. XmlElement* const nextChild = firstChildElement->nextElement;
  12067. delete firstChildElement;
  12068. firstChildElement = nextChild;
  12069. }
  12070. }
  12071. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  12072. {
  12073. XmlElement* child = firstChildElement;
  12074. while (child != 0)
  12075. {
  12076. if (child->hasTagName (name))
  12077. {
  12078. XmlElement* const nextChild = child->nextElement;
  12079. removeChildElement (child, true);
  12080. child = nextChild;
  12081. }
  12082. else
  12083. {
  12084. child = child->nextElement;
  12085. }
  12086. }
  12087. }
  12088. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12089. {
  12090. const XmlElement* child = firstChildElement;
  12091. while (child != 0)
  12092. {
  12093. if (child == possibleChild)
  12094. return true;
  12095. child = child->nextElement;
  12096. }
  12097. return false;
  12098. }
  12099. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12100. {
  12101. if (this == elementToLookFor || elementToLookFor == 0)
  12102. return 0;
  12103. XmlElement* child = firstChildElement;
  12104. while (child != 0)
  12105. {
  12106. if (elementToLookFor == child)
  12107. return this;
  12108. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12109. if (found != 0)
  12110. return found;
  12111. child = child->nextElement;
  12112. }
  12113. return 0;
  12114. }
  12115. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  12116. {
  12117. XmlElement** const elems = new XmlElement* [num];
  12118. XmlElement* e = firstChildElement;
  12119. int i = 0;
  12120. while (e != 0)
  12121. {
  12122. elems [i++] = e;
  12123. e = e->nextElement;
  12124. }
  12125. return elems;
  12126. }
  12127. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12128. {
  12129. XmlElement* e = firstChildElement = elems[0];
  12130. for (int i = 1; i < num; ++i)
  12131. {
  12132. e->nextElement = elems[i];
  12133. e = e->nextElement;
  12134. }
  12135. e->nextElement = 0;
  12136. }
  12137. bool XmlElement::isTextElement() const throw()
  12138. {
  12139. return tagName.isEmpty();
  12140. }
  12141. static const tchar* const juce_xmltextContentAttributeName = T("text");
  12142. const String XmlElement::getText() const throw()
  12143. {
  12144. jassert (isTextElement()); // you're trying to get the text from an element that
  12145. // isn't actually a text element.. If this contains text sub-nodes, you
  12146. // can use getAllSubText instead to
  12147. return getStringAttribute (juce_xmltextContentAttributeName);
  12148. }
  12149. void XmlElement::setText (const String& newText) throw()
  12150. {
  12151. if (isTextElement())
  12152. {
  12153. setAttribute (juce_xmltextContentAttributeName, newText);
  12154. }
  12155. else
  12156. {
  12157. jassertfalse // you can only change the text in a text element, not a normal one.
  12158. }
  12159. }
  12160. const String XmlElement::getAllSubText() const throw()
  12161. {
  12162. String result;
  12163. const XmlElement* child = firstChildElement;
  12164. while (child != 0)
  12165. {
  12166. if (child->isTextElement())
  12167. result += child->getText();
  12168. child = child->nextElement;
  12169. }
  12170. return result;
  12171. }
  12172. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  12173. const String& defaultReturnValue) const throw()
  12174. {
  12175. const XmlElement* const child = getChildByName (childTagName);
  12176. if (child != 0)
  12177. return child->getAllSubText();
  12178. return defaultReturnValue;
  12179. }
  12180. XmlElement* XmlElement::createTextElement (const String& text) throw()
  12181. {
  12182. XmlElement* const e = new XmlElement ((int) 0);
  12183. e->setAttribute (juce_xmltextContentAttributeName, text);
  12184. return e;
  12185. }
  12186. void XmlElement::addTextElement (const String& text) throw()
  12187. {
  12188. addChildElement (createTextElement (text));
  12189. }
  12190. void XmlElement::deleteAllTextElements() throw()
  12191. {
  12192. XmlElement* child = firstChildElement;
  12193. while (child != 0)
  12194. {
  12195. XmlElement* const next = child->nextElement;
  12196. if (child->isTextElement())
  12197. removeChildElement (child, true);
  12198. child = next;
  12199. }
  12200. }
  12201. END_JUCE_NAMESPACE
  12202. /********* End of inlined file: juce_XmlElement.cpp *********/
  12203. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  12204. BEGIN_JUCE_NAMESPACE
  12205. // (implemented in the platform-specific code files)
  12206. END_JUCE_NAMESPACE
  12207. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  12208. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  12209. BEGIN_JUCE_NAMESPACE
  12210. ReadWriteLock::ReadWriteLock() throw()
  12211. : numWaitingWriters (0),
  12212. numWriters (0),
  12213. writerThreadId (0)
  12214. {
  12215. }
  12216. ReadWriteLock::~ReadWriteLock() throw()
  12217. {
  12218. jassert (readerThreads.size() == 0);
  12219. jassert (numWriters == 0);
  12220. }
  12221. void ReadWriteLock::enterRead() const throw()
  12222. {
  12223. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12224. const ScopedLock sl (accessLock);
  12225. for (;;)
  12226. {
  12227. jassert (readerThreads.size() % 2 == 0);
  12228. int i;
  12229. for (i = 0; i < readerThreads.size(); i += 2)
  12230. if (readerThreads.getUnchecked(i) == threadId)
  12231. break;
  12232. if (i < readerThreads.size()
  12233. || numWriters + numWaitingWriters == 0
  12234. || (threadId == writerThreadId && numWriters > 0))
  12235. {
  12236. if (i < readerThreads.size())
  12237. {
  12238. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12239. }
  12240. else
  12241. {
  12242. readerThreads.add (threadId);
  12243. readerThreads.add ((Thread::ThreadID) 1);
  12244. }
  12245. return;
  12246. }
  12247. const ScopedUnlock ul (accessLock);
  12248. waitEvent.wait (100);
  12249. }
  12250. }
  12251. void ReadWriteLock::exitRead() const throw()
  12252. {
  12253. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12254. const ScopedLock sl (accessLock);
  12255. for (int i = 0; i < readerThreads.size(); i += 2)
  12256. {
  12257. if (readerThreads.getUnchecked(i) == threadId)
  12258. {
  12259. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12260. if (newCount == 0)
  12261. {
  12262. readerThreads.removeRange (i, 2);
  12263. waitEvent.signal();
  12264. }
  12265. else
  12266. {
  12267. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12268. }
  12269. return;
  12270. }
  12271. }
  12272. jassertfalse // unlocking a lock that wasn't locked..
  12273. }
  12274. void ReadWriteLock::enterWrite() const throw()
  12275. {
  12276. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12277. const ScopedLock sl (accessLock);
  12278. for (;;)
  12279. {
  12280. if (readerThreads.size() + numWriters == 0
  12281. || threadId == writerThreadId
  12282. || (readerThreads.size() == 2
  12283. && readerThreads.getUnchecked(0) == threadId))
  12284. {
  12285. writerThreadId = threadId;
  12286. ++numWriters;
  12287. break;
  12288. }
  12289. ++numWaitingWriters;
  12290. accessLock.exit();
  12291. waitEvent.wait (100);
  12292. accessLock.enter();
  12293. --numWaitingWriters;
  12294. }
  12295. }
  12296. bool ReadWriteLock::tryEnterWrite() const throw()
  12297. {
  12298. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12299. const ScopedLock sl (accessLock);
  12300. if (readerThreads.size() + numWriters == 0
  12301. || threadId == writerThreadId
  12302. || (readerThreads.size() == 2
  12303. && readerThreads.getUnchecked(0) == threadId))
  12304. {
  12305. writerThreadId = threadId;
  12306. ++numWriters;
  12307. return true;
  12308. }
  12309. return false;
  12310. }
  12311. void ReadWriteLock::exitWrite() const throw()
  12312. {
  12313. const ScopedLock sl (accessLock);
  12314. // check this thread actually had the lock..
  12315. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12316. if (--numWriters == 0)
  12317. {
  12318. writerThreadId = 0;
  12319. waitEvent.signal();
  12320. }
  12321. }
  12322. END_JUCE_NAMESPACE
  12323. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  12324. /********* Start of inlined file: juce_Thread.cpp *********/
  12325. BEGIN_JUCE_NAMESPACE
  12326. // these functions are implemented in the platform-specific code.
  12327. void* juce_createThread (void* userData) throw();
  12328. void juce_killThread (void* handle) throw();
  12329. bool juce_setThreadPriority (void* handle, int priority) throw();
  12330. void juce_setCurrentThreadName (const String& name) throw();
  12331. #if JUCE_WIN32
  12332. void juce_CloseThreadHandle (void* handle) throw();
  12333. #endif
  12334. static VoidArray runningThreads (4);
  12335. static CriticalSection runningThreadsLock;
  12336. void Thread::threadEntryPoint (Thread* const thread) throw()
  12337. {
  12338. {
  12339. const ScopedLock sl (runningThreadsLock);
  12340. runningThreads.add (thread);
  12341. }
  12342. JUCE_TRY
  12343. {
  12344. thread->threadId_ = Thread::getCurrentThreadId();
  12345. if (thread->threadName_.isNotEmpty())
  12346. juce_setCurrentThreadName (thread->threadName_);
  12347. if (thread->startSuspensionEvent_.wait (10000))
  12348. {
  12349. if (thread->affinityMask_ != 0)
  12350. setCurrentThreadAffinityMask (thread->affinityMask_);
  12351. thread->run();
  12352. }
  12353. }
  12354. JUCE_CATCH_ALL_ASSERT
  12355. {
  12356. const ScopedLock sl (runningThreadsLock);
  12357. jassert (runningThreads.contains (thread));
  12358. runningThreads.removeValue (thread);
  12359. }
  12360. #if JUCE_WIN32
  12361. juce_CloseThreadHandle (thread->threadHandle_);
  12362. #endif
  12363. thread->threadHandle_ = 0;
  12364. thread->threadId_ = 0;
  12365. }
  12366. // used to wrap the incoming call from the platform-specific code
  12367. void JUCE_API juce_threadEntryPoint (void* userData)
  12368. {
  12369. Thread::threadEntryPoint ((Thread*) userData);
  12370. }
  12371. Thread::Thread (const String& threadName)
  12372. : threadName_ (threadName),
  12373. threadHandle_ (0),
  12374. threadPriority_ (5),
  12375. threadId_ (0),
  12376. affinityMask_ (0),
  12377. threadShouldExit_ (false)
  12378. {
  12379. }
  12380. Thread::~Thread()
  12381. {
  12382. stopThread (100);
  12383. }
  12384. void Thread::startThread() throw()
  12385. {
  12386. const ScopedLock sl (startStopLock);
  12387. threadShouldExit_ = false;
  12388. if (threadHandle_ == 0)
  12389. {
  12390. threadHandle_ = juce_createThread ((void*) this);
  12391. juce_setThreadPriority (threadHandle_, threadPriority_);
  12392. startSuspensionEvent_.signal();
  12393. }
  12394. }
  12395. void Thread::startThread (const int priority) throw()
  12396. {
  12397. const ScopedLock sl (startStopLock);
  12398. if (threadHandle_ == 0)
  12399. {
  12400. threadPriority_ = priority;
  12401. startThread();
  12402. }
  12403. else
  12404. {
  12405. setPriority (priority);
  12406. }
  12407. }
  12408. bool Thread::isThreadRunning() const throw()
  12409. {
  12410. return threadHandle_ != 0;
  12411. }
  12412. void Thread::signalThreadShouldExit() throw()
  12413. {
  12414. threadShouldExit_ = true;
  12415. }
  12416. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  12417. {
  12418. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12419. jassert (getThreadId() != getCurrentThreadId());
  12420. const int sleepMsPerIteration = 5;
  12421. int count = timeOutMilliseconds / sleepMsPerIteration;
  12422. while (isThreadRunning())
  12423. {
  12424. if (timeOutMilliseconds > 0 && --count < 0)
  12425. return false;
  12426. sleep (sleepMsPerIteration);
  12427. }
  12428. return true;
  12429. }
  12430. void Thread::stopThread (const int timeOutMilliseconds) throw()
  12431. {
  12432. // agh! You can't stop the thread that's calling this method! How on earth
  12433. // would that work??
  12434. jassert (getCurrentThreadId() != getThreadId());
  12435. const ScopedLock sl (startStopLock);
  12436. if (isThreadRunning())
  12437. {
  12438. signalThreadShouldExit();
  12439. notify();
  12440. if (timeOutMilliseconds != 0)
  12441. waitForThreadToExit (timeOutMilliseconds);
  12442. if (isThreadRunning())
  12443. {
  12444. // very bad karma if this point is reached, as
  12445. // there are bound to be locks and events left in
  12446. // silly states when a thread is killed by force..
  12447. jassertfalse
  12448. Logger::writeToLog ("!! killing thread by force !!");
  12449. juce_killThread (threadHandle_);
  12450. threadHandle_ = 0;
  12451. threadId_ = 0;
  12452. const ScopedLock sl (runningThreadsLock);
  12453. runningThreads.removeValue (this);
  12454. }
  12455. }
  12456. }
  12457. bool Thread::setPriority (const int priority) throw()
  12458. {
  12459. const ScopedLock sl (startStopLock);
  12460. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12461. if (worked)
  12462. threadPriority_ = priority;
  12463. return worked;
  12464. }
  12465. bool Thread::setCurrentThreadPriority (const int priority) throw()
  12466. {
  12467. return juce_setThreadPriority (0, priority);
  12468. }
  12469. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  12470. {
  12471. affinityMask_ = affinityMask;
  12472. }
  12473. Thread::ThreadID Thread::getThreadId() const throw()
  12474. {
  12475. return threadId_;
  12476. }
  12477. bool Thread::wait (const int timeOutMilliseconds) const throw()
  12478. {
  12479. return defaultEvent_.wait (timeOutMilliseconds);
  12480. }
  12481. void Thread::notify() const throw()
  12482. {
  12483. defaultEvent_.signal();
  12484. }
  12485. int Thread::getNumRunningThreads() throw()
  12486. {
  12487. return runningThreads.size();
  12488. }
  12489. Thread* Thread::getCurrentThread() throw()
  12490. {
  12491. const ThreadID thisId = getCurrentThreadId();
  12492. const ScopedLock sl (runningThreadsLock);
  12493. for (int i = runningThreads.size(); --i >= 0;)
  12494. {
  12495. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  12496. if (t->threadId_ == thisId)
  12497. return t;
  12498. }
  12499. return 0;
  12500. }
  12501. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  12502. {
  12503. {
  12504. const ScopedLock sl (runningThreadsLock);
  12505. for (int i = runningThreads.size(); --i >= 0;)
  12506. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  12507. }
  12508. for (;;)
  12509. {
  12510. runningThreadsLock.enter();
  12511. Thread* const t = (Thread*) runningThreads[0];
  12512. runningThreadsLock.exit();
  12513. if (t == 0)
  12514. break;
  12515. t->stopThread (timeOutMilliseconds);
  12516. }
  12517. }
  12518. END_JUCE_NAMESPACE
  12519. /********* End of inlined file: juce_Thread.cpp *********/
  12520. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  12521. BEGIN_JUCE_NAMESPACE
  12522. ThreadPoolJob::ThreadPoolJob (const String& name)
  12523. : jobName (name),
  12524. pool (0),
  12525. shouldStop (false),
  12526. isActive (false),
  12527. shouldBeDeleted (false)
  12528. {
  12529. }
  12530. ThreadPoolJob::~ThreadPoolJob()
  12531. {
  12532. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12533. // to remove it first!
  12534. jassert (pool == 0 || ! pool->contains (this));
  12535. }
  12536. const String ThreadPoolJob::getJobName() const
  12537. {
  12538. return jobName;
  12539. }
  12540. void ThreadPoolJob::setJobName (const String& newName)
  12541. {
  12542. jobName = newName;
  12543. }
  12544. void ThreadPoolJob::signalJobShouldExit()
  12545. {
  12546. shouldStop = true;
  12547. }
  12548. class ThreadPoolThread : public Thread
  12549. {
  12550. ThreadPool& pool;
  12551. bool volatile busy;
  12552. ThreadPoolThread (const ThreadPoolThread&);
  12553. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  12554. public:
  12555. ThreadPoolThread (ThreadPool& pool_)
  12556. : Thread (T("Pool")),
  12557. pool (pool_),
  12558. busy (false)
  12559. {
  12560. }
  12561. ~ThreadPoolThread()
  12562. {
  12563. }
  12564. void run()
  12565. {
  12566. while (! threadShouldExit())
  12567. {
  12568. if (! pool.runNextJob())
  12569. wait (500);
  12570. }
  12571. }
  12572. };
  12573. ThreadPool::ThreadPool (const int numThreads_,
  12574. const bool startThreadsOnlyWhenNeeded,
  12575. const int stopThreadsWhenNotUsedTimeoutMs)
  12576. : numThreads (jmax (1, numThreads_)),
  12577. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12578. priority (5)
  12579. {
  12580. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  12581. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  12582. for (int i = numThreads; --i >= 0;)
  12583. {
  12584. threads[i] = new ThreadPoolThread (*this);
  12585. if (! startThreadsOnlyWhenNeeded)
  12586. threads[i]->startThread (priority);
  12587. }
  12588. }
  12589. ThreadPool::~ThreadPool()
  12590. {
  12591. removeAllJobs (true, 4000);
  12592. int i;
  12593. for (i = numThreads; --i >= 0;)
  12594. threads[i]->signalThreadShouldExit();
  12595. for (i = numThreads; --i >= 0;)
  12596. {
  12597. threads[i]->stopThread (500);
  12598. delete threads[i];
  12599. }
  12600. juce_free (threads);
  12601. }
  12602. void ThreadPool::addJob (ThreadPoolJob* const job)
  12603. {
  12604. jassert (job->pool == 0);
  12605. if (job->pool == 0)
  12606. {
  12607. job->pool = this;
  12608. job->shouldStop = false;
  12609. job->isActive = false;
  12610. lock.enter();
  12611. jobs.add (job);
  12612. int numRunning = 0;
  12613. int i;
  12614. for (i = numThreads; --i >= 0;)
  12615. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  12616. ++numRunning;
  12617. if (numRunning < numThreads)
  12618. {
  12619. bool startedOne = false;
  12620. int n = 1000;
  12621. while (--n >= 0 && ! startedOne)
  12622. {
  12623. for (int i = numThreads; --i >= 0;)
  12624. {
  12625. if (! threads[i]->isThreadRunning())
  12626. {
  12627. threads[i]->startThread (priority);
  12628. startedOne = true;
  12629. }
  12630. }
  12631. if (! startedOne)
  12632. Thread::sleep (5);
  12633. }
  12634. }
  12635. lock.exit();
  12636. for (i = numThreads; --i >= 0;)
  12637. threads[i]->notify();
  12638. }
  12639. }
  12640. int ThreadPool::getNumJobs() const throw()
  12641. {
  12642. return jobs.size();
  12643. }
  12644. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12645. {
  12646. const ScopedLock sl (lock);
  12647. return (ThreadPoolJob*) jobs [index];
  12648. }
  12649. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  12650. {
  12651. const ScopedLock sl (lock);
  12652. return jobs.contains ((void*) job);
  12653. }
  12654. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12655. {
  12656. const ScopedLock sl (lock);
  12657. return jobs.contains ((void*) job) && job->isActive;
  12658. }
  12659. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12660. const int timeOutMs) const
  12661. {
  12662. if (job != 0)
  12663. {
  12664. const uint32 start = Time::getMillisecondCounter();
  12665. while (contains (job))
  12666. {
  12667. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12668. return false;
  12669. Thread::sleep (2);
  12670. }
  12671. }
  12672. return true;
  12673. }
  12674. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12675. const bool interruptIfRunning,
  12676. const int timeOutMs)
  12677. {
  12678. if (job != 0)
  12679. {
  12680. lock.enter();
  12681. if (jobs.contains (job))
  12682. {
  12683. if (job->isActive)
  12684. {
  12685. if (interruptIfRunning)
  12686. job->signalJobShouldExit();
  12687. lock.exit();
  12688. return waitForJobToFinish (job, timeOutMs);
  12689. }
  12690. else
  12691. {
  12692. jobs.removeValue (job);
  12693. }
  12694. }
  12695. lock.exit();
  12696. }
  12697. return true;
  12698. }
  12699. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12700. const int timeOutMs,
  12701. const bool deleteInactiveJobs)
  12702. {
  12703. lock.enter();
  12704. for (int i = jobs.size(); --i >= 0;)
  12705. {
  12706. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  12707. if (job->isActive)
  12708. {
  12709. if (interruptRunningJobs)
  12710. job->signalJobShouldExit();
  12711. }
  12712. else
  12713. {
  12714. jobs.remove (i);
  12715. if (deleteInactiveJobs)
  12716. delete job;
  12717. }
  12718. }
  12719. lock.exit();
  12720. const uint32 start = Time::getMillisecondCounter();
  12721. while (jobs.size() > 0)
  12722. {
  12723. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12724. return false;
  12725. Thread::sleep (2);
  12726. }
  12727. return true;
  12728. }
  12729. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12730. {
  12731. StringArray s;
  12732. const ScopedLock sl (lock);
  12733. for (int i = 0; i < jobs.size(); ++i)
  12734. {
  12735. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  12736. if (job->isActive || ! onlyReturnActiveJobs)
  12737. s.add (job->getJobName());
  12738. }
  12739. return s;
  12740. }
  12741. bool ThreadPool::setThreadPriorities (const int newPriority)
  12742. {
  12743. bool ok = true;
  12744. if (priority != newPriority)
  12745. {
  12746. priority = newPriority;
  12747. for (int i = numThreads; --i >= 0;)
  12748. if (! threads[i]->setPriority (newPriority))
  12749. ok = false;
  12750. }
  12751. return ok;
  12752. }
  12753. bool ThreadPool::runNextJob()
  12754. {
  12755. lock.enter();
  12756. ThreadPoolJob* job = 0;
  12757. for (int i = 0; i < jobs.size(); ++i)
  12758. {
  12759. job = (ThreadPoolJob*) jobs [i];
  12760. if (job != 0 && ! (job->isActive || job->shouldStop))
  12761. break;
  12762. job = 0;
  12763. }
  12764. if (job != 0)
  12765. {
  12766. job->isActive = true;
  12767. lock.exit();
  12768. JUCE_TRY
  12769. {
  12770. ThreadPoolJob::JobStatus result = job->runJob();
  12771. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12772. const ScopedLock sl (lock);
  12773. if (jobs.contains (job))
  12774. {
  12775. job->isActive = false;
  12776. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12777. {
  12778. job->pool = 0;
  12779. job->shouldStop = true;
  12780. jobs.removeValue (job);
  12781. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12782. delete job;
  12783. }
  12784. else
  12785. {
  12786. // move the job to the end of the queue if it wants another go
  12787. jobs.move (jobs.indexOf (job), -1);
  12788. }
  12789. }
  12790. }
  12791. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12792. catch (...)
  12793. {
  12794. lock.enter();
  12795. jobs.removeValue (job);
  12796. lock.exit();
  12797. }
  12798. #endif
  12799. }
  12800. else
  12801. {
  12802. lock.exit();
  12803. if (threadStopTimeout > 0
  12804. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12805. {
  12806. lock.enter();
  12807. if (jobs.size() == 0)
  12808. {
  12809. for (int i = numThreads; --i >= 0;)
  12810. threads[i]->signalThreadShouldExit();
  12811. }
  12812. lock.exit();
  12813. }
  12814. else
  12815. {
  12816. return false;
  12817. }
  12818. }
  12819. return true;
  12820. }
  12821. END_JUCE_NAMESPACE
  12822. /********* End of inlined file: juce_ThreadPool.cpp *********/
  12823. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  12824. BEGIN_JUCE_NAMESPACE
  12825. TimeSliceThread::TimeSliceThread (const String& threadName)
  12826. : Thread (threadName),
  12827. index (0),
  12828. clientBeingCalled (0),
  12829. clientsChanged (false)
  12830. {
  12831. }
  12832. TimeSliceThread::~TimeSliceThread()
  12833. {
  12834. stopThread (2000);
  12835. }
  12836. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12837. {
  12838. const ScopedLock sl (listLock);
  12839. clients.addIfNotAlreadyThere (client);
  12840. clientsChanged = true;
  12841. notify();
  12842. }
  12843. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12844. {
  12845. const ScopedLock sl1 (listLock);
  12846. clientsChanged = true;
  12847. // if there's a chance we're in the middle of calling this client, we need to
  12848. // also lock the outer lock..
  12849. if (clientBeingCalled == client)
  12850. {
  12851. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12852. const ScopedLock sl1 (callbackLock);
  12853. const ScopedLock sl2 (listLock);
  12854. clients.removeValue (client);
  12855. }
  12856. else
  12857. {
  12858. clients.removeValue (client);
  12859. }
  12860. }
  12861. int TimeSliceThread::getNumClients() const throw()
  12862. {
  12863. return clients.size();
  12864. }
  12865. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  12866. {
  12867. const ScopedLock sl (listLock);
  12868. return clients [index];
  12869. }
  12870. void TimeSliceThread::run()
  12871. {
  12872. int numCallsSinceBusy = 0;
  12873. while (! threadShouldExit())
  12874. {
  12875. int timeToWait = 500;
  12876. {
  12877. const ScopedLock sl (callbackLock);
  12878. {
  12879. const ScopedLock sl (listLock);
  12880. if (clients.size() > 0)
  12881. {
  12882. index = (index + 1) % clients.size();
  12883. clientBeingCalled = clients [index];
  12884. }
  12885. else
  12886. {
  12887. index = 0;
  12888. clientBeingCalled = 0;
  12889. }
  12890. if (clientsChanged)
  12891. {
  12892. clientsChanged = false;
  12893. numCallsSinceBusy = 0;
  12894. }
  12895. }
  12896. if (clientBeingCalled != 0)
  12897. {
  12898. if (clientBeingCalled->useTimeSlice())
  12899. numCallsSinceBusy = 0;
  12900. else
  12901. ++numCallsSinceBusy;
  12902. if (numCallsSinceBusy >= clients.size())
  12903. timeToWait = 500;
  12904. else if (index == 0)
  12905. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12906. else
  12907. timeToWait = 0;
  12908. }
  12909. }
  12910. if (timeToWait > 0)
  12911. wait (timeToWait);
  12912. }
  12913. }
  12914. END_JUCE_NAMESPACE
  12915. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  12916. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  12917. /********* Start of inlined file: juce_Application.cpp *********/
  12918. #if JUCE_MSVC
  12919. #pragma warning (push)
  12920. #pragma warning (disable: 4245 4514 4100)
  12921. #include <crtdbg.h>
  12922. #pragma warning (pop)
  12923. #endif
  12924. BEGIN_JUCE_NAMESPACE
  12925. void juce_setCurrentThreadName (const String& name) throw();
  12926. static JUCEApplication* appInstance = 0;
  12927. JUCEApplication::JUCEApplication()
  12928. : appReturnValue (0),
  12929. stillInitialising (true)
  12930. {
  12931. }
  12932. JUCEApplication::~JUCEApplication()
  12933. {
  12934. }
  12935. JUCEApplication* JUCEApplication::getInstance() throw()
  12936. {
  12937. return appInstance;
  12938. }
  12939. bool JUCEApplication::isInitialising() const throw()
  12940. {
  12941. return stillInitialising;
  12942. }
  12943. const String JUCEApplication::getApplicationVersion()
  12944. {
  12945. return String::empty;
  12946. }
  12947. bool JUCEApplication::moreThanOneInstanceAllowed()
  12948. {
  12949. return true;
  12950. }
  12951. void JUCEApplication::anotherInstanceStarted (const String&)
  12952. {
  12953. }
  12954. void JUCEApplication::systemRequestedQuit()
  12955. {
  12956. quit();
  12957. }
  12958. void JUCEApplication::quit()
  12959. {
  12960. MessageManager::getInstance()->stopDispatchLoop();
  12961. }
  12962. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  12963. {
  12964. appReturnValue = newReturnValue;
  12965. }
  12966. void JUCEApplication::unhandledException (const std::exception*,
  12967. const String&,
  12968. const int)
  12969. {
  12970. jassertfalse
  12971. }
  12972. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  12973. const char* const sourceFile,
  12974. const int lineNumber)
  12975. {
  12976. if (appInstance != 0)
  12977. appInstance->unhandledException (e, sourceFile, lineNumber);
  12978. }
  12979. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  12980. {
  12981. return 0;
  12982. }
  12983. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  12984. {
  12985. commands.add (StandardApplicationCommandIDs::quit);
  12986. }
  12987. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  12988. {
  12989. if (commandID == StandardApplicationCommandIDs::quit)
  12990. {
  12991. result.setInfo ("Quit",
  12992. "Quits the application",
  12993. "Application",
  12994. 0);
  12995. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  12996. }
  12997. }
  12998. bool JUCEApplication::perform (const InvocationInfo& info)
  12999. {
  13000. if (info.commandID == StandardApplicationCommandIDs::quit)
  13001. {
  13002. systemRequestedQuit();
  13003. return true;
  13004. }
  13005. return false;
  13006. }
  13007. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13008. {
  13009. jassert (appInstance == 0);
  13010. appInstance = app;
  13011. app->commandLineParameters = commandLine.trim();
  13012. commandLine = String::empty;
  13013. initialiseJuce_GUI();
  13014. InterProcessLock* appLock = 0;
  13015. if (! app->moreThanOneInstanceAllowed())
  13016. {
  13017. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  13018. if (! appLock->enter(0))
  13019. {
  13020. MessageManager::broadcastMessage (app->getApplicationName() + "/" + app->commandLineParameters);
  13021. delete appInstance;
  13022. appInstance = 0;
  13023. DBG ("Another instance is running - quitting...");
  13024. return 0;
  13025. }
  13026. }
  13027. JUCE_TRY
  13028. {
  13029. juce_setCurrentThreadName ("Juce Message Thread");
  13030. // let the app do its setting-up..
  13031. app->initialise (app->commandLineParameters);
  13032. // register for broadcast new app messages
  13033. MessageManager::getInstance()->registerBroadcastListener (app);
  13034. app->stillInitialising = false;
  13035. // now loop until a quit message is received..
  13036. MessageManager::getInstance()->runDispatchLoop();
  13037. MessageManager::getInstance()->deregisterBroadcastListener (app);
  13038. if (appLock != 0)
  13039. {
  13040. appLock->exit();
  13041. delete appLock;
  13042. }
  13043. }
  13044. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13045. catch (const std::exception& e)
  13046. {
  13047. app->unhandledException (&e, __FILE__, __LINE__);
  13048. }
  13049. catch (...)
  13050. {
  13051. app->unhandledException (0, __FILE__, __LINE__);
  13052. }
  13053. #endif
  13054. return shutdownAppAndClearUp();
  13055. }
  13056. int JUCEApplication::shutdownAppAndClearUp()
  13057. {
  13058. jassert (appInstance != 0);
  13059. JUCEApplication* const app = appInstance;
  13060. int returnValue = 0;
  13061. static bool reentrancyCheck = false;
  13062. if (! reentrancyCheck)
  13063. {
  13064. reentrancyCheck = true;
  13065. JUCE_TRY
  13066. {
  13067. // give the app a chance to clean up..
  13068. app->shutdown();
  13069. }
  13070. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13071. catch (const std::exception& e)
  13072. {
  13073. app->unhandledException (&e, __FILE__, __LINE__);
  13074. }
  13075. catch (...)
  13076. {
  13077. app->unhandledException (0, __FILE__, __LINE__);
  13078. }
  13079. #endif
  13080. JUCE_TRY
  13081. {
  13082. shutdownJuce_GUI();
  13083. returnValue = app->getApplicationReturnValue();
  13084. appInstance = 0;
  13085. delete app;
  13086. }
  13087. JUCE_CATCH_ALL_ASSERT
  13088. reentrancyCheck = false;
  13089. }
  13090. return returnValue;
  13091. }
  13092. int JUCEApplication::main (int argc, char* argv[],
  13093. JUCEApplication* const newApp)
  13094. {
  13095. #if JUCE_MAC
  13096. const ScopedAutoReleasePool pool;
  13097. #endif
  13098. String cmd;
  13099. for (int i = 1; i < argc; ++i)
  13100. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  13101. return JUCEApplication::main (cmd, newApp);
  13102. }
  13103. void JUCEApplication::actionListenerCallback (const String& message)
  13104. {
  13105. if (message.startsWith (getApplicationName() + "/"))
  13106. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13107. }
  13108. static bool juceInitialisedGUI = false;
  13109. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13110. {
  13111. if (! juceInitialisedGUI)
  13112. {
  13113. #if JUCE_MAC
  13114. const ScopedAutoReleasePool pool;
  13115. #endif
  13116. juceInitialisedGUI = true;
  13117. initialiseJuce_NonGUI();
  13118. MessageManager::getInstance();
  13119. LookAndFeel::setDefaultLookAndFeel (0);
  13120. #if JUCE_WIN32 && JUCE_DEBUG
  13121. // This section is just for catching people who mess up their project settings and
  13122. // turn RTTI off..
  13123. try
  13124. {
  13125. TextButton tb (String::empty);
  13126. Component* c = &tb;
  13127. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13128. c = dynamic_cast <Button*> (c);
  13129. }
  13130. catch (...)
  13131. {
  13132. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13133. // got as far as this catch statement, then why haven't you got exception catching
  13134. // turned on in the debugger???
  13135. jassertfalse
  13136. }
  13137. #endif
  13138. }
  13139. }
  13140. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13141. {
  13142. if (juceInitialisedGUI)
  13143. {
  13144. #if JUCE_MAC
  13145. const ScopedAutoReleasePool pool;
  13146. #endif
  13147. {
  13148. DeletedAtShutdown::deleteAll();
  13149. LookAndFeel::clearDefaultLookAndFeel();
  13150. }
  13151. delete MessageManager::getInstance();
  13152. shutdownJuce_NonGUI();
  13153. juceInitialisedGUI = false;
  13154. }
  13155. }
  13156. END_JUCE_NAMESPACE
  13157. /********* End of inlined file: juce_Application.cpp *********/
  13158. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13159. BEGIN_JUCE_NAMESPACE
  13160. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13161. : commandID (commandID_),
  13162. flags (0)
  13163. {
  13164. }
  13165. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13166. const String& description_,
  13167. const String& categoryName_,
  13168. const int flags_) throw()
  13169. {
  13170. shortName = shortName_;
  13171. description = description_;
  13172. categoryName = categoryName_;
  13173. flags = flags_;
  13174. }
  13175. void ApplicationCommandInfo::setActive (const bool b) throw()
  13176. {
  13177. if (b)
  13178. flags &= ~isDisabled;
  13179. else
  13180. flags |= isDisabled;
  13181. }
  13182. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13183. {
  13184. if (b)
  13185. flags |= isTicked;
  13186. else
  13187. flags &= ~isTicked;
  13188. }
  13189. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13190. {
  13191. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13192. }
  13193. END_JUCE_NAMESPACE
  13194. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13195. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  13196. BEGIN_JUCE_NAMESPACE
  13197. ApplicationCommandManager::ApplicationCommandManager()
  13198. : listeners (8),
  13199. firstTarget (0)
  13200. {
  13201. keyMappings = new KeyPressMappingSet (this);
  13202. Desktop::getInstance().addFocusChangeListener (this);
  13203. }
  13204. ApplicationCommandManager::~ApplicationCommandManager()
  13205. {
  13206. Desktop::getInstance().removeFocusChangeListener (this);
  13207. deleteAndZero (keyMappings);
  13208. }
  13209. void ApplicationCommandManager::clearCommands()
  13210. {
  13211. commands.clear();
  13212. keyMappings->clearAllKeyPresses();
  13213. triggerAsyncUpdate();
  13214. }
  13215. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13216. {
  13217. // zero isn't a valid command ID!
  13218. jassert (newCommand.commandID != 0);
  13219. // the name isn't optional!
  13220. jassert (newCommand.shortName.isNotEmpty());
  13221. if (getCommandForID (newCommand.commandID) == 0)
  13222. {
  13223. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13224. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13225. commands.add (newInfo);
  13226. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13227. triggerAsyncUpdate();
  13228. }
  13229. else
  13230. {
  13231. // trying to re-register the same command with different parameters?
  13232. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13233. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13234. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13235. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13236. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13237. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13238. }
  13239. }
  13240. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13241. {
  13242. if (target != 0)
  13243. {
  13244. Array <CommandID> commandIDs;
  13245. target->getAllCommands (commandIDs);
  13246. for (int i = 0; i < commandIDs.size(); ++i)
  13247. {
  13248. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13249. target->getCommandInfo (info.commandID, info);
  13250. registerCommand (info);
  13251. }
  13252. }
  13253. }
  13254. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13255. {
  13256. for (int i = commands.size(); --i >= 0;)
  13257. {
  13258. if (commands.getUnchecked (i)->commandID == commandID)
  13259. {
  13260. commands.remove (i);
  13261. triggerAsyncUpdate();
  13262. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13263. for (int j = keys.size(); --j >= 0;)
  13264. keyMappings->removeKeyPress (keys.getReference (j));
  13265. }
  13266. }
  13267. }
  13268. void ApplicationCommandManager::commandStatusChanged()
  13269. {
  13270. triggerAsyncUpdate();
  13271. }
  13272. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13273. {
  13274. for (int i = commands.size(); --i >= 0;)
  13275. if (commands.getUnchecked(i)->commandID == commandID)
  13276. return commands.getUnchecked(i);
  13277. return 0;
  13278. }
  13279. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13280. {
  13281. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13282. return (ci != 0) ? ci->shortName : String::empty;
  13283. }
  13284. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13285. {
  13286. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13287. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13288. : String::empty;
  13289. }
  13290. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13291. {
  13292. StringArray s;
  13293. for (int i = 0; i < commands.size(); ++i)
  13294. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13295. return s;
  13296. }
  13297. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13298. {
  13299. Array <CommandID> results (4);
  13300. for (int i = 0; i < commands.size(); ++i)
  13301. if (commands.getUnchecked(i)->categoryName == categoryName)
  13302. results.add (commands.getUnchecked(i)->commandID);
  13303. return results;
  13304. }
  13305. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13306. {
  13307. ApplicationCommandTarget::InvocationInfo info (commandID);
  13308. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13309. return invoke (info, asynchronously);
  13310. }
  13311. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13312. {
  13313. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13314. // manager first..
  13315. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13316. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13317. if (target == 0)
  13318. return false;
  13319. ApplicationCommandInfo commandInfo (0);
  13320. target->getCommandInfo (info_.commandID, commandInfo);
  13321. ApplicationCommandTarget::InvocationInfo info (info_);
  13322. info.commandFlags = commandInfo.flags;
  13323. sendListenerInvokeCallback (info);
  13324. const bool ok = target->invoke (info, asynchronously);
  13325. commandStatusChanged();
  13326. return ok;
  13327. }
  13328. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13329. {
  13330. return firstTarget != 0 ? firstTarget
  13331. : findDefaultComponentTarget();
  13332. }
  13333. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13334. {
  13335. firstTarget = newTarget;
  13336. }
  13337. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13338. ApplicationCommandInfo& upToDateInfo)
  13339. {
  13340. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13341. if (target == 0)
  13342. target = JUCEApplication::getInstance();
  13343. if (target != 0)
  13344. target = target->getTargetForCommand (commandID);
  13345. if (target != 0)
  13346. target->getCommandInfo (commandID, upToDateInfo);
  13347. return target;
  13348. }
  13349. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13350. {
  13351. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13352. if (target == 0 && c != 0)
  13353. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13354. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13355. return target;
  13356. }
  13357. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  13358. {
  13359. Component* c = Component::getCurrentlyFocusedComponent();
  13360. if (c == 0)
  13361. {
  13362. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  13363. if (activeWindow != 0)
  13364. {
  13365. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  13366. if (c == 0)
  13367. c = activeWindow;
  13368. }
  13369. }
  13370. if (c == 0 && Process::isForegroundProcess())
  13371. {
  13372. // getting a bit desperate now - try all desktop comps..
  13373. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  13374. {
  13375. ApplicationCommandTarget* const target
  13376. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  13377. ->getPeer()->getLastFocusedSubcomponent());
  13378. if (target != 0)
  13379. return target;
  13380. }
  13381. }
  13382. if (c != 0)
  13383. {
  13384. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  13385. // if we're focused on a ResizableWindow, chances are that it's the content
  13386. // component that really should get the event. And if not, the event will
  13387. // still be passed up to the top level window anyway, so let's send it to the
  13388. // content comp.
  13389. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  13390. c = resizableWindow->getContentComponent();
  13391. ApplicationCommandTarget* const target = findTargetForComponent (c);
  13392. if (target != 0)
  13393. return target;
  13394. }
  13395. return JUCEApplication::getInstance();
  13396. }
  13397. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  13398. {
  13399. jassert (listener != 0);
  13400. if (listener != 0)
  13401. listeners.add (listener);
  13402. }
  13403. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  13404. {
  13405. listeners.removeValue (listener);
  13406. }
  13407. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  13408. {
  13409. for (int i = listeners.size(); --i >= 0;)
  13410. {
  13411. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  13412. i = jmin (i, listeners.size());
  13413. }
  13414. }
  13415. void ApplicationCommandManager::handleAsyncUpdate()
  13416. {
  13417. for (int i = listeners.size(); --i >= 0;)
  13418. {
  13419. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  13420. i = jmin (i, listeners.size());
  13421. }
  13422. }
  13423. void ApplicationCommandManager::globalFocusChanged (Component*)
  13424. {
  13425. commandStatusChanged();
  13426. }
  13427. END_JUCE_NAMESPACE
  13428. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  13429. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13430. BEGIN_JUCE_NAMESPACE
  13431. ApplicationCommandTarget::ApplicationCommandTarget()
  13432. : messageInvoker (0)
  13433. {
  13434. }
  13435. ApplicationCommandTarget::~ApplicationCommandTarget()
  13436. {
  13437. deleteAndZero (messageInvoker);
  13438. }
  13439. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  13440. {
  13441. if (isCommandActive (info.commandID))
  13442. {
  13443. if (async)
  13444. {
  13445. if (messageInvoker == 0)
  13446. messageInvoker = new CommandTargetMessageInvoker (this);
  13447. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  13448. return true;
  13449. }
  13450. else
  13451. {
  13452. const bool success = perform (info);
  13453. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  13454. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  13455. // returns the command's info.
  13456. return success;
  13457. }
  13458. }
  13459. return false;
  13460. }
  13461. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  13462. {
  13463. Component* c = dynamic_cast <Component*> (this);
  13464. if (c != 0)
  13465. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13466. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13467. return 0;
  13468. }
  13469. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  13470. {
  13471. ApplicationCommandTarget* target = this;
  13472. int depth = 0;
  13473. while (target != 0)
  13474. {
  13475. Array <CommandID> commandIDs;
  13476. target->getAllCommands (commandIDs);
  13477. if (commandIDs.contains (commandID))
  13478. return target;
  13479. target = target->getNextCommandTarget();
  13480. ++depth;
  13481. jassert (depth < 100); // could be a recursive command chain??
  13482. jassert (target != this); // definitely a recursive command chain!
  13483. if (depth > 100 || target == this)
  13484. break;
  13485. }
  13486. if (target == 0)
  13487. {
  13488. target = JUCEApplication::getInstance();
  13489. if (target != 0)
  13490. {
  13491. Array <CommandID> commandIDs;
  13492. target->getAllCommands (commandIDs);
  13493. if (commandIDs.contains (commandID))
  13494. return target;
  13495. }
  13496. }
  13497. return 0;
  13498. }
  13499. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  13500. {
  13501. ApplicationCommandInfo info (commandID);
  13502. info.flags = ApplicationCommandInfo::isDisabled;
  13503. getCommandInfo (commandID, info);
  13504. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  13505. }
  13506. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  13507. {
  13508. ApplicationCommandTarget* target = this;
  13509. int depth = 0;
  13510. while (target != 0)
  13511. {
  13512. if (target->tryToInvoke (info, async))
  13513. return true;
  13514. target = target->getNextCommandTarget();
  13515. ++depth;
  13516. jassert (depth < 100); // could be a recursive command chain??
  13517. jassert (target != this); // definitely a recursive command chain!
  13518. if (depth > 100 || target == this)
  13519. break;
  13520. }
  13521. if (target == 0)
  13522. {
  13523. target = JUCEApplication::getInstance();
  13524. if (target != 0)
  13525. return target->tryToInvoke (info, async);
  13526. }
  13527. return false;
  13528. }
  13529. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13530. {
  13531. ApplicationCommandTarget::InvocationInfo info (commandID);
  13532. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13533. return invoke (info, asynchronously);
  13534. }
  13535. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  13536. : commandID (commandID_),
  13537. commandFlags (0),
  13538. invocationMethod (direct),
  13539. originatingComponent (0),
  13540. isKeyDown (false),
  13541. millisecsSinceKeyPressed (0)
  13542. {
  13543. }
  13544. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  13545. : owner (owner_)
  13546. {
  13547. }
  13548. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  13549. {
  13550. }
  13551. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  13552. {
  13553. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  13554. owner->tryToInvoke (*info, false);
  13555. delete info;
  13556. }
  13557. END_JUCE_NAMESPACE
  13558. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13559. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  13560. BEGIN_JUCE_NAMESPACE
  13561. juce_ImplementSingleton (ApplicationProperties)
  13562. ApplicationProperties::ApplicationProperties() throw()
  13563. : userProps (0),
  13564. commonProps (0),
  13565. msBeforeSaving (3000),
  13566. options (PropertiesFile::storeAsBinary),
  13567. commonSettingsAreReadOnly (0)
  13568. {
  13569. }
  13570. ApplicationProperties::~ApplicationProperties()
  13571. {
  13572. closeFiles();
  13573. clearSingletonInstance();
  13574. }
  13575. void ApplicationProperties::setStorageParameters (const String& applicationName,
  13576. const String& fileNameSuffix,
  13577. const String& folderName_,
  13578. const int millisecondsBeforeSaving,
  13579. const int propertiesFileOptions) throw()
  13580. {
  13581. appName = applicationName;
  13582. fileSuffix = fileNameSuffix;
  13583. folderName = folderName_;
  13584. msBeforeSaving = millisecondsBeforeSaving;
  13585. options = propertiesFileOptions;
  13586. }
  13587. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  13588. const bool testCommonSettings,
  13589. const bool showWarningDialogOnFailure)
  13590. {
  13591. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  13592. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  13593. if (! (userOk && commonOk))
  13594. {
  13595. if (showWarningDialogOnFailure)
  13596. {
  13597. String filenames;
  13598. if (userProps != 0 && ! userOk)
  13599. filenames << '\n' << userProps->getFile().getFullPathName();
  13600. if (commonProps != 0 && ! commonOk)
  13601. filenames << '\n' << commonProps->getFile().getFullPathName();
  13602. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13603. appName + TRANS(" - Unable to save settings"),
  13604. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  13605. + appName + TRANS(" needs to be able to write to the following files:\n")
  13606. + filenames
  13607. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  13608. }
  13609. return false;
  13610. }
  13611. return true;
  13612. }
  13613. void ApplicationProperties::openFiles() throw()
  13614. {
  13615. // You need to call setStorageParameters() before trying to get hold of the
  13616. // properties!
  13617. jassert (appName.isNotEmpty());
  13618. if (appName.isNotEmpty())
  13619. {
  13620. if (userProps == 0)
  13621. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13622. false, msBeforeSaving, options);
  13623. if (commonProps == 0)
  13624. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13625. true, msBeforeSaving, options);
  13626. userProps->setFallbackPropertySet (commonProps);
  13627. }
  13628. }
  13629. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  13630. {
  13631. if (userProps == 0)
  13632. openFiles();
  13633. return userProps;
  13634. }
  13635. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  13636. {
  13637. if (commonProps == 0)
  13638. openFiles();
  13639. if (returnUserPropsIfReadOnly)
  13640. {
  13641. if (commonSettingsAreReadOnly == 0)
  13642. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  13643. if (commonSettingsAreReadOnly > 0)
  13644. return userProps;
  13645. }
  13646. return commonProps;
  13647. }
  13648. bool ApplicationProperties::saveIfNeeded()
  13649. {
  13650. return (userProps == 0 || userProps->saveIfNeeded())
  13651. && (commonProps == 0 || commonProps->saveIfNeeded());
  13652. }
  13653. void ApplicationProperties::closeFiles()
  13654. {
  13655. deleteAndZero (userProps);
  13656. deleteAndZero (commonProps);
  13657. }
  13658. END_JUCE_NAMESPACE
  13659. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  13660. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  13661. BEGIN_JUCE_NAMESPACE
  13662. static VoidArray objectsToDelete (16);
  13663. static CriticalSection lock;
  13664. DeletedAtShutdown::DeletedAtShutdown() throw()
  13665. {
  13666. const ScopedLock sl (lock);
  13667. objectsToDelete.add (this);
  13668. }
  13669. DeletedAtShutdown::~DeletedAtShutdown()
  13670. {
  13671. const ScopedLock sl (lock);
  13672. objectsToDelete.removeValue (this);
  13673. }
  13674. void DeletedAtShutdown::deleteAll()
  13675. {
  13676. // make a local copy of the array, so it can't get into a loop if something
  13677. // creates another DeletedAtShutdown object during its destructor.
  13678. lock.enter();
  13679. const VoidArray localCopy (objectsToDelete);
  13680. lock.exit();
  13681. for (int i = localCopy.size(); --i >= 0;)
  13682. {
  13683. JUCE_TRY
  13684. {
  13685. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  13686. // double-check that it's not already been deleted during another object's destructor.
  13687. lock.enter();
  13688. const bool okToDelete = objectsToDelete.contains (deletee);
  13689. lock.exit();
  13690. if (okToDelete)
  13691. delete deletee;
  13692. }
  13693. JUCE_CATCH_EXCEPTION
  13694. }
  13695. // if no objects got re-created during shutdown, this should have been emptied by their
  13696. // destructors
  13697. jassert (objectsToDelete.size() == 0);
  13698. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  13699. }
  13700. END_JUCE_NAMESPACE
  13701. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  13702. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  13703. BEGIN_JUCE_NAMESPACE
  13704. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  13705. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  13706. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  13707. static const tchar* const propertyTagName = T("VALUE");
  13708. PropertiesFile::PropertiesFile (const File& f,
  13709. const int millisecondsBeforeSaving,
  13710. const int options_) throw()
  13711. : PropertySet (ignoreCaseOfKeyNames),
  13712. file (f),
  13713. timerInterval (millisecondsBeforeSaving),
  13714. options (options_),
  13715. needsWriting (false)
  13716. {
  13717. // You need to correctly specify just one storage format for the file
  13718. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  13719. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  13720. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  13721. InputStream* fileStream = f.createInputStream();
  13722. if (fileStream != 0)
  13723. {
  13724. int magicNumber = fileStream->readInt();
  13725. if (magicNumber == propFileMagicNumberCompressed)
  13726. {
  13727. fileStream = new SubregionStream (fileStream, 4, -1, true);
  13728. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  13729. magicNumber = propFileMagicNumber;
  13730. }
  13731. if (magicNumber == propFileMagicNumber)
  13732. {
  13733. BufferedInputStream in (fileStream, 2048, true);
  13734. int numValues = in.readInt();
  13735. while (--numValues >= 0 && ! in.isExhausted())
  13736. {
  13737. const String key (in.readString());
  13738. const String value (in.readString());
  13739. jassert (key.isNotEmpty());
  13740. if (key.isNotEmpty())
  13741. getAllProperties().set (key, value);
  13742. }
  13743. }
  13744. else
  13745. {
  13746. // Not a binary props file - let's see if it's XML..
  13747. delete fileStream;
  13748. XmlDocument parser (f);
  13749. XmlElement* doc = parser.getDocumentElement (true);
  13750. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  13751. {
  13752. delete doc;
  13753. doc = parser.getDocumentElement();
  13754. if (doc != 0)
  13755. {
  13756. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  13757. {
  13758. const String name (e->getStringAttribute (T("name")));
  13759. if (name.isNotEmpty())
  13760. {
  13761. getAllProperties().set (name,
  13762. e->getFirstChildElement() != 0
  13763. ? e->getFirstChildElement()->createDocument (String::empty, true)
  13764. : e->getStringAttribute (T("val")));
  13765. }
  13766. }
  13767. }
  13768. else
  13769. {
  13770. // must be a pretty broken XML file we're trying to parse here!
  13771. jassertfalse
  13772. }
  13773. delete doc;
  13774. }
  13775. }
  13776. }
  13777. }
  13778. PropertiesFile::~PropertiesFile()
  13779. {
  13780. saveIfNeeded();
  13781. }
  13782. bool PropertiesFile::saveIfNeeded()
  13783. {
  13784. const ScopedLock sl (getLock());
  13785. return (! needsWriting) || save();
  13786. }
  13787. bool PropertiesFile::needsToBeSaved() const throw()
  13788. {
  13789. const ScopedLock sl (getLock());
  13790. return needsWriting;
  13791. }
  13792. bool PropertiesFile::save()
  13793. {
  13794. const ScopedLock sl (getLock());
  13795. stopTimer();
  13796. if (file == File::nonexistent
  13797. || file.isDirectory()
  13798. || ! file.getParentDirectory().createDirectory())
  13799. return false;
  13800. if ((options & storeAsXML) != 0)
  13801. {
  13802. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  13803. for (int i = 0; i < getAllProperties().size(); ++i)
  13804. {
  13805. XmlElement* const e = new XmlElement (propertyTagName);
  13806. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  13807. // if the value seems to contain xml, store it as such..
  13808. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  13809. XmlElement* const childElement = xmlContent.getDocumentElement();
  13810. if (childElement != 0)
  13811. e->addChildElement (childElement);
  13812. else
  13813. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  13814. doc->addChildElement (e);
  13815. }
  13816. const bool ok = doc->writeToFile (file, String::empty);
  13817. delete doc;
  13818. return ok;
  13819. }
  13820. else
  13821. {
  13822. const File tempFile (file.getNonexistentSibling (false));
  13823. OutputStream* out = tempFile.createOutputStream();
  13824. if (out != 0)
  13825. {
  13826. if ((options & storeAsCompressedBinary) != 0)
  13827. {
  13828. out->writeInt (propFileMagicNumberCompressed);
  13829. out->flush();
  13830. out = new GZIPCompressorOutputStream (out, 9, true);
  13831. }
  13832. else
  13833. {
  13834. // have you set up the storage option flags correctly?
  13835. jassert ((options & storeAsBinary) != 0);
  13836. out->writeInt (propFileMagicNumber);
  13837. }
  13838. const int numProperties = getAllProperties().size();
  13839. out->writeInt (numProperties);
  13840. for (int i = 0; i < numProperties; ++i)
  13841. {
  13842. out->writeString (getAllProperties().getAllKeys() [i]);
  13843. out->writeString (getAllProperties().getAllValues() [i]);
  13844. }
  13845. out->flush();
  13846. delete out;
  13847. if (tempFile.moveFileTo (file))
  13848. {
  13849. needsWriting = false;
  13850. return true;
  13851. }
  13852. tempFile.deleteFile();
  13853. }
  13854. }
  13855. return false;
  13856. }
  13857. void PropertiesFile::timerCallback()
  13858. {
  13859. saveIfNeeded();
  13860. }
  13861. void PropertiesFile::propertyChanged()
  13862. {
  13863. sendChangeMessage (this);
  13864. needsWriting = true;
  13865. if (timerInterval > 0)
  13866. startTimer (timerInterval);
  13867. else if (timerInterval == 0)
  13868. saveIfNeeded();
  13869. }
  13870. const File PropertiesFile::getFile() const throw()
  13871. {
  13872. return file;
  13873. }
  13874. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  13875. const String& fileNameSuffix,
  13876. const String& folderName,
  13877. const bool commonToAllUsers)
  13878. {
  13879. // mustn't have illegal characters in this name..
  13880. jassert (applicationName == File::createLegalFileName (applicationName));
  13881. #if JUCE_MAC
  13882. File dir (commonToAllUsers ? "/Library/Preferences"
  13883. : "~/Library/Preferences");
  13884. if (folderName.isNotEmpty())
  13885. dir = dir.getChildFile (folderName);
  13886. #endif
  13887. #ifdef JUCE_LINUX
  13888. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  13889. + (folderName.isNotEmpty() ? folderName
  13890. : (T(".") + applicationName)));
  13891. #endif
  13892. #if JUCE_WIN32
  13893. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  13894. : File::userApplicationDataDirectory));
  13895. if (dir == File::nonexistent)
  13896. return File::nonexistent;
  13897. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  13898. : applicationName);
  13899. #endif
  13900. return dir.getChildFile (applicationName)
  13901. .withFileExtension (fileNameSuffix);
  13902. }
  13903. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  13904. const String& fileNameSuffix,
  13905. const String& folderName,
  13906. const bool commonToAllUsers,
  13907. const int millisecondsBeforeSaving,
  13908. const int propertiesFileOptions)
  13909. {
  13910. const File file (getDefaultAppSettingsFile (applicationName,
  13911. fileNameSuffix,
  13912. folderName,
  13913. commonToAllUsers));
  13914. jassert (file != File::nonexistent);
  13915. if (file == File::nonexistent)
  13916. return 0;
  13917. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  13918. }
  13919. END_JUCE_NAMESPACE
  13920. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  13921. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  13922. BEGIN_JUCE_NAMESPACE
  13923. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  13924. const String& fileWildcard_,
  13925. const String& openFileDialogTitle_,
  13926. const String& saveFileDialogTitle_)
  13927. : changedSinceSave (false),
  13928. fileExtension (fileExtension_),
  13929. fileWildcard (fileWildcard_),
  13930. openFileDialogTitle (openFileDialogTitle_),
  13931. saveFileDialogTitle (saveFileDialogTitle_)
  13932. {
  13933. }
  13934. FileBasedDocument::~FileBasedDocument()
  13935. {
  13936. }
  13937. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  13938. {
  13939. changedSinceSave = hasChanged;
  13940. }
  13941. void FileBasedDocument::changed()
  13942. {
  13943. changedSinceSave = true;
  13944. sendChangeMessage (this);
  13945. }
  13946. void FileBasedDocument::setFile (const File& newFile)
  13947. {
  13948. if (documentFile != newFile)
  13949. {
  13950. documentFile = newFile;
  13951. changedSinceSave = true;
  13952. }
  13953. }
  13954. bool FileBasedDocument::loadFrom (const File& newFile,
  13955. const bool showMessageOnFailure)
  13956. {
  13957. MouseCursor::showWaitCursor();
  13958. const File oldFile (documentFile);
  13959. documentFile = newFile;
  13960. String error;
  13961. if (newFile.existsAsFile())
  13962. {
  13963. error = loadDocument (newFile);
  13964. if (error.isEmpty())
  13965. {
  13966. setChangedFlag (false);
  13967. MouseCursor::hideWaitCursor();
  13968. setLastDocumentOpened (newFile);
  13969. return true;
  13970. }
  13971. }
  13972. else
  13973. {
  13974. error = "The file doesn't exist";
  13975. }
  13976. documentFile = oldFile;
  13977. MouseCursor::hideWaitCursor();
  13978. if (showMessageOnFailure)
  13979. {
  13980. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13981. TRANS("Failed to open file..."),
  13982. TRANS("There was an error while trying to load the file:\n\n")
  13983. + newFile.getFullPathName()
  13984. + T("\n\n")
  13985. + error);
  13986. }
  13987. return false;
  13988. }
  13989. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  13990. {
  13991. FileChooser fc (openFileDialogTitle,
  13992. getLastDocumentOpened(),
  13993. fileWildcard);
  13994. if (fc.browseForFileToOpen())
  13995. return loadFrom (fc.getResult(), showMessageOnFailure);
  13996. return false;
  13997. }
  13998. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  13999. const bool showMessageOnFailure)
  14000. {
  14001. return saveAs (documentFile,
  14002. false,
  14003. askUserForFileIfNotSpecified,
  14004. showMessageOnFailure);
  14005. }
  14006. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14007. const bool warnAboutOverwritingExistingFiles,
  14008. const bool askUserForFileIfNotSpecified,
  14009. const bool showMessageOnFailure)
  14010. {
  14011. if (newFile == File::nonexistent)
  14012. {
  14013. if (askUserForFileIfNotSpecified)
  14014. {
  14015. return saveAsInteractive (true);
  14016. }
  14017. else
  14018. {
  14019. // can't save to an unspecified file
  14020. jassertfalse
  14021. return failedToWriteToFile;
  14022. }
  14023. }
  14024. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14025. {
  14026. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14027. TRANS("File already exists"),
  14028. TRANS("There's already a file called:\n\n")
  14029. + newFile.getFullPathName()
  14030. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14031. TRANS("overwrite"),
  14032. TRANS("cancel")))
  14033. {
  14034. return userCancelledSave;
  14035. }
  14036. }
  14037. MouseCursor::showWaitCursor();
  14038. const File oldFile (documentFile);
  14039. documentFile = newFile;
  14040. String error (saveDocument (newFile));
  14041. if (error.isEmpty())
  14042. {
  14043. setChangedFlag (false);
  14044. MouseCursor::hideWaitCursor();
  14045. return savedOk;
  14046. }
  14047. documentFile = oldFile;
  14048. MouseCursor::hideWaitCursor();
  14049. if (showMessageOnFailure)
  14050. {
  14051. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14052. TRANS("Error writing to file..."),
  14053. TRANS("An error occurred while trying to save \"")
  14054. + getDocumentTitle()
  14055. + TRANS("\" to the file:\n\n")
  14056. + newFile.getFullPathName()
  14057. + T("\n\n")
  14058. + error);
  14059. }
  14060. return failedToWriteToFile;
  14061. }
  14062. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14063. {
  14064. if (! hasChangedSinceSaved())
  14065. return savedOk;
  14066. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14067. TRANS("Closing document..."),
  14068. TRANS("Do you want to save the changes to \"")
  14069. + getDocumentTitle() + T("\"?"),
  14070. TRANS("save"),
  14071. TRANS("discard changes"),
  14072. TRANS("cancel"));
  14073. if (r == 1)
  14074. {
  14075. // save changes
  14076. return save (true, true);
  14077. }
  14078. else if (r == 2)
  14079. {
  14080. // discard changes
  14081. return savedOk;
  14082. }
  14083. return userCancelledSave;
  14084. }
  14085. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14086. {
  14087. File f;
  14088. if (documentFile.existsAsFile())
  14089. f = documentFile;
  14090. else
  14091. f = getLastDocumentOpened();
  14092. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14093. if (legalFilename.isEmpty())
  14094. legalFilename = "unnamed";
  14095. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14096. f = f.getSiblingFile (legalFilename);
  14097. else
  14098. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14099. f = f.withFileExtension (fileExtension)
  14100. .getNonexistentSibling (true);
  14101. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14102. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14103. {
  14104. setLastDocumentOpened (fc.getResult());
  14105. File chosen (fc.getResult());
  14106. if (chosen.getFileExtension().isEmpty())
  14107. chosen = chosen.withFileExtension (fileExtension);
  14108. return saveAs (chosen, false, false, true);
  14109. }
  14110. return userCancelledSave;
  14111. }
  14112. END_JUCE_NAMESPACE
  14113. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  14114. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14115. BEGIN_JUCE_NAMESPACE
  14116. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14117. : maxNumberOfItems (10)
  14118. {
  14119. }
  14120. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14121. {
  14122. }
  14123. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14124. {
  14125. maxNumberOfItems = jmax (1, newMaxNumber);
  14126. while (getNumFiles() > maxNumberOfItems)
  14127. files.remove (getNumFiles() - 1);
  14128. }
  14129. int RecentlyOpenedFilesList::getNumFiles() const
  14130. {
  14131. return files.size();
  14132. }
  14133. const File RecentlyOpenedFilesList::getFile (const int index) const
  14134. {
  14135. return File (files [index]);
  14136. }
  14137. void RecentlyOpenedFilesList::clear()
  14138. {
  14139. files.clear();
  14140. }
  14141. void RecentlyOpenedFilesList::addFile (const File& file)
  14142. {
  14143. const String path (file.getFullPathName());
  14144. files.removeString (path, true);
  14145. files.insert (0, path);
  14146. setMaxNumberOfItems (maxNumberOfItems);
  14147. }
  14148. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14149. {
  14150. for (int i = getNumFiles(); --i >= 0;)
  14151. if (! getFile(i).exists())
  14152. files.remove (i);
  14153. }
  14154. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14155. const int baseItemId,
  14156. const bool showFullPaths,
  14157. const bool dontAddNonExistentFiles,
  14158. const File** filesToAvoid)
  14159. {
  14160. int num = 0;
  14161. for (int i = 0; i < getNumFiles(); ++i)
  14162. {
  14163. const File f (getFile(i));
  14164. if ((! dontAddNonExistentFiles) || f.exists())
  14165. {
  14166. bool needsAvoiding = false;
  14167. if (filesToAvoid != 0)
  14168. {
  14169. const File** files = filesToAvoid;
  14170. while (*files != 0)
  14171. {
  14172. if (f == **files)
  14173. {
  14174. needsAvoiding = true;
  14175. break;
  14176. }
  14177. ++files;
  14178. }
  14179. }
  14180. if (! needsAvoiding)
  14181. {
  14182. menuToAddTo.addItem (baseItemId + i,
  14183. showFullPaths ? f.getFullPathName()
  14184. : f.getFileName());
  14185. ++num;
  14186. }
  14187. }
  14188. }
  14189. return num;
  14190. }
  14191. const String RecentlyOpenedFilesList::toString() const
  14192. {
  14193. return files.joinIntoString (T("\n"));
  14194. }
  14195. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14196. {
  14197. clear();
  14198. files.addLines (stringifiedVersion);
  14199. setMaxNumberOfItems (maxNumberOfItems);
  14200. }
  14201. END_JUCE_NAMESPACE
  14202. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14203. /********* Start of inlined file: juce_UndoManager.cpp *********/
  14204. BEGIN_JUCE_NAMESPACE
  14205. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14206. const int minimumTransactions)
  14207. : totalUnitsStored (0),
  14208. nextIndex (0),
  14209. newTransaction (true),
  14210. reentrancyCheck (false)
  14211. {
  14212. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14213. minimumTransactions);
  14214. }
  14215. UndoManager::~UndoManager()
  14216. {
  14217. clearUndoHistory();
  14218. }
  14219. void UndoManager::clearUndoHistory()
  14220. {
  14221. transactions.clear();
  14222. transactionNames.clear();
  14223. totalUnitsStored = 0;
  14224. nextIndex = 0;
  14225. sendChangeMessage (this);
  14226. }
  14227. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14228. {
  14229. return totalUnitsStored;
  14230. }
  14231. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14232. const int minimumTransactions)
  14233. {
  14234. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14235. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14236. }
  14237. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  14238. {
  14239. if (command != 0)
  14240. {
  14241. if (actionName.isNotEmpty())
  14242. currentTransactionName = actionName;
  14243. if (reentrancyCheck)
  14244. {
  14245. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14246. // undo() methods, or else these actions won't actually get done.
  14247. return false;
  14248. }
  14249. else
  14250. {
  14251. bool success = false;
  14252. JUCE_TRY
  14253. {
  14254. success = command->perform();
  14255. }
  14256. JUCE_CATCH_EXCEPTION
  14257. jassert (success);
  14258. if (success)
  14259. {
  14260. if (nextIndex > 0 && ! newTransaction)
  14261. {
  14262. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14263. jassert (commandSet != 0);
  14264. if (commandSet == 0)
  14265. return false;
  14266. commandSet->add (command);
  14267. }
  14268. else
  14269. {
  14270. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  14271. commandSet->add (command);
  14272. transactions.insert (nextIndex, commandSet);
  14273. transactionNames.insert (nextIndex, currentTransactionName);
  14274. ++nextIndex;
  14275. }
  14276. totalUnitsStored += command->getSizeInUnits();
  14277. newTransaction = false;
  14278. }
  14279. while (nextIndex < transactions.size())
  14280. {
  14281. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14282. for (int i = lastSet->size(); --i >= 0;)
  14283. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14284. transactions.removeLast();
  14285. transactionNames.remove (transactionNames.size() - 1);
  14286. }
  14287. while (nextIndex > 0
  14288. && totalUnitsStored > maxNumUnitsToKeep
  14289. && transactions.size() > minimumTransactionsToKeep)
  14290. {
  14291. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14292. for (int i = firstSet->size(); --i >= 0;)
  14293. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14294. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14295. transactions.remove (0);
  14296. transactionNames.remove (0);
  14297. --nextIndex;
  14298. }
  14299. sendChangeMessage (this);
  14300. return success;
  14301. }
  14302. }
  14303. return false;
  14304. }
  14305. void UndoManager::beginNewTransaction (const String& actionName)
  14306. {
  14307. newTransaction = true;
  14308. currentTransactionName = actionName;
  14309. }
  14310. void UndoManager::setCurrentTransactionName (const String& newName)
  14311. {
  14312. currentTransactionName = newName;
  14313. }
  14314. bool UndoManager::canUndo() const
  14315. {
  14316. return nextIndex > 0;
  14317. }
  14318. bool UndoManager::canRedo() const
  14319. {
  14320. return nextIndex < transactions.size();
  14321. }
  14322. const String UndoManager::getUndoDescription() const
  14323. {
  14324. return transactionNames [nextIndex - 1];
  14325. }
  14326. const String UndoManager::getRedoDescription() const
  14327. {
  14328. return transactionNames [nextIndex];
  14329. }
  14330. bool UndoManager::undo()
  14331. {
  14332. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14333. if (commandSet == 0)
  14334. return false;
  14335. reentrancyCheck = true;
  14336. bool failed = false;
  14337. for (int i = commandSet->size(); --i >= 0;)
  14338. {
  14339. if (! commandSet->getUnchecked(i)->undo())
  14340. {
  14341. jassertfalse
  14342. failed = true;
  14343. break;
  14344. }
  14345. }
  14346. reentrancyCheck = false;
  14347. if (failed)
  14348. {
  14349. clearUndoHistory();
  14350. }
  14351. else
  14352. {
  14353. --nextIndex;
  14354. }
  14355. beginNewTransaction();
  14356. sendChangeMessage (this);
  14357. return true;
  14358. }
  14359. bool UndoManager::redo()
  14360. {
  14361. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  14362. if (commandSet == 0)
  14363. return false;
  14364. reentrancyCheck = true;
  14365. bool failed = false;
  14366. for (int i = 0; i < commandSet->size(); ++i)
  14367. {
  14368. if (! commandSet->getUnchecked(i)->perform())
  14369. {
  14370. jassertfalse
  14371. failed = true;
  14372. break;
  14373. }
  14374. }
  14375. reentrancyCheck = false;
  14376. if (failed)
  14377. {
  14378. clearUndoHistory();
  14379. }
  14380. else
  14381. {
  14382. ++nextIndex;
  14383. }
  14384. beginNewTransaction();
  14385. sendChangeMessage (this);
  14386. return true;
  14387. }
  14388. bool UndoManager::undoCurrentTransactionOnly()
  14389. {
  14390. return newTransaction ? false
  14391. : undo();
  14392. }
  14393. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  14394. {
  14395. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14396. if (commandSet != 0 && ! newTransaction)
  14397. {
  14398. for (int i = 0; i < commandSet->size(); ++i)
  14399. actionsFound.add (commandSet->getUnchecked(i));
  14400. }
  14401. }
  14402. END_JUCE_NAMESPACE
  14403. /********* End of inlined file: juce_UndoManager.cpp *********/
  14404. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  14405. BEGIN_JUCE_NAMESPACE
  14406. #undef chunkName
  14407. #define chunkName(a) (int)littleEndianInt(a)
  14408. #define aiffFormatName TRANS("AIFF file")
  14409. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  14410. class AiffAudioFormatReader : public AudioFormatReader
  14411. {
  14412. public:
  14413. int bytesPerFrame;
  14414. int64 dataChunkStart;
  14415. bool littleEndian;
  14416. AiffAudioFormatReader (InputStream* in)
  14417. : AudioFormatReader (in, aiffFormatName)
  14418. {
  14419. if (input->readInt() == chunkName ("FORM"))
  14420. {
  14421. const int len = input->readIntBigEndian();
  14422. const int64 end = input->getPosition() + len;
  14423. const int nextType = input->readInt();
  14424. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  14425. {
  14426. bool hasGotVer = false;
  14427. bool hasGotData = false;
  14428. bool hasGotType = false;
  14429. while (input->getPosition() < end)
  14430. {
  14431. const int type = input->readInt();
  14432. const uint32 length = (uint32) input->readIntBigEndian();
  14433. const int64 chunkEnd = input->getPosition() + length;
  14434. if (type == chunkName ("FVER"))
  14435. {
  14436. hasGotVer = true;
  14437. const int ver = input->readIntBigEndian();
  14438. if (ver != 0 && ver != (int)0xa2805140)
  14439. break;
  14440. }
  14441. else if (type == chunkName ("COMM"))
  14442. {
  14443. hasGotType = true;
  14444. numChannels = (unsigned int)input->readShortBigEndian();
  14445. lengthInSamples = input->readIntBigEndian();
  14446. bitsPerSample = input->readShortBigEndian();
  14447. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  14448. unsigned char sampleRateBytes[10];
  14449. input->read (sampleRateBytes, 10);
  14450. const int byte0 = sampleRateBytes[0];
  14451. if ((byte0 & 0x80) != 0
  14452. || byte0 <= 0x3F || byte0 > 0x40
  14453. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  14454. break;
  14455. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  14456. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  14457. sampleRate = (int)sampRate;
  14458. if (length <= 18)
  14459. {
  14460. // some types don't have a chunk large enough to include a compression
  14461. // type, so assume it's just big-endian pcm
  14462. littleEndian = false;
  14463. }
  14464. else
  14465. {
  14466. const int compType = input->readInt();
  14467. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  14468. {
  14469. littleEndian = false;
  14470. }
  14471. else if (compType == chunkName ("sowt"))
  14472. {
  14473. littleEndian = true;
  14474. }
  14475. else
  14476. {
  14477. sampleRate = 0;
  14478. break;
  14479. }
  14480. }
  14481. }
  14482. else if (type == chunkName ("SSND"))
  14483. {
  14484. hasGotData = true;
  14485. const int offset = input->readIntBigEndian();
  14486. dataChunkStart = input->getPosition() + 4 + offset;
  14487. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  14488. }
  14489. else if ((hasGotVer && hasGotData && hasGotType)
  14490. || chunkEnd < input->getPosition()
  14491. || input->isExhausted())
  14492. {
  14493. break;
  14494. }
  14495. input->setPosition (chunkEnd);
  14496. }
  14497. }
  14498. }
  14499. }
  14500. ~AiffAudioFormatReader()
  14501. {
  14502. }
  14503. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  14504. int64 startSampleInFile, int numSamples)
  14505. {
  14506. numSamples = (int) jmin ((int64) numSamples, lengthInSamples - startSampleInFile);
  14507. if (numSamples <= 0)
  14508. return true;
  14509. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  14510. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  14511. char tempBuffer [tempBufSize];
  14512. while (numSamples > 0)
  14513. {
  14514. int* left = destSamples[0];
  14515. if (left != 0)
  14516. left += startOffsetInDestBuffer;
  14517. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  14518. if (right != 0)
  14519. right += startOffsetInDestBuffer;
  14520. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  14521. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  14522. if (bytesRead < numThisTime * bytesPerFrame)
  14523. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  14524. if (bitsPerSample == 16)
  14525. {
  14526. if (littleEndian)
  14527. {
  14528. const short* src = (const short*) tempBuffer;
  14529. if (numChannels > 1)
  14530. {
  14531. if (left == 0)
  14532. {
  14533. for (int i = numThisTime; --i >= 0;)
  14534. {
  14535. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14536. ++src;
  14537. }
  14538. }
  14539. else if (right == 0)
  14540. {
  14541. for (int i = numThisTime; --i >= 0;)
  14542. {
  14543. ++src;
  14544. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14545. }
  14546. }
  14547. else
  14548. {
  14549. for (int i = numThisTime; --i >= 0;)
  14550. {
  14551. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14552. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14553. }
  14554. }
  14555. }
  14556. else
  14557. {
  14558. for (int i = numThisTime; --i >= 0;)
  14559. {
  14560. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14561. }
  14562. }
  14563. }
  14564. else
  14565. {
  14566. const char* src = (const char*) tempBuffer;
  14567. if (numChannels > 1)
  14568. {
  14569. if (left == 0)
  14570. {
  14571. for (int i = numThisTime; --i >= 0;)
  14572. {
  14573. *right++ = bigEndianShort (src) << 16;
  14574. src += 4;
  14575. }
  14576. }
  14577. else if (right == 0)
  14578. {
  14579. for (int i = numThisTime; --i >= 0;)
  14580. {
  14581. src += 2;
  14582. *left++ = bigEndianShort (src) << 16;
  14583. src += 2;
  14584. }
  14585. }
  14586. else
  14587. {
  14588. for (int i = numThisTime; --i >= 0;)
  14589. {
  14590. *left++ = bigEndianShort (src) << 16;
  14591. src += 2;
  14592. *right++ = bigEndianShort (src) << 16;
  14593. src += 2;
  14594. }
  14595. }
  14596. }
  14597. else
  14598. {
  14599. for (int i = numThisTime; --i >= 0;)
  14600. {
  14601. *left++ = bigEndianShort (src) << 16;
  14602. src += 2;
  14603. }
  14604. }
  14605. }
  14606. }
  14607. else if (bitsPerSample == 24)
  14608. {
  14609. const char* src = (const char*)tempBuffer;
  14610. if (littleEndian)
  14611. {
  14612. if (numChannels > 1)
  14613. {
  14614. if (left == 0)
  14615. {
  14616. for (int i = numThisTime; --i >= 0;)
  14617. {
  14618. *right++ = littleEndian24Bit (src) << 8;
  14619. src += 6;
  14620. }
  14621. }
  14622. else if (right == 0)
  14623. {
  14624. for (int i = numThisTime; --i >= 0;)
  14625. {
  14626. src += 3;
  14627. *left++ = littleEndian24Bit (src) << 8;
  14628. src += 3;
  14629. }
  14630. }
  14631. else
  14632. {
  14633. for (int i = numThisTime; --i >= 0;)
  14634. {
  14635. *left++ = littleEndian24Bit (src) << 8;
  14636. src += 3;
  14637. *right++ = littleEndian24Bit (src) << 8;
  14638. src += 3;
  14639. }
  14640. }
  14641. }
  14642. else
  14643. {
  14644. for (int i = numThisTime; --i >= 0;)
  14645. {
  14646. *left++ = littleEndian24Bit (src) << 8;
  14647. src += 3;
  14648. }
  14649. }
  14650. }
  14651. else
  14652. {
  14653. if (numChannels > 1)
  14654. {
  14655. if (left == 0)
  14656. {
  14657. for (int i = numThisTime; --i >= 0;)
  14658. {
  14659. *right++ = bigEndian24Bit (src) << 8;
  14660. src += 6;
  14661. }
  14662. }
  14663. else if (right == 0)
  14664. {
  14665. for (int i = numThisTime; --i >= 0;)
  14666. {
  14667. src += 3;
  14668. *left++ = bigEndian24Bit (src) << 8;
  14669. src += 3;
  14670. }
  14671. }
  14672. else
  14673. {
  14674. for (int i = numThisTime; --i >= 0;)
  14675. {
  14676. *left++ = bigEndian24Bit (src) << 8;
  14677. src += 3;
  14678. *right++ = bigEndian24Bit (src) << 8;
  14679. src += 3;
  14680. }
  14681. }
  14682. }
  14683. else
  14684. {
  14685. for (int i = numThisTime; --i >= 0;)
  14686. {
  14687. *left++ = bigEndian24Bit (src) << 8;
  14688. src += 3;
  14689. }
  14690. }
  14691. }
  14692. }
  14693. else if (bitsPerSample == 32)
  14694. {
  14695. const unsigned int* src = (const unsigned int*) tempBuffer;
  14696. unsigned int* l = (unsigned int*) left;
  14697. unsigned int* r = (unsigned int*) right;
  14698. if (littleEndian)
  14699. {
  14700. if (numChannels > 1)
  14701. {
  14702. if (l == 0)
  14703. {
  14704. for (int i = numThisTime; --i >= 0;)
  14705. {
  14706. ++src;
  14707. *r++ = swapIfBigEndian (*src++);
  14708. }
  14709. }
  14710. else if (r == 0)
  14711. {
  14712. for (int i = numThisTime; --i >= 0;)
  14713. {
  14714. *l++ = swapIfBigEndian (*src++);
  14715. ++src;
  14716. }
  14717. }
  14718. else
  14719. {
  14720. for (int i = numThisTime; --i >= 0;)
  14721. {
  14722. *l++ = swapIfBigEndian (*src++);
  14723. *r++ = swapIfBigEndian (*src++);
  14724. }
  14725. }
  14726. }
  14727. else
  14728. {
  14729. for (int i = numThisTime; --i >= 0;)
  14730. {
  14731. *l++ = swapIfBigEndian (*src++);
  14732. }
  14733. }
  14734. }
  14735. else
  14736. {
  14737. if (numChannels > 1)
  14738. {
  14739. if (l == 0)
  14740. {
  14741. for (int i = numThisTime; --i >= 0;)
  14742. {
  14743. ++src;
  14744. *r++ = swapIfLittleEndian (*src++);
  14745. }
  14746. }
  14747. else if (r == 0)
  14748. {
  14749. for (int i = numThisTime; --i >= 0;)
  14750. {
  14751. *l++ = swapIfLittleEndian (*src++);
  14752. ++src;
  14753. }
  14754. }
  14755. else
  14756. {
  14757. for (int i = numThisTime; --i >= 0;)
  14758. {
  14759. *l++ = swapIfLittleEndian (*src++);
  14760. *r++ = swapIfLittleEndian (*src++);
  14761. }
  14762. }
  14763. }
  14764. else
  14765. {
  14766. for (int i = numThisTime; --i >= 0;)
  14767. {
  14768. *l++ = swapIfLittleEndian (*src++);
  14769. }
  14770. }
  14771. }
  14772. left = (int*) l;
  14773. right = (int*) r;
  14774. }
  14775. else if (bitsPerSample == 8)
  14776. {
  14777. const char* src = (const char*) tempBuffer;
  14778. if (numChannels > 1)
  14779. {
  14780. if (left == 0)
  14781. {
  14782. for (int i = numThisTime; --i >= 0;)
  14783. {
  14784. *right++ = ((int) *src++) << 24;
  14785. ++src;
  14786. }
  14787. }
  14788. else if (right == 0)
  14789. {
  14790. for (int i = numThisTime; --i >= 0;)
  14791. {
  14792. ++src;
  14793. *left++ = ((int) *src++) << 24;
  14794. }
  14795. }
  14796. else
  14797. {
  14798. for (int i = numThisTime; --i >= 0;)
  14799. {
  14800. *left++ = ((int) *src++) << 24;
  14801. *right++ = ((int) *src++) << 24;
  14802. }
  14803. }
  14804. }
  14805. else
  14806. {
  14807. for (int i = numThisTime; --i >= 0;)
  14808. {
  14809. *left++ = ((int) *src++) << 24;
  14810. }
  14811. }
  14812. }
  14813. startOffsetInDestBuffer += numThisTime;
  14814. numSamples -= numThisTime;
  14815. }
  14816. if (numSamples > 0)
  14817. {
  14818. for (int i = numDestChannels; --i >= 0;)
  14819. if (destSamples[i] != 0)
  14820. zeromem (destSamples[i] + startOffsetInDestBuffer,
  14821. sizeof (int) * numSamples);
  14822. }
  14823. return true;
  14824. }
  14825. juce_UseDebuggingNewOperator
  14826. private:
  14827. AiffAudioFormatReader (const AiffAudioFormatReader&);
  14828. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  14829. };
  14830. class AiffAudioFormatWriter : public AudioFormatWriter
  14831. {
  14832. MemoryBlock tempBlock;
  14833. uint32 lengthInSamples, bytesWritten;
  14834. int64 headerPosition;
  14835. bool writeFailed;
  14836. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  14837. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  14838. void writeHeader()
  14839. {
  14840. const bool couldSeekOk = output->setPosition (headerPosition);
  14841. (void) couldSeekOk;
  14842. // if this fails, you've given it an output stream that can't seek! It needs
  14843. // to be able to seek back to write the header
  14844. jassert (couldSeekOk);
  14845. const int headerLen = 54;
  14846. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  14847. audioBytes += (audioBytes & 1);
  14848. output->writeInt (chunkName ("FORM"));
  14849. output->writeIntBigEndian (headerLen + audioBytes - 8);
  14850. output->writeInt (chunkName ("AIFF"));
  14851. output->writeInt (chunkName ("COMM"));
  14852. output->writeIntBigEndian (18);
  14853. output->writeShortBigEndian ((short) numChannels);
  14854. output->writeIntBigEndian (lengthInSamples);
  14855. output->writeShortBigEndian ((short) bitsPerSample);
  14856. uint8 sampleRateBytes[10];
  14857. zeromem (sampleRateBytes, 10);
  14858. if (sampleRate <= 1)
  14859. {
  14860. sampleRateBytes[0] = 0x3f;
  14861. sampleRateBytes[1] = 0xff;
  14862. sampleRateBytes[2] = 0x80;
  14863. }
  14864. else
  14865. {
  14866. int mask = 0x40000000;
  14867. sampleRateBytes[0] = 0x40;
  14868. if (sampleRate >= mask)
  14869. {
  14870. jassertfalse
  14871. sampleRateBytes[1] = 0x1d;
  14872. }
  14873. else
  14874. {
  14875. int n = (int) sampleRate;
  14876. int i;
  14877. for (i = 0; i <= 32 ; ++i)
  14878. {
  14879. if ((n & mask) != 0)
  14880. break;
  14881. mask >>= 1;
  14882. }
  14883. n = n << (i + 1);
  14884. sampleRateBytes[1] = (uint8) (29 - i);
  14885. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  14886. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  14887. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  14888. sampleRateBytes[5] = (uint8) (n & 0xff);
  14889. }
  14890. }
  14891. output->write (sampleRateBytes, 10);
  14892. output->writeInt (chunkName ("SSND"));
  14893. output->writeIntBigEndian (audioBytes + 8);
  14894. output->writeInt (0);
  14895. output->writeInt (0);
  14896. jassert (output->getPosition() == headerLen);
  14897. }
  14898. public:
  14899. AiffAudioFormatWriter (OutputStream* out,
  14900. const double sampleRate_,
  14901. const unsigned int chans,
  14902. const int bits)
  14903. : AudioFormatWriter (out,
  14904. aiffFormatName,
  14905. sampleRate_,
  14906. chans,
  14907. bits),
  14908. lengthInSamples (0),
  14909. bytesWritten (0),
  14910. writeFailed (false)
  14911. {
  14912. headerPosition = out->getPosition();
  14913. writeHeader();
  14914. }
  14915. ~AiffAudioFormatWriter()
  14916. {
  14917. if ((bytesWritten & 1) != 0)
  14918. output->writeByte (0);
  14919. writeHeader();
  14920. }
  14921. bool write (const int** data, int numSamples)
  14922. {
  14923. if (writeFailed)
  14924. return false;
  14925. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  14926. tempBlock.ensureSize (bytes, false);
  14927. char* buffer = (char*) tempBlock.getData();
  14928. const int* left = data[0];
  14929. const int* right = data[1];
  14930. if (right == 0)
  14931. right = left;
  14932. if (bitsPerSample == 16)
  14933. {
  14934. short* b = (short*) buffer;
  14935. if (numChannels > 1)
  14936. {
  14937. for (int i = numSamples; --i >= 0;)
  14938. {
  14939. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  14940. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  14941. }
  14942. }
  14943. else
  14944. {
  14945. for (int i = numSamples; --i >= 0;)
  14946. {
  14947. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  14948. }
  14949. }
  14950. }
  14951. else if (bitsPerSample == 24)
  14952. {
  14953. char* b = (char*) buffer;
  14954. if (numChannels > 1)
  14955. {
  14956. for (int i = numSamples; --i >= 0;)
  14957. {
  14958. bigEndian24BitToChars (*left++ >> 8, b);
  14959. b += 3;
  14960. bigEndian24BitToChars (*right++ >> 8, b);
  14961. b += 3;
  14962. }
  14963. }
  14964. else
  14965. {
  14966. for (int i = numSamples; --i >= 0;)
  14967. {
  14968. bigEndian24BitToChars (*left++ >> 8, b);
  14969. b += 3;
  14970. }
  14971. }
  14972. }
  14973. else if (bitsPerSample == 32)
  14974. {
  14975. unsigned int* b = (unsigned int*) buffer;
  14976. if (numChannels > 1)
  14977. {
  14978. for (int i = numSamples; --i >= 0;)
  14979. {
  14980. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  14981. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  14982. }
  14983. }
  14984. else
  14985. {
  14986. for (int i = numSamples; --i >= 0;)
  14987. {
  14988. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  14989. }
  14990. }
  14991. }
  14992. else if (bitsPerSample == 8)
  14993. {
  14994. char* b = (char*)buffer;
  14995. if (numChannels > 1)
  14996. {
  14997. for (int i = numSamples; --i >= 0;)
  14998. {
  14999. *b++ = (char) (*left++ >> 24);
  15000. *b++ = (char) (*right++ >> 24);
  15001. }
  15002. }
  15003. else
  15004. {
  15005. for (int i = numSamples; --i >= 0;)
  15006. {
  15007. *b++ = (char) (*left++ >> 24);
  15008. }
  15009. }
  15010. }
  15011. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15012. || ! output->write (buffer, bytes))
  15013. {
  15014. // failed to write to disk, so let's try writing the header.
  15015. // If it's just run out of disk space, then if it does manage
  15016. // to write the header, we'll still have a useable file..
  15017. writeHeader();
  15018. writeFailed = true;
  15019. return false;
  15020. }
  15021. else
  15022. {
  15023. bytesWritten += bytes;
  15024. lengthInSamples += numSamples;
  15025. return true;
  15026. }
  15027. }
  15028. juce_UseDebuggingNewOperator
  15029. };
  15030. AiffAudioFormat::AiffAudioFormat()
  15031. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  15032. {
  15033. }
  15034. AiffAudioFormat::~AiffAudioFormat()
  15035. {
  15036. }
  15037. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15038. {
  15039. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15040. return Array <int> (rates);
  15041. }
  15042. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15043. {
  15044. const int depths[] = { 8, 16, 24, 0 };
  15045. return Array <int> (depths);
  15046. }
  15047. bool AiffAudioFormat::canDoStereo()
  15048. {
  15049. return true;
  15050. }
  15051. bool AiffAudioFormat::canDoMono()
  15052. {
  15053. return true;
  15054. }
  15055. #if JUCE_MAC
  15056. bool AiffAudioFormat::canHandleFile (const File& f)
  15057. {
  15058. if (AudioFormat::canHandleFile (f))
  15059. return true;
  15060. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15061. return type == 'AIFF' || type == 'AIFC'
  15062. || type == 'aiff' || type == 'aifc';
  15063. }
  15064. #endif
  15065. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15066. const bool deleteStreamIfOpeningFails)
  15067. {
  15068. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  15069. if (w->sampleRate == 0)
  15070. {
  15071. if (! deleteStreamIfOpeningFails)
  15072. w->input = 0;
  15073. deleteAndZero (w);
  15074. }
  15075. return w;
  15076. }
  15077. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15078. double sampleRate,
  15079. unsigned int chans,
  15080. int bitsPerSample,
  15081. const StringPairArray& /*metadataValues*/,
  15082. int /*qualityOptionIndex*/)
  15083. {
  15084. if (getPossibleBitDepths().contains (bitsPerSample))
  15085. {
  15086. return new AiffAudioFormatWriter (out,
  15087. sampleRate,
  15088. chans,
  15089. bitsPerSample);
  15090. }
  15091. return 0;
  15092. }
  15093. END_JUCE_NAMESPACE
  15094. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  15095. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  15096. BEGIN_JUCE_NAMESPACE
  15097. #if JUCE_MAC
  15098. // Mac version doesn't need any native code because it's all done with files..
  15099. // Windows + Linux versions are in the platform-dependent code sections.
  15100. static void findCDs (OwnedArray<File>& cds)
  15101. {
  15102. File volumes ("/Volumes");
  15103. volumes.findChildFiles (cds, File::findDirectories, false);
  15104. for (int i = cds.size(); --i >= 0;)
  15105. if (! cds[i]->getChildFile (".TOC.plist").exists())
  15106. cds.remove (i);
  15107. }
  15108. const StringArray AudioCDReader::getAvailableCDNames()
  15109. {
  15110. OwnedArray<File> cds;
  15111. findCDs (cds);
  15112. StringArray names;
  15113. for (int i = 0; i < cds.size(); ++i)
  15114. names.add (cds[i]->getFileName());
  15115. return names;
  15116. }
  15117. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15118. {
  15119. OwnedArray<File> cds;
  15120. findCDs (cds);
  15121. if (cds[index] != 0)
  15122. return new AudioCDReader (*cds[index]);
  15123. else
  15124. return 0;
  15125. }
  15126. AudioCDReader::AudioCDReader (const File& volume)
  15127. : AudioFormatReader (0, "CD Audio"),
  15128. volumeDir (volume),
  15129. currentReaderTrack (-1),
  15130. reader (0)
  15131. {
  15132. sampleRate = 44100.0;
  15133. bitsPerSample = 16;
  15134. numChannels = 2;
  15135. usesFloatingPointData = false;
  15136. refreshTrackLengths();
  15137. }
  15138. AudioCDReader::~AudioCDReader()
  15139. {
  15140. if (reader != 0)
  15141. delete reader;
  15142. }
  15143. static int getTrackNumber (const File& file)
  15144. {
  15145. return file.getFileName()
  15146. .initialSectionContainingOnly (T("0123456789"))
  15147. .getIntValue();
  15148. }
  15149. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  15150. {
  15151. const int firstTrack = getTrackNumber (*first);
  15152. const int secondTrack = getTrackNumber (*second);
  15153. jassert (firstTrack > 0 && secondTrack > 0);
  15154. return firstTrack - secondTrack;
  15155. }
  15156. void AudioCDReader::refreshTrackLengths()
  15157. {
  15158. tracks.clear();
  15159. trackStartSamples.clear();
  15160. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  15161. tracks.sort (*this);
  15162. AiffAudioFormat format;
  15163. int sample = 0;
  15164. for (int i = 0; i < tracks.size(); ++i)
  15165. {
  15166. trackStartSamples.add (sample);
  15167. FileInputStream* const in = tracks[i]->createInputStream();
  15168. if (in != 0)
  15169. {
  15170. AudioFormatReader* const r = format.createReaderFor (in, true);
  15171. if (r != 0)
  15172. {
  15173. sample += r->lengthInSamples;
  15174. delete r;
  15175. }
  15176. }
  15177. }
  15178. trackStartSamples.add (sample);
  15179. lengthInSamples = sample;
  15180. }
  15181. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15182. int64 startSampleInFile, int numSamples)
  15183. {
  15184. while (numSamples > 0)
  15185. {
  15186. int track = -1;
  15187. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15188. {
  15189. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15190. {
  15191. track = i;
  15192. break;
  15193. }
  15194. }
  15195. if (track < 0)
  15196. return false;
  15197. if (track != currentReaderTrack)
  15198. {
  15199. deleteAndZero (reader);
  15200. if (tracks [track] != 0)
  15201. {
  15202. FileInputStream* const in = tracks [track]->createInputStream();
  15203. if (in != 0)
  15204. {
  15205. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15206. AiffAudioFormat format;
  15207. reader = format.createReaderFor (bin, true);
  15208. if (reader == 0)
  15209. currentReaderTrack = -1;
  15210. else
  15211. currentReaderTrack = track;
  15212. }
  15213. }
  15214. }
  15215. if (reader == 0)
  15216. return false;
  15217. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15218. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15219. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15220. numSamples -= numAvailable;
  15221. startSampleInFile += numAvailable;
  15222. }
  15223. return true;
  15224. }
  15225. bool AudioCDReader::isCDStillPresent() const
  15226. {
  15227. return volumeDir.exists();
  15228. }
  15229. int AudioCDReader::getNumTracks() const
  15230. {
  15231. return tracks.size();
  15232. }
  15233. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15234. {
  15235. return trackStartSamples [trackNum];
  15236. }
  15237. bool AudioCDReader::isTrackAudio (int trackNum) const
  15238. {
  15239. return tracks [trackNum] != 0;
  15240. }
  15241. void AudioCDReader::enableIndexScanning (bool b)
  15242. {
  15243. // any way to do this on a Mac??
  15244. }
  15245. int AudioCDReader::getLastIndex() const
  15246. {
  15247. return 0;
  15248. }
  15249. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15250. {
  15251. return Array <int>();
  15252. }
  15253. int AudioCDReader::getCDDBId()
  15254. {
  15255. return 0; //xxx
  15256. }
  15257. #endif
  15258. END_JUCE_NAMESPACE
  15259. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  15260. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  15261. BEGIN_JUCE_NAMESPACE
  15262. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15263. const String& formatName_)
  15264. : sampleRate (0),
  15265. bitsPerSample (0),
  15266. lengthInSamples (0),
  15267. numChannels (0),
  15268. usesFloatingPointData (false),
  15269. input (in),
  15270. formatName (formatName_)
  15271. {
  15272. }
  15273. AudioFormatReader::~AudioFormatReader()
  15274. {
  15275. delete input;
  15276. }
  15277. bool AudioFormatReader::read (int** destSamples,
  15278. int numDestChannels,
  15279. int64 startSampleInSource,
  15280. int numSamplesToRead,
  15281. const bool fillLeftoverChannelsWithCopies)
  15282. {
  15283. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15284. int startOffsetInDestBuffer = 0;
  15285. if (startSampleInSource < 0)
  15286. {
  15287. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15288. for (int i = numDestChannels; --i >= 0;)
  15289. if (destSamples[i] != 0)
  15290. zeromem (destSamples[i], sizeof (int) * silence);
  15291. startOffsetInDestBuffer += silence;
  15292. numSamplesToRead -= silence;
  15293. startSampleInSource = 0;
  15294. }
  15295. if (numSamplesToRead <= 0)
  15296. return true;
  15297. if (! readSamples (destSamples, jmin (numChannels, numDestChannels), startOffsetInDestBuffer,
  15298. startSampleInSource, numSamplesToRead))
  15299. return false;
  15300. if (numDestChannels > (int) numChannels)
  15301. {
  15302. if (fillLeftoverChannelsWithCopies)
  15303. {
  15304. int* lastFullChannel = destSamples[0];
  15305. for (int i = numDestChannels; --i > 0;)
  15306. {
  15307. if (destSamples[i] != 0)
  15308. {
  15309. lastFullChannel = destSamples[i];
  15310. break;
  15311. }
  15312. }
  15313. if (lastFullChannel != 0)
  15314. for (int i = numChannels; i < numDestChannels; ++i)
  15315. if (destSamples[i] != 0)
  15316. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15317. }
  15318. else
  15319. {
  15320. for (int i = numChannels; i < numDestChannels; ++i)
  15321. if (destSamples[i] != 0)
  15322. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15323. }
  15324. }
  15325. return true;
  15326. }
  15327. static void findMaxMin (const float* src, const int num,
  15328. float& maxVal, float& minVal)
  15329. {
  15330. float mn = src[0];
  15331. float mx = mn;
  15332. for (int i = 1; i < num; ++i)
  15333. {
  15334. const float s = src[i];
  15335. if (s > mx)
  15336. mx = s;
  15337. if (s < mn)
  15338. mn = s;
  15339. }
  15340. maxVal = mx;
  15341. minVal = mn;
  15342. }
  15343. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15344. int64 numSamples,
  15345. float& lowestLeft, float& highestLeft,
  15346. float& lowestRight, float& highestRight)
  15347. {
  15348. if (numSamples <= 0)
  15349. {
  15350. lowestLeft = 0;
  15351. lowestRight = 0;
  15352. highestLeft = 0;
  15353. highestRight = 0;
  15354. return;
  15355. }
  15356. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  15357. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15358. int* tempBuffer[3];
  15359. tempBuffer[0] = (int*) tempSpace.getData();
  15360. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15361. tempBuffer[2] = 0;
  15362. if (usesFloatingPointData)
  15363. {
  15364. float lmin = 1.0e6;
  15365. float lmax = -lmin;
  15366. float rmin = lmin;
  15367. float rmax = lmax;
  15368. while (numSamples > 0)
  15369. {
  15370. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15371. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15372. numSamples -= numToDo;
  15373. startSampleInFile += numToDo;
  15374. float bufmin, bufmax;
  15375. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  15376. lmin = jmin (lmin, bufmin);
  15377. lmax = jmax (lmax, bufmax);
  15378. if (numChannels > 1)
  15379. {
  15380. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  15381. rmin = jmin (rmin, bufmin);
  15382. rmax = jmax (rmax, bufmax);
  15383. }
  15384. }
  15385. if (numChannels <= 1)
  15386. {
  15387. rmax = lmax;
  15388. rmin = lmin;
  15389. }
  15390. lowestLeft = lmin;
  15391. highestLeft = lmax;
  15392. lowestRight = rmin;
  15393. highestRight = rmax;
  15394. }
  15395. else
  15396. {
  15397. int lmax = INT_MIN;
  15398. int lmin = INT_MAX;
  15399. int rmax = INT_MIN;
  15400. int rmin = INT_MAX;
  15401. while (numSamples > 0)
  15402. {
  15403. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15404. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15405. numSamples -= numToDo;
  15406. startSampleInFile += numToDo;
  15407. for (int j = numChannels; --j >= 0;)
  15408. {
  15409. int bufMax = INT_MIN;
  15410. int bufMin = INT_MAX;
  15411. const int* const b = tempBuffer[j];
  15412. for (int i = 0; i < numToDo; ++i)
  15413. {
  15414. const int samp = b[i];
  15415. if (samp < bufMin)
  15416. bufMin = samp;
  15417. if (samp > bufMax)
  15418. bufMax = samp;
  15419. }
  15420. if (j == 0)
  15421. {
  15422. lmax = jmax (lmax, bufMax);
  15423. lmin = jmin (lmin, bufMin);
  15424. }
  15425. else
  15426. {
  15427. rmax = jmax (rmax, bufMax);
  15428. rmin = jmin (rmin, bufMin);
  15429. }
  15430. }
  15431. }
  15432. if (numChannels <= 1)
  15433. {
  15434. rmax = lmax;
  15435. rmin = lmin;
  15436. }
  15437. lowestLeft = lmin / (float)INT_MAX;
  15438. highestLeft = lmax / (float)INT_MAX;
  15439. lowestRight = rmin / (float)INT_MAX;
  15440. highestRight = rmax / (float)INT_MAX;
  15441. }
  15442. }
  15443. int64 AudioFormatReader::searchForLevel (int64 startSample,
  15444. int64 numSamplesToSearch,
  15445. const double magnitudeRangeMinimum,
  15446. const double magnitudeRangeMaximum,
  15447. const int minimumConsecutiveSamples)
  15448. {
  15449. if (numSamplesToSearch == 0)
  15450. return -1;
  15451. const int bufferSize = 4096;
  15452. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15453. int* tempBuffer[3];
  15454. tempBuffer[0] = (int*) tempSpace.getData();
  15455. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15456. tempBuffer[2] = 0;
  15457. int consecutive = 0;
  15458. int64 firstMatchPos = -1;
  15459. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  15460. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  15461. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  15462. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  15463. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  15464. while (numSamplesToSearch != 0)
  15465. {
  15466. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  15467. int64 bufferStart = startSample;
  15468. if (numSamplesToSearch < 0)
  15469. bufferStart -= numThisTime;
  15470. if (bufferStart >= (int) lengthInSamples)
  15471. break;
  15472. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  15473. int num = numThisTime;
  15474. while (--num >= 0)
  15475. {
  15476. if (numSamplesToSearch < 0)
  15477. --startSample;
  15478. bool matches = false;
  15479. const int index = (int) (startSample - bufferStart);
  15480. if (usesFloatingPointData)
  15481. {
  15482. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  15483. if (sample1 >= magnitudeRangeMinimum
  15484. && sample1 <= magnitudeRangeMaximum)
  15485. {
  15486. matches = true;
  15487. }
  15488. else if (numChannels > 1)
  15489. {
  15490. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  15491. matches = (sample2 >= magnitudeRangeMinimum
  15492. && sample2 <= magnitudeRangeMaximum);
  15493. }
  15494. }
  15495. else
  15496. {
  15497. const int sample1 = abs (tempBuffer[0] [index]);
  15498. if (sample1 >= intMagnitudeRangeMinimum
  15499. && sample1 <= intMagnitudeRangeMaximum)
  15500. {
  15501. matches = true;
  15502. }
  15503. else if (numChannels > 1)
  15504. {
  15505. const int sample2 = abs (tempBuffer[1][index]);
  15506. matches = (sample2 >= intMagnitudeRangeMinimum
  15507. && sample2 <= intMagnitudeRangeMaximum);
  15508. }
  15509. }
  15510. if (matches)
  15511. {
  15512. if (firstMatchPos < 0)
  15513. firstMatchPos = startSample;
  15514. if (++consecutive >= minimumConsecutiveSamples)
  15515. {
  15516. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  15517. return -1;
  15518. return firstMatchPos;
  15519. }
  15520. }
  15521. else
  15522. {
  15523. consecutive = 0;
  15524. firstMatchPos = -1;
  15525. }
  15526. if (numSamplesToSearch > 0)
  15527. ++startSample;
  15528. }
  15529. if (numSamplesToSearch > 0)
  15530. numSamplesToSearch -= numThisTime;
  15531. else
  15532. numSamplesToSearch += numThisTime;
  15533. }
  15534. return -1;
  15535. }
  15536. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  15537. const String& formatName_,
  15538. const double rate,
  15539. const unsigned int numChannels_,
  15540. const unsigned int bitsPerSample_)
  15541. : sampleRate (rate),
  15542. numChannels (numChannels_),
  15543. bitsPerSample (bitsPerSample_),
  15544. usesFloatingPointData (false),
  15545. output (out),
  15546. formatName (formatName_)
  15547. {
  15548. }
  15549. AudioFormatWriter::~AudioFormatWriter()
  15550. {
  15551. delete output;
  15552. }
  15553. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  15554. int64 startSample,
  15555. int64 numSamplesToRead)
  15556. {
  15557. const int bufferSize = 16384;
  15558. const int maxChans = 128;
  15559. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  15560. int* buffers [maxChans];
  15561. for (int i = maxChans; --i >= 0;)
  15562. buffers[i] = 0;
  15563. if (numSamplesToRead < 0)
  15564. numSamplesToRead = reader.lengthInSamples;
  15565. while (numSamplesToRead > 0)
  15566. {
  15567. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  15568. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  15569. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15570. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  15571. return false;
  15572. if (reader.usesFloatingPointData != isFloatingPoint())
  15573. {
  15574. int** bufferChan = buffers;
  15575. while (*bufferChan != 0)
  15576. {
  15577. int* b = *bufferChan++;
  15578. if (isFloatingPoint())
  15579. {
  15580. // int -> float
  15581. const double factor = 1.0 / INT_MAX;
  15582. for (int i = 0; i < numToDo; ++i)
  15583. ((float*)b)[i] = (float) (factor * b[i]);
  15584. }
  15585. else
  15586. {
  15587. // float -> int
  15588. for (int i = 0; i < numToDo; ++i)
  15589. {
  15590. const double samp = *(const float*) b;
  15591. if (samp <= -1.0)
  15592. *b++ = INT_MIN;
  15593. else if (samp >= 1.0)
  15594. *b++ = INT_MAX;
  15595. else
  15596. *b++ = roundDoubleToInt (INT_MAX * samp);
  15597. }
  15598. }
  15599. }
  15600. }
  15601. if (! write ((const int**) buffers, numToDo))
  15602. return false;
  15603. numSamplesToRead -= numToDo;
  15604. startSample += numToDo;
  15605. }
  15606. return true;
  15607. }
  15608. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  15609. int numSamplesToRead,
  15610. const int samplesPerBlock)
  15611. {
  15612. const int maxChans = 128;
  15613. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  15614. int* buffers [maxChans];
  15615. while (numSamplesToRead > 0)
  15616. {
  15617. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  15618. AudioSourceChannelInfo info;
  15619. info.buffer = &tempBuffer;
  15620. info.startSample = 0;
  15621. info.numSamples = numToDo;
  15622. info.clearActiveBufferRegion();
  15623. source.getNextAudioBlock (info);
  15624. int i;
  15625. for (i = maxChans; --i >= 0;)
  15626. buffers[i] = 0;
  15627. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  15628. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15629. if (! isFloatingPoint())
  15630. {
  15631. int** bufferChan = buffers;
  15632. while (*bufferChan != 0)
  15633. {
  15634. int* b = *bufferChan++;
  15635. // float -> int
  15636. for (int j = numToDo; --j >= 0;)
  15637. {
  15638. const double samp = *(const float*) b;
  15639. if (samp <= -1.0)
  15640. *b++ = INT_MIN;
  15641. else if (samp >= 1.0)
  15642. *b++ = INT_MAX;
  15643. else
  15644. *b++ = roundDoubleToInt (INT_MAX * samp);
  15645. }
  15646. }
  15647. }
  15648. if (! write ((const int**) buffers, numToDo))
  15649. return false;
  15650. numSamplesToRead -= numToDo;
  15651. }
  15652. return true;
  15653. }
  15654. AudioFormat::AudioFormat (const String& name,
  15655. const tchar** const extensions)
  15656. : formatName (name),
  15657. fileExtensions (extensions)
  15658. {
  15659. }
  15660. AudioFormat::~AudioFormat()
  15661. {
  15662. }
  15663. const String& AudioFormat::getFormatName() const
  15664. {
  15665. return formatName;
  15666. }
  15667. const StringArray& AudioFormat::getFileExtensions() const
  15668. {
  15669. return fileExtensions;
  15670. }
  15671. bool AudioFormat::canHandleFile (const File& f)
  15672. {
  15673. for (int i = 0; i < fileExtensions.size(); ++i)
  15674. if (f.hasFileExtension (fileExtensions[i]))
  15675. return true;
  15676. return false;
  15677. }
  15678. bool AudioFormat::isCompressed()
  15679. {
  15680. return false;
  15681. }
  15682. const StringArray AudioFormat::getQualityOptions()
  15683. {
  15684. return StringArray();
  15685. }
  15686. END_JUCE_NAMESPACE
  15687. /********* End of inlined file: juce_AudioFormat.cpp *********/
  15688. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  15689. BEGIN_JUCE_NAMESPACE
  15690. AudioFormatManager::AudioFormatManager()
  15691. : knownFormats (4),
  15692. defaultFormatIndex (0)
  15693. {
  15694. }
  15695. AudioFormatManager::~AudioFormatManager()
  15696. {
  15697. clearFormats();
  15698. clearSingletonInstance();
  15699. }
  15700. juce_ImplementSingleton (AudioFormatManager);
  15701. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  15702. const bool makeThisTheDefaultFormat)
  15703. {
  15704. jassert (newFormat != 0);
  15705. if (newFormat != 0)
  15706. {
  15707. #ifdef JUCE_DEBUG
  15708. for (int i = getNumKnownFormats(); --i >= 0;)
  15709. {
  15710. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  15711. {
  15712. jassertfalse // trying to add the same format twice!
  15713. }
  15714. }
  15715. #endif
  15716. if (makeThisTheDefaultFormat)
  15717. defaultFormatIndex = knownFormats.size();
  15718. knownFormats.add (newFormat);
  15719. }
  15720. }
  15721. void AudioFormatManager::registerBasicFormats()
  15722. {
  15723. #if JUCE_MAC
  15724. registerFormat (new AiffAudioFormat(), true);
  15725. registerFormat (new WavAudioFormat(), false);
  15726. #else
  15727. registerFormat (new WavAudioFormat(), true);
  15728. registerFormat (new AiffAudioFormat(), false);
  15729. #endif
  15730. #if JUCE_USE_FLAC
  15731. registerFormat (new FlacAudioFormat(), false);
  15732. #endif
  15733. #if JUCE_USE_OGGVORBIS
  15734. registerFormat (new OggVorbisAudioFormat(), false);
  15735. #endif
  15736. }
  15737. void AudioFormatManager::clearFormats()
  15738. {
  15739. for (int i = getNumKnownFormats(); --i >= 0;)
  15740. {
  15741. AudioFormat* const af = getKnownFormat(i);
  15742. delete af;
  15743. }
  15744. knownFormats.clear();
  15745. defaultFormatIndex = 0;
  15746. }
  15747. int AudioFormatManager::getNumKnownFormats() const
  15748. {
  15749. return knownFormats.size();
  15750. }
  15751. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  15752. {
  15753. return (AudioFormat*) knownFormats [index];
  15754. }
  15755. AudioFormat* AudioFormatManager::getDefaultFormat() const
  15756. {
  15757. return getKnownFormat (defaultFormatIndex);
  15758. }
  15759. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  15760. {
  15761. String e (fileExtension);
  15762. if (! e.startsWithChar (T('.')))
  15763. e = T(".") + e;
  15764. for (int i = 0; i < getNumKnownFormats(); ++i)
  15765. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  15766. return getKnownFormat(i);
  15767. return 0;
  15768. }
  15769. const String AudioFormatManager::getWildcardForAllFormats() const
  15770. {
  15771. StringArray allExtensions;
  15772. int i;
  15773. for (i = 0; i < getNumKnownFormats(); ++i)
  15774. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  15775. allExtensions.trim();
  15776. allExtensions.removeEmptyStrings();
  15777. String s;
  15778. for (i = 0; i < allExtensions.size(); ++i)
  15779. {
  15780. s << T('*');
  15781. if (! allExtensions[i].startsWithChar (T('.')))
  15782. s << T('.');
  15783. s << allExtensions[i];
  15784. if (i < allExtensions.size() - 1)
  15785. s << T(';');
  15786. }
  15787. return s;
  15788. }
  15789. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  15790. {
  15791. // you need to actually register some formats before the manager can
  15792. // use them to open a file!
  15793. jassert (knownFormats.size() > 0);
  15794. for (int i = 0; i < getNumKnownFormats(); ++i)
  15795. {
  15796. AudioFormat* const af = getKnownFormat(i);
  15797. if (af->canHandleFile (file))
  15798. {
  15799. InputStream* const in = file.createInputStream();
  15800. if (in != 0)
  15801. {
  15802. AudioFormatReader* const r = af->createReaderFor (in, true);
  15803. if (r != 0)
  15804. return r;
  15805. }
  15806. }
  15807. }
  15808. return 0;
  15809. }
  15810. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  15811. {
  15812. // you need to actually register some formats before the manager can
  15813. // use them to open a file!
  15814. jassert (knownFormats.size() > 0);
  15815. if (in != 0)
  15816. {
  15817. const int64 originalStreamPos = in->getPosition();
  15818. for (int i = 0; i < getNumKnownFormats(); ++i)
  15819. {
  15820. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  15821. if (r != 0)
  15822. return r;
  15823. in->setPosition (originalStreamPos);
  15824. // the stream that is passed-in must be capable of being repositioned so
  15825. // that all the formats can have a go at opening it.
  15826. jassert (in->getPosition() == originalStreamPos);
  15827. }
  15828. delete in;
  15829. }
  15830. return 0;
  15831. }
  15832. END_JUCE_NAMESPACE
  15833. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  15834. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  15835. BEGIN_JUCE_NAMESPACE
  15836. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  15837. const int64 startSample_,
  15838. const int64 length_,
  15839. const bool deleteSourceWhenDeleted_)
  15840. : AudioFormatReader (0, source_->getFormatName()),
  15841. source (source_),
  15842. startSample (startSample_),
  15843. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  15844. {
  15845. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  15846. sampleRate = source->sampleRate;
  15847. bitsPerSample = source->bitsPerSample;
  15848. lengthInSamples = length;
  15849. numChannels = source->numChannels;
  15850. usesFloatingPointData = source->usesFloatingPointData;
  15851. }
  15852. AudioSubsectionReader::~AudioSubsectionReader()
  15853. {
  15854. if (deleteSourceWhenDeleted)
  15855. delete source;
  15856. }
  15857. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15858. int64 startSampleInFile, int numSamples)
  15859. {
  15860. if (startSampleInFile + numSamples > length)
  15861. {
  15862. for (int i = numDestChannels; --i >= 0;)
  15863. if (destSamples[i] != 0)
  15864. zeromem (destSamples[i], sizeof (int) * numSamples);
  15865. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  15866. if (numSamples <= 0)
  15867. return true;
  15868. }
  15869. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  15870. startSampleInFile + startSample, numSamples);
  15871. }
  15872. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  15873. int64 numSamples,
  15874. float& lowestLeft,
  15875. float& highestLeft,
  15876. float& lowestRight,
  15877. float& highestRight)
  15878. {
  15879. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  15880. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  15881. source->readMaxLevels (startSampleInFile + startSample,
  15882. numSamples,
  15883. lowestLeft,
  15884. highestLeft,
  15885. lowestRight,
  15886. highestRight);
  15887. }
  15888. END_JUCE_NAMESPACE
  15889. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  15890. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  15891. BEGIN_JUCE_NAMESPACE
  15892. const int timeBeforeDeletingReader = 2000;
  15893. struct AudioThumbnailDataFormat
  15894. {
  15895. char thumbnailMagic[4];
  15896. int samplesPerThumbSample;
  15897. int64 totalSamples; // source samples
  15898. int64 numFinishedSamples; // source samples
  15899. int numThumbnailSamples;
  15900. int numChannels;
  15901. int sampleRate;
  15902. char future[16];
  15903. char data[1];
  15904. };
  15905. #if JUCE_BIG_ENDIAN
  15906. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  15907. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  15908. #endif
  15909. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  15910. {
  15911. (void) d;
  15912. #if JUCE_BIG_ENDIAN
  15913. swap (d->samplesPerThumbSample);
  15914. swap (d->totalSamples);
  15915. swap (d->numFinishedSamples);
  15916. swap (d->numThumbnailSamples);
  15917. swap (d->numChannels);
  15918. swap (d->sampleRate);
  15919. #endif
  15920. }
  15921. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  15922. AudioFormatManager& formatManagerToUse_,
  15923. AudioThumbnailCache& cacheToUse)
  15924. : formatManagerToUse (formatManagerToUse_),
  15925. cache (cacheToUse),
  15926. source (0),
  15927. reader (0),
  15928. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  15929. {
  15930. clear();
  15931. }
  15932. AudioThumbnail::~AudioThumbnail()
  15933. {
  15934. cache.removeThumbnail (this);
  15935. const ScopedLock sl (readerLock);
  15936. deleteAndZero (reader);
  15937. delete source;
  15938. }
  15939. void AudioThumbnail::setSource (InputSource* const newSource)
  15940. {
  15941. cache.removeThumbnail (this);
  15942. timerCallback(); // stops the timer and deletes the reader
  15943. delete source;
  15944. source = newSource;
  15945. clear();
  15946. if (newSource != 0
  15947. && ! (cache.loadThumb (*this, newSource->hashCode())
  15948. && isFullyLoaded()))
  15949. {
  15950. {
  15951. const ScopedLock sl (readerLock);
  15952. reader = createReader();
  15953. }
  15954. if (reader != 0)
  15955. {
  15956. initialiseFromAudioFile (*reader);
  15957. cache.addThumbnail (this);
  15958. }
  15959. }
  15960. sendChangeMessage (this);
  15961. }
  15962. bool AudioThumbnail::useTimeSlice()
  15963. {
  15964. const ScopedLock sl (readerLock);
  15965. if (isFullyLoaded())
  15966. {
  15967. if (reader != 0)
  15968. startTimer (timeBeforeDeletingReader);
  15969. cache.removeThumbnail (this);
  15970. return false;
  15971. }
  15972. if (reader == 0)
  15973. reader = createReader();
  15974. if (reader != 0)
  15975. {
  15976. readNextBlockFromAudioFile (*reader);
  15977. stopTimer();
  15978. sendChangeMessage (this);
  15979. const bool justFinished = isFullyLoaded();
  15980. if (justFinished)
  15981. cache.storeThumb (*this, source->hashCode());
  15982. return ! justFinished;
  15983. }
  15984. return false;
  15985. }
  15986. AudioFormatReader* AudioThumbnail::createReader() const
  15987. {
  15988. if (source != 0)
  15989. {
  15990. InputStream* const audioFileStream = source->createInputStream();
  15991. if (audioFileStream != 0)
  15992. return formatManagerToUse.createReaderFor (audioFileStream);
  15993. }
  15994. return 0;
  15995. }
  15996. void AudioThumbnail::timerCallback()
  15997. {
  15998. stopTimer();
  15999. const ScopedLock sl (readerLock);
  16000. deleteAndZero (reader);
  16001. }
  16002. void AudioThumbnail::clear()
  16003. {
  16004. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16005. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16006. d->thumbnailMagic[0] = 'j';
  16007. d->thumbnailMagic[1] = 'a';
  16008. d->thumbnailMagic[2] = 't';
  16009. d->thumbnailMagic[3] = 'm';
  16010. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16011. d->totalSamples = 0;
  16012. d->numFinishedSamples = 0;
  16013. d->numThumbnailSamples = 0;
  16014. d->numChannels = 0;
  16015. d->sampleRate = 0;
  16016. numSamplesCached = 0;
  16017. cacheNeedsRefilling = true;
  16018. }
  16019. void AudioThumbnail::loadFrom (InputStream& input)
  16020. {
  16021. data.setSize (0);
  16022. input.readIntoMemoryBlock (data);
  16023. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16024. swapEndiannessIfNeeded (d);
  16025. if (! (d->thumbnailMagic[0] == 'j'
  16026. && d->thumbnailMagic[1] == 'a'
  16027. && d->thumbnailMagic[2] == 't'
  16028. && d->thumbnailMagic[3] == 'm'))
  16029. {
  16030. clear();
  16031. }
  16032. numSamplesCached = 0;
  16033. cacheNeedsRefilling = true;
  16034. }
  16035. void AudioThumbnail::saveTo (OutputStream& output) const
  16036. {
  16037. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16038. swapEndiannessIfNeeded (d);
  16039. output.write (data.getData(), data.getSize());
  16040. swapEndiannessIfNeeded (d);
  16041. }
  16042. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  16043. {
  16044. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16045. d->totalSamples = reader.lengthInSamples;
  16046. d->numChannels = jmin (2, reader.numChannels);
  16047. d->numFinishedSamples = 0;
  16048. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  16049. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16050. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16051. d = (AudioThumbnailDataFormat*) data.getData();
  16052. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16053. return d->totalSamples > 0;
  16054. }
  16055. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  16056. {
  16057. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16058. if (d->numFinishedSamples < d->totalSamples)
  16059. {
  16060. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16061. generateSection (reader,
  16062. d->numFinishedSamples,
  16063. numToDo);
  16064. d->numFinishedSamples += numToDo;
  16065. }
  16066. cacheNeedsRefilling = true;
  16067. return (d->numFinishedSamples < d->totalSamples);
  16068. }
  16069. int AudioThumbnail::getNumChannels() const throw()
  16070. {
  16071. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16072. jassert (d != 0);
  16073. return d->numChannels;
  16074. }
  16075. double AudioThumbnail::getTotalLength() const throw()
  16076. {
  16077. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16078. jassert (d != 0);
  16079. if (d->sampleRate > 0)
  16080. return d->totalSamples / (double)d->sampleRate;
  16081. else
  16082. return 0.0;
  16083. }
  16084. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  16085. int64 startSample,
  16086. int numSamples)
  16087. {
  16088. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16089. jassert (d != 0);
  16090. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16091. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16092. char* l = getChannelData (0);
  16093. char* r = getChannelData (1);
  16094. for (int i = firstDataPos; i < lastDataPos; ++i)
  16095. {
  16096. const int sourceStart = i * d->samplesPerThumbSample;
  16097. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16098. float lowestLeft, highestLeft, lowestRight, highestRight;
  16099. reader.readMaxLevels (sourceStart,
  16100. sourceEnd - sourceStart,
  16101. lowestLeft,
  16102. highestLeft,
  16103. lowestRight,
  16104. highestRight);
  16105. int n = i * 2;
  16106. if (r != 0)
  16107. {
  16108. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16109. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16110. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16111. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16112. }
  16113. else
  16114. {
  16115. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16116. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16117. }
  16118. }
  16119. }
  16120. char* AudioThumbnail::getChannelData (int channel) const
  16121. {
  16122. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16123. jassert (d != 0);
  16124. if (channel >= 0 && channel < d->numChannels)
  16125. return d->data + (channel * 2 * d->numThumbnailSamples);
  16126. return 0;
  16127. }
  16128. bool AudioThumbnail::isFullyLoaded() const throw()
  16129. {
  16130. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16131. jassert (d != 0);
  16132. return d->numFinishedSamples >= d->totalSamples;
  16133. }
  16134. void AudioThumbnail::refillCache (const int numSamples,
  16135. double startTime,
  16136. const double timePerPixel)
  16137. {
  16138. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16139. jassert (d != 0);
  16140. if (numSamples <= 0
  16141. || timePerPixel <= 0.0
  16142. || d->sampleRate <= 0)
  16143. {
  16144. numSamplesCached = 0;
  16145. cacheNeedsRefilling = true;
  16146. return;
  16147. }
  16148. if (numSamples == numSamplesCached
  16149. && numChannelsCached == d->numChannels
  16150. && startTime == cachedStart
  16151. && timePerPixel == cachedTimePerPixel
  16152. && ! cacheNeedsRefilling)
  16153. {
  16154. return;
  16155. }
  16156. numSamplesCached = numSamples;
  16157. numChannelsCached = d->numChannels;
  16158. cachedStart = startTime;
  16159. cachedTimePerPixel = timePerPixel;
  16160. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16161. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16162. const ScopedLock sl (readerLock);
  16163. cacheNeedsRefilling = false;
  16164. if (needExtraDetail && reader == 0)
  16165. reader = createReader();
  16166. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16167. {
  16168. startTimer (timeBeforeDeletingReader);
  16169. char* cacheData = (char*) cachedLevels.getData();
  16170. int sample = roundDoubleToInt (startTime * d->sampleRate);
  16171. for (int i = numSamples; --i >= 0;)
  16172. {
  16173. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  16174. if (sample >= 0)
  16175. {
  16176. if (sample >= reader->lengthInSamples)
  16177. break;
  16178. float lmin, lmax, rmin, rmax;
  16179. reader->readMaxLevels (sample,
  16180. jmax (1, nextSample - sample),
  16181. lmin, lmax, rmin, rmax);
  16182. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16183. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16184. if (numChannelsCached > 1)
  16185. {
  16186. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16187. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16188. }
  16189. cacheData += 2 * numChannelsCached;
  16190. }
  16191. startTime += timePerPixel;
  16192. sample = nextSample;
  16193. }
  16194. }
  16195. else
  16196. {
  16197. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16198. {
  16199. char* const data = getChannelData (channelNum);
  16200. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  16201. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16202. startTime = cachedStart;
  16203. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  16204. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16205. for (int i = numSamples; --i >= 0;)
  16206. {
  16207. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16208. if (sample >= 0 && data != 0)
  16209. {
  16210. char mx = -128;
  16211. char mn = 127;
  16212. while (sample <= nextSample)
  16213. {
  16214. if (sample >= numFinished)
  16215. break;
  16216. const int n = sample << 1;
  16217. const char sampMin = data [n];
  16218. const char sampMax = data [n + 1];
  16219. if (sampMin < mn)
  16220. mn = sampMin;
  16221. if (sampMax > mx)
  16222. mx = sampMax;
  16223. ++sample;
  16224. }
  16225. if (mn <= mx)
  16226. {
  16227. cacheData[0] = mn;
  16228. cacheData[1] = mx;
  16229. }
  16230. else
  16231. {
  16232. cacheData[0] = 1;
  16233. cacheData[1] = 0;
  16234. }
  16235. }
  16236. else
  16237. {
  16238. cacheData[0] = 1;
  16239. cacheData[1] = 0;
  16240. }
  16241. cacheData += numChannelsCached * 2;
  16242. startTime += timePerPixel;
  16243. sample = nextSample;
  16244. }
  16245. }
  16246. }
  16247. }
  16248. void AudioThumbnail::drawChannel (Graphics& g,
  16249. int x, int y, int w, int h,
  16250. double startTime,
  16251. double endTime,
  16252. int channelNum,
  16253. const float verticalZoomFactor)
  16254. {
  16255. refillCache (w, startTime, (endTime - startTime) / w);
  16256. if (numSamplesCached >= w
  16257. && channelNum >= 0
  16258. && channelNum < numChannelsCached)
  16259. {
  16260. const float topY = (float) y;
  16261. const float bottomY = topY + h;
  16262. const float midY = topY + h * 0.5f;
  16263. const float vscale = verticalZoomFactor * h / 256.0f;
  16264. const Rectangle clip (g.getClipBounds());
  16265. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16266. w -= skipLeft;
  16267. x += skipLeft;
  16268. const char* cacheData = ((const char*) cachedLevels.getData())
  16269. + (channelNum << 1)
  16270. + skipLeft * (numChannelsCached << 1);
  16271. while (--w >= 0)
  16272. {
  16273. const char mn = cacheData[0];
  16274. const char mx = cacheData[1];
  16275. cacheData += numChannelsCached << 1;
  16276. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16277. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16278. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16279. ++x;
  16280. if (x >= clip.getRight())
  16281. break;
  16282. }
  16283. }
  16284. }
  16285. END_JUCE_NAMESPACE
  16286. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  16287. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  16288. BEGIN_JUCE_NAMESPACE
  16289. struct ThumbnailCacheEntry
  16290. {
  16291. int64 hash;
  16292. uint32 lastUsed;
  16293. MemoryBlock data;
  16294. juce_UseDebuggingNewOperator
  16295. };
  16296. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16297. : TimeSliceThread (T("thumb cache")),
  16298. maxNumThumbsToStore (maxNumThumbsToStore_)
  16299. {
  16300. startThread (2);
  16301. }
  16302. AudioThumbnailCache::~AudioThumbnailCache()
  16303. {
  16304. }
  16305. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16306. {
  16307. for (int i = thumbs.size(); --i >= 0;)
  16308. {
  16309. if (thumbs[i]->hash == hashCode)
  16310. {
  16311. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  16312. thumbs[i]->data.getSize(),
  16313. false);
  16314. thumb.loadFrom (in);
  16315. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16316. return true;
  16317. }
  16318. }
  16319. return false;
  16320. }
  16321. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16322. const int64 hashCode)
  16323. {
  16324. MemoryOutputStream out;
  16325. thumb.saveTo (out);
  16326. ThumbnailCacheEntry* te = 0;
  16327. for (int i = thumbs.size(); --i >= 0;)
  16328. {
  16329. if (thumbs[i]->hash == hashCode)
  16330. {
  16331. te = thumbs[i];
  16332. break;
  16333. }
  16334. }
  16335. if (te == 0)
  16336. {
  16337. te = new ThumbnailCacheEntry();
  16338. te->hash = hashCode;
  16339. if (thumbs.size() < maxNumThumbsToStore)
  16340. {
  16341. thumbs.add (te);
  16342. }
  16343. else
  16344. {
  16345. int oldest = 0;
  16346. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16347. int i;
  16348. for (i = thumbs.size(); --i >= 0;)
  16349. if (thumbs[i]->lastUsed < oldestTime)
  16350. oldest = i;
  16351. thumbs.set (i, te);
  16352. }
  16353. }
  16354. te->lastUsed = Time::getMillisecondCounter();
  16355. te->data.setSize (0);
  16356. te->data.append (out.getData(), out.getDataSize());
  16357. }
  16358. void AudioThumbnailCache::clear()
  16359. {
  16360. thumbs.clear();
  16361. }
  16362. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  16363. {
  16364. addTimeSliceClient (thumb);
  16365. }
  16366. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  16367. {
  16368. removeTimeSliceClient (thumb);
  16369. }
  16370. END_JUCE_NAMESPACE
  16371. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  16372. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16373. #if JUCE_QUICKTIME
  16374. #if ! defined (_WIN32)
  16375. #include <QuickTime/Movies.h>
  16376. #include <QuickTime/QTML.h>
  16377. #include <QuickTime/QuickTimeComponents.h>
  16378. #include <QuickTime/MediaHandlers.h>
  16379. #include <QuickTime/ImageCodec.h>
  16380. #else
  16381. #ifdef _MSC_VER
  16382. #pragma warning (push)
  16383. #pragma warning (disable : 4100)
  16384. #endif
  16385. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  16386. add its header directory to your include path.
  16387. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  16388. flag in juce_Config.h
  16389. */
  16390. #include <Movies.h>
  16391. #include <QTML.h>
  16392. #include <QuickTimeComponents.h>
  16393. #include <MediaHandlers.h>
  16394. #include <ImageCodec.h>
  16395. #ifdef _MSC_VER
  16396. #pragma warning (pop)
  16397. #endif
  16398. #endif
  16399. #if ! (JUCE_MAC && JUCE_64BIT)
  16400. BEGIN_JUCE_NAMESPACE
  16401. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  16402. #define quickTimeFormatName TRANS("QuickTime file")
  16403. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  16404. class QTAudioReader : public AudioFormatReader
  16405. {
  16406. public:
  16407. QTAudioReader (InputStream* const input_, const int trackNum_)
  16408. : AudioFormatReader (input_, quickTimeFormatName),
  16409. ok (false),
  16410. movie (0),
  16411. trackNum (trackNum_),
  16412. extractor (0),
  16413. lastSampleRead (0),
  16414. lastThreadId (0),
  16415. dataHandle (0)
  16416. {
  16417. bufferList = (AudioBufferList*) juce_calloc (256);
  16418. #ifdef WIN32
  16419. if (InitializeQTML (0) != noErr)
  16420. return;
  16421. #endif
  16422. if (EnterMovies() != noErr)
  16423. return;
  16424. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  16425. if (! opened)
  16426. return;
  16427. {
  16428. const int numTracks = GetMovieTrackCount (movie);
  16429. int trackCount = 0;
  16430. for (int i = 1; i <= numTracks; ++i)
  16431. {
  16432. track = GetMovieIndTrack (movie, i);
  16433. media = GetTrackMedia (track);
  16434. OSType mediaType;
  16435. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  16436. if (mediaType == SoundMediaType
  16437. && trackCount++ == trackNum_)
  16438. {
  16439. ok = true;
  16440. break;
  16441. }
  16442. }
  16443. }
  16444. if (! ok)
  16445. return;
  16446. ok = false;
  16447. lengthInSamples = GetMediaDecodeDuration (media);
  16448. usesFloatingPointData = false;
  16449. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  16450. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  16451. / GetMediaTimeScale (media);
  16452. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  16453. unsigned long output_layout_size;
  16454. err = MovieAudioExtractionGetPropertyInfo (extractor,
  16455. kQTPropertyClass_MovieAudioExtraction_Audio,
  16456. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16457. 0, &output_layout_size, 0);
  16458. if (err != noErr)
  16459. return;
  16460. AudioChannelLayout* const qt_audio_channel_layout
  16461. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  16462. err = MovieAudioExtractionGetProperty (extractor,
  16463. kQTPropertyClass_MovieAudioExtraction_Audio,
  16464. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16465. output_layout_size, qt_audio_channel_layout, 0);
  16466. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  16467. err = MovieAudioExtractionSetProperty (extractor,
  16468. kQTPropertyClass_MovieAudioExtraction_Audio,
  16469. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16470. sizeof (qt_audio_channel_layout),
  16471. qt_audio_channel_layout);
  16472. juce_free (qt_audio_channel_layout);
  16473. err = MovieAudioExtractionGetProperty (extractor,
  16474. kQTPropertyClass_MovieAudioExtraction_Audio,
  16475. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16476. sizeof (inputStreamDesc),
  16477. &inputStreamDesc, 0);
  16478. if (err != noErr)
  16479. return;
  16480. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  16481. | kAudioFormatFlagIsPacked
  16482. | kAudioFormatFlagsNativeEndian;
  16483. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  16484. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  16485. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  16486. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  16487. err = MovieAudioExtractionSetProperty (extractor,
  16488. kQTPropertyClass_MovieAudioExtraction_Audio,
  16489. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16490. sizeof (inputStreamDesc),
  16491. &inputStreamDesc);
  16492. if (err != noErr)
  16493. return;
  16494. Boolean allChannelsDiscrete = false;
  16495. err = MovieAudioExtractionSetProperty (extractor,
  16496. kQTPropertyClass_MovieAudioExtraction_Movie,
  16497. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  16498. sizeof (allChannelsDiscrete),
  16499. &allChannelsDiscrete);
  16500. if (err != noErr)
  16501. return;
  16502. bufferList->mNumberBuffers = 1;
  16503. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  16504. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  16505. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  16506. sampleRate = inputStreamDesc.mSampleRate;
  16507. bitsPerSample = 16;
  16508. numChannels = inputStreamDesc.mChannelsPerFrame;
  16509. detachThread();
  16510. ok = true;
  16511. }
  16512. ~QTAudioReader()
  16513. {
  16514. if (dataHandle != 0)
  16515. DisposeHandle (dataHandle);
  16516. if (extractor != 0)
  16517. {
  16518. MovieAudioExtractionEnd (extractor);
  16519. extractor = 0;
  16520. }
  16521. checkThreadIsAttached();
  16522. DisposeMovie (movie);
  16523. juce_free (bufferList->mBuffers[0].mData);
  16524. juce_free (bufferList);
  16525. #if JUCE_MAC
  16526. ExitMoviesOnThread ();
  16527. #endif
  16528. }
  16529. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16530. int64 startSampleInFile, int numSamples)
  16531. {
  16532. checkThreadIsAttached();
  16533. while (numSamples > 0)
  16534. {
  16535. if (! loadFrame ((int) startSampleInFile))
  16536. return false;
  16537. const int numToDo = jmin (numSamples, samplesPerFrame);
  16538. for (int j = numDestChannels; --j >= 0;)
  16539. {
  16540. if (destSamples[j] != 0)
  16541. {
  16542. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  16543. for (int i = 0; i < numToDo; ++i)
  16544. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  16545. }
  16546. }
  16547. startOffsetInDestBuffer += numToDo;
  16548. startSampleInFile += numToDo;
  16549. numSamples -= numToDo;
  16550. }
  16551. detachThread();
  16552. return true;
  16553. }
  16554. bool loadFrame (const int sampleNum)
  16555. {
  16556. if (lastSampleRead != sampleNum)
  16557. {
  16558. TimeRecord time;
  16559. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  16560. time.base = 0;
  16561. time.value.hi = 0;
  16562. time.value.lo = (UInt32) sampleNum;
  16563. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  16564. kQTPropertyClass_MovieAudioExtraction_Movie,
  16565. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  16566. sizeof (time), &time);
  16567. if (err != noErr)
  16568. return false;
  16569. }
  16570. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  16571. UInt32 outFlags = 0;
  16572. UInt32 actualNumSamples = samplesPerFrame;
  16573. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  16574. bufferList, &outFlags);
  16575. lastSampleRead = sampleNum + samplesPerFrame;
  16576. return err == noErr;
  16577. }
  16578. juce_UseDebuggingNewOperator
  16579. bool ok;
  16580. private:
  16581. Movie movie;
  16582. Media media;
  16583. Track track;
  16584. const int trackNum;
  16585. double trackUnitsPerFrame;
  16586. int samplesPerFrame;
  16587. int lastSampleRead;
  16588. Thread::ThreadID lastThreadId;
  16589. MovieAudioExtractionRef extractor;
  16590. AudioStreamBasicDescription inputStreamDesc;
  16591. AudioBufferList* bufferList;
  16592. Handle dataHandle;
  16593. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  16594. {
  16595. input->setPosition (offset);
  16596. input->read (dataPtr, size);
  16597. return noErr;
  16598. }
  16599. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  16600. {
  16601. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  16602. }*/
  16603. void checkThreadIsAttached()
  16604. {
  16605. #if JUCE_MAC
  16606. if (Thread::getCurrentThreadId() != lastThreadId)
  16607. EnterMoviesOnThread (0);
  16608. AttachMovieToCurrentThread (movie);
  16609. #endif
  16610. }
  16611. void detachThread()
  16612. {
  16613. #if JUCE_MAC
  16614. DetachMovieFromCurrentThread (movie);
  16615. #endif
  16616. }
  16617. };
  16618. QuickTimeAudioFormat::QuickTimeAudioFormat()
  16619. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  16620. {
  16621. }
  16622. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  16623. {
  16624. }
  16625. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  16626. {
  16627. return Array<int>();
  16628. }
  16629. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  16630. {
  16631. return Array<int>();
  16632. }
  16633. bool QuickTimeAudioFormat::canDoStereo()
  16634. {
  16635. return true;
  16636. }
  16637. bool QuickTimeAudioFormat::canDoMono()
  16638. {
  16639. return true;
  16640. }
  16641. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  16642. const bool deleteStreamIfOpeningFails)
  16643. {
  16644. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  16645. if (! r->ok)
  16646. {
  16647. if (! deleteStreamIfOpeningFails)
  16648. r->input = 0;
  16649. deleteAndZero (r);
  16650. }
  16651. return r;
  16652. }
  16653. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  16654. double /*sampleRateToUse*/,
  16655. unsigned int /*numberOfChannels*/,
  16656. int /*bitsPerSample*/,
  16657. const StringPairArray& /*metadataValues*/,
  16658. int /*qualityOptionIndex*/)
  16659. {
  16660. jassertfalse // not yet implemented!
  16661. return 0;
  16662. }
  16663. END_JUCE_NAMESPACE
  16664. #endif
  16665. #endif
  16666. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16667. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  16668. BEGIN_JUCE_NAMESPACE
  16669. #define wavFormatName TRANS("WAV file")
  16670. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  16671. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  16672. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  16673. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  16674. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  16675. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  16676. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  16677. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  16678. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  16679. const String& originator,
  16680. const String& originatorRef,
  16681. const Time& date,
  16682. const int64 timeReferenceSamples,
  16683. const String& codingHistory)
  16684. {
  16685. StringPairArray m;
  16686. m.set (bwavDescription, description);
  16687. m.set (bwavOriginator, originator);
  16688. m.set (bwavOriginatorRef, originatorRef);
  16689. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  16690. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  16691. m.set (bwavTimeReference, String (timeReferenceSamples));
  16692. m.set (bwavCodingHistory, codingHistory);
  16693. return m;
  16694. }
  16695. #if JUCE_MSVC
  16696. #pragma pack (push, 1)
  16697. #define PACKED
  16698. #elif defined (JUCE_GCC)
  16699. #define PACKED __attribute__((packed))
  16700. #else
  16701. #define PACKED
  16702. #endif
  16703. struct BWAVChunk
  16704. {
  16705. uint8 description [256];
  16706. uint8 originator [32];
  16707. uint8 originatorRef [32];
  16708. uint8 originationDate [10];
  16709. uint8 originationTime [8];
  16710. uint32 timeRefLow;
  16711. uint32 timeRefHigh;
  16712. uint16 version;
  16713. uint8 umid[64];
  16714. uint8 reserved[190];
  16715. uint8 codingHistory[1];
  16716. void copyTo (StringPairArray& values) const
  16717. {
  16718. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  16719. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  16720. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  16721. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  16722. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  16723. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  16724. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  16725. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  16726. values.set (WavAudioFormat::bwavTimeReference, String (time));
  16727. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  16728. }
  16729. static MemoryBlock createFrom (const StringPairArray& values)
  16730. {
  16731. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (0) - 1;
  16732. MemoryBlock data ((sizeNeeded + 3) & ~3);
  16733. data.fillWith (0);
  16734. BWAVChunk* b = (BWAVChunk*) data.getData();
  16735. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  16736. // as they get called in the right order..
  16737. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  16738. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  16739. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  16740. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  16741. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  16742. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  16743. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  16744. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  16745. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory);
  16746. if (b->description[0] != 0
  16747. || b->originator[0] != 0
  16748. || b->originationDate[0] != 0
  16749. || b->originationTime[0] != 0
  16750. || b->codingHistory[0] != 0
  16751. || time != 0)
  16752. {
  16753. return data;
  16754. }
  16755. return MemoryBlock();
  16756. }
  16757. } PACKED;
  16758. struct SMPLChunk
  16759. {
  16760. struct SampleLoop
  16761. {
  16762. uint32 identifier;
  16763. uint32 type;
  16764. uint32 start;
  16765. uint32 end;
  16766. uint32 fraction;
  16767. uint32 playCount;
  16768. } PACKED;
  16769. uint32 manufacturer;
  16770. uint32 product;
  16771. uint32 samplePeriod;
  16772. uint32 midiUnityNote;
  16773. uint32 midiPitchFraction;
  16774. uint32 smpteFormat;
  16775. uint32 smpteOffset;
  16776. uint32 numSampleLoops;
  16777. uint32 samplerData;
  16778. SampleLoop loops[1];
  16779. void copyTo (StringPairArray& values, const int totalSize) const
  16780. {
  16781. values.set (T("Manufacturer"), String (swapIfBigEndian (manufacturer)));
  16782. values.set (T("Product"), String (swapIfBigEndian (product)));
  16783. values.set (T("SamplePeriod"), String (swapIfBigEndian (samplePeriod)));
  16784. values.set (T("MidiUnityNote"), String (swapIfBigEndian (midiUnityNote)));
  16785. values.set (T("MidiPitchFraction"), String (swapIfBigEndian (midiPitchFraction)));
  16786. values.set (T("SmpteFormat"), String (swapIfBigEndian (smpteFormat)));
  16787. values.set (T("SmpteOffset"), String (swapIfBigEndian (smpteOffset)));
  16788. values.set (T("NumSampleLoops"), String (swapIfBigEndian (numSampleLoops)));
  16789. values.set (T("SamplerData"), String (swapIfBigEndian (samplerData)));
  16790. for (uint32 i = 0; i < numSampleLoops; ++i)
  16791. {
  16792. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  16793. break;
  16794. values.set (String::formatted (T("Loop%dIdentifier"), i), String (swapIfBigEndian (loops[i].identifier)));
  16795. values.set (String::formatted (T("Loop%dType"), i), String (swapIfBigEndian (loops[i].type)));
  16796. values.set (String::formatted (T("Loop%dStart"), i), String (swapIfBigEndian (loops[i].start)));
  16797. values.set (String::formatted (T("Loop%dEnd"), i), String (swapIfBigEndian (loops[i].end)));
  16798. values.set (String::formatted (T("Loop%dFraction"), i), String (swapIfBigEndian (loops[i].fraction)));
  16799. values.set (String::formatted (T("Loop%dPlayCount"), i), String (swapIfBigEndian (loops[i].playCount)));
  16800. }
  16801. }
  16802. } PACKED;
  16803. #if JUCE_MSVC
  16804. #pragma pack (pop)
  16805. #endif
  16806. #undef PACKED
  16807. #undef chunkName
  16808. #define chunkName(a) ((int) littleEndianInt(a))
  16809. class WavAudioFormatReader : public AudioFormatReader
  16810. {
  16811. int bytesPerFrame;
  16812. int64 dataChunkStart, dataLength;
  16813. WavAudioFormatReader (const WavAudioFormatReader&);
  16814. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  16815. public:
  16816. int64 bwavChunkStart, bwavSize;
  16817. WavAudioFormatReader (InputStream* const in)
  16818. : AudioFormatReader (in, wavFormatName),
  16819. dataLength (0),
  16820. bwavChunkStart (0),
  16821. bwavSize (0)
  16822. {
  16823. if (input->readInt() == chunkName ("RIFF"))
  16824. {
  16825. const uint32 len = (uint32) input->readInt();
  16826. const int64 end = input->getPosition() + len;
  16827. bool hasGotType = false;
  16828. bool hasGotData = false;
  16829. if (input->readInt() == chunkName ("WAVE"))
  16830. {
  16831. while (input->getPosition() < end
  16832. && ! input->isExhausted())
  16833. {
  16834. const int chunkType = input->readInt();
  16835. uint32 length = (uint32) input->readInt();
  16836. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  16837. if (chunkType == chunkName ("fmt "))
  16838. {
  16839. // read the format chunk
  16840. const short format = input->readShort();
  16841. const short numChans = input->readShort();
  16842. sampleRate = input->readInt();
  16843. const int bytesPerSec = input->readInt();
  16844. numChannels = numChans;
  16845. bytesPerFrame = bytesPerSec / (int)sampleRate;
  16846. bitsPerSample = 8 * bytesPerFrame / numChans;
  16847. if (format == 3)
  16848. usesFloatingPointData = true;
  16849. else if (format != 1)
  16850. bytesPerFrame = 0;
  16851. hasGotType = true;
  16852. }
  16853. else if (chunkType == chunkName ("data"))
  16854. {
  16855. // get the data chunk's position
  16856. dataLength = length;
  16857. dataChunkStart = input->getPosition();
  16858. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  16859. hasGotData = true;
  16860. }
  16861. else if (chunkType == chunkName ("bext"))
  16862. {
  16863. bwavChunkStart = input->getPosition();
  16864. bwavSize = length;
  16865. // Broadcast-wav extension chunk..
  16866. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  16867. input->read (bwav, length);
  16868. bwav->copyTo (metadataValues);
  16869. juce_free (bwav);
  16870. }
  16871. else if (chunkType == chunkName ("smpl"))
  16872. {
  16873. SMPLChunk* const smpl = (SMPLChunk*) juce_calloc (jmax (length + 1, (int) sizeof (SMPLChunk)));
  16874. input->read (smpl, length);
  16875. smpl->copyTo (metadataValues, length);
  16876. juce_free (smpl);
  16877. }
  16878. else if (chunkEnd <= input->getPosition())
  16879. {
  16880. break;
  16881. }
  16882. input->setPosition (chunkEnd);
  16883. }
  16884. }
  16885. }
  16886. }
  16887. ~WavAudioFormatReader()
  16888. {
  16889. }
  16890. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16891. int64 startSampleInFile, int numSamples)
  16892. {
  16893. numSamples = (int) jmin ((int64) numSamples, lengthInSamples - startSampleInFile);
  16894. if (numSamples <= 0)
  16895. return true;
  16896. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16897. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16898. char tempBuffer [tempBufSize];
  16899. while (numSamples > 0)
  16900. {
  16901. int* left = destSamples[0];
  16902. if (left != 0)
  16903. left += startOffsetInDestBuffer;
  16904. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  16905. if (right != 0)
  16906. right += startOffsetInDestBuffer;
  16907. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16908. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16909. if (bytesRead < numThisTime * bytesPerFrame)
  16910. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16911. if (bitsPerSample == 16)
  16912. {
  16913. const short* src = (const short*) tempBuffer;
  16914. if (numChannels > 1)
  16915. {
  16916. if (left == 0)
  16917. {
  16918. for (int i = numThisTime; --i >= 0;)
  16919. {
  16920. ++src;
  16921. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16922. }
  16923. }
  16924. else if (right == 0)
  16925. {
  16926. for (int i = numThisTime; --i >= 0;)
  16927. {
  16928. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16929. ++src;
  16930. }
  16931. }
  16932. else
  16933. {
  16934. for (int i = numThisTime; --i >= 0;)
  16935. {
  16936. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16937. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16938. }
  16939. }
  16940. }
  16941. else
  16942. {
  16943. for (int i = numThisTime; --i >= 0;)
  16944. {
  16945. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16946. }
  16947. }
  16948. }
  16949. else if (bitsPerSample == 24)
  16950. {
  16951. const char* src = (const char*) tempBuffer;
  16952. if (numChannels > 1)
  16953. {
  16954. if (left == 0)
  16955. {
  16956. for (int i = numThisTime; --i >= 0;)
  16957. {
  16958. src += 3;
  16959. *right++ = littleEndian24Bit (src) << 8;
  16960. src += 3;
  16961. }
  16962. }
  16963. else if (right == 0)
  16964. {
  16965. for (int i = numThisTime; --i >= 0;)
  16966. {
  16967. *left++ = littleEndian24Bit (src) << 8;
  16968. src += 6;
  16969. }
  16970. }
  16971. else
  16972. {
  16973. for (int i = 0; i < numThisTime; ++i)
  16974. {
  16975. *left++ = littleEndian24Bit (src) << 8;
  16976. src += 3;
  16977. *right++ = littleEndian24Bit (src) << 8;
  16978. src += 3;
  16979. }
  16980. }
  16981. }
  16982. else
  16983. {
  16984. for (int i = 0; i < numThisTime; ++i)
  16985. {
  16986. *left++ = littleEndian24Bit (src) << 8;
  16987. src += 3;
  16988. }
  16989. }
  16990. }
  16991. else if (bitsPerSample == 32)
  16992. {
  16993. const unsigned int* src = (const unsigned int*) tempBuffer;
  16994. unsigned int* l = (unsigned int*) left;
  16995. unsigned int* r = (unsigned int*) right;
  16996. if (numChannels > 1)
  16997. {
  16998. if (l == 0)
  16999. {
  17000. for (int i = numThisTime; --i >= 0;)
  17001. {
  17002. ++src;
  17003. *r++ = swapIfBigEndian (*src++);
  17004. }
  17005. }
  17006. else if (r == 0)
  17007. {
  17008. for (int i = numThisTime; --i >= 0;)
  17009. {
  17010. *l++ = swapIfBigEndian (*src++);
  17011. ++src;
  17012. }
  17013. }
  17014. else
  17015. {
  17016. for (int i = numThisTime; --i >= 0;)
  17017. {
  17018. *l++ = swapIfBigEndian (*src++);
  17019. *r++ = swapIfBigEndian (*src++);
  17020. }
  17021. }
  17022. }
  17023. else
  17024. {
  17025. for (int i = numThisTime; --i >= 0;)
  17026. {
  17027. *l++ = swapIfBigEndian (*src++);
  17028. }
  17029. }
  17030. left = (int*)l;
  17031. right = (int*)r;
  17032. }
  17033. else if (bitsPerSample == 8)
  17034. {
  17035. const unsigned char* src = (const unsigned char*) tempBuffer;
  17036. if (numChannels > 1)
  17037. {
  17038. if (left == 0)
  17039. {
  17040. for (int i = numThisTime; --i >= 0;)
  17041. {
  17042. ++src;
  17043. *right++ = ((int) *src++ - 128) << 24;
  17044. }
  17045. }
  17046. else if (right == 0)
  17047. {
  17048. for (int i = numThisTime; --i >= 0;)
  17049. {
  17050. *left++ = ((int) *src++ - 128) << 24;
  17051. ++src;
  17052. }
  17053. }
  17054. else
  17055. {
  17056. for (int i = numThisTime; --i >= 0;)
  17057. {
  17058. *left++ = ((int) *src++ - 128) << 24;
  17059. *right++ = ((int) *src++ - 128) << 24;
  17060. }
  17061. }
  17062. }
  17063. else
  17064. {
  17065. for (int i = numThisTime; --i >= 0;)
  17066. {
  17067. *left++ = ((int)*src++ - 128) << 24;
  17068. }
  17069. }
  17070. }
  17071. startOffsetInDestBuffer += numThisTime;
  17072. numSamples -= numThisTime;
  17073. }
  17074. if (numSamples > 0)
  17075. {
  17076. for (int i = numDestChannels; --i >= 0;)
  17077. if (destSamples[i] != 0)
  17078. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17079. sizeof (int) * numSamples);
  17080. }
  17081. return true;
  17082. }
  17083. juce_UseDebuggingNewOperator
  17084. };
  17085. class WavAudioFormatWriter : public AudioFormatWriter
  17086. {
  17087. MemoryBlock tempBlock, bwavChunk;
  17088. uint32 lengthInSamples, bytesWritten;
  17089. int64 headerPosition;
  17090. bool writeFailed;
  17091. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17092. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17093. void writeHeader()
  17094. {
  17095. const bool seekedOk = output->setPosition (headerPosition);
  17096. (void) seekedOk;
  17097. // if this fails, you've given it an output stream that can't seek! It needs
  17098. // to be able to seek back to write the header
  17099. jassert (seekedOk);
  17100. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17101. output->writeInt (chunkName ("RIFF"));
  17102. output->writeInt (lengthInSamples * bytesPerFrame
  17103. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  17104. output->writeInt (chunkName ("WAVE"));
  17105. output->writeInt (chunkName ("fmt "));
  17106. output->writeInt (16);
  17107. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17108. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17109. output->writeShort ((short) numChannels);
  17110. output->writeInt ((int) sampleRate);
  17111. output->writeInt (bytesPerFrame * (int) sampleRate);
  17112. output->writeShort ((short) bytesPerFrame);
  17113. output->writeShort ((short) bitsPerSample);
  17114. if (bwavChunk.getSize() > 0)
  17115. {
  17116. output->writeInt (chunkName ("bext"));
  17117. output->writeInt (bwavChunk.getSize());
  17118. output->write (bwavChunk.getData(), bwavChunk.getSize());
  17119. }
  17120. output->writeInt (chunkName ("data"));
  17121. output->writeInt (lengthInSamples * bytesPerFrame);
  17122. usesFloatingPointData = (bitsPerSample == 32);
  17123. }
  17124. public:
  17125. WavAudioFormatWriter (OutputStream* const out,
  17126. const double sampleRate,
  17127. const unsigned int numChannels_,
  17128. const int bits,
  17129. const StringPairArray& metadataValues)
  17130. : AudioFormatWriter (out,
  17131. wavFormatName,
  17132. sampleRate,
  17133. numChannels_,
  17134. bits),
  17135. lengthInSamples (0),
  17136. bytesWritten (0),
  17137. writeFailed (false)
  17138. {
  17139. if (metadataValues.size() > 0)
  17140. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17141. headerPosition = out->getPosition();
  17142. writeHeader();
  17143. }
  17144. ~WavAudioFormatWriter()
  17145. {
  17146. writeHeader();
  17147. }
  17148. bool write (const int** data, int numSamples)
  17149. {
  17150. if (writeFailed)
  17151. return false;
  17152. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17153. tempBlock.ensureSize (bytes, false);
  17154. char* buffer = (char*) tempBlock.getData();
  17155. const int* left = data[0];
  17156. const int* right = data[1];
  17157. if (right == 0)
  17158. right = left;
  17159. if (bitsPerSample == 16)
  17160. {
  17161. short* b = (short*) buffer;
  17162. if (numChannels > 1)
  17163. {
  17164. for (int i = numSamples; --i >= 0;)
  17165. {
  17166. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17167. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17168. }
  17169. }
  17170. else
  17171. {
  17172. for (int i = numSamples; --i >= 0;)
  17173. {
  17174. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17175. }
  17176. }
  17177. }
  17178. else if (bitsPerSample == 24)
  17179. {
  17180. char* b = (char*) buffer;
  17181. if (numChannels > 1)
  17182. {
  17183. for (int i = numSamples; --i >= 0;)
  17184. {
  17185. littleEndian24BitToChars ((*left++) >> 8, b);
  17186. b += 3;
  17187. littleEndian24BitToChars ((*right++) >> 8, b);
  17188. b += 3;
  17189. }
  17190. }
  17191. else
  17192. {
  17193. for (int i = numSamples; --i >= 0;)
  17194. {
  17195. littleEndian24BitToChars ((*left++) >> 8, b);
  17196. b += 3;
  17197. }
  17198. }
  17199. }
  17200. else if (bitsPerSample == 32)
  17201. {
  17202. unsigned int* b = (unsigned int*) buffer;
  17203. if (numChannels > 1)
  17204. {
  17205. for (int i = numSamples; --i >= 0;)
  17206. {
  17207. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17208. *b++ = swapIfBigEndian ((unsigned int) *right++);
  17209. }
  17210. }
  17211. else
  17212. {
  17213. for (int i = numSamples; --i >= 0;)
  17214. {
  17215. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17216. }
  17217. }
  17218. }
  17219. else if (bitsPerSample == 8)
  17220. {
  17221. unsigned char* b = (unsigned char*) buffer;
  17222. if (numChannels > 1)
  17223. {
  17224. for (int i = numSamples; --i >= 0;)
  17225. {
  17226. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17227. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17228. }
  17229. }
  17230. else
  17231. {
  17232. for (int i = numSamples; --i >= 0;)
  17233. {
  17234. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17235. }
  17236. }
  17237. }
  17238. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17239. || ! output->write (buffer, bytes))
  17240. {
  17241. // failed to write to disk, so let's try writing the header.
  17242. // If it's just run out of disk space, then if it does manage
  17243. // to write the header, we'll still have a useable file..
  17244. writeHeader();
  17245. writeFailed = true;
  17246. return false;
  17247. }
  17248. else
  17249. {
  17250. bytesWritten += bytes;
  17251. lengthInSamples += numSamples;
  17252. return true;
  17253. }
  17254. }
  17255. juce_UseDebuggingNewOperator
  17256. };
  17257. WavAudioFormat::WavAudioFormat()
  17258. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  17259. {
  17260. }
  17261. WavAudioFormat::~WavAudioFormat()
  17262. {
  17263. }
  17264. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17265. {
  17266. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17267. return Array <int> (rates);
  17268. }
  17269. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17270. {
  17271. const int depths[] = { 8, 16, 24, 32, 0 };
  17272. return Array <int> (depths);
  17273. }
  17274. bool WavAudioFormat::canDoStereo()
  17275. {
  17276. return true;
  17277. }
  17278. bool WavAudioFormat::canDoMono()
  17279. {
  17280. return true;
  17281. }
  17282. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  17283. const bool deleteStreamIfOpeningFails)
  17284. {
  17285. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  17286. if (r->sampleRate == 0)
  17287. {
  17288. if (! deleteStreamIfOpeningFails)
  17289. r->input = 0;
  17290. deleteAndZero (r);
  17291. }
  17292. return r;
  17293. }
  17294. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  17295. double sampleRate,
  17296. unsigned int numChannels,
  17297. int bitsPerSample,
  17298. const StringPairArray& metadataValues,
  17299. int /*qualityOptionIndex*/)
  17300. {
  17301. if (getPossibleBitDepths().contains (bitsPerSample))
  17302. {
  17303. return new WavAudioFormatWriter (out,
  17304. sampleRate,
  17305. numChannels,
  17306. bitsPerSample,
  17307. metadataValues);
  17308. }
  17309. return 0;
  17310. }
  17311. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  17312. {
  17313. bool ok = false;
  17314. WavAudioFormat wav;
  17315. const File dest (file.getNonexistentSibling());
  17316. OutputStream* outStream = dest.createOutputStream();
  17317. if (outStream != 0)
  17318. {
  17319. AudioFormatReader* reader = wav.createReaderFor (file.createInputStream(), true);
  17320. if (reader != 0)
  17321. {
  17322. AudioFormatWriter* writer = wav.createWriterFor (outStream, reader->sampleRate,
  17323. reader->numChannels, reader->bitsPerSample,
  17324. metadata, 0);
  17325. if (writer != 0)
  17326. {
  17327. ok = writer->writeFromAudioReader (*reader, 0, -1);
  17328. outStream = 0;
  17329. delete writer;
  17330. }
  17331. delete reader;
  17332. }
  17333. delete outStream;
  17334. }
  17335. if (ok)
  17336. ok = dest.moveFileTo (file);
  17337. if (! ok)
  17338. dest.deleteFile();
  17339. return ok;
  17340. }
  17341. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  17342. {
  17343. WavAudioFormatReader* reader = (WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true);
  17344. if (reader != 0)
  17345. {
  17346. const int64 bwavPos = reader->bwavChunkStart;
  17347. const int64 bwavSize = reader->bwavSize;
  17348. delete reader;
  17349. if (bwavSize > 0)
  17350. {
  17351. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  17352. if (chunk.getSize() <= bwavSize)
  17353. {
  17354. // the new one will fit in the space available, so write it directly..
  17355. const int64 oldSize = wavFile.getSize();
  17356. FileOutputStream* out = wavFile.createOutputStream();
  17357. out->setPosition (bwavPos);
  17358. out->write (chunk.getData(), chunk.getSize());
  17359. out->setPosition (oldSize);
  17360. delete out;
  17361. jassert (wavFile.getSize() == oldSize);
  17362. return true;
  17363. }
  17364. }
  17365. }
  17366. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  17367. }
  17368. END_JUCE_NAMESPACE
  17369. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  17370. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17371. BEGIN_JUCE_NAMESPACE
  17372. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  17373. const bool deleteReaderWhenThisIsDeleted)
  17374. : reader (reader_),
  17375. deleteReader (deleteReaderWhenThisIsDeleted),
  17376. nextPlayPos (0),
  17377. looping (false)
  17378. {
  17379. jassert (reader != 0);
  17380. }
  17381. AudioFormatReaderSource::~AudioFormatReaderSource()
  17382. {
  17383. releaseResources();
  17384. if (deleteReader)
  17385. delete reader;
  17386. }
  17387. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  17388. {
  17389. nextPlayPos = newPosition;
  17390. }
  17391. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  17392. {
  17393. looping = shouldLoop;
  17394. }
  17395. int AudioFormatReaderSource::getNextReadPosition() const
  17396. {
  17397. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  17398. : nextPlayPos;
  17399. }
  17400. int AudioFormatReaderSource::getTotalLength() const
  17401. {
  17402. return (int) reader->lengthInSamples;
  17403. }
  17404. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  17405. double /*sampleRate*/)
  17406. {
  17407. }
  17408. void AudioFormatReaderSource::releaseResources()
  17409. {
  17410. }
  17411. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17412. {
  17413. if (info.numSamples > 0)
  17414. {
  17415. const int start = nextPlayPos;
  17416. if (looping)
  17417. {
  17418. const int newStart = start % (int) reader->lengthInSamples;
  17419. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  17420. if (newEnd > newStart)
  17421. {
  17422. info.buffer->readFromAudioReader (reader,
  17423. info.startSample,
  17424. newEnd - newStart,
  17425. newStart,
  17426. true, true);
  17427. }
  17428. else
  17429. {
  17430. const int endSamps = (int) reader->lengthInSamples - newStart;
  17431. info.buffer->readFromAudioReader (reader,
  17432. info.startSample,
  17433. endSamps,
  17434. newStart,
  17435. true, true);
  17436. info.buffer->readFromAudioReader (reader,
  17437. info.startSample + endSamps,
  17438. newEnd,
  17439. 0,
  17440. true, true);
  17441. }
  17442. nextPlayPos = newEnd;
  17443. }
  17444. else
  17445. {
  17446. info.buffer->readFromAudioReader (reader,
  17447. info.startSample,
  17448. info.numSamples,
  17449. start,
  17450. true, true);
  17451. nextPlayPos += info.numSamples;
  17452. }
  17453. }
  17454. }
  17455. END_JUCE_NAMESPACE
  17456. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17457. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  17458. BEGIN_JUCE_NAMESPACE
  17459. AudioSourcePlayer::AudioSourcePlayer()
  17460. : source (0),
  17461. sampleRate (0),
  17462. bufferSize (0),
  17463. tempBuffer (2, 8),
  17464. lastGain (1.0f),
  17465. gain (1.0f)
  17466. {
  17467. }
  17468. AudioSourcePlayer::~AudioSourcePlayer()
  17469. {
  17470. setSource (0);
  17471. }
  17472. void AudioSourcePlayer::setSource (AudioSource* newSource)
  17473. {
  17474. if (source != newSource)
  17475. {
  17476. AudioSource* const oldSource = source;
  17477. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  17478. newSource->prepareToPlay (bufferSize, sampleRate);
  17479. {
  17480. const ScopedLock sl (readLock);
  17481. source = newSource;
  17482. }
  17483. if (oldSource != 0)
  17484. oldSource->releaseResources();
  17485. }
  17486. }
  17487. void AudioSourcePlayer::setGain (const float newGain) throw()
  17488. {
  17489. gain = newGain;
  17490. }
  17491. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  17492. int totalNumInputChannels,
  17493. float** outputChannelData,
  17494. int totalNumOutputChannels,
  17495. int numSamples)
  17496. {
  17497. // these should have been prepared by audioDeviceAboutToStart()...
  17498. jassert (sampleRate > 0 && bufferSize > 0);
  17499. const ScopedLock sl (readLock);
  17500. if (source != 0)
  17501. {
  17502. AudioSourceChannelInfo info;
  17503. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  17504. // messy stuff needed to compact the channels down into an array
  17505. // of non-zero pointers..
  17506. for (i = 0; i < totalNumInputChannels; ++i)
  17507. {
  17508. if (inputChannelData[i] != 0)
  17509. {
  17510. inputChans [numInputs++] = inputChannelData[i];
  17511. if (numInputs >= numElementsInArray (inputChans))
  17512. break;
  17513. }
  17514. }
  17515. for (i = 0; i < totalNumOutputChannels; ++i)
  17516. {
  17517. if (outputChannelData[i] != 0)
  17518. {
  17519. outputChans [numOutputs++] = outputChannelData[i];
  17520. if (numOutputs >= numElementsInArray (outputChans))
  17521. break;
  17522. }
  17523. }
  17524. if (numInputs > numOutputs)
  17525. {
  17526. // if there aren't enough output channels for the number of
  17527. // inputs, we need to create some temporary extra ones (can't
  17528. // use the input data in case it gets written to)
  17529. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  17530. false, false, true);
  17531. for (i = 0; i < numOutputs; ++i)
  17532. {
  17533. channels[numActiveChans] = outputChans[i];
  17534. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17535. ++numActiveChans;
  17536. }
  17537. for (i = numOutputs; i < numInputs; ++i)
  17538. {
  17539. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  17540. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17541. ++numActiveChans;
  17542. }
  17543. }
  17544. else
  17545. {
  17546. for (i = 0; i < numInputs; ++i)
  17547. {
  17548. channels[numActiveChans] = outputChans[i];
  17549. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17550. ++numActiveChans;
  17551. }
  17552. for (i = numInputs; i < numOutputs; ++i)
  17553. {
  17554. channels[numActiveChans] = outputChans[i];
  17555. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  17556. ++numActiveChans;
  17557. }
  17558. }
  17559. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  17560. info.buffer = &buffer;
  17561. info.startSample = 0;
  17562. info.numSamples = numSamples;
  17563. source->getNextAudioBlock (info);
  17564. for (i = info.buffer->getNumChannels(); --i >= 0;)
  17565. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  17566. lastGain = gain;
  17567. }
  17568. else
  17569. {
  17570. for (int i = 0; i < totalNumOutputChannels; ++i)
  17571. if (outputChannelData[i] != 0)
  17572. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17573. }
  17574. }
  17575. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  17576. {
  17577. sampleRate = device->getCurrentSampleRate();
  17578. bufferSize = device->getCurrentBufferSizeSamples();
  17579. zeromem (channels, sizeof (channels));
  17580. if (source != 0)
  17581. source->prepareToPlay (bufferSize, sampleRate);
  17582. }
  17583. void AudioSourcePlayer::audioDeviceStopped()
  17584. {
  17585. if (source != 0)
  17586. source->releaseResources();
  17587. sampleRate = 0.0;
  17588. bufferSize = 0;
  17589. tempBuffer.setSize (2, 8);
  17590. }
  17591. END_JUCE_NAMESPACE
  17592. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  17593. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  17594. BEGIN_JUCE_NAMESPACE
  17595. AudioTransportSource::AudioTransportSource()
  17596. : source (0),
  17597. resamplerSource (0),
  17598. bufferingSource (0),
  17599. positionableSource (0),
  17600. masterSource (0),
  17601. gain (1.0f),
  17602. lastGain (1.0f),
  17603. playing (false),
  17604. stopped (true),
  17605. sampleRate (44100.0),
  17606. sourceSampleRate (0.0),
  17607. blockSize (128),
  17608. readAheadBufferSize (0),
  17609. isPrepared (false),
  17610. inputStreamEOF (false)
  17611. {
  17612. }
  17613. AudioTransportSource::~AudioTransportSource()
  17614. {
  17615. setSource (0);
  17616. releaseResources();
  17617. }
  17618. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  17619. int readAheadBufferSize_,
  17620. double sourceSampleRateToCorrectFor)
  17621. {
  17622. if (source == newSource)
  17623. {
  17624. if (source == 0)
  17625. return;
  17626. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  17627. }
  17628. readAheadBufferSize = readAheadBufferSize_;
  17629. sourceSampleRate = sourceSampleRateToCorrectFor;
  17630. ResamplingAudioSource* newResamplerSource = 0;
  17631. BufferingAudioSource* newBufferingSource = 0;
  17632. PositionableAudioSource* newPositionableSource = 0;
  17633. AudioSource* newMasterSource = 0;
  17634. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  17635. BufferingAudioSource* oldBufferingSource = bufferingSource;
  17636. AudioSource* oldMasterSource = masterSource;
  17637. if (newSource != 0)
  17638. {
  17639. newPositionableSource = newSource;
  17640. if (readAheadBufferSize_ > 0)
  17641. newPositionableSource = newBufferingSource
  17642. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  17643. newPositionableSource->setNextReadPosition (0);
  17644. if (sourceSampleRateToCorrectFor != 0)
  17645. newMasterSource = newResamplerSource
  17646. = new ResamplingAudioSource (newPositionableSource, false);
  17647. else
  17648. newMasterSource = newPositionableSource;
  17649. if (isPrepared)
  17650. {
  17651. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  17652. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17653. newMasterSource->prepareToPlay (blockSize, sampleRate);
  17654. }
  17655. }
  17656. {
  17657. const ScopedLock sl (callbackLock);
  17658. source = newSource;
  17659. resamplerSource = newResamplerSource;
  17660. bufferingSource = newBufferingSource;
  17661. masterSource = newMasterSource;
  17662. positionableSource = newPositionableSource;
  17663. playing = false;
  17664. }
  17665. if (oldMasterSource != 0)
  17666. oldMasterSource->releaseResources();
  17667. delete oldResamplerSource;
  17668. delete oldBufferingSource;
  17669. }
  17670. void AudioTransportSource::start()
  17671. {
  17672. if ((! playing) && masterSource != 0)
  17673. {
  17674. callbackLock.enter();
  17675. playing = true;
  17676. stopped = false;
  17677. inputStreamEOF = false;
  17678. callbackLock.exit();
  17679. sendChangeMessage (this);
  17680. }
  17681. }
  17682. void AudioTransportSource::stop()
  17683. {
  17684. if (playing)
  17685. {
  17686. callbackLock.enter();
  17687. playing = false;
  17688. callbackLock.exit();
  17689. int n = 500;
  17690. while (--n >= 0 && ! stopped)
  17691. Thread::sleep (2);
  17692. sendChangeMessage (this);
  17693. }
  17694. }
  17695. void AudioTransportSource::setPosition (double newPosition)
  17696. {
  17697. if (sampleRate > 0.0)
  17698. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  17699. }
  17700. double AudioTransportSource::getCurrentPosition() const
  17701. {
  17702. if (sampleRate > 0.0)
  17703. return getNextReadPosition() / sampleRate;
  17704. else
  17705. return 0.0;
  17706. }
  17707. void AudioTransportSource::setNextReadPosition (int newPosition)
  17708. {
  17709. if (positionableSource != 0)
  17710. {
  17711. if (sampleRate > 0 && sourceSampleRate > 0)
  17712. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  17713. positionableSource->setNextReadPosition (newPosition);
  17714. }
  17715. }
  17716. int AudioTransportSource::getNextReadPosition() const
  17717. {
  17718. if (positionableSource != 0)
  17719. {
  17720. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17721. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  17722. }
  17723. return 0;
  17724. }
  17725. int AudioTransportSource::getTotalLength() const
  17726. {
  17727. const ScopedLock sl (callbackLock);
  17728. if (positionableSource != 0)
  17729. {
  17730. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17731. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  17732. }
  17733. return 0;
  17734. }
  17735. bool AudioTransportSource::isLooping() const
  17736. {
  17737. const ScopedLock sl (callbackLock);
  17738. return positionableSource != 0
  17739. && positionableSource->isLooping();
  17740. }
  17741. void AudioTransportSource::setGain (const float newGain) throw()
  17742. {
  17743. gain = newGain;
  17744. }
  17745. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  17746. double sampleRate_)
  17747. {
  17748. const ScopedLock sl (callbackLock);
  17749. sampleRate = sampleRate_;
  17750. blockSize = samplesPerBlockExpected;
  17751. if (masterSource != 0)
  17752. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17753. if (resamplerSource != 0 && sourceSampleRate != 0)
  17754. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17755. isPrepared = true;
  17756. }
  17757. void AudioTransportSource::releaseResources()
  17758. {
  17759. const ScopedLock sl (callbackLock);
  17760. if (masterSource != 0)
  17761. masterSource->releaseResources();
  17762. isPrepared = false;
  17763. }
  17764. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17765. {
  17766. const ScopedLock sl (callbackLock);
  17767. inputStreamEOF = false;
  17768. if (masterSource != 0 && ! stopped)
  17769. {
  17770. masterSource->getNextAudioBlock (info);
  17771. if (! playing)
  17772. {
  17773. // just stopped playing, so fade out the last block..
  17774. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17775. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  17776. if (info.numSamples > 256)
  17777. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  17778. }
  17779. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  17780. && ! positionableSource->isLooping())
  17781. {
  17782. playing = false;
  17783. inputStreamEOF = true;
  17784. sendChangeMessage (this);
  17785. }
  17786. stopped = ! playing;
  17787. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17788. {
  17789. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  17790. lastGain, gain);
  17791. }
  17792. }
  17793. else
  17794. {
  17795. info.clearActiveBufferRegion();
  17796. stopped = true;
  17797. }
  17798. lastGain = gain;
  17799. }
  17800. END_JUCE_NAMESPACE
  17801. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  17802. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  17803. BEGIN_JUCE_NAMESPACE
  17804. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  17805. public Thread,
  17806. private Timer
  17807. {
  17808. public:
  17809. SharedBufferingAudioSourceThread()
  17810. : Thread ("Audio Buffer"),
  17811. sources (8)
  17812. {
  17813. }
  17814. ~SharedBufferingAudioSourceThread()
  17815. {
  17816. stopThread (10000);
  17817. clearSingletonInstance();
  17818. }
  17819. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  17820. void addSource (BufferingAudioSource* source)
  17821. {
  17822. const ScopedLock sl (lock);
  17823. if (! sources.contains ((void*) source))
  17824. {
  17825. sources.add ((void*) source);
  17826. startThread();
  17827. stopTimer();
  17828. }
  17829. notify();
  17830. }
  17831. void removeSource (BufferingAudioSource* source)
  17832. {
  17833. const ScopedLock sl (lock);
  17834. sources.removeValue ((void*) source);
  17835. if (sources.size() == 0)
  17836. startTimer (5000);
  17837. }
  17838. private:
  17839. VoidArray sources;
  17840. CriticalSection lock;
  17841. void run()
  17842. {
  17843. while (! threadShouldExit())
  17844. {
  17845. bool busy = false;
  17846. for (int i = sources.size(); --i >= 0;)
  17847. {
  17848. if (threadShouldExit())
  17849. return;
  17850. const ScopedLock sl (lock);
  17851. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  17852. if (b != 0 && b->readNextBufferChunk())
  17853. busy = true;
  17854. }
  17855. if (! busy)
  17856. wait (500);
  17857. }
  17858. }
  17859. void timerCallback()
  17860. {
  17861. stopTimer();
  17862. if (sources.size() == 0)
  17863. deleteInstance();
  17864. }
  17865. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  17866. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  17867. };
  17868. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  17869. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  17870. const bool deleteSourceWhenDeleted_,
  17871. int numberOfSamplesToBuffer_)
  17872. : source (source_),
  17873. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  17874. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  17875. buffer (2, 0),
  17876. bufferValidStart (0),
  17877. bufferValidEnd (0),
  17878. nextPlayPos (0),
  17879. wasSourceLooping (false)
  17880. {
  17881. jassert (source_ != 0);
  17882. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  17883. // not using a larger buffer..
  17884. }
  17885. BufferingAudioSource::~BufferingAudioSource()
  17886. {
  17887. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17888. if (thread != 0)
  17889. thread->removeSource (this);
  17890. if (deleteSourceWhenDeleted)
  17891. delete source;
  17892. }
  17893. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  17894. {
  17895. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  17896. sampleRate = sampleRate_;
  17897. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  17898. buffer.clear();
  17899. bufferValidStart = 0;
  17900. bufferValidEnd = 0;
  17901. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  17902. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  17903. buffer.getNumSamples() / 2))
  17904. {
  17905. SharedBufferingAudioSourceThread::getInstance()->notify();
  17906. Thread::sleep (5);
  17907. }
  17908. }
  17909. void BufferingAudioSource::releaseResources()
  17910. {
  17911. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17912. if (thread != 0)
  17913. thread->removeSource (this);
  17914. buffer.setSize (2, 0);
  17915. source->releaseResources();
  17916. }
  17917. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17918. {
  17919. const ScopedLock sl (bufferStartPosLock);
  17920. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  17921. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  17922. if (validStart == validEnd)
  17923. {
  17924. // total cache miss
  17925. info.clearActiveBufferRegion();
  17926. }
  17927. else
  17928. {
  17929. if (validStart > 0)
  17930. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  17931. if (validEnd < info.numSamples)
  17932. info.buffer->clear (info.startSample + validEnd,
  17933. info.numSamples - validEnd); // partial cache miss at end
  17934. if (validStart < validEnd)
  17935. {
  17936. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  17937. {
  17938. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  17939. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  17940. if (startBufferIndex < endBufferIndex)
  17941. {
  17942. info.buffer->copyFrom (chan, info.startSample + validStart,
  17943. buffer,
  17944. chan, startBufferIndex,
  17945. validEnd - validStart);
  17946. }
  17947. else
  17948. {
  17949. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  17950. info.buffer->copyFrom (chan, info.startSample + validStart,
  17951. buffer,
  17952. chan, startBufferIndex,
  17953. initialSize);
  17954. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  17955. buffer,
  17956. chan, 0,
  17957. (validEnd - validStart) - initialSize);
  17958. }
  17959. }
  17960. }
  17961. nextPlayPos += info.numSamples;
  17962. if (source->isLooping() && nextPlayPos > 0)
  17963. nextPlayPos %= source->getTotalLength();
  17964. }
  17965. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17966. if (thread != 0)
  17967. thread->notify();
  17968. }
  17969. int BufferingAudioSource::getNextReadPosition() const
  17970. {
  17971. return (source->isLooping() && nextPlayPos > 0)
  17972. ? nextPlayPos % source->getTotalLength()
  17973. : nextPlayPos;
  17974. }
  17975. void BufferingAudioSource::setNextReadPosition (int newPosition)
  17976. {
  17977. const ScopedLock sl (bufferStartPosLock);
  17978. nextPlayPos = newPosition;
  17979. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17980. if (thread != 0)
  17981. thread->notify();
  17982. }
  17983. bool BufferingAudioSource::readNextBufferChunk()
  17984. {
  17985. bufferStartPosLock.enter();
  17986. if (wasSourceLooping != isLooping())
  17987. {
  17988. wasSourceLooping = isLooping();
  17989. bufferValidStart = 0;
  17990. bufferValidEnd = 0;
  17991. }
  17992. int newBVS = jmax (0, nextPlayPos);
  17993. int newBVE = newBVS + buffer.getNumSamples() - 4;
  17994. int sectionToReadStart = 0;
  17995. int sectionToReadEnd = 0;
  17996. const int maxChunkSize = 2048;
  17997. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  17998. {
  17999. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18000. sectionToReadStart = newBVS;
  18001. sectionToReadEnd = newBVE;
  18002. bufferValidStart = 0;
  18003. bufferValidEnd = 0;
  18004. }
  18005. else if (abs (newBVS - bufferValidStart) > 512
  18006. || abs (newBVE - bufferValidEnd) > 512)
  18007. {
  18008. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18009. sectionToReadStart = bufferValidEnd;
  18010. sectionToReadEnd = newBVE;
  18011. bufferValidStart = newBVS;
  18012. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18013. }
  18014. bufferStartPosLock.exit();
  18015. if (sectionToReadStart != sectionToReadEnd)
  18016. {
  18017. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18018. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18019. if (bufferIndexStart < bufferIndexEnd)
  18020. {
  18021. readBufferSection (sectionToReadStart,
  18022. sectionToReadEnd - sectionToReadStart,
  18023. bufferIndexStart);
  18024. }
  18025. else
  18026. {
  18027. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18028. readBufferSection (sectionToReadStart,
  18029. initialSize,
  18030. bufferIndexStart);
  18031. readBufferSection (sectionToReadStart + initialSize,
  18032. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18033. 0);
  18034. }
  18035. const ScopedLock sl2 (bufferStartPosLock);
  18036. bufferValidStart = newBVS;
  18037. bufferValidEnd = newBVE;
  18038. return true;
  18039. }
  18040. else
  18041. {
  18042. return false;
  18043. }
  18044. }
  18045. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18046. {
  18047. if (source->getNextReadPosition() != start)
  18048. source->setNextReadPosition (start);
  18049. AudioSourceChannelInfo info;
  18050. info.buffer = &buffer;
  18051. info.startSample = bufferOffset;
  18052. info.numSamples = length;
  18053. source->getNextAudioBlock (info);
  18054. }
  18055. END_JUCE_NAMESPACE
  18056. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  18057. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18058. BEGIN_JUCE_NAMESPACE
  18059. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18060. const bool deleteSourceWhenDeleted_)
  18061. : requiredNumberOfChannels (2),
  18062. source (source_),
  18063. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18064. buffer (2, 16)
  18065. {
  18066. remappedInfo.buffer = &buffer;
  18067. remappedInfo.startSample = 0;
  18068. }
  18069. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18070. {
  18071. if (deleteSourceWhenDeleted)
  18072. delete source;
  18073. }
  18074. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18075. {
  18076. const ScopedLock sl (lock);
  18077. requiredNumberOfChannels = requiredNumberOfChannels_;
  18078. }
  18079. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18080. {
  18081. const ScopedLock sl (lock);
  18082. remappedInputs.clear();
  18083. remappedOutputs.clear();
  18084. }
  18085. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18086. {
  18087. const ScopedLock sl (lock);
  18088. while (remappedInputs.size() < destIndex)
  18089. remappedInputs.add (-1);
  18090. remappedInputs.set (destIndex, sourceIndex);
  18091. }
  18092. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18093. {
  18094. const ScopedLock sl (lock);
  18095. while (remappedOutputs.size() < sourceIndex)
  18096. remappedOutputs.add (-1);
  18097. remappedOutputs.set (sourceIndex, destIndex);
  18098. }
  18099. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18100. {
  18101. const ScopedLock sl (lock);
  18102. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18103. return remappedInputs.getUnchecked (inputChannelIndex);
  18104. return -1;
  18105. }
  18106. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18107. {
  18108. const ScopedLock sl (lock);
  18109. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18110. return remappedOutputs .getUnchecked (outputChannelIndex);
  18111. return -1;
  18112. }
  18113. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18114. {
  18115. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18116. }
  18117. void ChannelRemappingAudioSource::releaseResources()
  18118. {
  18119. source->releaseResources();
  18120. }
  18121. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18122. {
  18123. const ScopedLock sl (lock);
  18124. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18125. const int numChans = bufferToFill.buffer->getNumChannels();
  18126. int i;
  18127. for (i = 0; i < buffer.getNumChannels(); ++i)
  18128. {
  18129. const int remappedChan = getRemappedInputChannel (i);
  18130. if (remappedChan >= 0 && remappedChan < numChans)
  18131. {
  18132. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18133. remappedChan,
  18134. bufferToFill.startSample,
  18135. bufferToFill.numSamples);
  18136. }
  18137. else
  18138. {
  18139. buffer.clear (i, 0, bufferToFill.numSamples);
  18140. }
  18141. }
  18142. remappedInfo.numSamples = bufferToFill.numSamples;
  18143. source->getNextAudioBlock (remappedInfo);
  18144. bufferToFill.clearActiveBufferRegion();
  18145. for (i = 0; i < requiredNumberOfChannels; ++i)
  18146. {
  18147. const int remappedChan = getRemappedOutputChannel (i);
  18148. if (remappedChan >= 0 && remappedChan < numChans)
  18149. {
  18150. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18151. buffer, i, 0, bufferToFill.numSamples);
  18152. }
  18153. }
  18154. }
  18155. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18156. {
  18157. XmlElement* e = new XmlElement (T("MAPPINGS"));
  18158. String ins, outs;
  18159. int i;
  18160. const ScopedLock sl (lock);
  18161. for (i = 0; i < remappedInputs.size(); ++i)
  18162. ins << remappedInputs.getUnchecked(i) << T(' ');
  18163. for (i = 0; i < remappedOutputs.size(); ++i)
  18164. outs << remappedOutputs.getUnchecked(i) << T(' ');
  18165. e->setAttribute (T("inputs"), ins.trimEnd());
  18166. e->setAttribute (T("outputs"), outs.trimEnd());
  18167. return e;
  18168. }
  18169. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18170. {
  18171. if (e.hasTagName (T("MAPPINGS")))
  18172. {
  18173. const ScopedLock sl (lock);
  18174. clearAllMappings();
  18175. StringArray ins, outs;
  18176. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  18177. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  18178. int i;
  18179. for (i = 0; i < ins.size(); ++i)
  18180. remappedInputs.add (ins[i].getIntValue());
  18181. for (i = 0; i < outs.size(); ++i)
  18182. remappedOutputs.add (outs[i].getIntValue());
  18183. }
  18184. }
  18185. END_JUCE_NAMESPACE
  18186. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18187. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18188. BEGIN_JUCE_NAMESPACE
  18189. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18190. const bool deleteInputWhenDeleted_)
  18191. : input (inputSource),
  18192. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18193. {
  18194. jassert (inputSource != 0);
  18195. for (int i = 2; --i >= 0;)
  18196. iirFilters.add (new IIRFilter());
  18197. }
  18198. IIRFilterAudioSource::~IIRFilterAudioSource()
  18199. {
  18200. if (deleteInputWhenDeleted)
  18201. delete input;
  18202. }
  18203. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18204. {
  18205. for (int i = iirFilters.size(); --i >= 0;)
  18206. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18207. }
  18208. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18209. {
  18210. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18211. for (int i = iirFilters.size(); --i >= 0;)
  18212. iirFilters.getUnchecked(i)->reset();
  18213. }
  18214. void IIRFilterAudioSource::releaseResources()
  18215. {
  18216. input->releaseResources();
  18217. }
  18218. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18219. {
  18220. input->getNextAudioBlock (bufferToFill);
  18221. const int numChannels = bufferToFill.buffer->getNumChannels();
  18222. while (numChannels > iirFilters.size())
  18223. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18224. for (int i = 0; i < numChannels; ++i)
  18225. iirFilters.getUnchecked(i)
  18226. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18227. bufferToFill.numSamples);
  18228. }
  18229. END_JUCE_NAMESPACE
  18230. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18231. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  18232. BEGIN_JUCE_NAMESPACE
  18233. MixerAudioSource::MixerAudioSource()
  18234. : tempBuffer (2, 0),
  18235. currentSampleRate (0.0),
  18236. bufferSizeExpected (0)
  18237. {
  18238. }
  18239. MixerAudioSource::~MixerAudioSource()
  18240. {
  18241. removeAllInputs();
  18242. }
  18243. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18244. {
  18245. if (input != 0 && ! inputs.contains (input))
  18246. {
  18247. lock.enter();
  18248. double localRate = currentSampleRate;
  18249. int localBufferSize = bufferSizeExpected;
  18250. lock.exit();
  18251. if (localRate != 0.0)
  18252. input->prepareToPlay (localBufferSize, localRate);
  18253. const ScopedLock sl (lock);
  18254. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18255. inputs.add (input);
  18256. }
  18257. }
  18258. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18259. {
  18260. if (input != 0)
  18261. {
  18262. lock.enter();
  18263. const int index = inputs.indexOf ((void*) input);
  18264. if (index >= 0)
  18265. {
  18266. inputsToDelete.shiftBits (index, 1);
  18267. inputs.remove (index);
  18268. }
  18269. lock.exit();
  18270. if (index >= 0)
  18271. {
  18272. input->releaseResources();
  18273. if (deleteInput)
  18274. delete input;
  18275. }
  18276. }
  18277. }
  18278. void MixerAudioSource::removeAllInputs()
  18279. {
  18280. lock.enter();
  18281. VoidArray inputsCopy (inputs);
  18282. BitArray inputsToDeleteCopy (inputsToDelete);
  18283. inputs.clear();
  18284. lock.exit();
  18285. for (int i = inputsCopy.size(); --i >= 0;)
  18286. if (inputsToDeleteCopy[i])
  18287. delete (AudioSource*) inputsCopy[i];
  18288. }
  18289. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18290. {
  18291. tempBuffer.setSize (2, samplesPerBlockExpected);
  18292. const ScopedLock sl (lock);
  18293. currentSampleRate = sampleRate;
  18294. bufferSizeExpected = samplesPerBlockExpected;
  18295. for (int i = inputs.size(); --i >= 0;)
  18296. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  18297. sampleRate);
  18298. }
  18299. void MixerAudioSource::releaseResources()
  18300. {
  18301. const ScopedLock sl (lock);
  18302. for (int i = inputs.size(); --i >= 0;)
  18303. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  18304. tempBuffer.setSize (2, 0);
  18305. currentSampleRate = 0;
  18306. bufferSizeExpected = 0;
  18307. }
  18308. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18309. {
  18310. const ScopedLock sl (lock);
  18311. if (inputs.size() > 0)
  18312. {
  18313. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  18314. if (inputs.size() > 1)
  18315. {
  18316. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  18317. info.buffer->getNumSamples());
  18318. AudioSourceChannelInfo info2;
  18319. info2.buffer = &tempBuffer;
  18320. info2.numSamples = info.numSamples;
  18321. info2.startSample = 0;
  18322. for (int i = 1; i < inputs.size(); ++i)
  18323. {
  18324. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  18325. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  18326. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  18327. }
  18328. }
  18329. }
  18330. else
  18331. {
  18332. info.clearActiveBufferRegion();
  18333. }
  18334. }
  18335. END_JUCE_NAMESPACE
  18336. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  18337. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  18338. BEGIN_JUCE_NAMESPACE
  18339. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  18340. const bool deleteInputWhenDeleted_)
  18341. : input (inputSource),
  18342. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  18343. ratio (1.0),
  18344. lastRatio (1.0),
  18345. buffer (2, 0),
  18346. sampsInBuffer (0)
  18347. {
  18348. jassert (input != 0);
  18349. }
  18350. ResamplingAudioSource::~ResamplingAudioSource()
  18351. {
  18352. if (deleteInputWhenDeleted)
  18353. delete input;
  18354. }
  18355. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  18356. {
  18357. jassert (samplesInPerOutputSample > 0);
  18358. const ScopedLock sl (ratioLock);
  18359. ratio = jmax (0.0, samplesInPerOutputSample);
  18360. }
  18361. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  18362. double sampleRate)
  18363. {
  18364. const ScopedLock sl (ratioLock);
  18365. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18366. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  18367. buffer.clear();
  18368. sampsInBuffer = 0;
  18369. bufferPos = 0;
  18370. subSampleOffset = 0.0;
  18371. createLowPass (ratio);
  18372. resetFilters();
  18373. }
  18374. void ResamplingAudioSource::releaseResources()
  18375. {
  18376. input->releaseResources();
  18377. buffer.setSize (2, 0);
  18378. }
  18379. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18380. {
  18381. const ScopedLock sl (ratioLock);
  18382. if (lastRatio != ratio)
  18383. {
  18384. createLowPass (ratio);
  18385. lastRatio = ratio;
  18386. }
  18387. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  18388. int bufferSize = buffer.getNumSamples();
  18389. if (bufferSize < sampsNeeded + 8)
  18390. {
  18391. bufferPos %= bufferSize;
  18392. bufferSize = sampsNeeded + 32;
  18393. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  18394. }
  18395. bufferPos %= bufferSize;
  18396. int endOfBufferPos = bufferPos + sampsInBuffer;
  18397. while (sampsNeeded > sampsInBuffer)
  18398. {
  18399. endOfBufferPos %= bufferSize;
  18400. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  18401. bufferSize - endOfBufferPos);
  18402. AudioSourceChannelInfo readInfo;
  18403. readInfo.buffer = &buffer;
  18404. readInfo.numSamples = numToDo;
  18405. readInfo.startSample = endOfBufferPos;
  18406. input->getNextAudioBlock (readInfo);
  18407. if (ratio > 1.0001)
  18408. {
  18409. // for down-sampling, pre-apply the filter..
  18410. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18411. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  18412. }
  18413. sampsInBuffer += numToDo;
  18414. endOfBufferPos += numToDo;
  18415. }
  18416. float* dl = info.buffer->getSampleData (0, info.startSample);
  18417. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  18418. const float* const bl = buffer.getSampleData (0, 0);
  18419. const float* const br = buffer.getSampleData (1, 0);
  18420. int nextPos = (bufferPos + 1) % bufferSize;
  18421. for (int m = info.numSamples; --m >= 0;)
  18422. {
  18423. const float alpha = (float) subSampleOffset;
  18424. const float invAlpha = 1.0f - alpha;
  18425. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  18426. if (dr != 0)
  18427. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  18428. subSampleOffset += ratio;
  18429. jassert (sampsInBuffer > 0);
  18430. while (subSampleOffset >= 1.0)
  18431. {
  18432. if (++bufferPos >= bufferSize)
  18433. bufferPos = 0;
  18434. --sampsInBuffer;
  18435. nextPos = (bufferPos + 1) % bufferSize;
  18436. subSampleOffset -= 1.0;
  18437. }
  18438. }
  18439. if (ratio < 0.9999)
  18440. {
  18441. // for up-sampling, apply the filter after transposing..
  18442. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18443. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  18444. }
  18445. else if (ratio <= 1.0001)
  18446. {
  18447. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  18448. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18449. {
  18450. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  18451. FilterState& fs = filterStates[i];
  18452. if (info.numSamples > 1)
  18453. {
  18454. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  18455. }
  18456. else
  18457. {
  18458. fs.y2 = fs.y1;
  18459. fs.x2 = fs.x1;
  18460. }
  18461. fs.y1 = fs.x1 = *endOfBuffer;
  18462. }
  18463. }
  18464. jassert (sampsInBuffer >= 0);
  18465. }
  18466. void ResamplingAudioSource::createLowPass (const double ratio)
  18467. {
  18468. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  18469. : 0.5 * ratio;
  18470. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  18471. const double nSquared = n * n;
  18472. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18473. setFilterCoefficients (c1,
  18474. c1 * 2.0f,
  18475. c1,
  18476. 1.0,
  18477. c1 * 2.0 * (1.0 - nSquared),
  18478. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18479. }
  18480. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  18481. {
  18482. const double a = 1.0 / c4;
  18483. c1 *= a;
  18484. c2 *= a;
  18485. c3 *= a;
  18486. c5 *= a;
  18487. c6 *= a;
  18488. coefficients[0] = c1;
  18489. coefficients[1] = c2;
  18490. coefficients[2] = c3;
  18491. coefficients[3] = c4;
  18492. coefficients[4] = c5;
  18493. coefficients[5] = c6;
  18494. }
  18495. void ResamplingAudioSource::resetFilters()
  18496. {
  18497. zeromem (filterStates, sizeof (filterStates));
  18498. }
  18499. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  18500. {
  18501. while (--num >= 0)
  18502. {
  18503. const double in = *samples;
  18504. double out = coefficients[0] * in
  18505. + coefficients[1] * fs.x1
  18506. + coefficients[2] * fs.x2
  18507. - coefficients[4] * fs.y1
  18508. - coefficients[5] * fs.y2;
  18509. #if JUCE_INTEL
  18510. if (! (out < -1.0e-8 || out > 1.0e-8))
  18511. out = 0;
  18512. #endif
  18513. fs.x2 = fs.x1;
  18514. fs.x1 = in;
  18515. fs.y2 = fs.y1;
  18516. fs.y1 = out;
  18517. *samples++ = (float) out;
  18518. }
  18519. }
  18520. END_JUCE_NAMESPACE
  18521. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  18522. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18523. BEGIN_JUCE_NAMESPACE
  18524. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  18525. : frequency (1000.0),
  18526. sampleRate (44100.0),
  18527. currentPhase (0.0),
  18528. phasePerSample (0.0),
  18529. amplitude (0.5f)
  18530. {
  18531. }
  18532. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  18533. {
  18534. }
  18535. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  18536. {
  18537. amplitude = newAmplitude;
  18538. }
  18539. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  18540. {
  18541. frequency = newFrequencyHz;
  18542. phasePerSample = 0.0;
  18543. }
  18544. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18545. double sampleRate_)
  18546. {
  18547. currentPhase = 0.0;
  18548. phasePerSample = 0.0;
  18549. sampleRate = sampleRate_;
  18550. }
  18551. void ToneGeneratorAudioSource::releaseResources()
  18552. {
  18553. }
  18554. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18555. {
  18556. if (phasePerSample == 0.0)
  18557. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  18558. for (int i = 0; i < info.numSamples; ++i)
  18559. {
  18560. const float sample = amplitude * (float) sin (currentPhase);
  18561. currentPhase += phasePerSample;
  18562. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  18563. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  18564. }
  18565. }
  18566. END_JUCE_NAMESPACE
  18567. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18568. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  18569. BEGIN_JUCE_NAMESPACE
  18570. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  18571. : sampleRate (0),
  18572. bufferSize (0),
  18573. useDefaultInputChannels (true),
  18574. useDefaultOutputChannels (true)
  18575. {
  18576. }
  18577. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  18578. {
  18579. return outputDeviceName == other.outputDeviceName
  18580. && inputDeviceName == other.inputDeviceName
  18581. && sampleRate == other.sampleRate
  18582. && bufferSize == other.bufferSize
  18583. && inputChannels == other.inputChannels
  18584. && useDefaultInputChannels == other.useDefaultInputChannels
  18585. && outputChannels == other.outputChannels
  18586. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  18587. }
  18588. AudioDeviceManager::AudioDeviceManager()
  18589. : currentAudioDevice (0),
  18590. numInputChansNeeded (0),
  18591. numOutputChansNeeded (2),
  18592. lastExplicitSettings (0),
  18593. listNeedsScanning (true),
  18594. useInputNames (false),
  18595. inputLevelMeasurementEnabledCount (0),
  18596. inputLevel (0),
  18597. testSound (0),
  18598. tempBuffer (2, 2),
  18599. enabledMidiInputs (4),
  18600. midiCallbacks (4),
  18601. midiCallbackDevices (4),
  18602. defaultMidiOutput (0),
  18603. cpuUsageMs (0),
  18604. timeToCpuScale (0)
  18605. {
  18606. callbackHandler.owner = this;
  18607. }
  18608. AudioDeviceManager::~AudioDeviceManager()
  18609. {
  18610. deleteAndZero (currentAudioDevice);
  18611. deleteAndZero (defaultMidiOutput);
  18612. delete lastExplicitSettings;
  18613. delete testSound;
  18614. }
  18615. void AudioDeviceManager::createDeviceTypesIfNeeded()
  18616. {
  18617. if (availableDeviceTypes.size() == 0)
  18618. {
  18619. createAudioDeviceTypes (availableDeviceTypes);
  18620. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  18621. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  18622. if (availableDeviceTypes.size() > 0)
  18623. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  18624. }
  18625. }
  18626. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  18627. {
  18628. scanDevicesIfNeeded();
  18629. return availableDeviceTypes;
  18630. }
  18631. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  18632. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  18633. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  18634. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  18635. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  18636. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  18637. {
  18638. #if JUCE_WIN32
  18639. #if JUCE_WASAPI
  18640. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  18641. list.add (juce_createAudioIODeviceType_WASAPI());
  18642. #endif
  18643. #if JUCE_DIRECTSOUND
  18644. list.add (juce_createAudioIODeviceType_DirectSound());
  18645. #endif
  18646. #if JUCE_ASIO
  18647. list.add (juce_createAudioIODeviceType_ASIO());
  18648. #endif
  18649. #endif
  18650. #if JUCE_MAC
  18651. list.add (juce_createAudioIODeviceType_CoreAudio());
  18652. #endif
  18653. #if JUCE_LINUX && JUCE_ALSA
  18654. list.add (juce_createAudioIODeviceType_ALSA());
  18655. #endif
  18656. }
  18657. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  18658. const int numOutputChannelsNeeded,
  18659. const XmlElement* const e,
  18660. const bool selectDefaultDeviceOnFailure,
  18661. const String& preferredDefaultDeviceName,
  18662. const AudioDeviceSetup* preferredSetupOptions)
  18663. {
  18664. scanDevicesIfNeeded();
  18665. numInputChansNeeded = numInputChannelsNeeded;
  18666. numOutputChansNeeded = numOutputChannelsNeeded;
  18667. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  18668. {
  18669. delete lastExplicitSettings;
  18670. lastExplicitSettings = new XmlElement (*e);
  18671. String error;
  18672. AudioDeviceSetup setup;
  18673. if (preferredSetupOptions != 0)
  18674. setup = *preferredSetupOptions;
  18675. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  18676. {
  18677. setup.inputDeviceName = setup.outputDeviceName
  18678. = e->getStringAttribute (T("audioDeviceName"));
  18679. }
  18680. else
  18681. {
  18682. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  18683. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  18684. }
  18685. currentDeviceType = e->getStringAttribute (T("deviceType"));
  18686. if (currentDeviceType.isEmpty())
  18687. {
  18688. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  18689. if (type != 0)
  18690. currentDeviceType = type->getTypeName();
  18691. else if (availableDeviceTypes.size() > 0)
  18692. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  18693. }
  18694. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  18695. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  18696. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  18697. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  18698. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  18699. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  18700. error = setAudioDeviceSetup (setup, true);
  18701. midiInsFromXml.clear();
  18702. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  18703. midiInsFromXml.add (c->getStringAttribute (T("name")));
  18704. const StringArray allMidiIns (MidiInput::getDevices());
  18705. for (int i = allMidiIns.size(); --i >= 0;)
  18706. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  18707. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  18708. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  18709. false, preferredDefaultDeviceName);
  18710. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  18711. return error;
  18712. }
  18713. else
  18714. {
  18715. AudioDeviceSetup setup;
  18716. if (preferredSetupOptions != 0)
  18717. {
  18718. setup = *preferredSetupOptions;
  18719. }
  18720. else if (preferredDefaultDeviceName.isNotEmpty())
  18721. {
  18722. for (int j = availableDeviceTypes.size(); --j >= 0;)
  18723. {
  18724. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  18725. StringArray outs (type->getDeviceNames (false));
  18726. int i;
  18727. for (i = 0; i < outs.size(); ++i)
  18728. {
  18729. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  18730. {
  18731. setup.outputDeviceName = outs[i];
  18732. break;
  18733. }
  18734. }
  18735. StringArray ins (type->getDeviceNames (true));
  18736. for (i = 0; i < ins.size(); ++i)
  18737. {
  18738. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  18739. {
  18740. setup.inputDeviceName = ins[i];
  18741. break;
  18742. }
  18743. }
  18744. }
  18745. }
  18746. insertDefaultDeviceNames (setup);
  18747. return setAudioDeviceSetup (setup, false);
  18748. }
  18749. }
  18750. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  18751. {
  18752. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18753. if (type != 0)
  18754. {
  18755. if (setup.outputDeviceName.isEmpty())
  18756. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  18757. if (setup.inputDeviceName.isEmpty())
  18758. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  18759. }
  18760. }
  18761. XmlElement* AudioDeviceManager::createStateXml() const
  18762. {
  18763. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  18764. }
  18765. void AudioDeviceManager::scanDevicesIfNeeded()
  18766. {
  18767. if (listNeedsScanning)
  18768. {
  18769. listNeedsScanning = false;
  18770. createDeviceTypesIfNeeded();
  18771. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18772. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  18773. }
  18774. }
  18775. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  18776. {
  18777. scanDevicesIfNeeded();
  18778. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18779. {
  18780. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  18781. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  18782. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  18783. {
  18784. return type;
  18785. }
  18786. }
  18787. return 0;
  18788. }
  18789. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  18790. {
  18791. setup = currentSetup;
  18792. }
  18793. void AudioDeviceManager::deleteCurrentDevice()
  18794. {
  18795. deleteAndZero (currentAudioDevice);
  18796. currentSetup.inputDeviceName = String::empty;
  18797. currentSetup.outputDeviceName = String::empty;
  18798. }
  18799. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  18800. const bool treatAsChosenDevice)
  18801. {
  18802. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18803. {
  18804. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  18805. && currentDeviceType != type)
  18806. {
  18807. currentDeviceType = type;
  18808. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  18809. insertDefaultDeviceNames (s);
  18810. setAudioDeviceSetup (s, treatAsChosenDevice);
  18811. sendChangeMessage (this);
  18812. break;
  18813. }
  18814. }
  18815. }
  18816. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  18817. {
  18818. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18819. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  18820. return availableDeviceTypes[i];
  18821. return availableDeviceTypes[0];
  18822. }
  18823. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  18824. const bool treatAsChosenDevice)
  18825. {
  18826. jassert (&newSetup != &currentSetup); // this will have no effect
  18827. if (newSetup == currentSetup && currentAudioDevice != 0)
  18828. return String::empty;
  18829. if (! (newSetup == currentSetup))
  18830. sendChangeMessage (this);
  18831. stopDevice();
  18832. String error;
  18833. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18834. if (type == 0 || (newSetup.inputDeviceName.isEmpty()
  18835. && newSetup.outputDeviceName.isEmpty()))
  18836. {
  18837. deleteCurrentDevice();
  18838. if (treatAsChosenDevice)
  18839. updateXml();
  18840. return String::empty;
  18841. }
  18842. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  18843. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  18844. if (currentSetup.inputDeviceName != newInputDeviceName
  18845. || currentSetup.outputDeviceName != newOutputDeviceName
  18846. || currentAudioDevice == 0)
  18847. {
  18848. deleteCurrentDevice();
  18849. scanDevicesIfNeeded();
  18850. if (newOutputDeviceName.isNotEmpty()
  18851. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  18852. {
  18853. return "No such device: " + newOutputDeviceName;
  18854. }
  18855. if (newInputDeviceName.isNotEmpty()
  18856. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  18857. {
  18858. return "No such device: " + newInputDeviceName;
  18859. }
  18860. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  18861. if (currentAudioDevice == 0)
  18862. 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!";
  18863. else
  18864. error = currentAudioDevice->getLastError();
  18865. if (error.isNotEmpty())
  18866. {
  18867. deleteCurrentDevice();
  18868. return error;
  18869. }
  18870. if (newSetup.useDefaultInputChannels)
  18871. {
  18872. inputChannels.clear();
  18873. inputChannels.setRange (0, numInputChansNeeded, true);
  18874. }
  18875. if (newSetup.useDefaultOutputChannels)
  18876. {
  18877. outputChannels.clear();
  18878. outputChannels.setRange (0, numOutputChansNeeded, true);
  18879. }
  18880. if (newInputDeviceName.isEmpty())
  18881. inputChannels.clear();
  18882. if (newOutputDeviceName.isEmpty())
  18883. outputChannels.clear();
  18884. }
  18885. if (! newSetup.useDefaultInputChannels)
  18886. inputChannels = newSetup.inputChannels;
  18887. if (! newSetup.useDefaultOutputChannels)
  18888. outputChannels = newSetup.outputChannels;
  18889. currentSetup = newSetup;
  18890. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  18891. error = currentAudioDevice->open (inputChannels,
  18892. outputChannels,
  18893. currentSetup.sampleRate,
  18894. currentSetup.bufferSize);
  18895. if (error.isEmpty())
  18896. {
  18897. currentDeviceType = currentAudioDevice->getTypeName();
  18898. currentAudioDevice->start (&callbackHandler);
  18899. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  18900. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  18901. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  18902. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  18903. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18904. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  18905. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  18906. if (treatAsChosenDevice)
  18907. updateXml();
  18908. }
  18909. else
  18910. {
  18911. deleteCurrentDevice();
  18912. }
  18913. return error;
  18914. }
  18915. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  18916. {
  18917. jassert (currentAudioDevice != 0);
  18918. if (rate > 0)
  18919. {
  18920. bool ok = false;
  18921. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  18922. {
  18923. const double sr = currentAudioDevice->getSampleRate (i);
  18924. if (sr == rate)
  18925. ok = true;
  18926. }
  18927. if (! ok)
  18928. rate = 0;
  18929. }
  18930. if (rate == 0)
  18931. {
  18932. double lowestAbove44 = 0.0;
  18933. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  18934. {
  18935. const double sr = currentAudioDevice->getSampleRate (i);
  18936. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  18937. lowestAbove44 = sr;
  18938. }
  18939. if (lowestAbove44 == 0.0)
  18940. rate = currentAudioDevice->getSampleRate (0);
  18941. else
  18942. rate = lowestAbove44;
  18943. }
  18944. return rate;
  18945. }
  18946. void AudioDeviceManager::stopDevice()
  18947. {
  18948. if (currentAudioDevice != 0)
  18949. currentAudioDevice->stop();
  18950. deleteAndZero (testSound);
  18951. }
  18952. void AudioDeviceManager::closeAudioDevice()
  18953. {
  18954. stopDevice();
  18955. deleteAndZero (currentAudioDevice);
  18956. }
  18957. void AudioDeviceManager::restartLastAudioDevice()
  18958. {
  18959. if (currentAudioDevice == 0)
  18960. {
  18961. if (currentSetup.inputDeviceName.isEmpty()
  18962. && currentSetup.outputDeviceName.isEmpty())
  18963. {
  18964. // This method will only reload the last device that was running
  18965. // before closeAudioDevice() was called - you need to actually open
  18966. // one first, with setAudioDevice().
  18967. jassertfalse
  18968. return;
  18969. }
  18970. AudioDeviceSetup s (currentSetup);
  18971. setAudioDeviceSetup (s, false);
  18972. }
  18973. }
  18974. void AudioDeviceManager::updateXml()
  18975. {
  18976. delete lastExplicitSettings;
  18977. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  18978. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  18979. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  18980. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  18981. if (currentAudioDevice != 0)
  18982. {
  18983. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  18984. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  18985. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  18986. if (! currentSetup.useDefaultInputChannels)
  18987. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  18988. if (! currentSetup.useDefaultOutputChannels)
  18989. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  18990. }
  18991. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  18992. {
  18993. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  18994. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  18995. lastExplicitSettings->addChildElement (m);
  18996. }
  18997. if (midiInsFromXml.size() > 0)
  18998. {
  18999. // Add any midi devices that have been enabled before, but which aren't currently
  19000. // open because the device has been disconnected.
  19001. const StringArray availableMidiDevices (MidiInput::getDevices());
  19002. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19003. {
  19004. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19005. {
  19006. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  19007. m->setAttribute (T("name"), midiInsFromXml[i]);
  19008. lastExplicitSettings->addChildElement (m);
  19009. }
  19010. }
  19011. }
  19012. if (defaultMidiOutputName.isNotEmpty())
  19013. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  19014. }
  19015. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19016. {
  19017. {
  19018. const ScopedLock sl (audioCallbackLock);
  19019. if (callbacks.contains (newCallback))
  19020. return;
  19021. }
  19022. if (currentAudioDevice != 0 && newCallback != 0)
  19023. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19024. const ScopedLock sl (audioCallbackLock);
  19025. callbacks.add (newCallback);
  19026. }
  19027. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19028. {
  19029. if (callback != 0)
  19030. {
  19031. bool needsDeinitialising = currentAudioDevice != 0;
  19032. {
  19033. const ScopedLock sl (audioCallbackLock);
  19034. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19035. callbacks.removeValue (callback);
  19036. }
  19037. if (needsDeinitialising)
  19038. callback->audioDeviceStopped();
  19039. }
  19040. }
  19041. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19042. int numInputChannels,
  19043. float** outputChannelData,
  19044. int numOutputChannels,
  19045. int numSamples)
  19046. {
  19047. const ScopedLock sl (audioCallbackLock);
  19048. if (inputLevelMeasurementEnabledCount > 0)
  19049. {
  19050. for (int j = 0; j < numSamples; ++j)
  19051. {
  19052. float s = 0;
  19053. for (int i = 0; i < numInputChannels; ++i)
  19054. s += fabsf (inputChannelData[i][j]);
  19055. s /= numInputChannels;
  19056. const double decayFactor = 0.99992;
  19057. if (s > inputLevel)
  19058. inputLevel = s;
  19059. else if (inputLevel > 0.001f)
  19060. inputLevel *= decayFactor;
  19061. else
  19062. inputLevel = 0;
  19063. }
  19064. }
  19065. if (callbacks.size() > 0)
  19066. {
  19067. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19068. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19069. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19070. outputChannelData, numOutputChannels, numSamples);
  19071. float** const tempChans = tempBuffer.getArrayOfChannels();
  19072. for (int i = callbacks.size(); --i > 0;)
  19073. {
  19074. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19075. tempChans, numOutputChannels, numSamples);
  19076. for (int chan = 0; chan < numOutputChannels; ++chan)
  19077. {
  19078. const float* const src = tempChans [chan];
  19079. float* const dst = outputChannelData [chan];
  19080. if (src != 0 && dst != 0)
  19081. for (int j = 0; j < numSamples; ++j)
  19082. dst[j] += src[j];
  19083. }
  19084. }
  19085. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19086. const double filterAmount = 0.2;
  19087. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19088. }
  19089. else
  19090. {
  19091. for (int i = 0; i < numOutputChannels; ++i)
  19092. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19093. }
  19094. if (testSound != 0)
  19095. {
  19096. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19097. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19098. for (int i = 0; i < numOutputChannels; ++i)
  19099. for (int j = 0; j < numSamps; ++j)
  19100. outputChannelData [i][j] += src[j];
  19101. testSoundPosition += numSamps;
  19102. if (testSoundPosition >= testSound->getNumSamples())
  19103. {
  19104. delete testSound;
  19105. testSound = 0;
  19106. }
  19107. }
  19108. }
  19109. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19110. {
  19111. cpuUsageMs = 0;
  19112. const double sampleRate = device->getCurrentSampleRate();
  19113. const int blockSize = device->getCurrentBufferSizeSamples();
  19114. if (sampleRate > 0.0 && blockSize > 0)
  19115. {
  19116. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19117. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19118. }
  19119. {
  19120. const ScopedLock sl (audioCallbackLock);
  19121. for (int i = callbacks.size(); --i >= 0;)
  19122. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19123. }
  19124. sendChangeMessage (this);
  19125. }
  19126. void AudioDeviceManager::audioDeviceStoppedInt()
  19127. {
  19128. cpuUsageMs = 0;
  19129. timeToCpuScale = 0;
  19130. sendChangeMessage (this);
  19131. const ScopedLock sl (audioCallbackLock);
  19132. for (int i = callbacks.size(); --i >= 0;)
  19133. callbacks.getUnchecked(i)->audioDeviceStopped();
  19134. }
  19135. double AudioDeviceManager::getCpuUsage() const
  19136. {
  19137. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19138. }
  19139. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19140. const bool enabled)
  19141. {
  19142. if (enabled != isMidiInputEnabled (name))
  19143. {
  19144. if (enabled)
  19145. {
  19146. const int index = MidiInput::getDevices().indexOf (name);
  19147. if (index >= 0)
  19148. {
  19149. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19150. if (min != 0)
  19151. {
  19152. enabledMidiInputs.add (min);
  19153. min->start();
  19154. }
  19155. }
  19156. }
  19157. else
  19158. {
  19159. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19160. if (enabledMidiInputs[i]->getName() == name)
  19161. enabledMidiInputs.remove (i);
  19162. }
  19163. updateXml();
  19164. sendChangeMessage (this);
  19165. }
  19166. }
  19167. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19168. {
  19169. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19170. if (enabledMidiInputs[i]->getName() == name)
  19171. return true;
  19172. return false;
  19173. }
  19174. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19175. MidiInputCallback* callback)
  19176. {
  19177. removeMidiInputCallback (name, callback);
  19178. if (name.isEmpty())
  19179. {
  19180. midiCallbacks.add (callback);
  19181. midiCallbackDevices.add (0);
  19182. }
  19183. else
  19184. {
  19185. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19186. {
  19187. if (enabledMidiInputs[i]->getName() == name)
  19188. {
  19189. const ScopedLock sl (midiCallbackLock);
  19190. midiCallbacks.add (callback);
  19191. midiCallbackDevices.add (enabledMidiInputs[i]);
  19192. break;
  19193. }
  19194. }
  19195. }
  19196. }
  19197. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19198. MidiInputCallback* /*callback*/)
  19199. {
  19200. const ScopedLock sl (midiCallbackLock);
  19201. for (int i = midiCallbacks.size(); --i >= 0;)
  19202. {
  19203. String devName;
  19204. if (midiCallbackDevices.getUnchecked(i) != 0)
  19205. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19206. if (devName == name)
  19207. {
  19208. midiCallbacks.remove (i);
  19209. midiCallbackDevices.remove (i);
  19210. }
  19211. }
  19212. }
  19213. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19214. const MidiMessage& message)
  19215. {
  19216. if (! message.isActiveSense())
  19217. {
  19218. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19219. const ScopedLock sl (midiCallbackLock);
  19220. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19221. {
  19222. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19223. if (md == source || (md == 0 && isDefaultSource))
  19224. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19225. }
  19226. }
  19227. }
  19228. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19229. {
  19230. if (defaultMidiOutputName != deviceName)
  19231. {
  19232. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19233. {
  19234. const ScopedLock sl (audioCallbackLock);
  19235. oldCallbacks = callbacks;
  19236. callbacks.clear();
  19237. }
  19238. if (currentAudioDevice != 0)
  19239. for (int i = oldCallbacks.size(); --i >= 0;)
  19240. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19241. deleteAndZero (defaultMidiOutput);
  19242. defaultMidiOutputName = deviceName;
  19243. if (deviceName.isNotEmpty())
  19244. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19245. if (currentAudioDevice != 0)
  19246. for (int i = oldCallbacks.size(); --i >= 0;)
  19247. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19248. {
  19249. const ScopedLock sl (audioCallbackLock);
  19250. callbacks = oldCallbacks;
  19251. }
  19252. updateXml();
  19253. sendChangeMessage (this);
  19254. }
  19255. }
  19256. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19257. int numInputChannels,
  19258. float** outputChannelData,
  19259. int numOutputChannels,
  19260. int numSamples)
  19261. {
  19262. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19263. }
  19264. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19265. {
  19266. owner->audioDeviceAboutToStartInt (device);
  19267. }
  19268. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19269. {
  19270. owner->audioDeviceStoppedInt();
  19271. }
  19272. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19273. {
  19274. owner->handleIncomingMidiMessageInt (source, message);
  19275. }
  19276. void AudioDeviceManager::playTestSound()
  19277. {
  19278. audioCallbackLock.enter();
  19279. AudioSampleBuffer* oldSound = testSound;
  19280. testSound = 0;
  19281. audioCallbackLock.exit();
  19282. delete oldSound;
  19283. testSoundPosition = 0;
  19284. if (currentAudioDevice != 0)
  19285. {
  19286. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  19287. const int soundLength = (int) sampleRate;
  19288. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  19289. float* samples = newSound->getSampleData (0);
  19290. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  19291. const float amplitude = 0.5f;
  19292. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19293. for (int i = 0; i < soundLength; ++i)
  19294. samples[i] = amplitude * (float) sin (i * phasePerSample);
  19295. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  19296. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  19297. const ScopedLock sl (audioCallbackLock);
  19298. testSound = newSound;
  19299. }
  19300. }
  19301. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  19302. {
  19303. const ScopedLock sl (audioCallbackLock);
  19304. if (enableMeasurement)
  19305. ++inputLevelMeasurementEnabledCount;
  19306. else
  19307. --inputLevelMeasurementEnabledCount;
  19308. inputLevel = 0;
  19309. }
  19310. double AudioDeviceManager::getCurrentInputLevel() const
  19311. {
  19312. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  19313. return inputLevel;
  19314. }
  19315. END_JUCE_NAMESPACE
  19316. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  19317. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  19318. BEGIN_JUCE_NAMESPACE
  19319. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  19320. : name (deviceName),
  19321. typeName (typeName_)
  19322. {
  19323. }
  19324. AudioIODevice::~AudioIODevice()
  19325. {
  19326. }
  19327. bool AudioIODevice::hasControlPanel() const
  19328. {
  19329. return false;
  19330. }
  19331. bool AudioIODevice::showControlPanel()
  19332. {
  19333. jassertfalse // this should only be called for devices which return true from
  19334. // their hasControlPanel() method.
  19335. return false;
  19336. }
  19337. END_JUCE_NAMESPACE
  19338. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  19339. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  19340. BEGIN_JUCE_NAMESPACE
  19341. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  19342. : typeName (name)
  19343. {
  19344. }
  19345. AudioIODeviceType::~AudioIODeviceType()
  19346. {
  19347. }
  19348. END_JUCE_NAMESPACE
  19349. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  19350. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  19351. BEGIN_JUCE_NAMESPACE
  19352. MidiOutput::MidiOutput() throw()
  19353. : Thread ("midi out"),
  19354. internal (0),
  19355. firstMessage (0)
  19356. {
  19357. }
  19358. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  19359. const int len,
  19360. const double sampleNumber) throw()
  19361. : message (data, len, sampleNumber)
  19362. {
  19363. }
  19364. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  19365. const double millisecondCounterToStartAt,
  19366. double samplesPerSecondForBuffer) throw()
  19367. {
  19368. // You've got to call startBackgroundThread() for this to actually work..
  19369. jassert (isThreadRunning());
  19370. // this needs to be a value in the future - RTFM for this method!
  19371. jassert (millisecondCounterToStartAt > 0);
  19372. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  19373. MidiBuffer::Iterator i (buffer);
  19374. const uint8* data;
  19375. int len, time;
  19376. while (i.getNextEvent (data, len, time))
  19377. {
  19378. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  19379. PendingMessage* const m
  19380. = new PendingMessage (data, len, eventTime);
  19381. const ScopedLock sl (lock);
  19382. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  19383. {
  19384. m->next = firstMessage;
  19385. firstMessage = m;
  19386. }
  19387. else
  19388. {
  19389. PendingMessage* mm = firstMessage;
  19390. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  19391. mm = mm->next;
  19392. m->next = mm->next;
  19393. mm->next = m;
  19394. }
  19395. }
  19396. notify();
  19397. }
  19398. void MidiOutput::clearAllPendingMessages() throw()
  19399. {
  19400. const ScopedLock sl (lock);
  19401. while (firstMessage != 0)
  19402. {
  19403. PendingMessage* const m = firstMessage;
  19404. firstMessage = firstMessage->next;
  19405. delete m;
  19406. }
  19407. }
  19408. void MidiOutput::startBackgroundThread() throw()
  19409. {
  19410. startThread (9);
  19411. }
  19412. void MidiOutput::stopBackgroundThread() throw()
  19413. {
  19414. stopThread (5000);
  19415. }
  19416. void MidiOutput::run()
  19417. {
  19418. while (! threadShouldExit())
  19419. {
  19420. uint32 now = Time::getMillisecondCounter();
  19421. uint32 eventTime = 0;
  19422. uint32 timeToWait = 500;
  19423. lock.enter();
  19424. PendingMessage* message = firstMessage;
  19425. if (message != 0)
  19426. {
  19427. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  19428. if (eventTime > now + 20)
  19429. {
  19430. timeToWait = jmax (10, eventTime - now - 100);
  19431. message = 0;
  19432. }
  19433. else
  19434. {
  19435. firstMessage = message->next;
  19436. }
  19437. }
  19438. lock.exit();
  19439. if (message != 0)
  19440. {
  19441. if (eventTime > now)
  19442. {
  19443. Time::waitForMillisecondCounter (eventTime);
  19444. if (threadShouldExit())
  19445. break;
  19446. }
  19447. if (eventTime > now - 200)
  19448. sendMessageNow (message->message);
  19449. delete message;
  19450. }
  19451. else
  19452. {
  19453. jassert (timeToWait < 1000 * 30);
  19454. wait (timeToWait);
  19455. }
  19456. }
  19457. clearAllPendingMessages();
  19458. }
  19459. END_JUCE_NAMESPACE
  19460. /********* End of inlined file: juce_MidiOutput.cpp *********/
  19461. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  19462. BEGIN_JUCE_NAMESPACE
  19463. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19464. {
  19465. const double maxVal = (double) 0x7fff;
  19466. char* intData = (char*) dest;
  19467. if (dest != (void*) source || destBytesPerSample <= 4)
  19468. {
  19469. for (int i = 0; i < numSamples; ++i)
  19470. {
  19471. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19472. intData += destBytesPerSample;
  19473. }
  19474. }
  19475. else
  19476. {
  19477. intData += destBytesPerSample * numSamples;
  19478. for (int i = numSamples; --i >= 0;)
  19479. {
  19480. intData -= destBytesPerSample;
  19481. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19482. }
  19483. }
  19484. }
  19485. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19486. {
  19487. const double maxVal = (double) 0x7fff;
  19488. char* intData = (char*) dest;
  19489. if (dest != (void*) source || destBytesPerSample <= 4)
  19490. {
  19491. for (int i = 0; i < numSamples; ++i)
  19492. {
  19493. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19494. intData += destBytesPerSample;
  19495. }
  19496. }
  19497. else
  19498. {
  19499. intData += destBytesPerSample * numSamples;
  19500. for (int i = numSamples; --i >= 0;)
  19501. {
  19502. intData -= destBytesPerSample;
  19503. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19504. }
  19505. }
  19506. }
  19507. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19508. {
  19509. const double maxVal = (double) 0x7fffff;
  19510. char* intData = (char*) dest;
  19511. if (dest != (void*) source || destBytesPerSample <= 4)
  19512. {
  19513. for (int i = 0; i < numSamples; ++i)
  19514. {
  19515. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19516. intData += destBytesPerSample;
  19517. }
  19518. }
  19519. else
  19520. {
  19521. intData += destBytesPerSample * numSamples;
  19522. for (int i = numSamples; --i >= 0;)
  19523. {
  19524. intData -= destBytesPerSample;
  19525. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19526. }
  19527. }
  19528. }
  19529. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19530. {
  19531. const double maxVal = (double) 0x7fffff;
  19532. char* intData = (char*) dest;
  19533. if (dest != (void*) source || destBytesPerSample <= 4)
  19534. {
  19535. for (int i = 0; i < numSamples; ++i)
  19536. {
  19537. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19538. intData += destBytesPerSample;
  19539. }
  19540. }
  19541. else
  19542. {
  19543. intData += destBytesPerSample * numSamples;
  19544. for (int i = numSamples; --i >= 0;)
  19545. {
  19546. intData -= destBytesPerSample;
  19547. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19548. }
  19549. }
  19550. }
  19551. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19552. {
  19553. const double maxVal = (double) 0x7fffffff;
  19554. char* intData = (char*) dest;
  19555. if (dest != (void*) source || destBytesPerSample <= 4)
  19556. {
  19557. for (int i = 0; i < numSamples; ++i)
  19558. {
  19559. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19560. intData += destBytesPerSample;
  19561. }
  19562. }
  19563. else
  19564. {
  19565. intData += destBytesPerSample * numSamples;
  19566. for (int i = numSamples; --i >= 0;)
  19567. {
  19568. intData -= destBytesPerSample;
  19569. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19570. }
  19571. }
  19572. }
  19573. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19574. {
  19575. const double maxVal = (double) 0x7fffffff;
  19576. char* intData = (char*) dest;
  19577. if (dest != (void*) source || destBytesPerSample <= 4)
  19578. {
  19579. for (int i = 0; i < numSamples; ++i)
  19580. {
  19581. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19582. intData += destBytesPerSample;
  19583. }
  19584. }
  19585. else
  19586. {
  19587. intData += destBytesPerSample * numSamples;
  19588. for (int i = numSamples; --i >= 0;)
  19589. {
  19590. intData -= destBytesPerSample;
  19591. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19592. }
  19593. }
  19594. }
  19595. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19596. {
  19597. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19598. char* d = (char*) dest;
  19599. for (int i = 0; i < numSamples; ++i)
  19600. {
  19601. *(float*)d = source[i];
  19602. #if JUCE_BIG_ENDIAN
  19603. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19604. #endif
  19605. d += destBytesPerSample;
  19606. }
  19607. }
  19608. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19609. {
  19610. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19611. char* d = (char*) dest;
  19612. for (int i = 0; i < numSamples; ++i)
  19613. {
  19614. *(float*)d = source[i];
  19615. #if JUCE_LITTLE_ENDIAN
  19616. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19617. #endif
  19618. d += destBytesPerSample;
  19619. }
  19620. }
  19621. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19622. {
  19623. const float scale = 1.0f / 0x7fff;
  19624. const char* intData = (const char*) source;
  19625. if (source != (void*) dest || srcBytesPerSample >= 4)
  19626. {
  19627. for (int i = 0; i < numSamples; ++i)
  19628. {
  19629. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19630. intData += srcBytesPerSample;
  19631. }
  19632. }
  19633. else
  19634. {
  19635. intData += srcBytesPerSample * numSamples;
  19636. for (int i = numSamples; --i >= 0;)
  19637. {
  19638. intData -= srcBytesPerSample;
  19639. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19640. }
  19641. }
  19642. }
  19643. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19644. {
  19645. const float scale = 1.0f / 0x7fff;
  19646. const char* intData = (const char*) source;
  19647. if (source != (void*) dest || srcBytesPerSample >= 4)
  19648. {
  19649. for (int i = 0; i < numSamples; ++i)
  19650. {
  19651. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19652. intData += srcBytesPerSample;
  19653. }
  19654. }
  19655. else
  19656. {
  19657. intData += srcBytesPerSample * numSamples;
  19658. for (int i = numSamples; --i >= 0;)
  19659. {
  19660. intData -= srcBytesPerSample;
  19661. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19662. }
  19663. }
  19664. }
  19665. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19666. {
  19667. const float scale = 1.0f / 0x7fffff;
  19668. const char* intData = (const char*) source;
  19669. if (source != (void*) dest || srcBytesPerSample >= 4)
  19670. {
  19671. for (int i = 0; i < numSamples; ++i)
  19672. {
  19673. dest[i] = scale * (short) littleEndian24Bit (intData);
  19674. intData += srcBytesPerSample;
  19675. }
  19676. }
  19677. else
  19678. {
  19679. intData += srcBytesPerSample * numSamples;
  19680. for (int i = numSamples; --i >= 0;)
  19681. {
  19682. intData -= srcBytesPerSample;
  19683. dest[i] = scale * (short) littleEndian24Bit (intData);
  19684. }
  19685. }
  19686. }
  19687. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19688. {
  19689. const float scale = 1.0f / 0x7fffff;
  19690. const char* intData = (const char*) source;
  19691. if (source != (void*) dest || srcBytesPerSample >= 4)
  19692. {
  19693. for (int i = 0; i < numSamples; ++i)
  19694. {
  19695. dest[i] = scale * (short) bigEndian24Bit (intData);
  19696. intData += srcBytesPerSample;
  19697. }
  19698. }
  19699. else
  19700. {
  19701. intData += srcBytesPerSample * numSamples;
  19702. for (int i = numSamples; --i >= 0;)
  19703. {
  19704. intData -= srcBytesPerSample;
  19705. dest[i] = scale * (short) bigEndian24Bit (intData);
  19706. }
  19707. }
  19708. }
  19709. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19710. {
  19711. const float scale = 1.0f / 0x7fffffff;
  19712. const char* intData = (const char*) source;
  19713. if (source != (void*) dest || srcBytesPerSample >= 4)
  19714. {
  19715. for (int i = 0; i < numSamples; ++i)
  19716. {
  19717. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19718. intData += srcBytesPerSample;
  19719. }
  19720. }
  19721. else
  19722. {
  19723. intData += srcBytesPerSample * numSamples;
  19724. for (int i = numSamples; --i >= 0;)
  19725. {
  19726. intData -= srcBytesPerSample;
  19727. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19728. }
  19729. }
  19730. }
  19731. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19732. {
  19733. const float scale = 1.0f / 0x7fffffff;
  19734. const char* intData = (const char*) source;
  19735. if (source != (void*) dest || srcBytesPerSample >= 4)
  19736. {
  19737. for (int i = 0; i < numSamples; ++i)
  19738. {
  19739. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19740. intData += srcBytesPerSample;
  19741. }
  19742. }
  19743. else
  19744. {
  19745. intData += srcBytesPerSample * numSamples;
  19746. for (int i = numSamples; --i >= 0;)
  19747. {
  19748. intData -= srcBytesPerSample;
  19749. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19750. }
  19751. }
  19752. }
  19753. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19754. {
  19755. const char* s = (const char*) source;
  19756. for (int i = 0; i < numSamples; ++i)
  19757. {
  19758. dest[i] = *(float*)s;
  19759. #if JUCE_BIG_ENDIAN
  19760. uint32* const d = (uint32*) (dest + i);
  19761. *d = swapByteOrder (*d);
  19762. #endif
  19763. s += srcBytesPerSample;
  19764. }
  19765. }
  19766. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19767. {
  19768. const char* s = (const char*) source;
  19769. for (int i = 0; i < numSamples; ++i)
  19770. {
  19771. dest[i] = *(float*)s;
  19772. #if JUCE_LITTLE_ENDIAN
  19773. uint32* const d = (uint32*) (dest + i);
  19774. *d = swapByteOrder (*d);
  19775. #endif
  19776. s += srcBytesPerSample;
  19777. }
  19778. }
  19779. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  19780. const float* const source,
  19781. void* const dest,
  19782. const int numSamples)
  19783. {
  19784. switch (destFormat)
  19785. {
  19786. case int16LE:
  19787. convertFloatToInt16LE (source, dest, numSamples);
  19788. break;
  19789. case int16BE:
  19790. convertFloatToInt16BE (source, dest, numSamples);
  19791. break;
  19792. case int24LE:
  19793. convertFloatToInt24LE (source, dest, numSamples);
  19794. break;
  19795. case int24BE:
  19796. convertFloatToInt24BE (source, dest, numSamples);
  19797. break;
  19798. case int32LE:
  19799. convertFloatToInt32LE (source, dest, numSamples);
  19800. break;
  19801. case int32BE:
  19802. convertFloatToInt32BE (source, dest, numSamples);
  19803. break;
  19804. case float32LE:
  19805. convertFloatToFloat32LE (source, dest, numSamples);
  19806. break;
  19807. case float32BE:
  19808. convertFloatToFloat32BE (source, dest, numSamples);
  19809. break;
  19810. default:
  19811. jassertfalse
  19812. break;
  19813. }
  19814. }
  19815. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  19816. const void* const source,
  19817. float* const dest,
  19818. const int numSamples)
  19819. {
  19820. switch (sourceFormat)
  19821. {
  19822. case int16LE:
  19823. convertInt16LEToFloat (source, dest, numSamples);
  19824. break;
  19825. case int16BE:
  19826. convertInt16BEToFloat (source, dest, numSamples);
  19827. break;
  19828. case int24LE:
  19829. convertInt24LEToFloat (source, dest, numSamples);
  19830. break;
  19831. case int24BE:
  19832. convertInt24BEToFloat (source, dest, numSamples);
  19833. break;
  19834. case int32LE:
  19835. convertInt32LEToFloat (source, dest, numSamples);
  19836. break;
  19837. case int32BE:
  19838. convertInt32BEToFloat (source, dest, numSamples);
  19839. break;
  19840. case float32LE:
  19841. convertFloat32LEToFloat (source, dest, numSamples);
  19842. break;
  19843. case float32BE:
  19844. convertFloat32BEToFloat (source, dest, numSamples);
  19845. break;
  19846. default:
  19847. jassertfalse
  19848. break;
  19849. }
  19850. }
  19851. void AudioDataConverters::interleaveSamples (const float** const source,
  19852. float* const dest,
  19853. const int numSamples,
  19854. const int numChannels)
  19855. {
  19856. for (int chan = 0; chan < numChannels; ++chan)
  19857. {
  19858. int i = chan;
  19859. const float* src = source [chan];
  19860. for (int j = 0; j < numSamples; ++j)
  19861. {
  19862. dest [i] = src [j];
  19863. i += numChannels;
  19864. }
  19865. }
  19866. }
  19867. void AudioDataConverters::deinterleaveSamples (const float* const source,
  19868. float** const dest,
  19869. const int numSamples,
  19870. const int numChannels)
  19871. {
  19872. for (int chan = 0; chan < numChannels; ++chan)
  19873. {
  19874. int i = chan;
  19875. float* dst = dest [chan];
  19876. for (int j = 0; j < numSamples; ++j)
  19877. {
  19878. dst [j] = source [i];
  19879. i += numChannels;
  19880. }
  19881. }
  19882. }
  19883. END_JUCE_NAMESPACE
  19884. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  19885. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  19886. BEGIN_JUCE_NAMESPACE
  19887. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  19888. const int numSamples) throw()
  19889. : numChannels (numChannels_),
  19890. size (numSamples)
  19891. {
  19892. jassert (numSamples >= 0);
  19893. jassert (numChannels_ > 0);
  19894. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  19895. allocatedData = (float*) juce_malloc (allocatedBytes);
  19896. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  19897. float* chan = allocatedData;
  19898. for (int i = 0; i < numChannels_; ++i)
  19899. {
  19900. channels[i] = chan;
  19901. chan += numSamples;
  19902. }
  19903. channels [numChannels_] = 0;
  19904. }
  19905. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  19906. const int numChannels_,
  19907. const int numSamples) throw()
  19908. : numChannels (numChannels_),
  19909. size (numSamples),
  19910. allocatedBytes (0),
  19911. allocatedData (0)
  19912. {
  19913. jassert (numChannels_ > 0);
  19914. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  19915. if (numChannels_ < numElementsInArray (preallocatedChannelSpace))
  19916. channels = (float**) preallocatedChannelSpace;
  19917. else
  19918. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  19919. for (int i = 0; i < numChannels_; ++i)
  19920. {
  19921. // you have to pass in the same number of valid pointers as numChannels
  19922. jassert (dataToReferTo[i] != 0);
  19923. channels[i] = dataToReferTo[i];
  19924. }
  19925. channels [numChannels_] = 0;
  19926. }
  19927. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  19928. const int numChannels_,
  19929. const int numSamples) throw()
  19930. {
  19931. jassert (numChannels_ > 0);
  19932. juce_free (allocatedData);
  19933. allocatedData = 0;
  19934. allocatedBytes = 0;
  19935. if (numChannels_ > numChannels)
  19936. channels = (float**) juce_realloc (channels, (numChannels_ + 1) * sizeof (float*));
  19937. numChannels = numChannels_;
  19938. size = numSamples;
  19939. for (int i = 0; i < numChannels_; ++i)
  19940. {
  19941. // you have to pass in the same number of valid pointers as numChannels
  19942. jassert (dataToReferTo[i] != 0);
  19943. channels[i] = dataToReferTo[i];
  19944. }
  19945. channels [numChannels_] = 0;
  19946. }
  19947. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  19948. : numChannels (other.numChannels),
  19949. size (other.size)
  19950. {
  19951. channels = (float**) juce_malloc ((other.numChannels + 1) * sizeof (float*));
  19952. if (other.allocatedData != 0)
  19953. {
  19954. allocatedBytes = numChannels * size * sizeof (float) + 32;
  19955. allocatedData = (float*) juce_malloc (allocatedBytes);
  19956. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  19957. float* chan = allocatedData;
  19958. for (int i = 0; i < numChannels; ++i)
  19959. {
  19960. channels[i] = chan;
  19961. chan += size;
  19962. }
  19963. channels [numChannels] = 0;
  19964. }
  19965. else
  19966. {
  19967. allocatedData = 0;
  19968. allocatedBytes = 0;
  19969. memcpy (channels, other.channels, sizeof (channels));
  19970. }
  19971. }
  19972. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  19973. {
  19974. if (this != &other)
  19975. {
  19976. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  19977. const int numBytes = size * sizeof (float);
  19978. for (int i = 0; i < numChannels; ++i)
  19979. memcpy (channels[i], other.channels[i], numBytes);
  19980. }
  19981. return *this;
  19982. }
  19983. AudioSampleBuffer::~AudioSampleBuffer() throw()
  19984. {
  19985. juce_free (allocatedData);
  19986. if (channels != (float**) preallocatedChannelSpace)
  19987. juce_free (channels);
  19988. }
  19989. void AudioSampleBuffer::setSize (const int newNumChannels,
  19990. const int newNumSamples,
  19991. const bool keepExistingContent,
  19992. const bool clearExtraSpace,
  19993. const bool avoidReallocating) throw()
  19994. {
  19995. jassert (newNumChannels > 0);
  19996. if (newNumSamples != size || newNumChannels != numChannels)
  19997. {
  19998. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  19999. if (keepExistingContent)
  20000. {
  20001. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20002. : (float*) juce_malloc (newTotalBytes);
  20003. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  20004. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  20005. {
  20006. memcpy (newData + i * newNumSamples,
  20007. channels[i],
  20008. sizeToCopy);
  20009. }
  20010. juce_free (allocatedData);
  20011. allocatedData = newData;
  20012. allocatedBytes = newTotalBytes;
  20013. }
  20014. else
  20015. {
  20016. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20017. {
  20018. if (clearExtraSpace)
  20019. zeromem (allocatedData, newTotalBytes);
  20020. }
  20021. else
  20022. {
  20023. juce_free (allocatedData);
  20024. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20025. : (float*) juce_malloc (newTotalBytes);
  20026. allocatedBytes = newTotalBytes;
  20027. }
  20028. }
  20029. size = newNumSamples;
  20030. if (newNumChannels > numChannels)
  20031. channels = (float**) juce_realloc (channels, (newNumChannels + 1) * sizeof (float*));
  20032. numChannels = newNumChannels;
  20033. float* chan = allocatedData;
  20034. for (int i = 0; i < newNumChannels; ++i)
  20035. {
  20036. channels[i] = chan;
  20037. chan += size;
  20038. }
  20039. channels [newNumChannels] = 0;
  20040. }
  20041. }
  20042. void AudioSampleBuffer::clear() throw()
  20043. {
  20044. for (int i = 0; i < numChannels; ++i)
  20045. zeromem (channels[i], size * sizeof (float));
  20046. }
  20047. void AudioSampleBuffer::clear (const int startSample,
  20048. const int numSamples) throw()
  20049. {
  20050. jassert (startSample >= 0 && startSample + numSamples <= size);
  20051. for (int i = 0; i < numChannels; ++i)
  20052. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20053. }
  20054. void AudioSampleBuffer::clear (const int channel,
  20055. const int startSample,
  20056. const int numSamples) throw()
  20057. {
  20058. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20059. jassert (startSample >= 0 && startSample + numSamples <= size);
  20060. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20061. }
  20062. void AudioSampleBuffer::applyGain (const int channel,
  20063. const int startSample,
  20064. int numSamples,
  20065. const float gain) throw()
  20066. {
  20067. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20068. jassert (startSample >= 0 && startSample + numSamples <= size);
  20069. if (gain != 1.0f)
  20070. {
  20071. float* d = channels [channel] + startSample;
  20072. if (gain == 0.0f)
  20073. {
  20074. zeromem (d, sizeof (float) * numSamples);
  20075. }
  20076. else
  20077. {
  20078. while (--numSamples >= 0)
  20079. *d++ *= gain;
  20080. }
  20081. }
  20082. }
  20083. void AudioSampleBuffer::applyGainRamp (const int channel,
  20084. const int startSample,
  20085. int numSamples,
  20086. float startGain,
  20087. float endGain) throw()
  20088. {
  20089. if (startGain == endGain)
  20090. {
  20091. applyGain (channel, startSample, numSamples, startGain);
  20092. }
  20093. else
  20094. {
  20095. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20096. jassert (startSample >= 0 && startSample + numSamples <= size);
  20097. const float increment = (endGain - startGain) / numSamples;
  20098. float* d = channels [channel] + startSample;
  20099. while (--numSamples >= 0)
  20100. {
  20101. *d++ *= startGain;
  20102. startGain += increment;
  20103. }
  20104. }
  20105. }
  20106. void AudioSampleBuffer::applyGain (const int startSample,
  20107. const int numSamples,
  20108. const float gain) throw()
  20109. {
  20110. for (int i = 0; i < numChannels; ++i)
  20111. applyGain (i, startSample, numSamples, gain);
  20112. }
  20113. void AudioSampleBuffer::addFrom (const int destChannel,
  20114. const int destStartSample,
  20115. const AudioSampleBuffer& source,
  20116. const int sourceChannel,
  20117. const int sourceStartSample,
  20118. int numSamples,
  20119. const float gain) throw()
  20120. {
  20121. jassert (&source != this || sourceChannel != destChannel);
  20122. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20123. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20124. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20125. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20126. if (gain != 0.0f && numSamples > 0)
  20127. {
  20128. float* d = channels [destChannel] + destStartSample;
  20129. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20130. if (gain != 1.0f)
  20131. {
  20132. while (--numSamples >= 0)
  20133. *d++ += gain * *s++;
  20134. }
  20135. else
  20136. {
  20137. while (--numSamples >= 0)
  20138. *d++ += *s++;
  20139. }
  20140. }
  20141. }
  20142. void AudioSampleBuffer::addFrom (const int destChannel,
  20143. const int destStartSample,
  20144. const float* source,
  20145. int numSamples,
  20146. const float gain) throw()
  20147. {
  20148. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20149. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20150. jassert (source != 0);
  20151. if (gain != 0.0f && numSamples > 0)
  20152. {
  20153. float* d = channels [destChannel] + destStartSample;
  20154. if (gain != 1.0f)
  20155. {
  20156. while (--numSamples >= 0)
  20157. *d++ += gain * *source++;
  20158. }
  20159. else
  20160. {
  20161. while (--numSamples >= 0)
  20162. *d++ += *source++;
  20163. }
  20164. }
  20165. }
  20166. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20167. const int destStartSample,
  20168. const float* source,
  20169. int numSamples,
  20170. float startGain,
  20171. const float endGain) throw()
  20172. {
  20173. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20174. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20175. jassert (source != 0);
  20176. if (startGain == endGain)
  20177. {
  20178. addFrom (destChannel,
  20179. destStartSample,
  20180. source,
  20181. numSamples,
  20182. startGain);
  20183. }
  20184. else
  20185. {
  20186. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20187. {
  20188. const float increment = (endGain - startGain) / numSamples;
  20189. float* d = channels [destChannel] + destStartSample;
  20190. while (--numSamples >= 0)
  20191. {
  20192. *d++ += startGain * *source++;
  20193. startGain += increment;
  20194. }
  20195. }
  20196. }
  20197. }
  20198. void AudioSampleBuffer::copyFrom (const int destChannel,
  20199. const int destStartSample,
  20200. const AudioSampleBuffer& source,
  20201. const int sourceChannel,
  20202. const int sourceStartSample,
  20203. int numSamples) throw()
  20204. {
  20205. jassert (&source != this || sourceChannel != destChannel);
  20206. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20207. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20208. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20209. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20210. if (numSamples > 0)
  20211. {
  20212. memcpy (channels [destChannel] + destStartSample,
  20213. source.channels [sourceChannel] + sourceStartSample,
  20214. sizeof (float) * numSamples);
  20215. }
  20216. }
  20217. void AudioSampleBuffer::copyFrom (const int destChannel,
  20218. const int destStartSample,
  20219. const float* source,
  20220. int numSamples) throw()
  20221. {
  20222. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20223. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20224. jassert (source != 0);
  20225. if (numSamples > 0)
  20226. {
  20227. memcpy (channels [destChannel] + destStartSample,
  20228. source,
  20229. sizeof (float) * numSamples);
  20230. }
  20231. }
  20232. void AudioSampleBuffer::copyFrom (const int destChannel,
  20233. const int destStartSample,
  20234. const float* source,
  20235. int numSamples,
  20236. const float gain) throw()
  20237. {
  20238. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20239. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20240. jassert (source != 0);
  20241. if (numSamples > 0 && gain != 0)
  20242. {
  20243. float* d = channels [destChannel] + destStartSample;
  20244. if (gain != 1.0f)
  20245. {
  20246. while (--numSamples >= 0)
  20247. *d++ = gain * *source++;
  20248. }
  20249. else
  20250. {
  20251. memcpy (d, source, sizeof (float) * numSamples);
  20252. }
  20253. }
  20254. }
  20255. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20256. const int destStartSample,
  20257. const float* source,
  20258. int numSamples,
  20259. float startGain,
  20260. float endGain) throw()
  20261. {
  20262. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20263. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20264. jassert (source != 0);
  20265. if (startGain == endGain)
  20266. {
  20267. copyFrom (destChannel,
  20268. destStartSample,
  20269. source,
  20270. numSamples,
  20271. startGain);
  20272. }
  20273. else
  20274. {
  20275. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20276. {
  20277. const float increment = (endGain - startGain) / numSamples;
  20278. float* d = channels [destChannel] + destStartSample;
  20279. while (--numSamples >= 0)
  20280. {
  20281. *d++ = startGain * *source++;
  20282. startGain += increment;
  20283. }
  20284. }
  20285. }
  20286. }
  20287. void AudioSampleBuffer::findMinMax (const int channel,
  20288. const int startSample,
  20289. int numSamples,
  20290. float& minVal,
  20291. float& maxVal) const throw()
  20292. {
  20293. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20294. jassert (startSample >= 0 && startSample + numSamples <= size);
  20295. if (numSamples <= 0)
  20296. {
  20297. minVal = 0.0f;
  20298. maxVal = 0.0f;
  20299. }
  20300. else
  20301. {
  20302. const float* d = channels [channel] + startSample;
  20303. float mn = *d++;
  20304. float mx = mn;
  20305. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  20306. {
  20307. const float samp = *d++;
  20308. if (samp > mx)
  20309. mx = samp;
  20310. if (samp < mn)
  20311. mn = samp;
  20312. }
  20313. maxVal = mx;
  20314. minVal = mn;
  20315. }
  20316. }
  20317. float AudioSampleBuffer::getMagnitude (const int channel,
  20318. const int startSample,
  20319. const int numSamples) const throw()
  20320. {
  20321. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20322. jassert (startSample >= 0 && startSample + numSamples <= size);
  20323. float mn, mx;
  20324. findMinMax (channel, startSample, numSamples, mn, mx);
  20325. return jmax (mn, -mn, mx, -mx);
  20326. }
  20327. float AudioSampleBuffer::getMagnitude (const int startSample,
  20328. const int numSamples) const throw()
  20329. {
  20330. float mag = 0.0f;
  20331. for (int i = 0; i < numChannels; ++i)
  20332. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  20333. return mag;
  20334. }
  20335. float AudioSampleBuffer::getRMSLevel (const int channel,
  20336. const int startSample,
  20337. const int numSamples) const throw()
  20338. {
  20339. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20340. jassert (startSample >= 0 && startSample + numSamples <= size);
  20341. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  20342. return 0.0f;
  20343. const float* const data = channels [channel] + startSample;
  20344. double sum = 0.0;
  20345. for (int i = 0; i < numSamples; ++i)
  20346. {
  20347. const float sample = data [i];
  20348. sum += sample * sample;
  20349. }
  20350. return (float) sqrt (sum / numSamples);
  20351. }
  20352. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  20353. const int startSample,
  20354. const int numSamples,
  20355. const int readerStartSample,
  20356. const bool useLeftChan,
  20357. const bool useRightChan) throw()
  20358. {
  20359. jassert (reader != 0);
  20360. jassert (startSample >= 0 && startSample + numSamples <= size);
  20361. if (numSamples > 0)
  20362. {
  20363. int* chans[3];
  20364. if (useLeftChan == useRightChan)
  20365. {
  20366. chans[0] = (int*) getSampleData (0, startSample);
  20367. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  20368. }
  20369. else if (useLeftChan || (reader->numChannels == 1))
  20370. {
  20371. chans[0] = (int*) getSampleData (0, startSample);
  20372. chans[1] = 0;
  20373. }
  20374. else if (useRightChan)
  20375. {
  20376. chans[0] = 0;
  20377. chans[1] = (int*) getSampleData (0, startSample);
  20378. }
  20379. chans[2] = 0;
  20380. reader->read (chans, 2, readerStartSample, numSamples, true);
  20381. if (! reader->usesFloatingPointData)
  20382. {
  20383. for (int j = 0; j < 2; ++j)
  20384. {
  20385. float* const d = (float*) (chans[j]);
  20386. if (d != 0)
  20387. {
  20388. const float multiplier = 1.0f / 0x7fffffff;
  20389. for (int i = 0; i < numSamples; ++i)
  20390. d[i] = *(int*)(d + i) * multiplier;
  20391. }
  20392. }
  20393. }
  20394. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  20395. {
  20396. // if this is a stereo buffer and the source was mono, dupe the first channel..
  20397. memcpy (getSampleData (1, startSample),
  20398. getSampleData (0, startSample),
  20399. sizeof (float) * numSamples);
  20400. }
  20401. }
  20402. }
  20403. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  20404. const int startSample,
  20405. const int numSamples) const throw()
  20406. {
  20407. jassert (startSample >= 0 && startSample + numSamples <= size);
  20408. if (numSamples > 0)
  20409. {
  20410. int* chans [3];
  20411. if (writer->isFloatingPoint())
  20412. {
  20413. chans[0] = (int*) getSampleData (0, startSample);
  20414. if (numChannels > 1)
  20415. chans[1] = (int*) getSampleData (1, startSample);
  20416. else
  20417. chans[1] = 0;
  20418. chans[2] = 0;
  20419. writer->write ((const int**) chans, numSamples);
  20420. }
  20421. else
  20422. {
  20423. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  20424. if (numChannels > 1)
  20425. chans[1] = chans[0] + numSamples;
  20426. else
  20427. chans[1] = 0;
  20428. chans[2] = 0;
  20429. for (int j = 0; j < 2; ++j)
  20430. {
  20431. int* const dest = chans[j];
  20432. if (dest != 0)
  20433. {
  20434. const float* const src = channels [j] + startSample;
  20435. for (int i = 0; i < numSamples; ++i)
  20436. {
  20437. const double samp = src[i];
  20438. if (samp <= -1.0)
  20439. dest[i] = INT_MIN;
  20440. else if (samp >= 1.0)
  20441. dest[i] = INT_MAX;
  20442. else
  20443. dest[i] = roundDoubleToInt (INT_MAX * samp);
  20444. }
  20445. }
  20446. }
  20447. writer->write ((const int**) chans, numSamples);
  20448. juce_free (chans[0]);
  20449. }
  20450. }
  20451. }
  20452. END_JUCE_NAMESPACE
  20453. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  20454. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  20455. BEGIN_JUCE_NAMESPACE
  20456. IIRFilter::IIRFilter() throw()
  20457. : active (false)
  20458. {
  20459. reset();
  20460. }
  20461. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  20462. : active (other.active)
  20463. {
  20464. const ScopedLock sl (other.processLock);
  20465. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20466. reset();
  20467. }
  20468. IIRFilter::~IIRFilter() throw()
  20469. {
  20470. }
  20471. void IIRFilter::reset() throw()
  20472. {
  20473. const ScopedLock sl (processLock);
  20474. x1 = 0;
  20475. x2 = 0;
  20476. y1 = 0;
  20477. y2 = 0;
  20478. }
  20479. float IIRFilter::processSingleSampleRaw (const float in) throw()
  20480. {
  20481. float out = coefficients[0] * in
  20482. + coefficients[1] * x1
  20483. + coefficients[2] * x2
  20484. - coefficients[4] * y1
  20485. - coefficients[5] * y2;
  20486. #if JUCE_INTEL
  20487. if (! (out < -1.0e-8 || out > 1.0e-8))
  20488. out = 0;
  20489. #endif
  20490. x2 = x1;
  20491. x1 = in;
  20492. y2 = y1;
  20493. y1 = out;
  20494. return out;
  20495. }
  20496. void IIRFilter::processSamples (float* const samples,
  20497. const int numSamples) throw()
  20498. {
  20499. const ScopedLock sl (processLock);
  20500. if (active)
  20501. {
  20502. for (int i = 0; i < numSamples; ++i)
  20503. {
  20504. const float in = samples[i];
  20505. float out = coefficients[0] * in
  20506. + coefficients[1] * x1
  20507. + coefficients[2] * x2
  20508. - coefficients[4] * y1
  20509. - coefficients[5] * y2;
  20510. #if JUCE_INTEL
  20511. if (! (out < -1.0e-8 || out > 1.0e-8))
  20512. out = 0;
  20513. #endif
  20514. x2 = x1;
  20515. x1 = in;
  20516. y2 = y1;
  20517. y1 = out;
  20518. samples[i] = out;
  20519. }
  20520. }
  20521. }
  20522. void IIRFilter::makeLowPass (const double sampleRate,
  20523. const double frequency) throw()
  20524. {
  20525. jassert (sampleRate > 0);
  20526. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  20527. const double nSquared = n * n;
  20528. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20529. setCoefficients (c1,
  20530. c1 * 2.0f,
  20531. c1,
  20532. 1.0,
  20533. c1 * 2.0 * (1.0 - nSquared),
  20534. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20535. }
  20536. void IIRFilter::makeHighPass (const double sampleRate,
  20537. const double frequency) throw()
  20538. {
  20539. const double n = tan (double_Pi * frequency / sampleRate);
  20540. const double nSquared = n * n;
  20541. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20542. setCoefficients (c1,
  20543. c1 * -2.0f,
  20544. c1,
  20545. 1.0,
  20546. c1 * 2.0 * (nSquared - 1.0),
  20547. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20548. }
  20549. void IIRFilter::makeLowShelf (const double sampleRate,
  20550. const double cutOffFrequency,
  20551. const double Q,
  20552. const float gainFactor) throw()
  20553. {
  20554. jassert (sampleRate > 0);
  20555. jassert (Q > 0);
  20556. const double A = jmax (0.0f, gainFactor);
  20557. const double aminus1 = A - 1.0;
  20558. const double aplus1 = A + 1.0;
  20559. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20560. const double coso = cos (omega);
  20561. const double beta = sin (omega) * sqrt (A) / Q;
  20562. const double aminus1TimesCoso = aminus1 * coso;
  20563. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  20564. A * 2.0 * (aminus1 - aplus1 * coso),
  20565. A * (aplus1 - aminus1TimesCoso - beta),
  20566. aplus1 + aminus1TimesCoso + beta,
  20567. -2.0 * (aminus1 + aplus1 * coso),
  20568. aplus1 + aminus1TimesCoso - beta);
  20569. }
  20570. void IIRFilter::makeHighShelf (const double sampleRate,
  20571. const double cutOffFrequency,
  20572. const double Q,
  20573. const float gainFactor) throw()
  20574. {
  20575. jassert (sampleRate > 0);
  20576. jassert (Q > 0);
  20577. const double A = jmax (0.0f, gainFactor);
  20578. const double aminus1 = A - 1.0;
  20579. const double aplus1 = A + 1.0;
  20580. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20581. const double coso = cos (omega);
  20582. const double beta = sin (omega) * sqrt (A) / Q;
  20583. const double aminus1TimesCoso = aminus1 * coso;
  20584. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  20585. A * -2.0 * (aminus1 + aplus1 * coso),
  20586. A * (aplus1 + aminus1TimesCoso - beta),
  20587. aplus1 - aminus1TimesCoso + beta,
  20588. 2.0 * (aminus1 - aplus1 * coso),
  20589. aplus1 - aminus1TimesCoso - beta);
  20590. }
  20591. void IIRFilter::makeBandPass (const double sampleRate,
  20592. const double centreFrequency,
  20593. const double Q,
  20594. const float gainFactor) throw()
  20595. {
  20596. jassert (sampleRate > 0);
  20597. jassert (Q > 0);
  20598. const double A = jmax (0.0f, gainFactor);
  20599. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  20600. const double alpha = 0.5 * sin (omega) / Q;
  20601. const double c2 = -2.0 * cos (omega);
  20602. const double alphaTimesA = alpha * A;
  20603. const double alphaOverA = alpha / A;
  20604. setCoefficients (1.0 + alphaTimesA,
  20605. c2,
  20606. 1.0 - alphaTimesA,
  20607. 1.0 + alphaOverA,
  20608. c2,
  20609. 1.0 - alphaOverA);
  20610. }
  20611. void IIRFilter::makeInactive() throw()
  20612. {
  20613. const ScopedLock sl (processLock);
  20614. active = false;
  20615. }
  20616. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  20617. {
  20618. const ScopedLock sl (processLock);
  20619. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20620. active = other.active;
  20621. }
  20622. void IIRFilter::setCoefficients (double c1,
  20623. double c2,
  20624. double c3,
  20625. double c4,
  20626. double c5,
  20627. double c6) throw()
  20628. {
  20629. const double a = 1.0 / c4;
  20630. c1 *= a;
  20631. c2 *= a;
  20632. c3 *= a;
  20633. c5 *= a;
  20634. c6 *= a;
  20635. const ScopedLock sl (processLock);
  20636. coefficients[0] = (float) c1;
  20637. coefficients[1] = (float) c2;
  20638. coefficients[2] = (float) c3;
  20639. coefficients[3] = (float) c4;
  20640. coefficients[4] = (float) c5;
  20641. coefficients[5] = (float) c6;
  20642. active = true;
  20643. }
  20644. END_JUCE_NAMESPACE
  20645. /********* End of inlined file: juce_IIRFilter.cpp *********/
  20646. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  20647. BEGIN_JUCE_NAMESPACE
  20648. MidiBuffer::MidiBuffer() throw()
  20649. : ArrayAllocationBase <uint8> (32),
  20650. bytesUsed (0)
  20651. {
  20652. }
  20653. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  20654. : ArrayAllocationBase <uint8> (32),
  20655. bytesUsed (0)
  20656. {
  20657. addEvent (message, 0);
  20658. }
  20659. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  20660. : ArrayAllocationBase <uint8> (32),
  20661. bytesUsed (other.bytesUsed)
  20662. {
  20663. ensureAllocatedSize (bytesUsed);
  20664. memcpy (elements, other.elements, bytesUsed);
  20665. }
  20666. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  20667. {
  20668. if (this != &other)
  20669. {
  20670. bytesUsed = other.bytesUsed;
  20671. ensureAllocatedSize (bytesUsed);
  20672. if (bytesUsed > 0)
  20673. memcpy (elements, other.elements, bytesUsed);
  20674. }
  20675. return *this;
  20676. }
  20677. void MidiBuffer::swap (MidiBuffer& other)
  20678. {
  20679. swapVariables <uint8*> (this->elements, other.elements);
  20680. swapVariables <int> (this->numAllocated, other.numAllocated);
  20681. swapVariables <int> (this->bytesUsed, other.bytesUsed);
  20682. }
  20683. MidiBuffer::~MidiBuffer() throw()
  20684. {
  20685. }
  20686. void MidiBuffer::clear() throw()
  20687. {
  20688. bytesUsed = 0;
  20689. }
  20690. void MidiBuffer::clear (const int startSample,
  20691. const int numSamples) throw()
  20692. {
  20693. uint8* const start = findEventAfter (elements, startSample - 1);
  20694. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  20695. if (end > start)
  20696. {
  20697. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  20698. if (bytesToMove > 0)
  20699. memmove (start, end, bytesToMove);
  20700. bytesUsed -= (int) (end - start);
  20701. }
  20702. }
  20703. void MidiBuffer::addEvent (const MidiMessage& m,
  20704. const int sampleNumber) throw()
  20705. {
  20706. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  20707. }
  20708. static int findActualEventLength (const uint8* const data,
  20709. const int maxBytes) throw()
  20710. {
  20711. unsigned int byte = (unsigned int) *data;
  20712. int size = 0;
  20713. if (byte == 0xf0 || byte == 0xf7)
  20714. {
  20715. const uint8* d = data + 1;
  20716. while (d < data + maxBytes)
  20717. if (*d++ == 0xf7)
  20718. break;
  20719. size = (int) (d - data);
  20720. }
  20721. else if (byte == 0xff)
  20722. {
  20723. int n;
  20724. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  20725. size = jmin (maxBytes, n + 2 + bytesLeft);
  20726. }
  20727. else if (byte >= 0x80)
  20728. {
  20729. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  20730. }
  20731. return size;
  20732. }
  20733. void MidiBuffer::addEvent (const uint8* const newData,
  20734. const int maxBytes,
  20735. const int sampleNumber) throw()
  20736. {
  20737. const int numBytes = findActualEventLength (newData, maxBytes);
  20738. if (numBytes > 0)
  20739. {
  20740. ensureAllocatedSize (bytesUsed + numBytes + 6);
  20741. uint8* d = findEventAfter (elements, sampleNumber);
  20742. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  20743. if (bytesToMove > 0)
  20744. memmove (d + numBytes + 6,
  20745. d,
  20746. bytesToMove);
  20747. *(int*) d = sampleNumber;
  20748. d += 4;
  20749. *(uint16*) d = (uint16) numBytes;
  20750. d += 2;
  20751. memcpy (d, newData, numBytes);
  20752. bytesUsed += numBytes + 6;
  20753. }
  20754. }
  20755. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  20756. const int startSample,
  20757. const int numSamples,
  20758. const int sampleDeltaToAdd) throw()
  20759. {
  20760. Iterator i (otherBuffer);
  20761. i.setNextSamplePosition (startSample);
  20762. const uint8* data;
  20763. int size, position;
  20764. while (i.getNextEvent (data, size, position)
  20765. && (position < startSample + numSamples || numSamples < 0))
  20766. {
  20767. addEvent (data, size, position + sampleDeltaToAdd);
  20768. }
  20769. }
  20770. bool MidiBuffer::isEmpty() const throw()
  20771. {
  20772. return bytesUsed == 0;
  20773. }
  20774. int MidiBuffer::getNumEvents() const throw()
  20775. {
  20776. int n = 0;
  20777. const uint8* d = elements;
  20778. const uint8* const end = elements + bytesUsed;
  20779. while (d < end)
  20780. {
  20781. d += 4;
  20782. d += 2 + *(const uint16*) d;
  20783. ++n;
  20784. }
  20785. return n;
  20786. }
  20787. int MidiBuffer::getFirstEventTime() const throw()
  20788. {
  20789. return (bytesUsed > 0) ? *(const int*) elements : 0;
  20790. }
  20791. int MidiBuffer::getLastEventTime() const throw()
  20792. {
  20793. if (bytesUsed == 0)
  20794. return 0;
  20795. const uint8* d = elements;
  20796. const uint8* const endData = d + bytesUsed;
  20797. for (;;)
  20798. {
  20799. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  20800. if (nextOne >= endData)
  20801. return *(const int*) d;
  20802. d = nextOne;
  20803. }
  20804. }
  20805. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  20806. {
  20807. const uint8* const endData = elements + bytesUsed;
  20808. while (d < endData && *(int*) d <= samplePosition)
  20809. {
  20810. d += 4;
  20811. d += 2 + *(uint16*) d;
  20812. }
  20813. return d;
  20814. }
  20815. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  20816. : buffer (buffer),
  20817. data (buffer.elements)
  20818. {
  20819. }
  20820. MidiBuffer::Iterator::~Iterator() throw()
  20821. {
  20822. }
  20823. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  20824. {
  20825. data = buffer.elements;
  20826. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  20827. while (data < dataEnd && *(int*) data < samplePosition)
  20828. {
  20829. data += 4;
  20830. data += 2 + *(uint16*) data;
  20831. }
  20832. }
  20833. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  20834. int& numBytes,
  20835. int& samplePosition) throw()
  20836. {
  20837. if (data >= buffer.elements + buffer.bytesUsed)
  20838. return false;
  20839. samplePosition = *(int*) data;
  20840. data += 4;
  20841. numBytes = *(uint16*) data;
  20842. data += 2;
  20843. midiData = data;
  20844. data += numBytes;
  20845. return true;
  20846. }
  20847. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  20848. int& samplePosition) throw()
  20849. {
  20850. if (data >= buffer.elements + buffer.bytesUsed)
  20851. return false;
  20852. samplePosition = *(int*) data;
  20853. data += 4;
  20854. const int numBytes = *(uint16*) data;
  20855. data += 2;
  20856. result = MidiMessage (data, numBytes, samplePosition);
  20857. data += numBytes;
  20858. return true;
  20859. }
  20860. END_JUCE_NAMESPACE
  20861. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  20862. /********* Start of inlined file: juce_MidiFile.cpp *********/
  20863. BEGIN_JUCE_NAMESPACE
  20864. struct TempoInfo
  20865. {
  20866. double bpm, timestamp;
  20867. };
  20868. struct TimeSigInfo
  20869. {
  20870. int numerator, denominator;
  20871. double timestamp;
  20872. };
  20873. MidiFile::MidiFile() throw()
  20874. : numTracks (0),
  20875. timeFormat ((short)(unsigned short)0xe728)
  20876. {
  20877. }
  20878. MidiFile::~MidiFile() throw()
  20879. {
  20880. clear();
  20881. }
  20882. void MidiFile::clear() throw()
  20883. {
  20884. while (numTracks > 0)
  20885. delete tracks [--numTracks];
  20886. }
  20887. int MidiFile::getNumTracks() const throw()
  20888. {
  20889. return numTracks;
  20890. }
  20891. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  20892. {
  20893. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  20894. }
  20895. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  20896. {
  20897. jassert (numTracks < numElementsInArray (tracks));
  20898. if (numTracks < numElementsInArray (tracks))
  20899. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  20900. }
  20901. short MidiFile::getTimeFormat() const throw()
  20902. {
  20903. return timeFormat;
  20904. }
  20905. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  20906. {
  20907. timeFormat = (short)ticks;
  20908. }
  20909. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  20910. const int subframeResolution) throw()
  20911. {
  20912. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  20913. }
  20914. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  20915. {
  20916. for (int i = numTracks; --i >= 0;)
  20917. {
  20918. const int numEvents = tracks[i]->getNumEvents();
  20919. for (int j = 0; j < numEvents; ++j)
  20920. {
  20921. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  20922. if (m.isTempoMetaEvent())
  20923. tempoChangeEvents.addEvent (m);
  20924. }
  20925. }
  20926. }
  20927. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  20928. {
  20929. for (int i = numTracks; --i >= 0;)
  20930. {
  20931. const int numEvents = tracks[i]->getNumEvents();
  20932. for (int j = 0; j < numEvents; ++j)
  20933. {
  20934. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  20935. if (m.isTimeSignatureMetaEvent())
  20936. timeSigEvents.addEvent (m);
  20937. }
  20938. }
  20939. }
  20940. double MidiFile::getLastTimestamp() const
  20941. {
  20942. double t = 0.0;
  20943. for (int i = numTracks; --i >= 0;)
  20944. t = jmax (t, tracks[i]->getEndTime());
  20945. return t;
  20946. }
  20947. static bool parseMidiHeader (const char* &data,
  20948. short& timeFormat,
  20949. short& fileType,
  20950. short& numberOfTracks)
  20951. {
  20952. unsigned int ch = (int) bigEndianInt (data);
  20953. data += 4;
  20954. if (ch != bigEndianInt ("MThd"))
  20955. {
  20956. bool ok = false;
  20957. if (ch == bigEndianInt ("RIFF"))
  20958. {
  20959. for (int i = 0; i < 8; ++i)
  20960. {
  20961. ch = bigEndianInt (data);
  20962. data += 4;
  20963. if (ch == bigEndianInt ("MThd"))
  20964. {
  20965. ok = true;
  20966. break;
  20967. }
  20968. }
  20969. }
  20970. if (! ok)
  20971. return false;
  20972. }
  20973. unsigned int bytesRemaining = bigEndianInt (data);
  20974. data += 4;
  20975. fileType = (short)bigEndianShort (data);
  20976. data += 2;
  20977. numberOfTracks = (short)bigEndianShort (data);
  20978. data += 2;
  20979. timeFormat = (short)bigEndianShort (data);
  20980. data += 2;
  20981. bytesRemaining -= 6;
  20982. data += bytesRemaining;
  20983. return true;
  20984. }
  20985. bool MidiFile::readFrom (InputStream& sourceStream)
  20986. {
  20987. clear();
  20988. MemoryBlock data;
  20989. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  20990. // (put a sanity-check on the file size, as midi files are generally small)
  20991. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  20992. {
  20993. int size = data.getSize();
  20994. const char* d = (char*) data.getData();
  20995. short fileType, expectedTracks;
  20996. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  20997. {
  20998. size -= (int) (d - (char*) data.getData());
  20999. int track = 0;
  21000. while (size > 0 && track < expectedTracks)
  21001. {
  21002. const int chunkType = (int)bigEndianInt (d);
  21003. d += 4;
  21004. const int chunkSize = (int)bigEndianInt (d);
  21005. d += 4;
  21006. if (chunkSize <= 0)
  21007. break;
  21008. if (size < 0)
  21009. return false;
  21010. if (chunkType == (int)bigEndianInt ("MTrk"))
  21011. {
  21012. readNextTrack (d, chunkSize);
  21013. }
  21014. size -= chunkSize + 8;
  21015. d += chunkSize;
  21016. ++track;
  21017. }
  21018. return true;
  21019. }
  21020. }
  21021. return false;
  21022. }
  21023. // a comparator that puts all the note-offs before note-ons that have the same time
  21024. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21025. const MidiMessageSequence::MidiEventHolder* const second) throw()
  21026. {
  21027. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21028. if (diff == 0)
  21029. {
  21030. if (first->message.isNoteOff() && second->message.isNoteOn())
  21031. return -1;
  21032. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21033. return 1;
  21034. else
  21035. return 0;
  21036. }
  21037. else
  21038. {
  21039. return (diff > 0) ? 1 : -1;
  21040. }
  21041. }
  21042. void MidiFile::readNextTrack (const char* data, int size)
  21043. {
  21044. double time = 0;
  21045. char lastStatusByte = 0;
  21046. MidiMessageSequence result;
  21047. while (size > 0)
  21048. {
  21049. int bytesUsed;
  21050. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  21051. data += bytesUsed;
  21052. size -= bytesUsed;
  21053. time += delay;
  21054. int messSize = 0;
  21055. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  21056. if (messSize <= 0)
  21057. break;
  21058. size -= messSize;
  21059. data += messSize;
  21060. result.addEvent (mm);
  21061. const char firstByte = *(mm.getRawData());
  21062. if ((firstByte & 0xf0) != 0xf0)
  21063. lastStatusByte = firstByte;
  21064. }
  21065. // use a sort that puts all the note-offs before note-ons that have the same time
  21066. result.list.sort (*this, true);
  21067. result.updateMatchedPairs();
  21068. addTrack (result);
  21069. }
  21070. static double convertTicksToSeconds (const double time,
  21071. const MidiMessageSequence& tempoEvents,
  21072. const int timeFormat)
  21073. {
  21074. if (timeFormat > 0)
  21075. {
  21076. int numer = 4, denom = 4;
  21077. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21078. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21079. double secsPerTick = 0.5 * tickLen;
  21080. const int numEvents = tempoEvents.getNumEvents();
  21081. for (int i = 0; i < numEvents; ++i)
  21082. {
  21083. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21084. if (time <= m.getTimeStamp())
  21085. break;
  21086. if (timeFormat > 0)
  21087. {
  21088. correctedTempoTime = correctedTempoTime
  21089. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21090. }
  21091. else
  21092. {
  21093. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21094. }
  21095. tempoTime = m.getTimeStamp();
  21096. if (m.isTempoMetaEvent())
  21097. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21098. else if (m.isTimeSignatureMetaEvent())
  21099. m.getTimeSignatureInfo (numer, denom);
  21100. while (i + 1 < numEvents)
  21101. {
  21102. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21103. if (m2.getTimeStamp() == tempoTime)
  21104. {
  21105. ++i;
  21106. if (m2.isTempoMetaEvent())
  21107. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21108. else if (m2.isTimeSignatureMetaEvent())
  21109. m2.getTimeSignatureInfo (numer, denom);
  21110. }
  21111. else
  21112. {
  21113. break;
  21114. }
  21115. }
  21116. }
  21117. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21118. }
  21119. else
  21120. {
  21121. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21122. }
  21123. }
  21124. void MidiFile::convertTimestampTicksToSeconds()
  21125. {
  21126. MidiMessageSequence tempoEvents;
  21127. findAllTempoEvents (tempoEvents);
  21128. findAllTimeSigEvents (tempoEvents);
  21129. for (int i = 0; i < numTracks; ++i)
  21130. {
  21131. MidiMessageSequence& ms = *tracks[i];
  21132. for (int j = ms.getNumEvents(); --j >= 0;)
  21133. {
  21134. MidiMessage& m = ms.getEventPointer(j)->message;
  21135. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  21136. tempoEvents,
  21137. timeFormat));
  21138. }
  21139. }
  21140. }
  21141. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21142. {
  21143. unsigned int buffer = v & 0x7F;
  21144. while ((v >>= 7) != 0)
  21145. {
  21146. buffer <<= 8;
  21147. buffer |= ((v & 0x7F) | 0x80);
  21148. }
  21149. for (;;)
  21150. {
  21151. out.writeByte ((char) buffer);
  21152. if (buffer & 0x80)
  21153. buffer >>= 8;
  21154. else
  21155. break;
  21156. }
  21157. }
  21158. bool MidiFile::writeTo (OutputStream& out)
  21159. {
  21160. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  21161. out.writeIntBigEndian (6);
  21162. out.writeShortBigEndian (1); // type
  21163. out.writeShortBigEndian (numTracks);
  21164. out.writeShortBigEndian (timeFormat);
  21165. for (int i = 0; i < numTracks; ++i)
  21166. writeTrack (out, i);
  21167. out.flush();
  21168. return true;
  21169. }
  21170. void MidiFile::writeTrack (OutputStream& mainOut,
  21171. const int trackNum)
  21172. {
  21173. MemoryOutputStream out;
  21174. const MidiMessageSequence& ms = *tracks[trackNum];
  21175. int lastTick = 0;
  21176. char lastStatusByte = 0;
  21177. for (int i = 0; i < ms.getNumEvents(); ++i)
  21178. {
  21179. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21180. const int tick = roundDoubleToInt (mm.getTimeStamp());
  21181. const int delta = jmax (0, tick - lastTick);
  21182. writeVariableLengthInt (out, delta);
  21183. lastTick = tick;
  21184. const char statusByte = *(mm.getRawData());
  21185. if ((statusByte == lastStatusByte)
  21186. && ((statusByte & 0xf0) != 0xf0)
  21187. && i > 0
  21188. && mm.getRawDataSize() > 1)
  21189. {
  21190. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21191. }
  21192. else
  21193. {
  21194. out.write (mm.getRawData(), mm.getRawDataSize());
  21195. }
  21196. lastStatusByte = statusByte;
  21197. }
  21198. out.writeByte (0);
  21199. const MidiMessage m (MidiMessage::endOfTrack());
  21200. out.write (m.getRawData(),
  21201. m.getRawDataSize());
  21202. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  21203. mainOut.writeIntBigEndian (out.getDataSize());
  21204. mainOut.write (out.getData(), out.getDataSize());
  21205. }
  21206. END_JUCE_NAMESPACE
  21207. /********* End of inlined file: juce_MidiFile.cpp *********/
  21208. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  21209. BEGIN_JUCE_NAMESPACE
  21210. MidiKeyboardState::MidiKeyboardState()
  21211. : listeners (2)
  21212. {
  21213. zeromem (noteStates, sizeof (noteStates));
  21214. }
  21215. MidiKeyboardState::~MidiKeyboardState()
  21216. {
  21217. }
  21218. void MidiKeyboardState::reset()
  21219. {
  21220. const ScopedLock sl (lock);
  21221. zeromem (noteStates, sizeof (noteStates));
  21222. eventsToAdd.clear();
  21223. }
  21224. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21225. {
  21226. jassert (midiChannel >= 0 && midiChannel <= 16);
  21227. return ((unsigned int) n) < 128
  21228. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21229. }
  21230. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21231. {
  21232. return ((unsigned int) n) < 128
  21233. && (noteStates[n] & midiChannelMask) != 0;
  21234. }
  21235. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21236. {
  21237. jassert (midiChannel >= 0 && midiChannel <= 16);
  21238. jassert (((unsigned int) midiNoteNumber) < 128);
  21239. const ScopedLock sl (lock);
  21240. if (((unsigned int) midiNoteNumber) < 128)
  21241. {
  21242. const int timeNow = (int) Time::getMillisecondCounter();
  21243. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21244. eventsToAdd.clear (0, timeNow - 500);
  21245. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21246. }
  21247. }
  21248. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21249. {
  21250. if (((unsigned int) midiNoteNumber) < 128)
  21251. {
  21252. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21253. for (int i = listeners.size(); --i >= 0;)
  21254. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21255. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21256. }
  21257. }
  21258. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21259. {
  21260. const ScopedLock sl (lock);
  21261. if (isNoteOn (midiChannel, midiNoteNumber))
  21262. {
  21263. const int timeNow = (int) Time::getMillisecondCounter();
  21264. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21265. eventsToAdd.clear (0, timeNow - 500);
  21266. noteOffInternal (midiChannel, midiNoteNumber);
  21267. }
  21268. }
  21269. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21270. {
  21271. if (isNoteOn (midiChannel, midiNoteNumber))
  21272. {
  21273. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21274. for (int i = listeners.size(); --i >= 0;)
  21275. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21276. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  21277. }
  21278. }
  21279. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21280. {
  21281. const ScopedLock sl (lock);
  21282. if (midiChannel <= 0)
  21283. {
  21284. for (int i = 1; i <= 16; ++i)
  21285. allNotesOff (i);
  21286. }
  21287. else
  21288. {
  21289. for (int i = 0; i < 128; ++i)
  21290. noteOff (midiChannel, i);
  21291. }
  21292. }
  21293. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21294. {
  21295. if (message.isNoteOn())
  21296. {
  21297. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21298. }
  21299. else if (message.isNoteOff())
  21300. {
  21301. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21302. }
  21303. else if (message.isAllNotesOff())
  21304. {
  21305. for (int i = 0; i < 128; ++i)
  21306. noteOffInternal (message.getChannel(), i);
  21307. }
  21308. }
  21309. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  21310. const int startSample,
  21311. const int numSamples,
  21312. const bool injectIndirectEvents)
  21313. {
  21314. MidiBuffer::Iterator i (buffer);
  21315. MidiMessage message (0xf4, 0.0);
  21316. int time;
  21317. const ScopedLock sl (lock);
  21318. while (i.getNextEvent (message, time))
  21319. processNextMidiEvent (message);
  21320. if (injectIndirectEvents)
  21321. {
  21322. MidiBuffer::Iterator i2 (eventsToAdd);
  21323. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  21324. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  21325. while (i2.getNextEvent (message, time))
  21326. {
  21327. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  21328. buffer.addEvent (message, startSample + pos);
  21329. }
  21330. }
  21331. eventsToAdd.clear();
  21332. }
  21333. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  21334. {
  21335. const ScopedLock sl (lock);
  21336. listeners.addIfNotAlreadyThere (listener);
  21337. }
  21338. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  21339. {
  21340. const ScopedLock sl (lock);
  21341. listeners.removeValue (listener);
  21342. }
  21343. END_JUCE_NAMESPACE
  21344. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  21345. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  21346. BEGIN_JUCE_NAMESPACE
  21347. int MidiMessage::readVariableLengthVal (const uint8* data,
  21348. int& numBytesUsed) throw()
  21349. {
  21350. numBytesUsed = 0;
  21351. int v = 0;
  21352. int i;
  21353. do
  21354. {
  21355. i = (int) *data++;
  21356. if (++numBytesUsed > 6)
  21357. break;
  21358. v = (v << 7) + (i & 0x7f);
  21359. } while (i & 0x80);
  21360. return v;
  21361. }
  21362. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  21363. {
  21364. // this method only works for valid starting bytes of a short midi message
  21365. jassert (firstByte >= 0x80
  21366. && firstByte != 0xf0
  21367. && firstByte != 0xf7);
  21368. static const char messageLengths[] =
  21369. {
  21370. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21371. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21372. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21373. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21374. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21375. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21376. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21377. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  21378. };
  21379. return messageLengths [firstByte & 0x7f];
  21380. }
  21381. MidiMessage::MidiMessage (const uint8* const d,
  21382. const int dataSize,
  21383. const double t) throw()
  21384. : timeStamp (t),
  21385. message (0),
  21386. size (dataSize)
  21387. {
  21388. jassert (dataSize > 0);
  21389. if (dataSize <= 4)
  21390. data = (uint8*) &message;
  21391. else
  21392. data = (uint8*) juce_malloc (dataSize);
  21393. memcpy (data, d, dataSize);
  21394. // check that the length matches the data..
  21395. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  21396. }
  21397. MidiMessage::MidiMessage (const int byte1,
  21398. const double t) throw()
  21399. : timeStamp (t),
  21400. data ((uint8*) &message),
  21401. size (1)
  21402. {
  21403. data[0] = (uint8) byte1;
  21404. // check that the length matches the data..
  21405. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  21406. }
  21407. MidiMessage::MidiMessage (const int byte1,
  21408. const int byte2,
  21409. const double t) throw()
  21410. : timeStamp (t),
  21411. data ((uint8*) &message),
  21412. size (2)
  21413. {
  21414. data[0] = (uint8) byte1;
  21415. data[1] = (uint8) byte2;
  21416. // check that the length matches the data..
  21417. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  21418. }
  21419. MidiMessage::MidiMessage (const int byte1,
  21420. const int byte2,
  21421. const int byte3,
  21422. const double t) throw()
  21423. : timeStamp (t),
  21424. data ((uint8*) &message),
  21425. size (3)
  21426. {
  21427. data[0] = (uint8) byte1;
  21428. data[1] = (uint8) byte2;
  21429. data[2] = (uint8) byte3;
  21430. // check that the length matches the data..
  21431. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  21432. }
  21433. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  21434. : timeStamp (other.timeStamp),
  21435. message (other.message),
  21436. size (other.size)
  21437. {
  21438. if (other.data != (uint8*) &other.message)
  21439. {
  21440. data = (uint8*) juce_malloc (size);
  21441. memcpy (data, other.data, size);
  21442. }
  21443. else
  21444. {
  21445. data = (uint8*) &message;
  21446. }
  21447. }
  21448. MidiMessage::MidiMessage (const MidiMessage& other,
  21449. const double newTimeStamp) throw()
  21450. : timeStamp (newTimeStamp),
  21451. message (other.message),
  21452. size (other.size)
  21453. {
  21454. if (other.data != (uint8*) &other.message)
  21455. {
  21456. data = (uint8*) juce_malloc (size);
  21457. memcpy (data, other.data, size);
  21458. }
  21459. else
  21460. {
  21461. data = (uint8*) &message;
  21462. }
  21463. }
  21464. MidiMessage::MidiMessage (const uint8* src,
  21465. int sz,
  21466. int& numBytesUsed,
  21467. const uint8 lastStatusByte,
  21468. double t) throw()
  21469. : timeStamp (t),
  21470. data ((uint8*) &message),
  21471. message (0)
  21472. {
  21473. unsigned int byte = (unsigned int) *src;
  21474. if (byte < 0x80)
  21475. {
  21476. byte = (unsigned int) (uint8) lastStatusByte;
  21477. numBytesUsed = -1;
  21478. }
  21479. else
  21480. {
  21481. numBytesUsed = 0;
  21482. --sz;
  21483. ++src;
  21484. }
  21485. if (byte >= 0x80)
  21486. {
  21487. if (byte == 0xf0)
  21488. {
  21489. const uint8* d = (const uint8*) src;
  21490. while (d < src + sz)
  21491. {
  21492. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  21493. {
  21494. if (*d == 0xf7) // include an 0xf7 if we hit one
  21495. ++d;
  21496. break;
  21497. }
  21498. ++d;
  21499. }
  21500. size = 1 + (int) (d - src);
  21501. data = (uint8*) juce_malloc (size);
  21502. *data = (uint8) byte;
  21503. memcpy (data + 1, src, size - 1);
  21504. }
  21505. else if (byte == 0xff)
  21506. {
  21507. int n;
  21508. const int bytesLeft = readVariableLengthVal (src + 1, n);
  21509. size = jmin (sz + 1, n + 2 + bytesLeft);
  21510. data = (uint8*) juce_malloc (size);
  21511. *data = (uint8) byte;
  21512. memcpy (data + 1, src, size - 1);
  21513. }
  21514. else
  21515. {
  21516. size = getMessageLengthFromFirstByte ((uint8) byte);
  21517. *data = (uint8) byte;
  21518. if (size > 1)
  21519. {
  21520. data[1] = src[0];
  21521. if (size > 2)
  21522. data[2] = src[1];
  21523. }
  21524. }
  21525. numBytesUsed += size;
  21526. }
  21527. else
  21528. {
  21529. message = 0;
  21530. size = 0;
  21531. }
  21532. }
  21533. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  21534. {
  21535. if (this == &other)
  21536. return *this;
  21537. timeStamp = other.timeStamp;
  21538. size = other.size;
  21539. message = other.message;
  21540. if (data != (uint8*) &message)
  21541. juce_free (data);
  21542. if (other.data != (uint8*) &other.message)
  21543. {
  21544. data = (uint8*) juce_malloc (size);
  21545. memcpy (data, other.data, size);
  21546. }
  21547. else
  21548. {
  21549. data = (uint8*) &message;
  21550. }
  21551. return *this;
  21552. }
  21553. MidiMessage::~MidiMessage() throw()
  21554. {
  21555. if (data != (uint8*) &message)
  21556. juce_free (data);
  21557. }
  21558. int MidiMessage::getChannel() const throw()
  21559. {
  21560. if ((data[0] & 0xf0) != 0xf0)
  21561. return (data[0] & 0xf) + 1;
  21562. else
  21563. return 0;
  21564. }
  21565. bool MidiMessage::isForChannel (const int channel) const throw()
  21566. {
  21567. return ((data[0] & 0xf) == channel - 1)
  21568. && ((data[0] & 0xf0) != 0xf0);
  21569. }
  21570. void MidiMessage::setChannel (const int channel) throw()
  21571. {
  21572. if ((data[0] & 0xf0) != (uint8) 0xf0)
  21573. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  21574. | (uint8)(channel - 1));
  21575. }
  21576. bool MidiMessage::isNoteOn() const throw()
  21577. {
  21578. return ((data[0] & 0xf0) == 0x90)
  21579. && (data[2] != 0);
  21580. }
  21581. bool MidiMessage::isNoteOff() const throw()
  21582. {
  21583. return ((data[0] & 0xf0) == 0x80)
  21584. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  21585. }
  21586. bool MidiMessage::isNoteOnOrOff() const throw()
  21587. {
  21588. const int d = data[0] & 0xf0;
  21589. return (d == 0x90) || (d == 0x80);
  21590. }
  21591. int MidiMessage::getNoteNumber() const throw()
  21592. {
  21593. return data[1];
  21594. }
  21595. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  21596. {
  21597. if (isNoteOnOrOff())
  21598. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  21599. }
  21600. uint8 MidiMessage::getVelocity() const throw()
  21601. {
  21602. if (isNoteOnOrOff())
  21603. return data[2];
  21604. else
  21605. return 0;
  21606. }
  21607. float MidiMessage::getFloatVelocity() const throw()
  21608. {
  21609. return getVelocity() * (1.0f / 127.0f);
  21610. }
  21611. void MidiMessage::setVelocity (const float newVelocity) throw()
  21612. {
  21613. if (isNoteOnOrOff())
  21614. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  21615. }
  21616. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  21617. {
  21618. if (isNoteOnOrOff())
  21619. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  21620. }
  21621. bool MidiMessage::isAftertouch() const throw()
  21622. {
  21623. return (data[0] & 0xf0) == 0xa0;
  21624. }
  21625. int MidiMessage::getAfterTouchValue() const throw()
  21626. {
  21627. return data[2];
  21628. }
  21629. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  21630. const int noteNum,
  21631. const int aftertouchValue) throw()
  21632. {
  21633. jassert (channel > 0 && channel <= 16);
  21634. jassert (((unsigned int) noteNum) <= 127);
  21635. jassert (((unsigned int) aftertouchValue) <= 127);
  21636. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  21637. noteNum & 0x7f,
  21638. aftertouchValue & 0x7f);
  21639. }
  21640. bool MidiMessage::isChannelPressure() const throw()
  21641. {
  21642. return (data[0] & 0xf0) == 0xd0;
  21643. }
  21644. int MidiMessage::getChannelPressureValue() const throw()
  21645. {
  21646. jassert (isChannelPressure());
  21647. return data[1];
  21648. }
  21649. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  21650. const int pressure) throw()
  21651. {
  21652. jassert (channel > 0 && channel <= 16);
  21653. jassert (((unsigned int) pressure) <= 127);
  21654. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  21655. pressure & 0x7f);
  21656. }
  21657. bool MidiMessage::isProgramChange() const throw()
  21658. {
  21659. return (data[0] & 0xf0) == 0xc0;
  21660. }
  21661. int MidiMessage::getProgramChangeNumber() const throw()
  21662. {
  21663. return data[1];
  21664. }
  21665. const MidiMessage MidiMessage::programChange (const int channel,
  21666. const int programNumber) throw()
  21667. {
  21668. jassert (channel > 0 && channel <= 16);
  21669. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  21670. programNumber & 0x7f);
  21671. }
  21672. bool MidiMessage::isPitchWheel() const throw()
  21673. {
  21674. return (data[0] & 0xf0) == 0xe0;
  21675. }
  21676. int MidiMessage::getPitchWheelValue() const throw()
  21677. {
  21678. return data[1] | (data[2] << 7);
  21679. }
  21680. const MidiMessage MidiMessage::pitchWheel (const int channel,
  21681. const int position) throw()
  21682. {
  21683. jassert (channel > 0 && channel <= 16);
  21684. jassert (((unsigned int) position) <= 0x3fff);
  21685. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  21686. position & 127,
  21687. (position >> 7) & 127);
  21688. }
  21689. bool MidiMessage::isController() const throw()
  21690. {
  21691. return (data[0] & 0xf0) == 0xb0;
  21692. }
  21693. int MidiMessage::getControllerNumber() const throw()
  21694. {
  21695. jassert (isController());
  21696. return data[1];
  21697. }
  21698. int MidiMessage::getControllerValue() const throw()
  21699. {
  21700. jassert (isController());
  21701. return data[2];
  21702. }
  21703. const MidiMessage MidiMessage::controllerEvent (const int channel,
  21704. const int controllerType,
  21705. const int value) throw()
  21706. {
  21707. // the channel must be between 1 and 16 inclusive
  21708. jassert (channel > 0 && channel <= 16);
  21709. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  21710. controllerType & 127,
  21711. value & 127);
  21712. }
  21713. const MidiMessage MidiMessage::noteOn (const int channel,
  21714. const int noteNumber,
  21715. const float velocity) throw()
  21716. {
  21717. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  21718. }
  21719. const MidiMessage MidiMessage::noteOn (const int channel,
  21720. const int noteNumber,
  21721. const uint8 velocity) throw()
  21722. {
  21723. jassert (channel > 0 && channel <= 16);
  21724. jassert (((unsigned int) noteNumber) <= 127);
  21725. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  21726. noteNumber & 127,
  21727. jlimit (0, 127, roundFloatToInt (velocity)));
  21728. }
  21729. const MidiMessage MidiMessage::noteOff (const int channel,
  21730. const int noteNumber) throw()
  21731. {
  21732. jassert (channel > 0 && channel <= 16);
  21733. jassert (((unsigned int) noteNumber) <= 127);
  21734. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  21735. }
  21736. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  21737. {
  21738. jassert (channel > 0 && channel <= 16);
  21739. return controllerEvent (channel, 123, 0);
  21740. }
  21741. bool MidiMessage::isAllNotesOff() const throw()
  21742. {
  21743. return (data[0] & 0xf0) == 0xb0
  21744. && data[1] == 123;
  21745. }
  21746. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  21747. {
  21748. return controllerEvent (channel, 120, 0);
  21749. }
  21750. bool MidiMessage::isAllSoundOff() const throw()
  21751. {
  21752. return (data[0] & 0xf0) == 0xb0
  21753. && data[1] == 120;
  21754. }
  21755. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  21756. {
  21757. return controllerEvent (channel, 121, 0);
  21758. }
  21759. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  21760. {
  21761. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  21762. uint8 buf[8];
  21763. buf[0] = 0xf0;
  21764. buf[1] = 0x7f;
  21765. buf[2] = 0x7f;
  21766. buf[3] = 0x04;
  21767. buf[4] = 0x01;
  21768. buf[5] = (uint8) (vol & 0x7f);
  21769. buf[6] = (uint8) (vol >> 7);
  21770. buf[7] = 0xf7;
  21771. return MidiMessage (buf, 8);
  21772. }
  21773. bool MidiMessage::isSysEx() const throw()
  21774. {
  21775. return *data == 0xf0;
  21776. }
  21777. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  21778. const int dataSize) throw()
  21779. {
  21780. MemoryBlock mm (dataSize + 2);
  21781. uint8* const m = (uint8*) mm.getData();
  21782. m[0] = 0xf0;
  21783. memcpy (m + 1, sysexData, dataSize);
  21784. m[dataSize + 1] = 0xf7;
  21785. return MidiMessage (m, dataSize + 2);
  21786. }
  21787. const uint8* MidiMessage::getSysExData() const throw()
  21788. {
  21789. return (isSysEx()) ? getRawData() + 1
  21790. : 0;
  21791. }
  21792. int MidiMessage::getSysExDataSize() const throw()
  21793. {
  21794. return (isSysEx()) ? size - 2
  21795. : 0;
  21796. }
  21797. bool MidiMessage::isMetaEvent() const throw()
  21798. {
  21799. return *data == 0xff;
  21800. }
  21801. bool MidiMessage::isActiveSense() const throw()
  21802. {
  21803. return *data == 0xfe;
  21804. }
  21805. int MidiMessage::getMetaEventType() const throw()
  21806. {
  21807. if (*data != 0xff)
  21808. return -1;
  21809. else
  21810. return data[1];
  21811. }
  21812. int MidiMessage::getMetaEventLength() const throw()
  21813. {
  21814. if (*data == 0xff)
  21815. {
  21816. int n;
  21817. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  21818. }
  21819. return 0;
  21820. }
  21821. const uint8* MidiMessage::getMetaEventData() const throw()
  21822. {
  21823. int n;
  21824. const uint8* d = data + 2;
  21825. readVariableLengthVal (d, n);
  21826. return d + n;
  21827. }
  21828. bool MidiMessage::isTrackMetaEvent() const throw()
  21829. {
  21830. return getMetaEventType() == 0;
  21831. }
  21832. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  21833. {
  21834. return getMetaEventType() == 47;
  21835. }
  21836. bool MidiMessage::isTextMetaEvent() const throw()
  21837. {
  21838. const int t = getMetaEventType();
  21839. return t > 0 && t < 16;
  21840. }
  21841. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  21842. {
  21843. return String ((const char*) getMetaEventData(),
  21844. getMetaEventLength());
  21845. }
  21846. bool MidiMessage::isTrackNameEvent() const throw()
  21847. {
  21848. return (data[1] == 3)
  21849. && (*data == 0xff);
  21850. }
  21851. bool MidiMessage::isTempoMetaEvent() const throw()
  21852. {
  21853. return (data[1] == 81)
  21854. && (*data == 0xff);
  21855. }
  21856. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  21857. {
  21858. return (data[1] == 0x20)
  21859. && (*data == 0xff)
  21860. && (data[2] == 1);
  21861. }
  21862. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  21863. {
  21864. return data[3] + 1;
  21865. }
  21866. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  21867. {
  21868. if (! isTempoMetaEvent())
  21869. return 0.0;
  21870. const uint8* const d = getMetaEventData();
  21871. return (((unsigned int) d[0] << 16)
  21872. | ((unsigned int) d[1] << 8)
  21873. | d[2])
  21874. / 1000000.0;
  21875. }
  21876. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  21877. {
  21878. if (timeFormat > 0)
  21879. {
  21880. if (! isTempoMetaEvent())
  21881. return 0.5 / timeFormat;
  21882. return getTempoSecondsPerQuarterNote() / timeFormat;
  21883. }
  21884. else
  21885. {
  21886. const int frameCode = (-timeFormat) >> 8;
  21887. double framesPerSecond;
  21888. switch (frameCode)
  21889. {
  21890. case 24: framesPerSecond = 24.0; break;
  21891. case 25: framesPerSecond = 25.0; break;
  21892. case 29: framesPerSecond = 29.97; break;
  21893. case 30: framesPerSecond = 30.0; break;
  21894. default: framesPerSecond = 30.0; break;
  21895. }
  21896. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  21897. }
  21898. }
  21899. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  21900. {
  21901. uint8 d[8];
  21902. d[0] = 0xff;
  21903. d[1] = 81;
  21904. d[2] = 3;
  21905. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  21906. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  21907. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  21908. return MidiMessage (d, 6, 0.0);
  21909. }
  21910. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  21911. {
  21912. return (data[1] == 0x58)
  21913. && (*data == (uint8) 0xff);
  21914. }
  21915. void MidiMessage::getTimeSignatureInfo (int& numerator,
  21916. int& denominator) const throw()
  21917. {
  21918. if (isTimeSignatureMetaEvent())
  21919. {
  21920. const uint8* const d = getMetaEventData();
  21921. numerator = d[0];
  21922. denominator = 1 << d[1];
  21923. }
  21924. else
  21925. {
  21926. numerator = 4;
  21927. denominator = 4;
  21928. }
  21929. }
  21930. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  21931. const int denominator) throw()
  21932. {
  21933. uint8 d[8];
  21934. d[0] = 0xff;
  21935. d[1] = 0x58;
  21936. d[2] = 0x04;
  21937. d[3] = (uint8) numerator;
  21938. int n = 1;
  21939. int powerOfTwo = 0;
  21940. while (n < denominator)
  21941. {
  21942. n <<= 1;
  21943. ++powerOfTwo;
  21944. }
  21945. d[4] = (uint8) powerOfTwo;
  21946. d[5] = 0x01;
  21947. d[6] = 96;
  21948. return MidiMessage (d, 7, 0.0);
  21949. }
  21950. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  21951. {
  21952. uint8 d[8];
  21953. d[0] = 0xff;
  21954. d[1] = 0x20;
  21955. d[2] = 0x01;
  21956. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  21957. return MidiMessage (d, 4, 0.0);
  21958. }
  21959. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  21960. {
  21961. return getMetaEventType() == 89;
  21962. }
  21963. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  21964. {
  21965. return (int) *getMetaEventData();
  21966. }
  21967. const MidiMessage MidiMessage::endOfTrack() throw()
  21968. {
  21969. return MidiMessage (0xff, 0x2f, 0, 0.0);
  21970. }
  21971. bool MidiMessage::isSongPositionPointer() const throw()
  21972. {
  21973. return *data == 0xf2;
  21974. }
  21975. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  21976. {
  21977. return data[1] | (data[2] << 7);
  21978. }
  21979. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  21980. {
  21981. return MidiMessage (0xf2,
  21982. positionInMidiBeats & 127,
  21983. (positionInMidiBeats >> 7) & 127);
  21984. }
  21985. bool MidiMessage::isMidiStart() const throw()
  21986. {
  21987. return *data == 0xfa;
  21988. }
  21989. const MidiMessage MidiMessage::midiStart() throw()
  21990. {
  21991. return MidiMessage (0xfa);
  21992. }
  21993. bool MidiMessage::isMidiContinue() const throw()
  21994. {
  21995. return *data == 0xfb;
  21996. }
  21997. const MidiMessage MidiMessage::midiContinue() throw()
  21998. {
  21999. return MidiMessage (0xfb);
  22000. }
  22001. bool MidiMessage::isMidiStop() const throw()
  22002. {
  22003. return *data == 0xfc;
  22004. }
  22005. const MidiMessage MidiMessage::midiStop() throw()
  22006. {
  22007. return MidiMessage (0xfc);
  22008. }
  22009. bool MidiMessage::isMidiClock() const throw()
  22010. {
  22011. return *data == 0xf8;
  22012. }
  22013. const MidiMessage MidiMessage::midiClock() throw()
  22014. {
  22015. return MidiMessage (0xf8);
  22016. }
  22017. bool MidiMessage::isQuarterFrame() const throw()
  22018. {
  22019. return *data == 0xf1;
  22020. }
  22021. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22022. {
  22023. return ((int) data[1]) >> 4;
  22024. }
  22025. int MidiMessage::getQuarterFrameValue() const throw()
  22026. {
  22027. return ((int) data[1]) & 0x0f;
  22028. }
  22029. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22030. const int value) throw()
  22031. {
  22032. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22033. }
  22034. bool MidiMessage::isFullFrame() const throw()
  22035. {
  22036. return data[0] == 0xf0
  22037. && data[1] == 0x7f
  22038. && size >= 10
  22039. && data[3] == 0x01
  22040. && data[4] == 0x01;
  22041. }
  22042. void MidiMessage::getFullFrameParameters (int& hours,
  22043. int& minutes,
  22044. int& seconds,
  22045. int& frames,
  22046. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22047. {
  22048. jassert (isFullFrame());
  22049. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22050. hours = data[5] & 0x1f;
  22051. minutes = data[6];
  22052. seconds = data[7];
  22053. frames = data[8];
  22054. }
  22055. const MidiMessage MidiMessage::fullFrame (const int hours,
  22056. const int minutes,
  22057. const int seconds,
  22058. const int frames,
  22059. MidiMessage::SmpteTimecodeType timecodeType)
  22060. {
  22061. uint8 d[10];
  22062. d[0] = 0xf0;
  22063. d[1] = 0x7f;
  22064. d[2] = 0x7f;
  22065. d[3] = 0x01;
  22066. d[4] = 0x01;
  22067. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22068. d[6] = (uint8) minutes;
  22069. d[7] = (uint8) seconds;
  22070. d[8] = (uint8) frames;
  22071. d[9] = 0xf7;
  22072. return MidiMessage (d, 10, 0.0);
  22073. }
  22074. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22075. {
  22076. return data[0] == 0xf0
  22077. && data[1] == 0x7f
  22078. && data[3] == 0x06
  22079. && size > 5;
  22080. }
  22081. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22082. {
  22083. jassert (isMidiMachineControlMessage());
  22084. return (MidiMachineControlCommand) data[4];
  22085. }
  22086. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22087. {
  22088. uint8 d[6];
  22089. d[0] = 0xf0;
  22090. d[1] = 0x7f;
  22091. d[2] = 0x00;
  22092. d[3] = 0x06;
  22093. d[4] = (uint8) command;
  22094. d[5] = 0xf7;
  22095. return MidiMessage (d, 6, 0.0);
  22096. }
  22097. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22098. int& minutes,
  22099. int& seconds,
  22100. int& frames) const throw()
  22101. {
  22102. if (size >= 12
  22103. && data[0] == 0xf0
  22104. && data[1] == 0x7f
  22105. && data[3] == 0x06
  22106. && data[4] == 0x44
  22107. && data[5] == 0x06
  22108. && data[6] == 0x01)
  22109. {
  22110. hours = data[7] % 24; // (that some machines send out hours > 24)
  22111. minutes = data[8];
  22112. seconds = data[9];
  22113. frames = data[10];
  22114. return true;
  22115. }
  22116. return false;
  22117. }
  22118. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22119. int minutes,
  22120. int seconds,
  22121. int frames)
  22122. {
  22123. uint8 d[12];
  22124. d[0] = 0xf0;
  22125. d[1] = 0x7f;
  22126. d[2] = 0x00;
  22127. d[3] = 0x06;
  22128. d[4] = 0x44;
  22129. d[5] = 0x06;
  22130. d[6] = 0x01;
  22131. d[7] = (uint8) hours;
  22132. d[8] = (uint8) minutes;
  22133. d[9] = (uint8) seconds;
  22134. d[10] = (uint8) frames;
  22135. d[11] = 0xf7;
  22136. return MidiMessage (d, 12, 0.0);
  22137. }
  22138. const String MidiMessage::getMidiNoteName (int note,
  22139. bool useSharps,
  22140. bool includeOctaveNumber,
  22141. int octaveNumForMiddleC) throw()
  22142. {
  22143. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22144. "F", "F#", "G", "G#", "A",
  22145. "A#", "B" };
  22146. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22147. "F", "Gb", "G", "Ab", "A",
  22148. "Bb", "B" };
  22149. if (((unsigned int) note) < 128)
  22150. {
  22151. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22152. : flatNoteNames [note % 12]);
  22153. if (includeOctaveNumber)
  22154. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22155. else
  22156. return s;
  22157. }
  22158. return String::empty;
  22159. }
  22160. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22161. {
  22162. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22163. return 440.0 * pow (2.0, noteNumber / 12.0);
  22164. }
  22165. const String MidiMessage::getGMInstrumentName (int n) throw()
  22166. {
  22167. const char *names[] =
  22168. {
  22169. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22170. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22171. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22172. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22173. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22174. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22175. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22176. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22177. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22178. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22179. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22180. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22181. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22182. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22183. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22184. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22185. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22186. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22187. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22188. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22189. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22190. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22191. "Applause", "Gunshot"
  22192. };
  22193. return (((unsigned int) n) < 128) ? names[n]
  22194. : (const char*)0;
  22195. }
  22196. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22197. {
  22198. const char* names[] =
  22199. {
  22200. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22201. "Bass", "Strings", "Ensemble", "Brass",
  22202. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22203. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22204. };
  22205. return (((unsigned int) n) <= 15) ? names[n]
  22206. : (const char*)0;
  22207. }
  22208. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22209. {
  22210. const char* names[] =
  22211. {
  22212. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22213. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22214. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22215. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22216. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22217. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22218. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22219. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22220. "Mute Triangle", "Open Triangle"
  22221. };
  22222. return (n >= 35 && n <= 81) ? names [n - 35]
  22223. : (const char*)0;
  22224. }
  22225. const String MidiMessage::getControllerName (int n) throw()
  22226. {
  22227. const char* names[] =
  22228. {
  22229. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22230. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22231. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22232. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22233. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22234. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22235. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22236. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22237. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22238. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22239. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22240. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22241. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22242. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22243. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22244. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22245. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22246. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22247. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22249. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22250. "Poly Operation"
  22251. };
  22252. return (((unsigned int) n) < 128) ? names[n]
  22253. : (const char*)0;
  22254. }
  22255. END_JUCE_NAMESPACE
  22256. /********* End of inlined file: juce_MidiMessage.cpp *********/
  22257. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  22258. BEGIN_JUCE_NAMESPACE
  22259. MidiMessageCollector::MidiMessageCollector()
  22260. : lastCallbackTime (0),
  22261. sampleRate (44100.0001)
  22262. {
  22263. }
  22264. MidiMessageCollector::~MidiMessageCollector()
  22265. {
  22266. }
  22267. void MidiMessageCollector::reset (const double sampleRate_)
  22268. {
  22269. jassert (sampleRate_ > 0);
  22270. const ScopedLock sl (midiCallbackLock);
  22271. sampleRate = sampleRate_;
  22272. incomingMessages.clear();
  22273. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22274. }
  22275. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22276. {
  22277. // you need to call reset() to set the correct sample rate before using this object
  22278. jassert (sampleRate != 44100.0001);
  22279. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22280. // for details of what the number should be.
  22281. jassert (message.getTimeStamp() != 0);
  22282. const ScopedLock sl (midiCallbackLock);
  22283. const int sampleNumber
  22284. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22285. incomingMessages.addEvent (message, sampleNumber);
  22286. // if the messages don't get used for over a second, we'd better
  22287. // get rid of any old ones to avoid the queue getting too big
  22288. if (sampleNumber > sampleRate)
  22289. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22290. }
  22291. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22292. const int numSamples)
  22293. {
  22294. // you need to call reset() to set the correct sample rate before using this object
  22295. jassert (sampleRate != 44100.0001);
  22296. const double timeNow = Time::getMillisecondCounterHiRes();
  22297. const double msElapsed = timeNow - lastCallbackTime;
  22298. const ScopedLock sl (midiCallbackLock);
  22299. lastCallbackTime = timeNow;
  22300. if (! incomingMessages.isEmpty())
  22301. {
  22302. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  22303. int startSample = 0;
  22304. int scale = 1 << 16;
  22305. const uint8* midiData;
  22306. int numBytes, samplePosition;
  22307. MidiBuffer::Iterator iter (incomingMessages);
  22308. if (numSourceSamples > numSamples)
  22309. {
  22310. // if our list of events is longer than the buffer we're being
  22311. // asked for, scale them down to squeeze them all in..
  22312. const int maxBlockLengthToUse = numSamples << 5;
  22313. if (numSourceSamples > maxBlockLengthToUse)
  22314. {
  22315. startSample = numSourceSamples - maxBlockLengthToUse;
  22316. numSourceSamples = maxBlockLengthToUse;
  22317. iter.setNextSamplePosition (startSample);
  22318. }
  22319. scale = (numSamples << 10) / numSourceSamples;
  22320. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22321. {
  22322. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22323. destBuffer.addEvent (midiData, numBytes,
  22324. jlimit (0, numSamples - 1, samplePosition));
  22325. }
  22326. }
  22327. else
  22328. {
  22329. // if our event list is shorter than the number we need, put them
  22330. // towards the end of the buffer
  22331. startSample = numSamples - numSourceSamples;
  22332. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22333. {
  22334. destBuffer.addEvent (midiData, numBytes,
  22335. jlimit (0, numSamples - 1, samplePosition + startSample));
  22336. }
  22337. }
  22338. incomingMessages.clear();
  22339. }
  22340. }
  22341. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  22342. {
  22343. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  22344. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22345. addMessageToQueue (m);
  22346. }
  22347. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  22348. {
  22349. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  22350. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22351. addMessageToQueue (m);
  22352. }
  22353. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  22354. {
  22355. addMessageToQueue (message);
  22356. }
  22357. END_JUCE_NAMESPACE
  22358. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  22359. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  22360. BEGIN_JUCE_NAMESPACE
  22361. MidiMessageSequence::MidiMessageSequence()
  22362. {
  22363. }
  22364. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  22365. {
  22366. list.ensureStorageAllocated (other.list.size());
  22367. for (int i = 0; i < other.list.size(); ++i)
  22368. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22369. }
  22370. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  22371. {
  22372. if (this != &other)
  22373. {
  22374. clear();
  22375. for (int i = 0; i < other.list.size(); ++i)
  22376. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22377. }
  22378. return *this;
  22379. }
  22380. MidiMessageSequence::~MidiMessageSequence()
  22381. {
  22382. }
  22383. void MidiMessageSequence::clear()
  22384. {
  22385. list.clear();
  22386. }
  22387. int MidiMessageSequence::getNumEvents() const
  22388. {
  22389. return list.size();
  22390. }
  22391. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  22392. {
  22393. return list [index];
  22394. }
  22395. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  22396. {
  22397. const MidiEventHolder* const meh = list [index];
  22398. if (meh != 0 && meh->noteOffObject != 0)
  22399. return meh->noteOffObject->message.getTimeStamp();
  22400. else
  22401. return 0.0;
  22402. }
  22403. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  22404. {
  22405. const MidiEventHolder* const meh = list [index];
  22406. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  22407. }
  22408. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  22409. {
  22410. return list.indexOf (event);
  22411. }
  22412. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  22413. {
  22414. const int numEvents = list.size();
  22415. int i;
  22416. for (i = 0; i < numEvents; ++i)
  22417. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  22418. break;
  22419. return i;
  22420. }
  22421. double MidiMessageSequence::getStartTime() const
  22422. {
  22423. if (list.size() > 0)
  22424. return list.getUnchecked(0)->message.getTimeStamp();
  22425. else
  22426. return 0;
  22427. }
  22428. double MidiMessageSequence::getEndTime() const
  22429. {
  22430. if (list.size() > 0)
  22431. return list.getLast()->message.getTimeStamp();
  22432. else
  22433. return 0;
  22434. }
  22435. double MidiMessageSequence::getEventTime (const int index) const
  22436. {
  22437. if (((unsigned int) index) < (unsigned int) list.size())
  22438. return list.getUnchecked (index)->message.getTimeStamp();
  22439. return 0.0;
  22440. }
  22441. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  22442. double timeAdjustment)
  22443. {
  22444. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  22445. timeAdjustment += newMessage.getTimeStamp();
  22446. newOne->message.setTimeStamp (timeAdjustment);
  22447. int i;
  22448. for (i = list.size(); --i >= 0;)
  22449. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  22450. break;
  22451. list.insert (i + 1, newOne);
  22452. }
  22453. void MidiMessageSequence::deleteEvent (const int index,
  22454. const bool deleteMatchingNoteUp)
  22455. {
  22456. if (((unsigned int) index) < (unsigned int) list.size())
  22457. {
  22458. if (deleteMatchingNoteUp)
  22459. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  22460. list.remove (index);
  22461. }
  22462. }
  22463. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  22464. double timeAdjustment,
  22465. double firstAllowableTime,
  22466. double endOfAllowableDestTimes)
  22467. {
  22468. firstAllowableTime -= timeAdjustment;
  22469. endOfAllowableDestTimes -= timeAdjustment;
  22470. for (int i = 0; i < other.list.size(); ++i)
  22471. {
  22472. const MidiMessage& m = other.list.getUnchecked(i)->message;
  22473. const double t = m.getTimeStamp();
  22474. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  22475. {
  22476. MidiEventHolder* const newOne = new MidiEventHolder (m);
  22477. newOne->message.setTimeStamp (timeAdjustment + t);
  22478. list.add (newOne);
  22479. }
  22480. }
  22481. sort();
  22482. }
  22483. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22484. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22485. {
  22486. const double diff = first->message.getTimeStamp()
  22487. - second->message.getTimeStamp();
  22488. return (diff > 0) - (diff < 0);
  22489. }
  22490. void MidiMessageSequence::sort()
  22491. {
  22492. list.sort (*this, true);
  22493. }
  22494. void MidiMessageSequence::updateMatchedPairs()
  22495. {
  22496. for (int i = 0; i < list.size(); ++i)
  22497. {
  22498. const MidiMessage& m1 = list.getUnchecked(i)->message;
  22499. if (m1.isNoteOn())
  22500. {
  22501. list.getUnchecked(i)->noteOffObject = 0;
  22502. const int note = m1.getNoteNumber();
  22503. const int chan = m1.getChannel();
  22504. const int len = list.size();
  22505. for (int j = i + 1; j < len; ++j)
  22506. {
  22507. const MidiMessage& m = list.getUnchecked(j)->message;
  22508. if (m.getNoteNumber() == note && m.getChannel() == chan)
  22509. {
  22510. if (m.isNoteOff())
  22511. {
  22512. list.getUnchecked(i)->noteOffObject = list[j];
  22513. break;
  22514. }
  22515. else if (m.isNoteOn())
  22516. {
  22517. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  22518. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  22519. list.getUnchecked(i)->noteOffObject = list[j];
  22520. break;
  22521. }
  22522. }
  22523. }
  22524. }
  22525. }
  22526. }
  22527. void MidiMessageSequence::addTimeToMessages (const double delta)
  22528. {
  22529. for (int i = list.size(); --i >= 0;)
  22530. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  22531. + delta);
  22532. }
  22533. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  22534. MidiMessageSequence& destSequence,
  22535. const bool alsoIncludeMetaEvents) const
  22536. {
  22537. for (int i = 0; i < list.size(); ++i)
  22538. {
  22539. const MidiMessage& mm = list.getUnchecked(i)->message;
  22540. if (mm.isForChannel (channelNumberToExtract)
  22541. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  22542. {
  22543. destSequence.addEvent (mm);
  22544. }
  22545. }
  22546. }
  22547. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  22548. {
  22549. for (int i = 0; i < list.size(); ++i)
  22550. {
  22551. const MidiMessage& mm = list.getUnchecked(i)->message;
  22552. if (mm.isSysEx())
  22553. destSequence.addEvent (mm);
  22554. }
  22555. }
  22556. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  22557. {
  22558. for (int i = list.size(); --i >= 0;)
  22559. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  22560. list.remove(i);
  22561. }
  22562. void MidiMessageSequence::deleteSysExMessages()
  22563. {
  22564. for (int i = list.size(); --i >= 0;)
  22565. if (list.getUnchecked(i)->message.isSysEx())
  22566. list.remove(i);
  22567. }
  22568. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  22569. const double time,
  22570. OwnedArray<MidiMessage>& dest)
  22571. {
  22572. bool doneProg = false;
  22573. bool donePitchWheel = false;
  22574. Array <int> doneControllers (32);
  22575. for (int i = list.size(); --i >= 0;)
  22576. {
  22577. const MidiMessage& mm = list.getUnchecked(i)->message;
  22578. if (mm.isForChannel (channelNumber)
  22579. && mm.getTimeStamp() <= time)
  22580. {
  22581. if (mm.isProgramChange())
  22582. {
  22583. if (! doneProg)
  22584. {
  22585. dest.add (new MidiMessage (mm, 0.0));
  22586. doneProg = true;
  22587. }
  22588. }
  22589. else if (mm.isController())
  22590. {
  22591. if (! doneControllers.contains (mm.getControllerNumber()))
  22592. {
  22593. dest.add (new MidiMessage (mm, 0.0));
  22594. doneControllers.add (mm.getControllerNumber());
  22595. }
  22596. }
  22597. else if (mm.isPitchWheel())
  22598. {
  22599. if (! donePitchWheel)
  22600. {
  22601. dest.add (new MidiMessage (mm, 0.0));
  22602. donePitchWheel = true;
  22603. }
  22604. }
  22605. }
  22606. }
  22607. }
  22608. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  22609. : message (message_),
  22610. noteOffObject (0)
  22611. {
  22612. }
  22613. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  22614. {
  22615. }
  22616. END_JUCE_NAMESPACE
  22617. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  22618. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  22619. BEGIN_JUCE_NAMESPACE
  22620. AudioPluginFormat::AudioPluginFormat() throw()
  22621. {
  22622. }
  22623. AudioPluginFormat::~AudioPluginFormat()
  22624. {
  22625. }
  22626. END_JUCE_NAMESPACE
  22627. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  22628. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22629. BEGIN_JUCE_NAMESPACE
  22630. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  22631. {
  22632. }
  22633. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  22634. {
  22635. clearSingletonInstance();
  22636. }
  22637. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  22638. void AudioPluginFormatManager::addDefaultFormats()
  22639. {
  22640. #ifdef JUCE_DEBUG
  22641. // you should only call this method once!
  22642. for (int i = formats.size(); --i >= 0;)
  22643. {
  22644. #if JUCE_PLUGINHOST_VST
  22645. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  22646. #endif
  22647. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22648. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  22649. #endif
  22650. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22651. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  22652. #endif
  22653. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22654. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  22655. #endif
  22656. }
  22657. #endif
  22658. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22659. formats.add (new AudioUnitPluginFormat());
  22660. #endif
  22661. #if JUCE_PLUGINHOST_VST
  22662. formats.add (new VSTPluginFormat());
  22663. #endif
  22664. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22665. formats.add (new DirectXPluginFormat());
  22666. #endif
  22667. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22668. formats.add (new LADSPAPluginFormat());
  22669. #endif
  22670. }
  22671. int AudioPluginFormatManager::getNumFormats() throw()
  22672. {
  22673. return formats.size();
  22674. }
  22675. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  22676. {
  22677. return formats [index];
  22678. }
  22679. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  22680. {
  22681. formats.add (format);
  22682. }
  22683. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  22684. String& errorMessage) const
  22685. {
  22686. AudioPluginInstance* result = 0;
  22687. for (int i = 0; i < formats.size(); ++i)
  22688. {
  22689. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  22690. if (result != 0)
  22691. break;
  22692. }
  22693. if (result == 0)
  22694. {
  22695. if (! doesPluginStillExist (description))
  22696. errorMessage = TRANS ("This plug-in file no longer exists");
  22697. else
  22698. errorMessage = TRANS ("This plug-in failed to load correctly");
  22699. }
  22700. return result;
  22701. }
  22702. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  22703. {
  22704. for (int i = 0; i < formats.size(); ++i)
  22705. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  22706. return formats.getUnchecked(i)->doesPluginStillExist (description);
  22707. return false;
  22708. }
  22709. END_JUCE_NAMESPACE
  22710. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22711. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  22712. #define JUCE_PLUGIN_HOST 1
  22713. BEGIN_JUCE_NAMESPACE
  22714. AudioPluginInstance::AudioPluginInstance()
  22715. {
  22716. }
  22717. AudioPluginInstance::~AudioPluginInstance()
  22718. {
  22719. }
  22720. END_JUCE_NAMESPACE
  22721. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  22722. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  22723. BEGIN_JUCE_NAMESPACE
  22724. KnownPluginList::KnownPluginList()
  22725. {
  22726. }
  22727. KnownPluginList::~KnownPluginList()
  22728. {
  22729. }
  22730. void KnownPluginList::clear()
  22731. {
  22732. if (types.size() > 0)
  22733. {
  22734. types.clear();
  22735. sendChangeMessage (this);
  22736. }
  22737. }
  22738. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  22739. {
  22740. for (int i = 0; i < types.size(); ++i)
  22741. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  22742. return types.getUnchecked(i);
  22743. return 0;
  22744. }
  22745. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  22746. {
  22747. for (int i = 0; i < types.size(); ++i)
  22748. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  22749. return types.getUnchecked(i);
  22750. return 0;
  22751. }
  22752. bool KnownPluginList::addType (const PluginDescription& type)
  22753. {
  22754. for (int i = types.size(); --i >= 0;)
  22755. {
  22756. if (types.getUnchecked(i)->isDuplicateOf (type))
  22757. {
  22758. // strange - found a duplicate plugin with different info..
  22759. jassert (types.getUnchecked(i)->name == type.name);
  22760. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  22761. *types.getUnchecked(i) = type;
  22762. return false;
  22763. }
  22764. }
  22765. types.add (new PluginDescription (type));
  22766. sendChangeMessage (this);
  22767. return true;
  22768. }
  22769. void KnownPluginList::removeType (const int index) throw()
  22770. {
  22771. types.remove (index);
  22772. sendChangeMessage (this);
  22773. }
  22774. static Time getFileModTime (const String& fileOrIdentifier) throw()
  22775. {
  22776. if (fileOrIdentifier.startsWithChar (T('/'))
  22777. || fileOrIdentifier[1] == T(':'))
  22778. {
  22779. return File (fileOrIdentifier).getLastModificationTime();
  22780. }
  22781. return Time (0);
  22782. }
  22783. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  22784. {
  22785. return t1 != t2 || t1 == Time (0);
  22786. }
  22787. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  22788. {
  22789. if (getTypeForFile (fileOrIdentifier) == 0)
  22790. return false;
  22791. for (int i = types.size(); --i >= 0;)
  22792. {
  22793. const PluginDescription* const d = types.getUnchecked(i);
  22794. if (d->fileOrIdentifier == fileOrIdentifier
  22795. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22796. {
  22797. return false;
  22798. }
  22799. }
  22800. return true;
  22801. }
  22802. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  22803. const bool dontRescanIfAlreadyInList,
  22804. OwnedArray <PluginDescription>& typesFound,
  22805. AudioPluginFormat& format)
  22806. {
  22807. bool addedOne = false;
  22808. if (dontRescanIfAlreadyInList
  22809. && getTypeForFile (fileOrIdentifier) != 0)
  22810. {
  22811. bool needsRescanning = false;
  22812. for (int i = types.size(); --i >= 0;)
  22813. {
  22814. const PluginDescription* const d = types.getUnchecked(i);
  22815. if (d->fileOrIdentifier == fileOrIdentifier)
  22816. {
  22817. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22818. needsRescanning = true;
  22819. else
  22820. typesFound.add (new PluginDescription (*d));
  22821. }
  22822. }
  22823. if (! needsRescanning)
  22824. return false;
  22825. }
  22826. OwnedArray <PluginDescription> found;
  22827. format.findAllTypesForFile (found, fileOrIdentifier);
  22828. for (int i = 0; i < found.size(); ++i)
  22829. {
  22830. PluginDescription* const desc = found.getUnchecked(i);
  22831. jassert (desc != 0);
  22832. if (addType (*desc))
  22833. addedOne = true;
  22834. typesFound.add (new PluginDescription (*desc));
  22835. }
  22836. return addedOne;
  22837. }
  22838. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  22839. OwnedArray <PluginDescription>& typesFound)
  22840. {
  22841. for (int i = 0; i < files.size(); ++i)
  22842. {
  22843. bool loaded = false;
  22844. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  22845. {
  22846. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  22847. if (scanAndAddFile (files[i], true, typesFound, *format))
  22848. loaded = true;
  22849. }
  22850. if (! loaded)
  22851. {
  22852. const File f (files[i]);
  22853. if (f.isDirectory())
  22854. {
  22855. StringArray s;
  22856. {
  22857. OwnedArray <File> subFiles;
  22858. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  22859. for (int j = 0; j < subFiles.size(); ++j)
  22860. s.add (subFiles.getUnchecked (j)->getFullPathName());
  22861. }
  22862. scanAndAddDragAndDroppedFiles (s, typesFound);
  22863. }
  22864. }
  22865. }
  22866. }
  22867. class PluginSorter
  22868. {
  22869. public:
  22870. KnownPluginList::SortMethod method;
  22871. PluginSorter() throw() {}
  22872. int compareElements (const PluginDescription* const first,
  22873. const PluginDescription* const second) const throw()
  22874. {
  22875. int diff = 0;
  22876. if (method == KnownPluginList::sortByCategory)
  22877. diff = first->category.compareLexicographically (second->category);
  22878. else if (method == KnownPluginList::sortByManufacturer)
  22879. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  22880. else if (method == KnownPluginList::sortByFileSystemLocation)
  22881. diff = first->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22882. .upToLastOccurrenceOf (T("/"), false, false)
  22883. .compare (second->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22884. .upToLastOccurrenceOf (T("/"), false, false));
  22885. if (diff == 0)
  22886. diff = first->name.compareLexicographically (second->name);
  22887. return diff;
  22888. }
  22889. };
  22890. void KnownPluginList::sort (const SortMethod method)
  22891. {
  22892. if (method != defaultOrder)
  22893. {
  22894. PluginSorter sorter;
  22895. sorter.method = method;
  22896. types.sort (sorter, true);
  22897. sendChangeMessage (this);
  22898. }
  22899. }
  22900. XmlElement* KnownPluginList::createXml() const
  22901. {
  22902. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  22903. for (int i = 0; i < types.size(); ++i)
  22904. e->addChildElement (types.getUnchecked(i)->createXml());
  22905. return e;
  22906. }
  22907. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  22908. {
  22909. clear();
  22910. if (xml.hasTagName (T("KNOWNPLUGINS")))
  22911. {
  22912. forEachXmlChildElement (xml, e)
  22913. {
  22914. PluginDescription info;
  22915. if (info.loadFromXml (*e))
  22916. addType (info);
  22917. }
  22918. }
  22919. }
  22920. const int menuIdBase = 0x324503f4;
  22921. // This is used to turn a bunch of paths into a nested menu structure.
  22922. struct PluginFilesystemTree
  22923. {
  22924. private:
  22925. String folder;
  22926. OwnedArray <PluginFilesystemTree> subFolders;
  22927. Array <PluginDescription*> plugins;
  22928. void addPlugin (PluginDescription* const pd, const String& path)
  22929. {
  22930. if (path.isEmpty())
  22931. {
  22932. plugins.add (pd);
  22933. }
  22934. else
  22935. {
  22936. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  22937. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  22938. for (int i = subFolders.size(); --i >= 0;)
  22939. {
  22940. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  22941. {
  22942. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  22943. return;
  22944. }
  22945. }
  22946. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  22947. newFolder->folder = firstSubFolder;
  22948. subFolders.add (newFolder);
  22949. newFolder->addPlugin (pd, remainingPath);
  22950. }
  22951. }
  22952. // removes any deeply nested folders that don't contain any actual plugins
  22953. void optimise()
  22954. {
  22955. for (int i = subFolders.size(); --i >= 0;)
  22956. {
  22957. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  22958. sub->optimise();
  22959. if (sub->plugins.size() == 0)
  22960. {
  22961. for (int j = 0; j < sub->subFolders.size(); ++j)
  22962. subFolders.add (sub->subFolders.getUnchecked(j));
  22963. sub->subFolders.clear (false);
  22964. subFolders.remove (i);
  22965. }
  22966. }
  22967. }
  22968. public:
  22969. void buildTree (const Array <PluginDescription*>& allPlugins)
  22970. {
  22971. for (int i = 0; i < allPlugins.size(); ++i)
  22972. {
  22973. String path (allPlugins.getUnchecked(i)
  22974. ->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22975. .upToLastOccurrenceOf (T("/"), false, false));
  22976. if (path.substring (1, 2) == T(":"))
  22977. path = path.substring (2);
  22978. addPlugin (allPlugins.getUnchecked(i), path);
  22979. }
  22980. optimise();
  22981. }
  22982. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  22983. {
  22984. int i;
  22985. for (i = 0; i < subFolders.size(); ++i)
  22986. {
  22987. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  22988. PopupMenu subMenu;
  22989. sub->addToMenu (subMenu, allPlugins);
  22990. #if JUCE_MAC
  22991. // avoid the special AU formatting nonsense on Mac..
  22992. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (T(":"), false, false), subMenu);
  22993. #else
  22994. m.addSubMenu (sub->folder, subMenu);
  22995. #endif
  22996. }
  22997. for (i = 0; i < plugins.size(); ++i)
  22998. {
  22999. PluginDescription* const plugin = plugins.getUnchecked(i);
  23000. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23001. plugin->name, true, false);
  23002. }
  23003. }
  23004. };
  23005. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23006. {
  23007. Array <PluginDescription*> sorted;
  23008. {
  23009. PluginSorter sorter;
  23010. sorter.method = sortMethod;
  23011. for (int i = 0; i < types.size(); ++i)
  23012. sorted.addSorted (sorter, types.getUnchecked(i));
  23013. }
  23014. if (sortMethod == sortByCategory
  23015. || sortMethod == sortByManufacturer)
  23016. {
  23017. String lastSubMenuName;
  23018. PopupMenu sub;
  23019. for (int i = 0; i < sorted.size(); ++i)
  23020. {
  23021. const PluginDescription* const pd = sorted.getUnchecked(i);
  23022. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23023. : pd->manufacturerName);
  23024. if (! thisSubMenuName.containsNonWhitespaceChars())
  23025. thisSubMenuName = T("Other");
  23026. if (thisSubMenuName != lastSubMenuName)
  23027. {
  23028. if (sub.getNumItems() > 0)
  23029. {
  23030. menu.addSubMenu (lastSubMenuName, sub);
  23031. sub.clear();
  23032. }
  23033. lastSubMenuName = thisSubMenuName;
  23034. }
  23035. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23036. }
  23037. if (sub.getNumItems() > 0)
  23038. menu.addSubMenu (lastSubMenuName, sub);
  23039. }
  23040. else if (sortMethod == sortByFileSystemLocation)
  23041. {
  23042. PluginFilesystemTree root;
  23043. root.buildTree (sorted);
  23044. root.addToMenu (menu, types);
  23045. }
  23046. else
  23047. {
  23048. for (int i = 0; i < sorted.size(); ++i)
  23049. {
  23050. const PluginDescription* const pd = sorted.getUnchecked(i);
  23051. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23052. }
  23053. }
  23054. }
  23055. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23056. {
  23057. const int i = menuResultCode - menuIdBase;
  23058. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23059. }
  23060. END_JUCE_NAMESPACE
  23061. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  23062. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  23063. BEGIN_JUCE_NAMESPACE
  23064. PluginDescription::PluginDescription() throw()
  23065. : uid (0),
  23066. isInstrument (false),
  23067. numInputChannels (0),
  23068. numOutputChannels (0)
  23069. {
  23070. }
  23071. PluginDescription::~PluginDescription() throw()
  23072. {
  23073. }
  23074. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23075. : name (other.name),
  23076. pluginFormatName (other.pluginFormatName),
  23077. category (other.category),
  23078. manufacturerName (other.manufacturerName),
  23079. version (other.version),
  23080. fileOrIdentifier (other.fileOrIdentifier),
  23081. lastFileModTime (other.lastFileModTime),
  23082. uid (other.uid),
  23083. isInstrument (other.isInstrument),
  23084. numInputChannels (other.numInputChannels),
  23085. numOutputChannels (other.numOutputChannels)
  23086. {
  23087. }
  23088. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23089. {
  23090. name = other.name;
  23091. pluginFormatName = other.pluginFormatName;
  23092. category = other.category;
  23093. manufacturerName = other.manufacturerName;
  23094. version = other.version;
  23095. fileOrIdentifier = other.fileOrIdentifier;
  23096. uid = other.uid;
  23097. isInstrument = other.isInstrument;
  23098. lastFileModTime = other.lastFileModTime;
  23099. numInputChannels = other.numInputChannels;
  23100. numOutputChannels = other.numOutputChannels;
  23101. return *this;
  23102. }
  23103. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23104. {
  23105. return fileOrIdentifier == other.fileOrIdentifier
  23106. && uid == other.uid;
  23107. }
  23108. const String PluginDescription::createIdentifierString() const throw()
  23109. {
  23110. return pluginFormatName
  23111. + T("-") + name
  23112. + T("-") + String::toHexString (fileOrIdentifier.hashCode())
  23113. + T("-") + String::toHexString (uid);
  23114. }
  23115. XmlElement* PluginDescription::createXml() const
  23116. {
  23117. XmlElement* const e = new XmlElement (T("PLUGIN"));
  23118. e->setAttribute (T("name"), name);
  23119. e->setAttribute (T("format"), pluginFormatName);
  23120. e->setAttribute (T("category"), category);
  23121. e->setAttribute (T("manufacturer"), manufacturerName);
  23122. e->setAttribute (T("version"), version);
  23123. e->setAttribute (T("file"), fileOrIdentifier);
  23124. e->setAttribute (T("uid"), String::toHexString (uid));
  23125. e->setAttribute (T("isInstrument"), isInstrument);
  23126. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  23127. e->setAttribute (T("numInputs"), numInputChannels);
  23128. e->setAttribute (T("numOutputs"), numOutputChannels);
  23129. return e;
  23130. }
  23131. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23132. {
  23133. if (xml.hasTagName (T("PLUGIN")))
  23134. {
  23135. name = xml.getStringAttribute (T("name"));
  23136. pluginFormatName = xml.getStringAttribute (T("format"));
  23137. category = xml.getStringAttribute (T("category"));
  23138. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  23139. version = xml.getStringAttribute (T("version"));
  23140. fileOrIdentifier = xml.getStringAttribute (T("file"));
  23141. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  23142. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  23143. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  23144. numInputChannels = xml.getIntAttribute (T("numInputs"));
  23145. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  23146. return true;
  23147. }
  23148. return false;
  23149. }
  23150. END_JUCE_NAMESPACE
  23151. /********* End of inlined file: juce_PluginDescription.cpp *********/
  23152. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23153. BEGIN_JUCE_NAMESPACE
  23154. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23155. AudioPluginFormat& formatToLookFor,
  23156. FileSearchPath directoriesToSearch,
  23157. const bool recursive,
  23158. const File& deadMansPedalFile_)
  23159. : list (listToAddTo),
  23160. format (formatToLookFor),
  23161. deadMansPedalFile (deadMansPedalFile_),
  23162. nextIndex (0),
  23163. progress (0)
  23164. {
  23165. directoriesToSearch.removeRedundantPaths();
  23166. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23167. // If any plugins have crashed recently when being loaded, move them to the
  23168. // end of the list to give the others a chance to load correctly..
  23169. const StringArray crashedPlugins (getDeadMansPedalFile());
  23170. for (int i = 0; i < crashedPlugins.size(); ++i)
  23171. {
  23172. const String f = crashedPlugins[i];
  23173. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23174. if (f == filesOrIdentifiersToScan[j])
  23175. filesOrIdentifiersToScan.move (j, -1);
  23176. }
  23177. }
  23178. PluginDirectoryScanner::~PluginDirectoryScanner()
  23179. {
  23180. }
  23181. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23182. {
  23183. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23184. }
  23185. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23186. {
  23187. String file (filesOrIdentifiersToScan [nextIndex]);
  23188. if (file.isNotEmpty())
  23189. {
  23190. if (! list.isListingUpToDate (file))
  23191. {
  23192. OwnedArray <PluginDescription> typesFound;
  23193. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23194. StringArray crashedPlugins (getDeadMansPedalFile());
  23195. crashedPlugins.removeString (file);
  23196. crashedPlugins.add (file);
  23197. setDeadMansPedalFile (crashedPlugins);
  23198. list.scanAndAddFile (file,
  23199. dontRescanIfAlreadyInList,
  23200. typesFound,
  23201. format);
  23202. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23203. crashedPlugins.removeString (file);
  23204. setDeadMansPedalFile (crashedPlugins);
  23205. if (typesFound.size() == 0)
  23206. failedFiles.add (file);
  23207. }
  23208. ++nextIndex;
  23209. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23210. }
  23211. return nextIndex < filesOrIdentifiersToScan.size();
  23212. }
  23213. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23214. {
  23215. StringArray lines;
  23216. if (deadMansPedalFile != File::nonexistent)
  23217. {
  23218. lines.addLines (deadMansPedalFile.loadFileAsString());
  23219. lines.removeEmptyStrings();
  23220. }
  23221. return lines;
  23222. }
  23223. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23224. {
  23225. if (deadMansPedalFile != File::nonexistent)
  23226. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23227. }
  23228. END_JUCE_NAMESPACE
  23229. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23230. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  23231. BEGIN_JUCE_NAMESPACE
  23232. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23233. const File& deadMansPedalFile_,
  23234. PropertiesFile* const propertiesToUse_)
  23235. : list (listToEdit),
  23236. deadMansPedalFile (deadMansPedalFile_),
  23237. propertiesToUse (propertiesToUse_)
  23238. {
  23239. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23240. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23241. optionsButton->addButtonListener (this);
  23242. optionsButton->setTriggeredOnMouseDown (true);
  23243. setSize (400, 600);
  23244. list.addChangeListener (this);
  23245. }
  23246. PluginListComponent::~PluginListComponent()
  23247. {
  23248. list.removeChangeListener (this);
  23249. deleteAllChildren();
  23250. }
  23251. void PluginListComponent::resized()
  23252. {
  23253. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23254. optionsButton->changeWidthToFitText (24);
  23255. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23256. }
  23257. void PluginListComponent::changeListenerCallback (void*)
  23258. {
  23259. listBox->updateContent();
  23260. listBox->repaint();
  23261. }
  23262. int PluginListComponent::getNumRows()
  23263. {
  23264. return list.getNumTypes();
  23265. }
  23266. void PluginListComponent::paintListBoxItem (int row,
  23267. Graphics& g,
  23268. int width, int height,
  23269. bool rowIsSelected)
  23270. {
  23271. if (rowIsSelected)
  23272. g.fillAll (findColour (TextEditor::highlightColourId));
  23273. const PluginDescription* const pd = list.getType (row);
  23274. if (pd != 0)
  23275. {
  23276. GlyphArrangement ga;
  23277. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23278. g.setColour (Colours::black);
  23279. ga.draw (g);
  23280. float x, y, r, b;
  23281. ga.getBoundingBox (0, -1, x, y, r, b, false);
  23282. String desc;
  23283. desc << pd->pluginFormatName
  23284. << (pd->isInstrument ? " instrument" : " effect")
  23285. << " - "
  23286. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23287. << " / "
  23288. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23289. if (pd->manufacturerName.isNotEmpty())
  23290. desc << " - " << pd->manufacturerName;
  23291. if (pd->version.isNotEmpty())
  23292. desc << " - " << pd->version;
  23293. if (pd->category.isNotEmpty())
  23294. desc << " - category: '" << pd->category << '\'';
  23295. g.setColour (Colours::grey);
  23296. ga.clear();
  23297. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  23298. ga.draw (g);
  23299. }
  23300. }
  23301. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23302. {
  23303. list.removeType (lastRowSelected);
  23304. }
  23305. void PluginListComponent::buttonClicked (Button* b)
  23306. {
  23307. if (optionsButton == b)
  23308. {
  23309. PopupMenu menu;
  23310. menu.addItem (1, TRANS("Clear list"));
  23311. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23312. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23313. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23314. menu.addSeparator();
  23315. menu.addItem (2, TRANS("Sort alphabetically"));
  23316. menu.addItem (3, TRANS("Sort by category"));
  23317. menu.addItem (4, TRANS("Sort by manufacturer"));
  23318. menu.addSeparator();
  23319. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23320. {
  23321. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23322. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23323. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23324. }
  23325. const int r = menu.showAt (optionsButton);
  23326. if (r == 1)
  23327. {
  23328. list.clear();
  23329. }
  23330. else if (r == 2)
  23331. {
  23332. list.sort (KnownPluginList::sortAlphabetically);
  23333. }
  23334. else if (r == 3)
  23335. {
  23336. list.sort (KnownPluginList::sortByCategory);
  23337. }
  23338. else if (r == 4)
  23339. {
  23340. list.sort (KnownPluginList::sortByManufacturer);
  23341. }
  23342. else if (r == 5)
  23343. {
  23344. const SparseSet <int> selected (listBox->getSelectedRows());
  23345. for (int i = list.getNumTypes(); --i >= 0;)
  23346. if (selected.contains (i))
  23347. list.removeType (i);
  23348. }
  23349. else if (r == 6)
  23350. {
  23351. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  23352. if (desc != 0)
  23353. {
  23354. if (File (desc->fileOrIdentifier).existsAsFile())
  23355. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  23356. }
  23357. }
  23358. else if (r == 7)
  23359. {
  23360. for (int i = list.getNumTypes(); --i >= 0;)
  23361. {
  23362. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  23363. {
  23364. list.removeType (i);
  23365. }
  23366. }
  23367. }
  23368. else if (r != 0)
  23369. {
  23370. typeToScan = r - 10;
  23371. startTimer (1);
  23372. }
  23373. }
  23374. }
  23375. void PluginListComponent::timerCallback()
  23376. {
  23377. stopTimer();
  23378. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  23379. }
  23380. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  23381. {
  23382. return true;
  23383. }
  23384. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  23385. {
  23386. OwnedArray <PluginDescription> typesFound;
  23387. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  23388. }
  23389. void PluginListComponent::scanFor (AudioPluginFormat* format)
  23390. {
  23391. if (format == 0)
  23392. return;
  23393. FileSearchPath path (format->getDefaultLocationsToSearch());
  23394. if (propertiesToUse != 0)
  23395. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23396. {
  23397. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  23398. FileSearchPathListComponent pathList;
  23399. pathList.setSize (500, 300);
  23400. pathList.setPath (path);
  23401. aw.addCustomComponent (&pathList);
  23402. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  23403. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23404. if (aw.runModalLoop() == 0)
  23405. return;
  23406. path = pathList.getPath();
  23407. }
  23408. if (propertiesToUse != 0)
  23409. {
  23410. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23411. propertiesToUse->saveIfNeeded();
  23412. }
  23413. double progress = 0.0;
  23414. AlertWindow aw (TRANS("Scanning for plugins..."),
  23415. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  23416. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23417. aw.addProgressBarComponent (progress);
  23418. aw.enterModalState();
  23419. MessageManager::getInstance()->runDispatchLoopUntil (300);
  23420. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  23421. for (;;)
  23422. {
  23423. aw.setMessage (TRANS("Testing:\n\n")
  23424. + scanner.getNextPluginFileThatWillBeScanned());
  23425. MessageManager::getInstance()->runDispatchLoopUntil (20);
  23426. if (! scanner.scanNextFile (true))
  23427. break;
  23428. if (! aw.isCurrentlyModal())
  23429. break;
  23430. progress = scanner.getProgress();
  23431. }
  23432. if (scanner.getFailedFiles().size() > 0)
  23433. {
  23434. StringArray shortNames;
  23435. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  23436. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  23437. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  23438. TRANS("Scan complete"),
  23439. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  23440. + shortNames.joinIntoString (", "));
  23441. }
  23442. }
  23443. END_JUCE_NAMESPACE
  23444. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  23445. /********* Start of inlined file: juce_AudioUnitPluginFormat.mm *********/
  23446. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  23447. #include <AudioUnit/AudioUnit.h>
  23448. #include <AudioUnit/AUCocoaUIView.h>
  23449. #include <CoreAudioKit/AUGenericView.h>
  23450. #if JUCE_SUPPORT_CARBON
  23451. #include <AudioToolbox/AudioUnitUtilities.h>
  23452. #include <AudioUnit/AudioUnitCarbonView.h>
  23453. #endif
  23454. BEGIN_JUCE_NAMESPACE
  23455. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  23456. #endif
  23457. #if JUCE_MAC
  23458. #if MACOS_10_3_OR_EARLIER
  23459. #define kAudioUnitType_Generator 'augn'
  23460. #endif
  23461. // Change this to disable logging of various activities
  23462. #ifndef AU_LOGGING
  23463. #define AU_LOGGING 1
  23464. #endif
  23465. #if AU_LOGGING
  23466. #define log(a) Logger::writeToLog(a);
  23467. #else
  23468. #define log(a)
  23469. #endif
  23470. static int insideCallback = 0;
  23471. static const String osTypeToString (OSType type) throw()
  23472. {
  23473. char s[4];
  23474. s[0] = (char) (((uint32) type) >> 24);
  23475. s[1] = (char) (((uint32) type) >> 16);
  23476. s[2] = (char) (((uint32) type) >> 8);
  23477. s[3] = (char) ((uint32) type);
  23478. return String (s, 4);
  23479. }
  23480. static OSType stringToOSType (const String& s1) throw()
  23481. {
  23482. const String s (s1 + " ");
  23483. return (((OSType) (unsigned char) s[0]) << 24)
  23484. | (((OSType) (unsigned char) s[1]) << 16)
  23485. | (((OSType) (unsigned char) s[2]) << 8)
  23486. | ((OSType) (unsigned char) s[3]);
  23487. }
  23488. static const tchar* auIdentifierPrefix = T("AudioUnit:");
  23489. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  23490. {
  23491. jassert (osTypeToString ('abcd') == T("abcd")); // agh, must have got the endianness wrong..
  23492. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  23493. String s (auIdentifierPrefix);
  23494. if (desc.componentType == kAudioUnitType_MusicDevice)
  23495. s << "Synths/";
  23496. else if (desc.componentType == kAudioUnitType_MusicEffect
  23497. || desc.componentType == kAudioUnitType_Effect)
  23498. s << "Effects/";
  23499. else if (desc.componentType == kAudioUnitType_Generator)
  23500. s << "Generators/";
  23501. else if (desc.componentType == kAudioUnitType_Panner)
  23502. s << "Panners/";
  23503. s << osTypeToString (desc.componentType)
  23504. << T(",")
  23505. << osTypeToString (desc.componentSubType)
  23506. << T(",")
  23507. << osTypeToString (desc.componentManufacturer);
  23508. return s;
  23509. }
  23510. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  23511. {
  23512. Handle componentNameHandle = NewHandle (sizeof (void*));
  23513. Handle componentInfoHandle = NewHandle (sizeof (void*));
  23514. if (componentNameHandle != 0 && componentInfoHandle != 0)
  23515. {
  23516. ComponentDescription desc;
  23517. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  23518. {
  23519. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  23520. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  23521. if (nameString != 0 && nameString[0] != 0)
  23522. {
  23523. const String all ((const char*) nameString + 1, nameString[0]);
  23524. DBG ("name: "+ all);
  23525. manufacturer = all.upToFirstOccurrenceOf (T(":"), false, false).trim();
  23526. name = all.fromFirstOccurrenceOf (T(":"), false, false).trim();
  23527. }
  23528. if (infoString != 0 && infoString[0] != 0)
  23529. {
  23530. const String all ((const char*) infoString + 1, infoString[0]);
  23531. DBG ("info: " + all);
  23532. }
  23533. if (name.isEmpty())
  23534. name = "<Unknown>";
  23535. }
  23536. DisposeHandle (componentNameHandle);
  23537. DisposeHandle (componentInfoHandle);
  23538. }
  23539. }
  23540. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  23541. String& name, String& version, String& manufacturer)
  23542. {
  23543. zerostruct (desc);
  23544. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  23545. {
  23546. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (T(':')),
  23547. fileOrIdentifier.lastIndexOfChar (T('/'))) + 1));
  23548. StringArray tokens;
  23549. tokens.addTokens (s, T(","), 0);
  23550. tokens.trim();
  23551. tokens.removeEmptyStrings();
  23552. if (tokens.size() == 3)
  23553. {
  23554. desc.componentType = stringToOSType (tokens[0]);
  23555. desc.componentSubType = stringToOSType (tokens[1]);
  23556. desc.componentManufacturer = stringToOSType (tokens[2]);
  23557. ComponentRecord* comp = FindNextComponent (0, &desc);
  23558. if (comp != 0)
  23559. {
  23560. getAUDetails (comp, name, manufacturer);
  23561. return true;
  23562. }
  23563. }
  23564. }
  23565. return false;
  23566. }
  23567. class AudioUnitPluginWindowCarbon;
  23568. class AudioUnitPluginWindowCocoa;
  23569. class AudioUnitPluginInstance : public AudioPluginInstance
  23570. {
  23571. public:
  23572. ~AudioUnitPluginInstance();
  23573. // AudioPluginInstance methods:
  23574. void fillInPluginDescription (PluginDescription& desc) const
  23575. {
  23576. desc.name = pluginName;
  23577. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  23578. desc.uid = ((int) componentDesc.componentType)
  23579. ^ ((int) componentDesc.componentSubType)
  23580. ^ ((int) componentDesc.componentManufacturer);
  23581. desc.lastFileModTime = 0;
  23582. desc.pluginFormatName = "AudioUnit";
  23583. desc.category = getCategory();
  23584. desc.manufacturerName = manufacturer;
  23585. desc.version = version;
  23586. desc.numInputChannels = getNumInputChannels();
  23587. desc.numOutputChannels = getNumOutputChannels();
  23588. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  23589. }
  23590. const String getName() const { return pluginName; }
  23591. bool acceptsMidi() const { return wantsMidiMessages; }
  23592. bool producesMidi() const { return false; }
  23593. // AudioProcessor methods:
  23594. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23595. void releaseResources();
  23596. void processBlock (AudioSampleBuffer& buffer,
  23597. MidiBuffer& midiMessages);
  23598. AudioProcessorEditor* createEditor();
  23599. const String getInputChannelName (const int index) const;
  23600. bool isInputChannelStereoPair (int index) const;
  23601. const String getOutputChannelName (const int index) const;
  23602. bool isOutputChannelStereoPair (int index) const;
  23603. int getNumParameters();
  23604. float getParameter (int index);
  23605. void setParameter (int index, float newValue);
  23606. const String getParameterName (int index);
  23607. const String getParameterText (int index);
  23608. bool isParameterAutomatable (int index) const;
  23609. int getNumPrograms();
  23610. int getCurrentProgram();
  23611. void setCurrentProgram (int index);
  23612. const String getProgramName (int index);
  23613. void changeProgramName (int index, const String& newName);
  23614. void getStateInformation (MemoryBlock& destData);
  23615. void getCurrentProgramStateInformation (MemoryBlock& destData);
  23616. void setStateInformation (const void* data, int sizeInBytes);
  23617. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  23618. juce_UseDebuggingNewOperator
  23619. private:
  23620. friend class AudioUnitPluginWindowCarbon;
  23621. friend class AudioUnitPluginWindowCocoa;
  23622. friend class AudioUnitPluginFormat;
  23623. ComponentDescription componentDesc;
  23624. String pluginName, manufacturer, version;
  23625. String fileOrIdentifier;
  23626. CriticalSection lock;
  23627. bool initialised, wantsMidiMessages, wasPlaying;
  23628. AudioBufferList* outputBufferList;
  23629. AudioTimeStamp timeStamp;
  23630. AudioSampleBuffer* currentBuffer;
  23631. AudioUnit audioUnit;
  23632. Array <int> parameterIds;
  23633. bool getComponentDescFromFile (const String& fileOrIdentifier);
  23634. void initialise();
  23635. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23636. const AudioTimeStamp* inTimeStamp,
  23637. UInt32 inBusNumber,
  23638. UInt32 inNumberFrames,
  23639. AudioBufferList* ioData) const;
  23640. static OSStatus renderGetInputCallback (void* inRefCon,
  23641. AudioUnitRenderActionFlags* ioActionFlags,
  23642. const AudioTimeStamp* inTimeStamp,
  23643. UInt32 inBusNumber,
  23644. UInt32 inNumberFrames,
  23645. AudioBufferList* ioData)
  23646. {
  23647. return ((AudioUnitPluginInstance*) inRefCon)
  23648. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  23649. }
  23650. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  23651. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  23652. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  23653. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23654. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23655. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  23656. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  23657. {
  23658. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  23659. }
  23660. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  23661. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  23662. Float64* outCurrentMeasureDownBeat)
  23663. {
  23664. return ((AudioUnitPluginInstance*) inHostUserData)
  23665. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  23666. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  23667. }
  23668. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23669. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23670. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  23671. {
  23672. return ((AudioUnitPluginInstance*) inHostUserData)
  23673. ->getTransportState (outIsPlaying, outTransportStateChanged,
  23674. outCurrentSampleInTimeLine, outIsCycling,
  23675. outCycleStartBeat, outCycleEndBeat);
  23676. }
  23677. void getNumChannels (int& numIns, int& numOuts)
  23678. {
  23679. numIns = 0;
  23680. numOuts = 0;
  23681. AUChannelInfo supportedChannels [128];
  23682. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  23683. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  23684. 0, supportedChannels, &supportedChannelsSize) == noErr
  23685. && supportedChannelsSize > 0)
  23686. {
  23687. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  23688. {
  23689. numIns = jmax (numIns, supportedChannels[i].inChannels);
  23690. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  23691. }
  23692. }
  23693. else
  23694. {
  23695. // (this really means the plugin will take any number of ins/outs as long
  23696. // as they are the same)
  23697. numIns = numOuts = 2;
  23698. }
  23699. }
  23700. const String getCategory() const;
  23701. AudioUnitPluginInstance (const String& fileOrIdentifier);
  23702. };
  23703. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  23704. : fileOrIdentifier (fileOrIdentifier),
  23705. initialised (false),
  23706. wantsMidiMessages (false),
  23707. audioUnit (0),
  23708. outputBufferList (0),
  23709. currentBuffer (0)
  23710. {
  23711. try
  23712. {
  23713. ++insideCallback;
  23714. log (T("Opening AU: ") + fileOrIdentifier);
  23715. if (getComponentDescFromFile (fileOrIdentifier))
  23716. {
  23717. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  23718. if (comp != 0)
  23719. {
  23720. audioUnit = (AudioUnit) OpenComponent (comp);
  23721. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  23722. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  23723. }
  23724. }
  23725. --insideCallback;
  23726. }
  23727. catch (...)
  23728. {
  23729. --insideCallback;
  23730. }
  23731. }
  23732. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  23733. {
  23734. {
  23735. const ScopedLock sl (lock);
  23736. jassert (insideCallback == 0);
  23737. if (audioUnit != 0)
  23738. {
  23739. AudioUnitUninitialize (audioUnit);
  23740. CloseComponent (audioUnit);
  23741. audioUnit = 0;
  23742. }
  23743. }
  23744. juce_free (outputBufferList);
  23745. }
  23746. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  23747. {
  23748. zerostruct (componentDesc);
  23749. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  23750. return true;
  23751. const File file (fileOrIdentifier);
  23752. if (! file.hasFileExtension (T(".component")))
  23753. return false;
  23754. const char* const utf8 = fileOrIdentifier.toUTF8();
  23755. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  23756. strlen (utf8), file.isDirectory());
  23757. if (url != 0)
  23758. {
  23759. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  23760. CFRelease (url);
  23761. if (bundleRef != 0)
  23762. {
  23763. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  23764. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  23765. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  23766. if (pluginName.isEmpty())
  23767. pluginName = file.getFileNameWithoutExtension();
  23768. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  23769. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  23770. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  23771. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  23772. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  23773. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  23774. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  23775. UseResFile (resFileId);
  23776. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  23777. {
  23778. Handle h = Get1IndResource ('thng', i);
  23779. if (h != 0)
  23780. {
  23781. HLock (h);
  23782. const uint32* const types = (const uint32*) *h;
  23783. if (types[0] == kAudioUnitType_MusicDevice
  23784. || types[0] == kAudioUnitType_MusicEffect
  23785. || types[0] == kAudioUnitType_Effect
  23786. || types[0] == kAudioUnitType_Generator
  23787. || types[0] == kAudioUnitType_Panner)
  23788. {
  23789. componentDesc.componentType = types[0];
  23790. componentDesc.componentSubType = types[1];
  23791. componentDesc.componentManufacturer = types[2];
  23792. break;
  23793. }
  23794. HUnlock (h);
  23795. ReleaseResource (h);
  23796. }
  23797. }
  23798. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  23799. CFRelease (bundleRef);
  23800. }
  23801. }
  23802. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  23803. }
  23804. void AudioUnitPluginInstance::initialise()
  23805. {
  23806. if (initialised || audioUnit == 0)
  23807. return;
  23808. log (T("Initialising AU: ") + pluginName);
  23809. parameterIds.clear();
  23810. {
  23811. UInt32 paramListSize = 0;
  23812. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23813. 0, 0, &paramListSize);
  23814. if (paramListSize > 0)
  23815. {
  23816. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  23817. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23818. 0, &parameterIds.getReference(0), &paramListSize);
  23819. }
  23820. }
  23821. {
  23822. AURenderCallbackStruct info;
  23823. zerostruct (info);
  23824. info.inputProcRefCon = this;
  23825. info.inputProc = renderGetInputCallback;
  23826. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  23827. 0, &info, sizeof (info));
  23828. }
  23829. {
  23830. HostCallbackInfo info;
  23831. zerostruct (info);
  23832. info.hostUserData = this;
  23833. info.beatAndTempoProc = getBeatAndTempoCallback;
  23834. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  23835. info.transportStateProc = getTransportStateCallback;
  23836. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  23837. 0, &info, sizeof (info));
  23838. }
  23839. int numIns, numOuts;
  23840. getNumChannels (numIns, numOuts);
  23841. setPlayConfigDetails (numIns, numOuts, 0, 0);
  23842. initialised = AudioUnitInitialize (audioUnit) == noErr;
  23843. setLatencySamples (0);
  23844. }
  23845. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  23846. int samplesPerBlockExpected)
  23847. {
  23848. initialise();
  23849. if (initialised)
  23850. {
  23851. int numIns, numOuts;
  23852. getNumChannels (numIns, numOuts);
  23853. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  23854. Float64 latencySecs = 0.0;
  23855. UInt32 latencySize = sizeof (latencySecs);
  23856. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  23857. 0, &latencySecs, &latencySize);
  23858. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  23859. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  23860. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  23861. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  23862. AudioStreamBasicDescription stream;
  23863. zerostruct (stream);
  23864. stream.mSampleRate = sampleRate_;
  23865. stream.mFormatID = kAudioFormatLinearPCM;
  23866. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  23867. stream.mFramesPerPacket = 1;
  23868. stream.mBytesPerPacket = 4;
  23869. stream.mBytesPerFrame = 4;
  23870. stream.mBitsPerChannel = 32;
  23871. stream.mChannelsPerFrame = numIns;
  23872. OSStatus err = AudioUnitSetProperty (audioUnit,
  23873. kAudioUnitProperty_StreamFormat,
  23874. kAudioUnitScope_Input,
  23875. 0, &stream, sizeof (stream));
  23876. stream.mChannelsPerFrame = numOuts;
  23877. err = AudioUnitSetProperty (audioUnit,
  23878. kAudioUnitProperty_StreamFormat,
  23879. kAudioUnitScope_Output,
  23880. 0, &stream, sizeof (stream));
  23881. juce_free (outputBufferList);
  23882. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  23883. outputBufferList->mNumberBuffers = numOuts;
  23884. for (int i = numOuts; --i >= 0;)
  23885. outputBufferList->mBuffers[i].mNumberChannels = 1;
  23886. zerostruct (timeStamp);
  23887. timeStamp.mSampleTime = 0;
  23888. timeStamp.mHostTime = AudioGetCurrentHostTime();
  23889. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  23890. currentBuffer = 0;
  23891. wasPlaying = false;
  23892. }
  23893. }
  23894. void AudioUnitPluginInstance::releaseResources()
  23895. {
  23896. if (initialised)
  23897. {
  23898. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  23899. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  23900. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  23901. juce_free (outputBufferList);
  23902. outputBufferList = 0;
  23903. currentBuffer = 0;
  23904. }
  23905. }
  23906. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23907. const AudioTimeStamp* inTimeStamp,
  23908. UInt32 inBusNumber,
  23909. UInt32 inNumberFrames,
  23910. AudioBufferList* ioData) const
  23911. {
  23912. if (inBusNumber == 0
  23913. && currentBuffer != 0)
  23914. {
  23915. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  23916. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  23917. {
  23918. if (i < currentBuffer->getNumChannels())
  23919. {
  23920. memcpy (ioData->mBuffers[i].mData,
  23921. currentBuffer->getSampleData (i, 0),
  23922. sizeof (float) * inNumberFrames);
  23923. }
  23924. else
  23925. {
  23926. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  23927. }
  23928. }
  23929. }
  23930. return noErr;
  23931. }
  23932. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  23933. MidiBuffer& midiMessages)
  23934. {
  23935. const int numSamples = buffer.getNumSamples();
  23936. if (initialised)
  23937. {
  23938. AudioUnitRenderActionFlags flags = 0;
  23939. timeStamp.mHostTime = AudioGetCurrentHostTime();
  23940. for (int i = getNumOutputChannels(); --i >= 0;)
  23941. {
  23942. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  23943. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  23944. }
  23945. currentBuffer = &buffer;
  23946. if (wantsMidiMessages)
  23947. {
  23948. const uint8* midiEventData;
  23949. int midiEventSize, midiEventPosition;
  23950. MidiBuffer::Iterator i (midiMessages);
  23951. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  23952. {
  23953. if (midiEventSize <= 3)
  23954. MusicDeviceMIDIEvent (audioUnit,
  23955. midiEventData[0], midiEventData[1], midiEventData[2],
  23956. midiEventPosition);
  23957. else
  23958. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  23959. }
  23960. midiMessages.clear();
  23961. }
  23962. AudioUnitRender (audioUnit, &flags, &timeStamp,
  23963. 0, numSamples, outputBufferList);
  23964. timeStamp.mSampleTime += numSamples;
  23965. }
  23966. else
  23967. {
  23968. // Not initialised, so just bypass..
  23969. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23970. buffer.clear (i, 0, buffer.getNumSamples());
  23971. }
  23972. }
  23973. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  23974. {
  23975. AudioPlayHead* const ph = getPlayHead();
  23976. AudioPlayHead::CurrentPositionInfo result;
  23977. if (ph != 0 && ph->getCurrentPosition (result))
  23978. {
  23979. if (outCurrentBeat != 0)
  23980. *outCurrentBeat = result.ppqPosition;
  23981. if (outCurrentTempo != 0)
  23982. *outCurrentTempo = result.bpm;
  23983. }
  23984. else
  23985. {
  23986. if (outCurrentBeat != 0)
  23987. *outCurrentBeat = 0;
  23988. if (outCurrentTempo != 0)
  23989. *outCurrentTempo = 120.0;
  23990. }
  23991. return noErr;
  23992. }
  23993. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  23994. Float32* outTimeSig_Numerator,
  23995. UInt32* outTimeSig_Denominator,
  23996. Float64* outCurrentMeasureDownBeat) const
  23997. {
  23998. AudioPlayHead* const ph = getPlayHead();
  23999. AudioPlayHead::CurrentPositionInfo result;
  24000. if (ph != 0 && ph->getCurrentPosition (result))
  24001. {
  24002. if (outTimeSig_Numerator != 0)
  24003. *outTimeSig_Numerator = result.timeSigNumerator;
  24004. if (outTimeSig_Denominator != 0)
  24005. *outTimeSig_Denominator = result.timeSigDenominator;
  24006. if (outDeltaSampleOffsetToNextBeat != 0)
  24007. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24008. if (outCurrentMeasureDownBeat != 0)
  24009. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24010. }
  24011. else
  24012. {
  24013. if (outDeltaSampleOffsetToNextBeat != 0)
  24014. *outDeltaSampleOffsetToNextBeat = 0;
  24015. if (outTimeSig_Numerator != 0)
  24016. *outTimeSig_Numerator = 4;
  24017. if (outTimeSig_Denominator != 0)
  24018. *outTimeSig_Denominator = 4;
  24019. if (outCurrentMeasureDownBeat != 0)
  24020. *outCurrentMeasureDownBeat = 0;
  24021. }
  24022. return noErr;
  24023. }
  24024. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24025. Boolean* outTransportStateChanged,
  24026. Float64* outCurrentSampleInTimeLine,
  24027. Boolean* outIsCycling,
  24028. Float64* outCycleStartBeat,
  24029. Float64* outCycleEndBeat)
  24030. {
  24031. AudioPlayHead* const ph = getPlayHead();
  24032. AudioPlayHead::CurrentPositionInfo result;
  24033. if (ph != 0 && ph->getCurrentPosition (result))
  24034. {
  24035. if (outIsPlaying != 0)
  24036. *outIsPlaying = result.isPlaying;
  24037. if (outTransportStateChanged != 0)
  24038. {
  24039. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24040. wasPlaying = result.isPlaying;
  24041. }
  24042. if (outCurrentSampleInTimeLine != 0)
  24043. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  24044. if (outIsCycling != 0)
  24045. *outIsCycling = false;
  24046. if (outCycleStartBeat != 0)
  24047. *outCycleStartBeat = 0;
  24048. if (outCycleEndBeat != 0)
  24049. *outCycleEndBeat = 0;
  24050. }
  24051. else
  24052. {
  24053. if (outIsPlaying != 0)
  24054. *outIsPlaying = false;
  24055. if (outTransportStateChanged != 0)
  24056. *outTransportStateChanged = false;
  24057. if (outCurrentSampleInTimeLine != 0)
  24058. *outCurrentSampleInTimeLine = 0;
  24059. if (outIsCycling != 0)
  24060. *outIsCycling = false;
  24061. if (outCycleStartBeat != 0)
  24062. *outCycleStartBeat = 0;
  24063. if (outCycleEndBeat != 0)
  24064. *outCycleEndBeat = 0;
  24065. }
  24066. return noErr;
  24067. }
  24068. static VoidArray activeWindows;
  24069. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24070. {
  24071. public:
  24072. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24073. : AudioProcessorEditor (&plugin_),
  24074. plugin (plugin_),
  24075. wrapper (0)
  24076. {
  24077. addAndMakeVisible (wrapper = new NSViewComponent());
  24078. activeWindows.add (this);
  24079. setOpaque (true);
  24080. setVisible (true);
  24081. setSize (100, 100);
  24082. createView (createGenericViewIfNeeded);
  24083. }
  24084. ~AudioUnitPluginWindowCocoa()
  24085. {
  24086. const bool wasValid = isValid();
  24087. wrapper->setView (0);
  24088. activeWindows.removeValue (this);
  24089. if (wasValid)
  24090. plugin.editorBeingDeleted (this);
  24091. delete wrapper;
  24092. }
  24093. bool isValid() const { return wrapper->getView() != 0; }
  24094. void paint (Graphics& g)
  24095. {
  24096. g.fillAll (Colours::white);
  24097. }
  24098. void resized()
  24099. {
  24100. wrapper->setSize (getWidth(), getHeight());
  24101. }
  24102. private:
  24103. AudioUnitPluginInstance& plugin;
  24104. NSViewComponent* wrapper;
  24105. bool createView (const bool createGenericViewIfNeeded)
  24106. {
  24107. NSView* pluginView = 0;
  24108. UInt32 dataSize = 0;
  24109. Boolean isWritable = false;
  24110. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24111. 0, &dataSize, &isWritable) == noErr
  24112. && dataSize != 0
  24113. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24114. 0, &dataSize, &isWritable) == noErr)
  24115. {
  24116. AudioUnitCocoaViewInfo* info = (AudioUnitCocoaViewInfo*) juce_calloc (dataSize);
  24117. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24118. 0, info, &dataSize) == noErr)
  24119. {
  24120. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24121. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24122. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24123. Class viewClass = [viewBundle classNamed: viewClassName];
  24124. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24125. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24126. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24127. {
  24128. id factory = [[[viewClass alloc] init] autorelease];
  24129. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24130. withSize: NSMakeSize (getWidth(), getHeight())];
  24131. }
  24132. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24133. {
  24134. CFRelease (info->mCocoaAUViewClass[i]);
  24135. CFRelease (info->mCocoaAUViewBundleLocation);
  24136. }
  24137. }
  24138. juce_free (info);
  24139. }
  24140. if (createGenericViewIfNeeded && (pluginView == 0))
  24141. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24142. wrapper->setView (pluginView);
  24143. if (pluginView != 0)
  24144. setSize ([pluginView frame].size.width,
  24145. [pluginView frame].size.height);
  24146. return pluginView != 0;
  24147. }
  24148. };
  24149. #if JUCE_SUPPORT_CARBON
  24150. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24151. {
  24152. public:
  24153. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24154. : AudioProcessorEditor (&plugin_),
  24155. plugin (plugin_),
  24156. viewComponent (0)
  24157. {
  24158. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24159. activeWindows.add (this);
  24160. setOpaque (true);
  24161. setVisible (true);
  24162. setSize (400, 300);
  24163. ComponentDescription viewList [16];
  24164. UInt32 viewListSize = sizeof (viewList);
  24165. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24166. 0, &viewList, &viewListSize);
  24167. componentRecord = FindNextComponent (0, &viewList[0]);
  24168. }
  24169. ~AudioUnitPluginWindowCarbon()
  24170. {
  24171. deleteAndZero (innerWrapper);
  24172. activeWindows.removeValue (this);
  24173. if (isValid())
  24174. plugin.editorBeingDeleted (this);
  24175. }
  24176. bool isValid() const throw() { return componentRecord != 0; }
  24177. void paint (Graphics& g)
  24178. {
  24179. g.fillAll (Colours::black);
  24180. }
  24181. void resized()
  24182. {
  24183. innerWrapper->setSize (getWidth(), getHeight());
  24184. }
  24185. bool keyStateChanged (const bool)
  24186. {
  24187. return false;
  24188. }
  24189. bool keyPressed (const KeyPress&)
  24190. {
  24191. return false;
  24192. }
  24193. void broughtToFront()
  24194. {
  24195. activeWindows.removeValue (this);
  24196. activeWindows.add (this);
  24197. }
  24198. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24199. AudioUnitCarbonView getViewComponent()
  24200. {
  24201. if (viewComponent == 0 && componentRecord != 0)
  24202. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24203. return viewComponent;
  24204. }
  24205. void closeViewComponent()
  24206. {
  24207. if (viewComponent != 0)
  24208. {
  24209. CloseComponent (viewComponent);
  24210. viewComponent = 0;
  24211. }
  24212. }
  24213. juce_UseDebuggingNewOperator
  24214. private:
  24215. AudioUnitPluginInstance& plugin;
  24216. ComponentRecord* componentRecord;
  24217. AudioUnitCarbonView viewComponent;
  24218. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24219. {
  24220. public:
  24221. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24222. : owner (owner_)
  24223. {
  24224. }
  24225. ~InnerWrapperComponent()
  24226. {
  24227. deleteWindow();
  24228. }
  24229. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24230. {
  24231. log (T("Opening AU GUI: ") + owner->plugin.getName());
  24232. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24233. if (viewComponent == 0)
  24234. return 0;
  24235. Float32Point pos = { 0, 0 };
  24236. Float32Point size = { 250, 200 };
  24237. HIViewRef pluginView = 0;
  24238. AudioUnitCarbonViewCreate (viewComponent,
  24239. owner->getAudioUnit(),
  24240. windowRef,
  24241. rootView,
  24242. &pos,
  24243. &size,
  24244. (ControlRef*) &pluginView);
  24245. return pluginView;
  24246. }
  24247. void removeView (HIViewRef)
  24248. {
  24249. log (T("Closing AU GUI: ") + owner->plugin.getName());
  24250. owner->closeViewComponent();
  24251. }
  24252. private:
  24253. AudioUnitPluginWindowCarbon* const owner;
  24254. };
  24255. friend class InnerWrapperComponent;
  24256. InnerWrapperComponent* innerWrapper;
  24257. };
  24258. #endif
  24259. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24260. {
  24261. AudioProcessorEditor* w = new AudioUnitPluginWindowCocoa (*this, false);
  24262. if (! ((AudioUnitPluginWindowCocoa*) w)->isValid())
  24263. deleteAndZero (w);
  24264. #if JUCE_SUPPORT_CARBON
  24265. if (w == 0)
  24266. {
  24267. w = new AudioUnitPluginWindowCarbon (*this);
  24268. if (! ((AudioUnitPluginWindowCarbon*) w)->isValid())
  24269. deleteAndZero (w);
  24270. }
  24271. #endif
  24272. if (w == 0)
  24273. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24274. return w;
  24275. }
  24276. const String AudioUnitPluginInstance::getCategory() const
  24277. {
  24278. const char* result = 0;
  24279. switch (componentDesc.componentType)
  24280. {
  24281. case kAudioUnitType_Effect:
  24282. case kAudioUnitType_MusicEffect:
  24283. result = "Effect";
  24284. break;
  24285. case kAudioUnitType_MusicDevice:
  24286. result = "Synth";
  24287. break;
  24288. case kAudioUnitType_Generator:
  24289. result = "Generator";
  24290. break;
  24291. case kAudioUnitType_Panner:
  24292. result = "Panner";
  24293. break;
  24294. default:
  24295. break;
  24296. }
  24297. return result;
  24298. }
  24299. int AudioUnitPluginInstance::getNumParameters()
  24300. {
  24301. return parameterIds.size();
  24302. }
  24303. float AudioUnitPluginInstance::getParameter (int index)
  24304. {
  24305. const ScopedLock sl (lock);
  24306. Float32 value = 0.0f;
  24307. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24308. {
  24309. AudioUnitGetParameter (audioUnit,
  24310. (UInt32) parameterIds.getUnchecked (index),
  24311. kAudioUnitScope_Global, 0,
  24312. &value);
  24313. }
  24314. return value;
  24315. }
  24316. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24317. {
  24318. const ScopedLock sl (lock);
  24319. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24320. {
  24321. AudioUnitSetParameter (audioUnit,
  24322. (UInt32) parameterIds.getUnchecked (index),
  24323. kAudioUnitScope_Global, 0,
  24324. newValue, 0);
  24325. }
  24326. }
  24327. const String AudioUnitPluginInstance::getParameterName (int index)
  24328. {
  24329. AudioUnitParameterInfo info;
  24330. zerostruct (info);
  24331. UInt32 sz = sizeof (info);
  24332. String name;
  24333. if (AudioUnitGetProperty (audioUnit,
  24334. kAudioUnitProperty_ParameterInfo,
  24335. kAudioUnitScope_Global,
  24336. parameterIds [index], &info, &sz) == noErr)
  24337. {
  24338. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  24339. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  24340. else
  24341. name = String (info.name, sizeof (info.name));
  24342. }
  24343. return name;
  24344. }
  24345. const String AudioUnitPluginInstance::getParameterText (int index)
  24346. {
  24347. return String (getParameter (index));
  24348. }
  24349. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  24350. {
  24351. AudioUnitParameterInfo info;
  24352. UInt32 sz = sizeof (info);
  24353. if (AudioUnitGetProperty (audioUnit,
  24354. kAudioUnitProperty_ParameterInfo,
  24355. kAudioUnitScope_Global,
  24356. parameterIds [index], &info, &sz) == noErr)
  24357. {
  24358. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  24359. }
  24360. return true;
  24361. }
  24362. int AudioUnitPluginInstance::getNumPrograms()
  24363. {
  24364. CFArrayRef presets;
  24365. UInt32 sz = sizeof (CFArrayRef);
  24366. int num = 0;
  24367. if (AudioUnitGetProperty (audioUnit,
  24368. kAudioUnitProperty_FactoryPresets,
  24369. kAudioUnitScope_Global,
  24370. 0, &presets, &sz) == noErr)
  24371. {
  24372. num = (int) CFArrayGetCount (presets);
  24373. CFRelease (presets);
  24374. }
  24375. return num;
  24376. }
  24377. int AudioUnitPluginInstance::getCurrentProgram()
  24378. {
  24379. AUPreset current;
  24380. current.presetNumber = 0;
  24381. UInt32 sz = sizeof (AUPreset);
  24382. AudioUnitGetProperty (audioUnit,
  24383. kAudioUnitProperty_FactoryPresets,
  24384. kAudioUnitScope_Global,
  24385. 0, &current, &sz);
  24386. return current.presetNumber;
  24387. }
  24388. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  24389. {
  24390. AUPreset current;
  24391. current.presetNumber = newIndex;
  24392. current.presetName = 0;
  24393. AudioUnitSetProperty (audioUnit,
  24394. kAudioUnitProperty_FactoryPresets,
  24395. kAudioUnitScope_Global,
  24396. 0, &current, sizeof (AUPreset));
  24397. }
  24398. const String AudioUnitPluginInstance::getProgramName (int index)
  24399. {
  24400. String s;
  24401. CFArrayRef presets;
  24402. UInt32 sz = sizeof (CFArrayRef);
  24403. if (AudioUnitGetProperty (audioUnit,
  24404. kAudioUnitProperty_FactoryPresets,
  24405. kAudioUnitScope_Global,
  24406. 0, &presets, &sz) == noErr)
  24407. {
  24408. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  24409. {
  24410. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  24411. if (p != 0 && p->presetNumber == index)
  24412. {
  24413. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  24414. break;
  24415. }
  24416. }
  24417. CFRelease (presets);
  24418. }
  24419. return s;
  24420. }
  24421. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  24422. {
  24423. jassertfalse // xxx not implemented!
  24424. }
  24425. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  24426. {
  24427. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  24428. return T("Input ") + String (index + 1);
  24429. return String::empty;
  24430. }
  24431. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  24432. {
  24433. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  24434. return false;
  24435. return true;
  24436. }
  24437. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  24438. {
  24439. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  24440. return T("Output ") + String (index + 1);
  24441. return String::empty;
  24442. }
  24443. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  24444. {
  24445. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  24446. return false;
  24447. return true;
  24448. }
  24449. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  24450. {
  24451. getCurrentProgramStateInformation (destData);
  24452. }
  24453. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24454. {
  24455. CFPropertyListRef propertyList = 0;
  24456. UInt32 sz = sizeof (CFPropertyListRef);
  24457. if (AudioUnitGetProperty (audioUnit,
  24458. kAudioUnitProperty_ClassInfo,
  24459. kAudioUnitScope_Global,
  24460. 0, &propertyList, &sz) == noErr)
  24461. {
  24462. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  24463. CFWriteStreamOpen (stream);
  24464. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  24465. CFWriteStreamClose (stream);
  24466. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  24467. destData.setSize (bytesWritten);
  24468. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  24469. CFRelease (data);
  24470. CFRelease (stream);
  24471. CFRelease (propertyList);
  24472. }
  24473. }
  24474. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24475. {
  24476. setCurrentProgramStateInformation (data, sizeInBytes);
  24477. }
  24478. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24479. {
  24480. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  24481. (const UInt8*) data,
  24482. sizeInBytes,
  24483. kCFAllocatorNull);
  24484. CFReadStreamOpen (stream);
  24485. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  24486. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  24487. stream,
  24488. 0,
  24489. kCFPropertyListImmutable,
  24490. &format,
  24491. 0);
  24492. CFRelease (stream);
  24493. if (propertyList != 0)
  24494. AudioUnitSetProperty (audioUnit,
  24495. kAudioUnitProperty_ClassInfo,
  24496. kAudioUnitScope_Global,
  24497. 0, &propertyList, sizeof (propertyList));
  24498. }
  24499. AudioUnitPluginFormat::AudioUnitPluginFormat()
  24500. {
  24501. }
  24502. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  24503. {
  24504. }
  24505. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24506. const String& fileOrIdentifier)
  24507. {
  24508. if (! fileMightContainThisPluginType (fileOrIdentifier))
  24509. return;
  24510. PluginDescription desc;
  24511. desc.fileOrIdentifier = fileOrIdentifier;
  24512. desc.uid = 0;
  24513. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  24514. if (instance == 0)
  24515. return;
  24516. try
  24517. {
  24518. instance->fillInPluginDescription (desc);
  24519. results.add (new PluginDescription (desc));
  24520. }
  24521. catch (...)
  24522. {
  24523. // crashed while loading...
  24524. }
  24525. deleteAndZero (instance);
  24526. }
  24527. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24528. {
  24529. AudioUnitPluginInstance* result = 0;
  24530. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  24531. {
  24532. result = new AudioUnitPluginInstance (desc.fileOrIdentifier);
  24533. if (result->audioUnit != 0)
  24534. {
  24535. result->initialise();
  24536. }
  24537. else
  24538. {
  24539. deleteAndZero (result);
  24540. }
  24541. }
  24542. return result;
  24543. }
  24544. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  24545. const bool /*recursive*/)
  24546. {
  24547. StringArray result;
  24548. ComponentRecord* comp = 0;
  24549. ComponentDescription desc;
  24550. zerostruct (desc);
  24551. for (;;)
  24552. {
  24553. zerostruct (desc);
  24554. comp = FindNextComponent (comp, &desc);
  24555. if (comp == 0)
  24556. break;
  24557. GetComponentInfo (comp, &desc, 0, 0, 0);
  24558. if (desc.componentType == kAudioUnitType_MusicDevice
  24559. || desc.componentType == kAudioUnitType_MusicEffect
  24560. || desc.componentType == kAudioUnitType_Effect
  24561. || desc.componentType == kAudioUnitType_Generator
  24562. || desc.componentType == kAudioUnitType_Panner)
  24563. {
  24564. const String s (createAUPluginIdentifier (desc));
  24565. DBG (s);
  24566. result.add (s);
  24567. }
  24568. }
  24569. return result;
  24570. }
  24571. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  24572. {
  24573. ComponentDescription desc;
  24574. String name, version, manufacturer;
  24575. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  24576. return FindNextComponent (0, &desc) != 0;
  24577. const File f (fileOrIdentifier);
  24578. return f.hasFileExtension (T(".component"))
  24579. && f.isDirectory();
  24580. }
  24581. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  24582. {
  24583. ComponentDescription desc;
  24584. String name, version, manufacturer;
  24585. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  24586. if (name.isEmpty())
  24587. name = fileOrIdentifier;
  24588. return name;
  24589. }
  24590. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  24591. {
  24592. return File (desc.fileOrIdentifier).exists();
  24593. }
  24594. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  24595. {
  24596. return FileSearchPath ("/(Default AudioUnit locations)");
  24597. }
  24598. #endif
  24599. END_JUCE_NAMESPACE
  24600. #undef log
  24601. #endif
  24602. /********* End of inlined file: juce_AudioUnitPluginFormat.mm *********/
  24603. /********* Start of inlined file: juce_VSTPluginFormat.mm *********/
  24604. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  24605. #define JUCE_MAC_VST_INCLUDED 1
  24606. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  24607. #if JUCE_PLUGINHOST_VST
  24608. #if (defined (_WIN32) || defined (_WIN64))
  24609. #undef _WIN32_WINNT
  24610. #define _WIN32_WINNT 0x500
  24611. #undef STRICT
  24612. #define STRICT
  24613. #include <windows.h>
  24614. #include <float.h>
  24615. #pragma warning (disable : 4312 4355)
  24616. #elif defined (LINUX) || defined (__linux__)
  24617. #include <float.h>
  24618. #include <sys/time.h>
  24619. #include <X11/Xlib.h>
  24620. #include <X11/Xutil.h>
  24621. #include <X11/Xatom.h>
  24622. #undef Font
  24623. #undef KeyPress
  24624. #undef Drawable
  24625. #undef Time
  24626. #else
  24627. #ifndef JUCE_MAC_VST_INCLUDED
  24628. // On the mac, this file needs to be compiled indirectly, by using
  24629. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  24630. #error
  24631. #endif
  24632. #include <Cocoa/Cocoa.h>
  24633. #include <Carbon/Carbon.h>
  24634. #endif
  24635. #if ! (JUCE_MAC && JUCE_64BIT)
  24636. BEGIN_JUCE_NAMESPACE
  24637. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24638. #endif
  24639. #undef PRAGMA_ALIGN_SUPPORTED
  24640. #define VST_FORCE_DEPRECATED 0
  24641. #ifdef _MSC_VER
  24642. #pragma warning (push)
  24643. #pragma warning (disable: 4996)
  24644. #endif
  24645. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  24646. your include path if you want to add VST support.
  24647. If you're not interested in VSTs, you can disable them by changing the
  24648. JUCE_PLUGINHOST_VST flag in juce_Config.h
  24649. */
  24650. #include "pluginterfaces/vst2.x/aeffectx.h"
  24651. #ifdef _MSC_VER
  24652. #pragma warning (pop)
  24653. #endif
  24654. #if JUCE_LINUX
  24655. #define Font JUCE_NAMESPACE::Font
  24656. #define KeyPress JUCE_NAMESPACE::KeyPress
  24657. #define Drawable JUCE_NAMESPACE::Drawable
  24658. #define Time JUCE_NAMESPACE::Time
  24659. #endif
  24660. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  24661. #ifdef __aeffect__
  24662. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24663. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24664. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  24665. events to the list.
  24666. This is used by both the VST hosting code and the plugin wrapper.
  24667. */
  24668. class VSTMidiEventList
  24669. {
  24670. public:
  24671. VSTMidiEventList()
  24672. : events (0), numEventsUsed (0), numEventsAllocated (0)
  24673. {
  24674. }
  24675. ~VSTMidiEventList()
  24676. {
  24677. freeEvents();
  24678. }
  24679. void clear()
  24680. {
  24681. numEventsUsed = 0;
  24682. if (events != 0)
  24683. events->numEvents = 0;
  24684. }
  24685. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  24686. {
  24687. ensureSize (numEventsUsed + 1);
  24688. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  24689. events->numEvents = ++numEventsUsed;
  24690. if (numBytes <= 4)
  24691. {
  24692. if (e->type == kVstSysExType)
  24693. {
  24694. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24695. e->type = kVstMidiType;
  24696. e->byteSize = sizeof (VstMidiEvent);
  24697. e->noteLength = 0;
  24698. e->noteOffset = 0;
  24699. e->detune = 0;
  24700. e->noteOffVelocity = 0;
  24701. }
  24702. e->deltaFrames = frameOffset;
  24703. memcpy (e->midiData, midiData, numBytes);
  24704. }
  24705. else
  24706. {
  24707. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  24708. if (se->type == kVstSysExType)
  24709. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  24710. else
  24711. se->sysexDump = (char*) juce_malloc (numBytes);
  24712. memcpy (se->sysexDump, midiData, numBytes);
  24713. se->type = kVstSysExType;
  24714. se->byteSize = sizeof (VstMidiSysexEvent);
  24715. se->deltaFrames = frameOffset;
  24716. se->flags = 0;
  24717. se->dumpBytes = numBytes;
  24718. se->resvd1 = 0;
  24719. se->resvd2 = 0;
  24720. }
  24721. }
  24722. // Handy method to pull the events out of an event buffer supplied by the host
  24723. // or plugin.
  24724. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  24725. {
  24726. for (int i = 0; i < events->numEvents; ++i)
  24727. {
  24728. const VstEvent* const e = events->events[i];
  24729. if (e != 0)
  24730. {
  24731. if (e->type == kVstMidiType)
  24732. {
  24733. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  24734. 4, e->deltaFrames);
  24735. }
  24736. else if (e->type == kVstSysExType)
  24737. {
  24738. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  24739. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  24740. e->deltaFrames);
  24741. }
  24742. }
  24743. }
  24744. }
  24745. void ensureSize (int numEventsNeeded)
  24746. {
  24747. if (numEventsNeeded > numEventsAllocated)
  24748. {
  24749. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  24750. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  24751. if (events == 0)
  24752. events = (VstEvents*) juce_calloc (size);
  24753. else
  24754. events = (VstEvents*) juce_realloc (events, size);
  24755. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  24756. {
  24757. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  24758. (int) sizeof (VstMidiSysexEvent)));
  24759. e->type = kVstMidiType;
  24760. e->byteSize = sizeof (VstMidiEvent);
  24761. events->events[i] = (VstEvent*) e;
  24762. }
  24763. numEventsAllocated = numEventsNeeded;
  24764. }
  24765. }
  24766. void freeEvents()
  24767. {
  24768. if (events != 0)
  24769. {
  24770. for (int i = numEventsAllocated; --i >= 0;)
  24771. {
  24772. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  24773. if (e->type == kVstSysExType)
  24774. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24775. juce_free (e);
  24776. }
  24777. juce_free (events);
  24778. events = 0;
  24779. numEventsUsed = 0;
  24780. numEventsAllocated = 0;
  24781. }
  24782. }
  24783. VstEvents* events;
  24784. private:
  24785. int numEventsUsed, numEventsAllocated;
  24786. };
  24787. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24788. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24789. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  24790. #if ! JUCE_WIN32
  24791. #define _fpreset()
  24792. #define _clearfp()
  24793. #endif
  24794. extern void juce_callAnyTimersSynchronously();
  24795. const int fxbVersionNum = 1;
  24796. struct fxProgram
  24797. {
  24798. long chunkMagic; // 'CcnK'
  24799. long byteSize; // of this chunk, excl. magic + byteSize
  24800. long fxMagic; // 'FxCk'
  24801. long version;
  24802. long fxID; // fx unique id
  24803. long fxVersion;
  24804. long numParams;
  24805. char prgName[28];
  24806. float params[1]; // variable no. of parameters
  24807. };
  24808. struct fxSet
  24809. {
  24810. long chunkMagic; // 'CcnK'
  24811. long byteSize; // of this chunk, excl. magic + byteSize
  24812. long fxMagic; // 'FxBk'
  24813. long version;
  24814. long fxID; // fx unique id
  24815. long fxVersion;
  24816. long numPrograms;
  24817. char future[128];
  24818. fxProgram programs[1]; // variable no. of programs
  24819. };
  24820. struct fxChunkSet
  24821. {
  24822. long chunkMagic; // 'CcnK'
  24823. long byteSize; // of this chunk, excl. magic + byteSize
  24824. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24825. long version;
  24826. long fxID; // fx unique id
  24827. long fxVersion;
  24828. long numPrograms;
  24829. char future[128];
  24830. long chunkSize;
  24831. char chunk[8]; // variable
  24832. };
  24833. struct fxProgramSet
  24834. {
  24835. long chunkMagic; // 'CcnK'
  24836. long byteSize; // of this chunk, excl. magic + byteSize
  24837. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24838. long version;
  24839. long fxID; // fx unique id
  24840. long fxVersion;
  24841. long numPrograms;
  24842. char name[28];
  24843. long chunkSize;
  24844. char chunk[8]; // variable
  24845. };
  24846. #ifdef JUCE_LITTLE_ENDIAN
  24847. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  24848. static float vst_swapFloat (const float x) throw()
  24849. {
  24850. union { uint32 asInt; float asFloat; } n;
  24851. n.asFloat = x;
  24852. n.asInt = swapByteOrder (n.asInt);
  24853. return n.asFloat;
  24854. }
  24855. #else
  24856. #define vst_swap(x) (x)
  24857. #define vst_swapFloat(x) (x)
  24858. #endif
  24859. typedef AEffect* (*MainCall) (audioMasterCallback);
  24860. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  24861. static int shellUIDToCreate = 0;
  24862. static int insideVSTCallback = 0;
  24863. class VSTPluginWindow;
  24864. // Change this to disable logging of various VST activities
  24865. #ifndef VST_LOGGING
  24866. #define VST_LOGGING 1
  24867. #endif
  24868. #if VST_LOGGING
  24869. #define log(a) Logger::writeToLog(a);
  24870. #else
  24871. #define log(a)
  24872. #endif
  24873. #if JUCE_MAC && JUCE_PPC
  24874. static void* NewCFMFromMachO (void* const machofp) throw()
  24875. {
  24876. void* result = juce_malloc (8);
  24877. ((void**) result)[0] = machofp;
  24878. ((void**) result)[1] = result;
  24879. return result;
  24880. }
  24881. #endif
  24882. #if JUCE_LINUX
  24883. extern Display* display;
  24884. extern XContext improbableNumber;
  24885. typedef void (*EventProcPtr) (XEvent* ev);
  24886. static bool xErrorTriggered;
  24887. static int temporaryErrorHandler (Display*, XErrorEvent*)
  24888. {
  24889. xErrorTriggered = true;
  24890. return 0;
  24891. }
  24892. static int getPropertyFromXWindow (Window handle, Atom atom)
  24893. {
  24894. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  24895. xErrorTriggered = false;
  24896. int userSize;
  24897. unsigned long bytes, userCount;
  24898. unsigned char* data;
  24899. Atom userType;
  24900. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  24901. &userType, &userSize, &userCount, &bytes, &data);
  24902. XSetErrorHandler (oldErrorHandler);
  24903. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  24904. : 0;
  24905. }
  24906. static Window getChildWindow (Window windowToCheck)
  24907. {
  24908. Window rootWindow, parentWindow;
  24909. Window* childWindows;
  24910. unsigned int numChildren;
  24911. XQueryTree (display,
  24912. windowToCheck,
  24913. &rootWindow,
  24914. &parentWindow,
  24915. &childWindows,
  24916. &numChildren);
  24917. if (numChildren > 0)
  24918. return childWindows [0];
  24919. return 0;
  24920. }
  24921. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  24922. {
  24923. if (e.mods.isLeftButtonDown())
  24924. {
  24925. ev.xbutton.button = Button1;
  24926. ev.xbutton.state |= Button1Mask;
  24927. }
  24928. else if (e.mods.isRightButtonDown())
  24929. {
  24930. ev.xbutton.button = Button3;
  24931. ev.xbutton.state |= Button3Mask;
  24932. }
  24933. else if (e.mods.isMiddleButtonDown())
  24934. {
  24935. ev.xbutton.button = Button2;
  24936. ev.xbutton.state |= Button2Mask;
  24937. }
  24938. }
  24939. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  24940. {
  24941. if (e.mods.isLeftButtonDown())
  24942. ev.xmotion.state |= Button1Mask;
  24943. else if (e.mods.isRightButtonDown())
  24944. ev.xmotion.state |= Button3Mask;
  24945. else if (e.mods.isMiddleButtonDown())
  24946. ev.xmotion.state |= Button2Mask;
  24947. }
  24948. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  24949. {
  24950. if (e.mods.isLeftButtonDown())
  24951. ev.xcrossing.state |= Button1Mask;
  24952. else if (e.mods.isRightButtonDown())
  24953. ev.xcrossing.state |= Button3Mask;
  24954. else if (e.mods.isMiddleButtonDown())
  24955. ev.xcrossing.state |= Button2Mask;
  24956. }
  24957. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  24958. {
  24959. if (increment < 0)
  24960. {
  24961. ev.xbutton.button = Button5;
  24962. ev.xbutton.state |= Button5Mask;
  24963. }
  24964. else if (increment > 0)
  24965. {
  24966. ev.xbutton.button = Button4;
  24967. ev.xbutton.state |= Button4Mask;
  24968. }
  24969. }
  24970. #endif
  24971. static VoidArray activeModules;
  24972. class ModuleHandle : public ReferenceCountedObject
  24973. {
  24974. public:
  24975. File file;
  24976. MainCall moduleMain;
  24977. String pluginName;
  24978. static ModuleHandle* findOrCreateModule (const File& file)
  24979. {
  24980. for (int i = activeModules.size(); --i >= 0;)
  24981. {
  24982. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  24983. if (module->file == file)
  24984. return module;
  24985. }
  24986. _fpreset(); // (doesn't do any harm)
  24987. ++insideVSTCallback;
  24988. shellUIDToCreate = 0;
  24989. log ("Attempting to load VST: " + file.getFullPathName());
  24990. ModuleHandle* m = new ModuleHandle (file);
  24991. if (! m->open())
  24992. deleteAndZero (m);
  24993. --insideVSTCallback;
  24994. _fpreset(); // (doesn't do any harm)
  24995. return m;
  24996. }
  24997. ModuleHandle (const File& file_)
  24998. : file (file_),
  24999. moduleMain (0),
  25000. #if JUCE_WIN32 || JUCE_LINUX
  25001. hModule (0)
  25002. #elif JUCE_MAC
  25003. fragId (0),
  25004. resHandle (0),
  25005. bundleRef (0),
  25006. resFileId (0)
  25007. #endif
  25008. {
  25009. activeModules.add (this);
  25010. #if JUCE_WIN32 || JUCE_LINUX
  25011. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25012. #elif JUCE_MAC
  25013. FSRef ref;
  25014. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25015. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25016. #endif
  25017. }
  25018. ~ModuleHandle()
  25019. {
  25020. activeModules.removeValue (this);
  25021. close();
  25022. }
  25023. juce_UseDebuggingNewOperator
  25024. #if JUCE_WIN32 || JUCE_LINUX
  25025. void* hModule;
  25026. String fullParentDirectoryPathName;
  25027. bool open()
  25028. {
  25029. #if JUCE_WIN32
  25030. static bool timePeriodSet = false;
  25031. if (! timePeriodSet)
  25032. {
  25033. timePeriodSet = true;
  25034. timeBeginPeriod (2);
  25035. }
  25036. #endif
  25037. pluginName = file.getFileNameWithoutExtension();
  25038. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25039. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25040. if (moduleMain == 0)
  25041. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25042. return moduleMain != 0;
  25043. }
  25044. void close()
  25045. {
  25046. _fpreset(); // (doesn't do any harm)
  25047. PlatformUtilities::freeDynamicLibrary (hModule);
  25048. }
  25049. void closeEffect (AEffect* eff)
  25050. {
  25051. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25052. }
  25053. #else
  25054. CFragConnectionID fragId;
  25055. Handle resHandle;
  25056. CFBundleRef bundleRef;
  25057. FSSpec parentDirFSSpec;
  25058. short resFileId;
  25059. bool open()
  25060. {
  25061. bool ok = false;
  25062. const String filename (file.getFullPathName());
  25063. if (file.hasFileExtension (T(".vst")))
  25064. {
  25065. const char* const utf8 = filename.toUTF8();
  25066. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25067. strlen (utf8), file.isDirectory());
  25068. if (url != 0)
  25069. {
  25070. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25071. CFRelease (url);
  25072. if (bundleRef != 0)
  25073. {
  25074. if (CFBundleLoadExecutable (bundleRef))
  25075. {
  25076. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25077. if (moduleMain == 0)
  25078. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25079. if (moduleMain != 0)
  25080. {
  25081. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25082. if (name != 0)
  25083. {
  25084. if (CFGetTypeID (name) == CFStringGetTypeID())
  25085. {
  25086. char buffer[1024];
  25087. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25088. pluginName = buffer;
  25089. }
  25090. }
  25091. if (pluginName.isEmpty())
  25092. pluginName = file.getFileNameWithoutExtension();
  25093. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25094. ok = true;
  25095. }
  25096. }
  25097. if (! ok)
  25098. {
  25099. CFBundleUnloadExecutable (bundleRef);
  25100. CFRelease (bundleRef);
  25101. bundleRef = 0;
  25102. }
  25103. }
  25104. }
  25105. }
  25106. #if JUCE_PPC
  25107. else
  25108. {
  25109. FSRef fn;
  25110. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  25111. {
  25112. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25113. if (resFileId != -1)
  25114. {
  25115. const int numEffs = Count1Resources ('aEff');
  25116. for (int i = 0; i < numEffs; ++i)
  25117. {
  25118. resHandle = Get1IndResource ('aEff', i + 1);
  25119. if (resHandle != 0)
  25120. {
  25121. OSType type;
  25122. Str255 name;
  25123. SInt16 id;
  25124. GetResInfo (resHandle, &id, &type, name);
  25125. pluginName = String ((const char*) name + 1, name[0]);
  25126. DetachResource (resHandle);
  25127. HLock (resHandle);
  25128. Ptr ptr;
  25129. Str255 errorText;
  25130. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25131. name, kPrivateCFragCopy,
  25132. &fragId, &ptr, errorText);
  25133. if (err == noErr)
  25134. {
  25135. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25136. ok = true;
  25137. }
  25138. else
  25139. {
  25140. HUnlock (resHandle);
  25141. }
  25142. break;
  25143. }
  25144. }
  25145. if (! ok)
  25146. CloseResFile (resFileId);
  25147. }
  25148. }
  25149. }
  25150. #endif
  25151. return ok;
  25152. }
  25153. void close()
  25154. {
  25155. #if JUCE_PPC
  25156. if (fragId != 0)
  25157. {
  25158. if (moduleMain != 0)
  25159. disposeMachOFromCFM ((void*) moduleMain);
  25160. CloseConnection (&fragId);
  25161. HUnlock (resHandle);
  25162. if (resFileId != 0)
  25163. CloseResFile (resFileId);
  25164. }
  25165. else
  25166. #endif
  25167. if (bundleRef != 0)
  25168. {
  25169. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25170. if (CFGetRetainCount (bundleRef) == 1)
  25171. CFBundleUnloadExecutable (bundleRef);
  25172. if (CFGetRetainCount (bundleRef) > 0)
  25173. CFRelease (bundleRef);
  25174. }
  25175. }
  25176. void closeEffect (AEffect* eff)
  25177. {
  25178. #if JUCE_PPC
  25179. if (fragId != 0)
  25180. {
  25181. VoidArray thingsToDelete;
  25182. thingsToDelete.add ((void*) eff->dispatcher);
  25183. thingsToDelete.add ((void*) eff->process);
  25184. thingsToDelete.add ((void*) eff->setParameter);
  25185. thingsToDelete.add ((void*) eff->getParameter);
  25186. thingsToDelete.add ((void*) eff->processReplacing);
  25187. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25188. for (int i = thingsToDelete.size(); --i >= 0;)
  25189. disposeMachOFromCFM (thingsToDelete[i]);
  25190. }
  25191. else
  25192. #endif
  25193. {
  25194. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25195. }
  25196. }
  25197. #if JUCE_PPC
  25198. static void* newMachOFromCFM (void* cfmfp)
  25199. {
  25200. if (cfmfp == 0)
  25201. return 0;
  25202. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  25203. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25204. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25205. mfp[2] = 0x800c0000;
  25206. mfp[3] = 0x804c0004;
  25207. mfp[4] = 0x7c0903a6;
  25208. mfp[5] = 0x4e800420;
  25209. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25210. return mfp;
  25211. }
  25212. static void disposeMachOFromCFM (void* ptr)
  25213. {
  25214. juce_free (ptr);
  25215. }
  25216. void coerceAEffectFunctionCalls (AEffect* eff)
  25217. {
  25218. if (fragId != 0)
  25219. {
  25220. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25221. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25222. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25223. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25224. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25225. }
  25226. }
  25227. #endif
  25228. #endif
  25229. };
  25230. /**
  25231. An instance of a plugin, created by a VSTPluginFormat.
  25232. */
  25233. class VSTPluginInstance : public AudioPluginInstance,
  25234. private Timer,
  25235. private AsyncUpdater
  25236. {
  25237. public:
  25238. ~VSTPluginInstance();
  25239. // AudioPluginInstance methods:
  25240. void fillInPluginDescription (PluginDescription& desc) const
  25241. {
  25242. desc.name = name;
  25243. desc.fileOrIdentifier = module->file.getFullPathName();
  25244. desc.uid = getUID();
  25245. desc.lastFileModTime = module->file.getLastModificationTime();
  25246. desc.pluginFormatName = "VST";
  25247. desc.category = getCategory();
  25248. {
  25249. char buffer [kVstMaxVendorStrLen + 8];
  25250. zerostruct (buffer);
  25251. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25252. desc.manufacturerName = buffer;
  25253. }
  25254. desc.version = getVersion();
  25255. desc.numInputChannels = getNumInputChannels();
  25256. desc.numOutputChannels = getNumOutputChannels();
  25257. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25258. }
  25259. const String getName() const { return name; }
  25260. int getUID() const throw();
  25261. bool acceptsMidi() const { return wantsMidiMessages; }
  25262. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25263. // AudioProcessor methods:
  25264. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25265. void releaseResources();
  25266. void processBlock (AudioSampleBuffer& buffer,
  25267. MidiBuffer& midiMessages);
  25268. AudioProcessorEditor* createEditor();
  25269. const String getInputChannelName (const int index) const;
  25270. bool isInputChannelStereoPair (int index) const;
  25271. const String getOutputChannelName (const int index) const;
  25272. bool isOutputChannelStereoPair (int index) const;
  25273. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25274. float getParameter (int index);
  25275. void setParameter (int index, float newValue);
  25276. const String getParameterName (int index);
  25277. const String getParameterText (int index);
  25278. bool isParameterAutomatable (int index) const;
  25279. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25280. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25281. void setCurrentProgram (int index);
  25282. const String getProgramName (int index);
  25283. void changeProgramName (int index, const String& newName);
  25284. void getStateInformation (MemoryBlock& destData);
  25285. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25286. void setStateInformation (const void* data, int sizeInBytes);
  25287. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25288. void timerCallback();
  25289. void handleAsyncUpdate();
  25290. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25291. juce_UseDebuggingNewOperator
  25292. private:
  25293. friend class VSTPluginWindow;
  25294. friend class VSTPluginFormat;
  25295. AEffect* effect;
  25296. String name;
  25297. CriticalSection lock;
  25298. bool wantsMidiMessages, initialised, isPowerOn;
  25299. mutable StringArray programNames;
  25300. AudioSampleBuffer tempBuffer;
  25301. CriticalSection midiInLock;
  25302. MidiBuffer incomingMidi;
  25303. VSTMidiEventList midiEventsToSend;
  25304. VstTimeInfo vstHostTime;
  25305. float** channels;
  25306. ReferenceCountedObjectPtr <ModuleHandle> module;
  25307. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25308. bool restoreProgramSettings (const fxProgram* const prog);
  25309. const String getCurrentProgramName();
  25310. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25311. void updateStoredProgramNames();
  25312. void initialise();
  25313. void handleMidiFromPlugin (const VstEvents* const events);
  25314. void createTempParameterStore (MemoryBlock& dest);
  25315. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25316. const String getParameterLabel (int index) const;
  25317. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25318. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25319. void setChunkData (const char* data, int size, bool isPreset);
  25320. bool loadFromFXBFile (const void* data, int numBytes);
  25321. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25322. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25323. const String getVersion() const throw();
  25324. const String getCategory() const throw();
  25325. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25326. void setPower (const bool on);
  25327. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25328. };
  25329. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25330. : effect (0),
  25331. wantsMidiMessages (false),
  25332. initialised (false),
  25333. isPowerOn (false),
  25334. tempBuffer (1, 1),
  25335. channels (0),
  25336. module (module_)
  25337. {
  25338. try
  25339. {
  25340. _fpreset();
  25341. ++insideVSTCallback;
  25342. name = module->pluginName;
  25343. log (T("Creating VST instance: ") + name);
  25344. #if JUCE_MAC
  25345. if (module->resFileId != 0)
  25346. UseResFile (module->resFileId);
  25347. #if JUCE_PPC
  25348. if (module->fragId != 0)
  25349. {
  25350. static void* audioMasterCoerced = 0;
  25351. if (audioMasterCoerced == 0)
  25352. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  25353. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  25354. }
  25355. else
  25356. #endif
  25357. #endif
  25358. {
  25359. effect = module->moduleMain (&audioMaster);
  25360. }
  25361. --insideVSTCallback;
  25362. if (effect != 0 && effect->magic == kEffectMagic)
  25363. {
  25364. #if JUCE_PPC
  25365. module->coerceAEffectFunctionCalls (effect);
  25366. #endif
  25367. jassert (effect->resvd2 == 0);
  25368. jassert (effect->object != 0);
  25369. _fpreset(); // some dodgy plugs fuck around with this
  25370. }
  25371. else
  25372. {
  25373. effect = 0;
  25374. }
  25375. }
  25376. catch (...)
  25377. {
  25378. --insideVSTCallback;
  25379. }
  25380. }
  25381. VSTPluginInstance::~VSTPluginInstance()
  25382. {
  25383. {
  25384. const ScopedLock sl (lock);
  25385. jassert (insideVSTCallback == 0);
  25386. if (effect != 0 && effect->magic == kEffectMagic)
  25387. {
  25388. try
  25389. {
  25390. #if JUCE_MAC
  25391. if (module->resFileId != 0)
  25392. UseResFile (module->resFileId);
  25393. #endif
  25394. // Must delete any editors before deleting the plugin instance!
  25395. jassert (getActiveEditor() == 0);
  25396. _fpreset(); // some dodgy plugs fuck around with this
  25397. module->closeEffect (effect);
  25398. }
  25399. catch (...)
  25400. {}
  25401. }
  25402. module = 0;
  25403. effect = 0;
  25404. }
  25405. juce_free (channels);
  25406. channels = 0;
  25407. }
  25408. void VSTPluginInstance::initialise()
  25409. {
  25410. if (initialised || effect == 0)
  25411. return;
  25412. log (T("Initialising VST: ") + module->pluginName);
  25413. initialised = true;
  25414. dispatch (effIdentify, 0, 0, 0, 0);
  25415. // this code would ask the plugin for its name, but so few plugins
  25416. // actually bother implementing this correctly, that it's better to
  25417. // just ignore it and use the file name instead.
  25418. /* {
  25419. char buffer [256];
  25420. zerostruct (buffer);
  25421. dispatch (effGetEffectName, 0, 0, buffer, 0);
  25422. name = String (buffer).trim();
  25423. if (name.isEmpty())
  25424. name = module->pluginName;
  25425. }
  25426. */
  25427. if (getSampleRate() > 0)
  25428. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  25429. if (getBlockSize() > 0)
  25430. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  25431. dispatch (effOpen, 0, 0, 0, 0);
  25432. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25433. getSampleRate(), getBlockSize());
  25434. if (getNumPrograms() > 1)
  25435. setCurrentProgram (0);
  25436. else
  25437. dispatch (effSetProgram, 0, 0, 0, 0);
  25438. int i;
  25439. for (i = effect->numInputs; --i >= 0;)
  25440. dispatch (effConnectInput, i, 1, 0, 0);
  25441. for (i = effect->numOutputs; --i >= 0;)
  25442. dispatch (effConnectOutput, i, 1, 0, 0);
  25443. updateStoredProgramNames();
  25444. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  25445. setLatencySamples (effect->initialDelay);
  25446. }
  25447. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  25448. int samplesPerBlockExpected)
  25449. {
  25450. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25451. sampleRate_, samplesPerBlockExpected);
  25452. setLatencySamples (effect->initialDelay);
  25453. juce_free (channels);
  25454. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  25455. vstHostTime.tempo = 120.0;
  25456. vstHostTime.timeSigNumerator = 4;
  25457. vstHostTime.timeSigDenominator = 4;
  25458. vstHostTime.sampleRate = sampleRate_;
  25459. vstHostTime.samplePos = 0;
  25460. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  25461. initialise();
  25462. if (initialised)
  25463. {
  25464. wantsMidiMessages = wantsMidiMessages
  25465. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  25466. if (wantsMidiMessages)
  25467. midiEventsToSend.ensureSize (256);
  25468. else
  25469. midiEventsToSend.freeEvents();
  25470. incomingMidi.clear();
  25471. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  25472. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  25473. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  25474. if (! isPowerOn)
  25475. setPower (true);
  25476. // dodgy hack to force some plugins to initialise the sample rate..
  25477. if ((! hasEditor()) && getNumParameters() > 0)
  25478. {
  25479. const float old = getParameter (0);
  25480. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  25481. setParameter (0, old);
  25482. }
  25483. dispatch (effStartProcess, 0, 0, 0, 0);
  25484. }
  25485. }
  25486. void VSTPluginInstance::releaseResources()
  25487. {
  25488. if (initialised)
  25489. {
  25490. dispatch (effStopProcess, 0, 0, 0, 0);
  25491. setPower (false);
  25492. }
  25493. tempBuffer.setSize (1, 1);
  25494. incomingMidi.clear();
  25495. midiEventsToSend.freeEvents();
  25496. juce_free (channels);
  25497. channels = 0;
  25498. }
  25499. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25500. MidiBuffer& midiMessages)
  25501. {
  25502. const int numSamples = buffer.getNumSamples();
  25503. if (initialised)
  25504. {
  25505. AudioPlayHead* playHead = getPlayHead();
  25506. if (playHead != 0)
  25507. {
  25508. AudioPlayHead::CurrentPositionInfo position;
  25509. playHead->getCurrentPosition (position);
  25510. vstHostTime.tempo = position.bpm;
  25511. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  25512. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  25513. vstHostTime.ppqPos = position.ppqPosition;
  25514. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  25515. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  25516. if (position.isPlaying)
  25517. vstHostTime.flags |= kVstTransportPlaying;
  25518. else
  25519. vstHostTime.flags &= ~kVstTransportPlaying;
  25520. }
  25521. #if JUCE_WIN32
  25522. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  25523. #elif JUCE_LINUX
  25524. timeval micro;
  25525. gettimeofday (&micro, 0);
  25526. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  25527. #elif JUCE_MAC
  25528. UnsignedWide micro;
  25529. Microseconds (&micro);
  25530. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  25531. #endif
  25532. if (wantsMidiMessages)
  25533. {
  25534. midiEventsToSend.clear();
  25535. midiEventsToSend.ensureSize (1);
  25536. MidiBuffer::Iterator iter (midiMessages);
  25537. const uint8* midiData;
  25538. int numBytesOfMidiData, samplePosition;
  25539. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  25540. {
  25541. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  25542. jlimit (0, numSamples - 1, samplePosition));
  25543. }
  25544. try
  25545. {
  25546. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  25547. }
  25548. catch (...)
  25549. {}
  25550. }
  25551. int i;
  25552. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  25553. for (i = 0; i < maxChans; ++i)
  25554. channels[i] = buffer.getSampleData (i);
  25555. channels [maxChans] = 0;
  25556. _clearfp();
  25557. if ((effect->flags & effFlagsCanReplacing) != 0)
  25558. {
  25559. try
  25560. {
  25561. effect->processReplacing (effect, channels, channels, numSamples);
  25562. }
  25563. catch (...)
  25564. {}
  25565. }
  25566. else
  25567. {
  25568. tempBuffer.setSize (effect->numOutputs, numSamples);
  25569. tempBuffer.clear();
  25570. float* outs [64];
  25571. for (i = effect->numOutputs; --i >= 0;)
  25572. outs[i] = tempBuffer.getSampleData (i);
  25573. outs [effect->numOutputs] = 0;
  25574. try
  25575. {
  25576. effect->process (effect, channels, outs, numSamples);
  25577. }
  25578. catch (...)
  25579. {}
  25580. for (i = effect->numOutputs; --i >= 0;)
  25581. buffer.copyFrom (i, 0, outs[i], numSamples);
  25582. }
  25583. }
  25584. else
  25585. {
  25586. // Not initialised, so just bypass..
  25587. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25588. buffer.clear (i, 0, buffer.getNumSamples());
  25589. }
  25590. {
  25591. // copy any incoming midi..
  25592. const ScopedLock sl (midiInLock);
  25593. midiMessages = incomingMidi;
  25594. incomingMidi.clear();
  25595. }
  25596. }
  25597. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  25598. {
  25599. if (events != 0)
  25600. {
  25601. const ScopedLock sl (midiInLock);
  25602. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  25603. }
  25604. }
  25605. static Array <VSTPluginWindow*> activeVSTWindows;
  25606. class VSTPluginWindow : public AudioProcessorEditor,
  25607. #if ! JUCE_MAC
  25608. public ComponentMovementWatcher,
  25609. #endif
  25610. public Timer
  25611. {
  25612. public:
  25613. VSTPluginWindow (VSTPluginInstance& plugin_)
  25614. : AudioProcessorEditor (&plugin_),
  25615. #if ! JUCE_MAC
  25616. ComponentMovementWatcher (this),
  25617. #endif
  25618. plugin (plugin_),
  25619. isOpen (false),
  25620. wasShowing (false),
  25621. pluginRefusesToResize (false),
  25622. pluginWantsKeys (false),
  25623. alreadyInside (false),
  25624. recursiveResize (false)
  25625. {
  25626. #if JUCE_WIN32
  25627. sizeCheckCount = 0;
  25628. pluginHWND = 0;
  25629. #elif JUCE_LINUX
  25630. pluginWindow = None;
  25631. pluginProc = None;
  25632. #else
  25633. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25634. #endif
  25635. activeVSTWindows.add (this);
  25636. setSize (1, 1);
  25637. setOpaque (true);
  25638. setVisible (true);
  25639. }
  25640. ~VSTPluginWindow()
  25641. {
  25642. #if JUCE_MAC
  25643. deleteAndZero (innerWrapper);
  25644. #else
  25645. closePluginWindow();
  25646. #endif
  25647. activeVSTWindows.removeValue (this);
  25648. plugin.editorBeingDeleted (this);
  25649. }
  25650. #if ! JUCE_MAC
  25651. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  25652. {
  25653. if (recursiveResize)
  25654. return;
  25655. Component* const topComp = getTopLevelComponent();
  25656. if (topComp->getPeer() != 0)
  25657. {
  25658. int x = 0, y = 0;
  25659. relativePositionToOtherComponent (topComp, x, y);
  25660. recursiveResize = true;
  25661. #if JUCE_WIN32
  25662. if (pluginHWND != 0)
  25663. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  25664. #elif JUCE_LINUX
  25665. if (pluginWindow != 0)
  25666. {
  25667. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  25668. XMoveWindow (display, pluginWindow, x, y);
  25669. XMapRaised (display, pluginWindow);
  25670. }
  25671. #endif
  25672. recursiveResize = false;
  25673. }
  25674. }
  25675. void componentVisibilityChanged (Component&)
  25676. {
  25677. const bool isShowingNow = isShowing();
  25678. if (wasShowing != isShowingNow)
  25679. {
  25680. wasShowing = isShowingNow;
  25681. if (isShowingNow)
  25682. openPluginWindow();
  25683. else
  25684. closePluginWindow();
  25685. }
  25686. componentMovedOrResized (true, true);
  25687. }
  25688. void componentPeerChanged()
  25689. {
  25690. closePluginWindow();
  25691. openPluginWindow();
  25692. }
  25693. #endif
  25694. bool keyStateChanged (const bool)
  25695. {
  25696. return pluginWantsKeys;
  25697. }
  25698. bool keyPressed (const KeyPress&)
  25699. {
  25700. return pluginWantsKeys;
  25701. }
  25702. #if JUCE_MAC
  25703. void paint (Graphics& g)
  25704. {
  25705. g.fillAll (Colours::black);
  25706. }
  25707. #else
  25708. void paint (Graphics& g)
  25709. {
  25710. if (isOpen)
  25711. {
  25712. ComponentPeer* const peer = getPeer();
  25713. if (peer != 0)
  25714. {
  25715. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  25716. getScreenY() - peer->getScreenY(),
  25717. getWidth(), getHeight());
  25718. #if JUCE_LINUX
  25719. if (pluginWindow != 0)
  25720. {
  25721. const Rectangle clip (g.getClipBounds());
  25722. XEvent ev;
  25723. zerostruct (ev);
  25724. ev.xexpose.type = Expose;
  25725. ev.xexpose.display = display;
  25726. ev.xexpose.window = pluginWindow;
  25727. ev.xexpose.x = clip.getX();
  25728. ev.xexpose.y = clip.getY();
  25729. ev.xexpose.width = clip.getWidth();
  25730. ev.xexpose.height = clip.getHeight();
  25731. sendEventToChild (&ev);
  25732. }
  25733. #endif
  25734. }
  25735. }
  25736. else
  25737. {
  25738. g.fillAll (Colours::black);
  25739. }
  25740. }
  25741. #endif
  25742. void timerCallback()
  25743. {
  25744. #if JUCE_WIN32
  25745. if (--sizeCheckCount <= 0)
  25746. {
  25747. sizeCheckCount = 10;
  25748. checkPluginWindowSize();
  25749. }
  25750. #endif
  25751. try
  25752. {
  25753. static bool reentrant = false;
  25754. if (! reentrant)
  25755. {
  25756. reentrant = true;
  25757. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  25758. reentrant = false;
  25759. }
  25760. }
  25761. catch (...)
  25762. {}
  25763. }
  25764. void mouseDown (const MouseEvent& e)
  25765. {
  25766. #if JUCE_LINUX
  25767. if (pluginWindow == 0)
  25768. return;
  25769. toFront (true);
  25770. XEvent ev;
  25771. zerostruct (ev);
  25772. ev.xbutton.display = display;
  25773. ev.xbutton.type = ButtonPress;
  25774. ev.xbutton.window = pluginWindow;
  25775. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  25776. ev.xbutton.time = CurrentTime;
  25777. ev.xbutton.x = e.x;
  25778. ev.xbutton.y = e.y;
  25779. ev.xbutton.x_root = e.getScreenX();
  25780. ev.xbutton.y_root = e.getScreenY();
  25781. translateJuceToXButtonModifiers (e, ev);
  25782. sendEventToChild (&ev);
  25783. #elif JUCE_WIN32
  25784. (void) e;
  25785. toFront (true);
  25786. #endif
  25787. }
  25788. void broughtToFront()
  25789. {
  25790. activeVSTWindows.removeValue (this);
  25791. activeVSTWindows.add (this);
  25792. #if JUCE_MAC
  25793. dispatch (effEditTop, 0, 0, 0, 0);
  25794. #endif
  25795. }
  25796. juce_UseDebuggingNewOperator
  25797. private:
  25798. VSTPluginInstance& plugin;
  25799. bool isOpen, wasShowing, recursiveResize;
  25800. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  25801. #if JUCE_WIN32
  25802. HWND pluginHWND;
  25803. void* originalWndProc;
  25804. int sizeCheckCount;
  25805. #elif JUCE_LINUX
  25806. Window pluginWindow;
  25807. EventProcPtr pluginProc;
  25808. #endif
  25809. #if JUCE_MAC
  25810. void openPluginWindow (WindowRef parentWindow)
  25811. {
  25812. if (isOpen || parentWindow == 0)
  25813. return;
  25814. isOpen = true;
  25815. ERect* rect = 0;
  25816. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25817. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  25818. // do this before and after like in the steinberg example
  25819. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25820. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25821. // Install keyboard hooks
  25822. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25823. // double-check it's not too tiny
  25824. int w = 250, h = 150;
  25825. if (rect != 0)
  25826. {
  25827. w = rect->right - rect->left;
  25828. h = rect->bottom - rect->top;
  25829. if (w == 0 || h == 0)
  25830. {
  25831. w = 250;
  25832. h = 150;
  25833. }
  25834. }
  25835. w = jmax (w, 32);
  25836. h = jmax (h, 32);
  25837. setSize (w, h);
  25838. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25839. repaint();
  25840. }
  25841. #else
  25842. void openPluginWindow()
  25843. {
  25844. if (isOpen || getWindowHandle() == 0)
  25845. return;
  25846. log (T("Opening VST UI: ") + plugin.name);
  25847. isOpen = true;
  25848. ERect* rect = 0;
  25849. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25850. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  25851. // do this before and after like in the steinberg example
  25852. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25853. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25854. // Install keyboard hooks
  25855. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25856. #if JUCE_WIN32
  25857. originalWndProc = 0;
  25858. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  25859. if (pluginHWND == 0)
  25860. {
  25861. isOpen = false;
  25862. setSize (300, 150);
  25863. return;
  25864. }
  25865. #pragma warning (push)
  25866. #pragma warning (disable: 4244)
  25867. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  25868. if (! pluginWantsKeys)
  25869. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  25870. #pragma warning (pop)
  25871. int w, h;
  25872. RECT r;
  25873. GetWindowRect (pluginHWND, &r);
  25874. w = r.right - r.left;
  25875. h = r.bottom - r.top;
  25876. if (rect != 0)
  25877. {
  25878. const int rw = rect->right - rect->left;
  25879. const int rh = rect->bottom - rect->top;
  25880. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  25881. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  25882. {
  25883. // very dodgy logic to decide which size is right.
  25884. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  25885. {
  25886. SetWindowPos (pluginHWND, 0,
  25887. 0, 0, rw, rh,
  25888. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  25889. GetWindowRect (pluginHWND, &r);
  25890. w = r.right - r.left;
  25891. h = r.bottom - r.top;
  25892. pluginRefusesToResize = (w != rw) || (h != rh);
  25893. w = rw;
  25894. h = rh;
  25895. }
  25896. }
  25897. }
  25898. #elif JUCE_LINUX
  25899. pluginWindow = getChildWindow ((Window) getWindowHandle());
  25900. if (pluginWindow != 0)
  25901. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  25902. XInternAtom (display, "_XEventProc", False));
  25903. int w = 250, h = 150;
  25904. if (rect != 0)
  25905. {
  25906. w = rect->right - rect->left;
  25907. h = rect->bottom - rect->top;
  25908. if (w == 0 || h == 0)
  25909. {
  25910. w = 250;
  25911. h = 150;
  25912. }
  25913. }
  25914. if (pluginWindow != 0)
  25915. XMapRaised (display, pluginWindow);
  25916. #endif
  25917. // double-check it's not too tiny
  25918. w = jmax (w, 32);
  25919. h = jmax (h, 32);
  25920. setSize (w, h);
  25921. #if JUCE_WIN32
  25922. checkPluginWindowSize();
  25923. #endif
  25924. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25925. repaint();
  25926. }
  25927. #endif
  25928. #if ! JUCE_MAC
  25929. void closePluginWindow()
  25930. {
  25931. if (isOpen)
  25932. {
  25933. log (T("Closing VST UI: ") + plugin.getName());
  25934. isOpen = false;
  25935. dispatch (effEditClose, 0, 0, 0, 0);
  25936. #if JUCE_WIN32
  25937. #pragma warning (push)
  25938. #pragma warning (disable: 4244)
  25939. if (pluginHWND != 0 && IsWindow (pluginHWND))
  25940. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  25941. #pragma warning (pop)
  25942. stopTimer();
  25943. if (pluginHWND != 0 && IsWindow (pluginHWND))
  25944. DestroyWindow (pluginHWND);
  25945. pluginHWND = 0;
  25946. #elif JUCE_LINUX
  25947. stopTimer();
  25948. pluginWindow = 0;
  25949. pluginProc = 0;
  25950. #endif
  25951. }
  25952. }
  25953. #endif
  25954. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  25955. {
  25956. return plugin.dispatch (opcode, index, value, ptr, opt);
  25957. }
  25958. #if JUCE_WIN32
  25959. void checkPluginWindowSize() throw()
  25960. {
  25961. RECT r;
  25962. GetWindowRect (pluginHWND, &r);
  25963. const int w = r.right - r.left;
  25964. const int h = r.bottom - r.top;
  25965. if (isShowing() && w > 0 && h > 0
  25966. && (w != getWidth() || h != getHeight())
  25967. && ! pluginRefusesToResize)
  25968. {
  25969. setSize (w, h);
  25970. sizeCheckCount = 0;
  25971. }
  25972. }
  25973. // hooks to get keyboard events from VST windows..
  25974. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  25975. {
  25976. for (int i = activeVSTWindows.size(); --i >= 0;)
  25977. {
  25978. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  25979. if (w->pluginHWND == hW)
  25980. {
  25981. if (message == WM_CHAR
  25982. || message == WM_KEYDOWN
  25983. || message == WM_SYSKEYDOWN
  25984. || message == WM_KEYUP
  25985. || message == WM_SYSKEYUP
  25986. || message == WM_APPCOMMAND)
  25987. {
  25988. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  25989. message, wParam, lParam);
  25990. }
  25991. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  25992. (HWND) w->pluginHWND,
  25993. message,
  25994. wParam,
  25995. lParam);
  25996. }
  25997. }
  25998. return DefWindowProc (hW, message, wParam, lParam);
  25999. }
  26000. #endif
  26001. #if JUCE_LINUX
  26002. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26003. void sendEventToChild (XEvent* event)
  26004. {
  26005. if (pluginProc != 0)
  26006. {
  26007. // if the plugin publishes an event procedure, pass the event directly..
  26008. pluginProc (event);
  26009. }
  26010. else if (pluginWindow != 0)
  26011. {
  26012. // if the plugin has a window, then send the event to the window so that
  26013. // its message thread will pick it up..
  26014. XSendEvent (display, pluginWindow, False, 0L, event);
  26015. XFlush (display);
  26016. }
  26017. }
  26018. void mouseEnter (const MouseEvent& e)
  26019. {
  26020. if (pluginWindow != 0)
  26021. {
  26022. XEvent ev;
  26023. zerostruct (ev);
  26024. ev.xcrossing.display = display;
  26025. ev.xcrossing.type = EnterNotify;
  26026. ev.xcrossing.window = pluginWindow;
  26027. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26028. ev.xcrossing.time = CurrentTime;
  26029. ev.xcrossing.x = e.x;
  26030. ev.xcrossing.y = e.y;
  26031. ev.xcrossing.x_root = e.getScreenX();
  26032. ev.xcrossing.y_root = e.getScreenY();
  26033. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26034. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26035. translateJuceToXCrossingModifiers (e, ev);
  26036. sendEventToChild (&ev);
  26037. }
  26038. }
  26039. void mouseExit (const MouseEvent& e)
  26040. {
  26041. if (pluginWindow != 0)
  26042. {
  26043. XEvent ev;
  26044. zerostruct (ev);
  26045. ev.xcrossing.display = display;
  26046. ev.xcrossing.type = LeaveNotify;
  26047. ev.xcrossing.window = pluginWindow;
  26048. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26049. ev.xcrossing.time = CurrentTime;
  26050. ev.xcrossing.x = e.x;
  26051. ev.xcrossing.y = e.y;
  26052. ev.xcrossing.x_root = e.getScreenX();
  26053. ev.xcrossing.y_root = e.getScreenY();
  26054. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26055. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26056. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26057. translateJuceToXCrossingModifiers (e, ev);
  26058. sendEventToChild (&ev);
  26059. }
  26060. }
  26061. void mouseMove (const MouseEvent& e)
  26062. {
  26063. if (pluginWindow != 0)
  26064. {
  26065. XEvent ev;
  26066. zerostruct (ev);
  26067. ev.xmotion.display = display;
  26068. ev.xmotion.type = MotionNotify;
  26069. ev.xmotion.window = pluginWindow;
  26070. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26071. ev.xmotion.time = CurrentTime;
  26072. ev.xmotion.is_hint = NotifyNormal;
  26073. ev.xmotion.x = e.x;
  26074. ev.xmotion.y = e.y;
  26075. ev.xmotion.x_root = e.getScreenX();
  26076. ev.xmotion.y_root = e.getScreenY();
  26077. sendEventToChild (&ev);
  26078. }
  26079. }
  26080. void mouseDrag (const MouseEvent& e)
  26081. {
  26082. if (pluginWindow != 0)
  26083. {
  26084. XEvent ev;
  26085. zerostruct (ev);
  26086. ev.xmotion.display = display;
  26087. ev.xmotion.type = MotionNotify;
  26088. ev.xmotion.window = pluginWindow;
  26089. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26090. ev.xmotion.time = CurrentTime;
  26091. ev.xmotion.x = e.x ;
  26092. ev.xmotion.y = e.y;
  26093. ev.xmotion.x_root = e.getScreenX();
  26094. ev.xmotion.y_root = e.getScreenY();
  26095. ev.xmotion.is_hint = NotifyNormal;
  26096. translateJuceToXMotionModifiers (e, ev);
  26097. sendEventToChild (&ev);
  26098. }
  26099. }
  26100. void mouseUp (const MouseEvent& e)
  26101. {
  26102. if (pluginWindow != 0)
  26103. {
  26104. XEvent ev;
  26105. zerostruct (ev);
  26106. ev.xbutton.display = display;
  26107. ev.xbutton.type = ButtonRelease;
  26108. ev.xbutton.window = pluginWindow;
  26109. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26110. ev.xbutton.time = CurrentTime;
  26111. ev.xbutton.x = e.x;
  26112. ev.xbutton.y = e.y;
  26113. ev.xbutton.x_root = e.getScreenX();
  26114. ev.xbutton.y_root = e.getScreenY();
  26115. translateJuceToXButtonModifiers (e, ev);
  26116. sendEventToChild (&ev);
  26117. }
  26118. }
  26119. void mouseWheelMove (const MouseEvent& e,
  26120. float incrementX,
  26121. float incrementY)
  26122. {
  26123. if (pluginWindow != 0)
  26124. {
  26125. XEvent ev;
  26126. zerostruct (ev);
  26127. ev.xbutton.display = display;
  26128. ev.xbutton.type = ButtonPress;
  26129. ev.xbutton.window = pluginWindow;
  26130. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26131. ev.xbutton.time = CurrentTime;
  26132. ev.xbutton.x = e.x;
  26133. ev.xbutton.y = e.y;
  26134. ev.xbutton.x_root = e.getScreenX();
  26135. ev.xbutton.y_root = e.getScreenY();
  26136. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26137. sendEventToChild (&ev);
  26138. // TODO - put a usleep here ?
  26139. ev.xbutton.type = ButtonRelease;
  26140. sendEventToChild (&ev);
  26141. }
  26142. }
  26143. #endif
  26144. #if JUCE_MAC
  26145. #if ! JUCE_SUPPORT_CARBON
  26146. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26147. #endif
  26148. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26149. {
  26150. public:
  26151. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26152. : owner (owner_),
  26153. alreadyInside (false)
  26154. {
  26155. }
  26156. ~InnerWrapperComponent()
  26157. {
  26158. deleteWindow();
  26159. }
  26160. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26161. {
  26162. owner->openPluginWindow (windowRef);
  26163. return 0;
  26164. }
  26165. void removeView (HIViewRef)
  26166. {
  26167. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26168. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26169. }
  26170. bool getEmbeddedViewSize (int& w, int& h)
  26171. {
  26172. ERect* rect = 0;
  26173. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26174. w = rect->right - rect->left;
  26175. h = rect->bottom - rect->top;
  26176. return true;
  26177. }
  26178. void mouseDown (int x, int y)
  26179. {
  26180. if (! alreadyInside)
  26181. {
  26182. alreadyInside = true;
  26183. getTopLevelComponent()->toFront (true);
  26184. owner->dispatch (effEditMouse, x, y, 0, 0);
  26185. alreadyInside = false;
  26186. }
  26187. else
  26188. {
  26189. PostEvent (::mouseDown, 0);
  26190. }
  26191. }
  26192. void paint()
  26193. {
  26194. ComponentPeer* const peer = getPeer();
  26195. if (peer != 0)
  26196. {
  26197. ERect r;
  26198. r.left = getScreenX() - peer->getScreenX();
  26199. r.right = r.left + getWidth();
  26200. r.top = getScreenY() - peer->getScreenY();
  26201. r.bottom = r.top + getHeight();
  26202. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26203. }
  26204. }
  26205. private:
  26206. VSTPluginWindow* const owner;
  26207. bool alreadyInside;
  26208. };
  26209. friend class InnerWrapperComponent;
  26210. InnerWrapperComponent* innerWrapper;
  26211. void resized()
  26212. {
  26213. innerWrapper->setSize (getWidth(), getHeight());
  26214. }
  26215. #endif
  26216. };
  26217. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26218. {
  26219. if (hasEditor())
  26220. return new VSTPluginWindow (*this);
  26221. return 0;
  26222. }
  26223. void VSTPluginInstance::handleAsyncUpdate()
  26224. {
  26225. // indicates that something about the plugin has changed..
  26226. updateHostDisplay();
  26227. }
  26228. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26229. {
  26230. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26231. {
  26232. changeProgramName (getCurrentProgram(), prog->prgName);
  26233. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26234. setParameter (i, vst_swapFloat (prog->params[i]));
  26235. return true;
  26236. }
  26237. return false;
  26238. }
  26239. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26240. const int dataSize)
  26241. {
  26242. if (dataSize < 28)
  26243. return false;
  26244. const fxSet* const set = (const fxSet*) data;
  26245. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26246. || vst_swap (set->version) > fxbVersionNum)
  26247. return false;
  26248. if (vst_swap (set->fxMagic) == 'FxBk')
  26249. {
  26250. // bank of programs
  26251. if (vst_swap (set->numPrograms) >= 0)
  26252. {
  26253. const int oldProg = getCurrentProgram();
  26254. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26255. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26256. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26257. {
  26258. if (i != oldProg)
  26259. {
  26260. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26261. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26262. return false;
  26263. if (vst_swap (set->numPrograms) > 0)
  26264. setCurrentProgram (i);
  26265. if (! restoreProgramSettings (prog))
  26266. return false;
  26267. }
  26268. }
  26269. if (vst_swap (set->numPrograms) > 0)
  26270. setCurrentProgram (oldProg);
  26271. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26272. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26273. return false;
  26274. if (! restoreProgramSettings (prog))
  26275. return false;
  26276. }
  26277. }
  26278. else if (vst_swap (set->fxMagic) == 'FxCk')
  26279. {
  26280. // single program
  26281. const fxProgram* const prog = (const fxProgram*) data;
  26282. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26283. return false;
  26284. changeProgramName (getCurrentProgram(), prog->prgName);
  26285. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26286. setParameter (i, vst_swapFloat (prog->params[i]));
  26287. }
  26288. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26289. {
  26290. // non-preset chunk
  26291. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26292. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26293. return false;
  26294. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26295. }
  26296. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26297. {
  26298. // preset chunk
  26299. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26300. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26301. return false;
  26302. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26303. changeProgramName (getCurrentProgram(), cset->name);
  26304. }
  26305. else
  26306. {
  26307. return false;
  26308. }
  26309. return true;
  26310. }
  26311. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26312. {
  26313. const int numParams = getNumParameters();
  26314. prog->chunkMagic = vst_swap ('CcnK');
  26315. prog->byteSize = 0;
  26316. prog->fxMagic = vst_swap ('FxCk');
  26317. prog->version = vst_swap (fxbVersionNum);
  26318. prog->fxID = vst_swap (getUID());
  26319. prog->fxVersion = vst_swap (getVersionNumber());
  26320. prog->numParams = vst_swap (numParams);
  26321. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  26322. for (int i = 0; i < numParams; ++i)
  26323. prog->params[i] = vst_swapFloat (getParameter (i));
  26324. }
  26325. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26326. {
  26327. const int numPrograms = getNumPrograms();
  26328. const int numParams = getNumParameters();
  26329. if (usesChunks())
  26330. {
  26331. if (isFXB)
  26332. {
  26333. MemoryBlock chunk;
  26334. getChunkData (chunk, false, maxSizeMB);
  26335. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26336. dest.setSize (totalLen, true);
  26337. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  26338. set->chunkMagic = vst_swap ('CcnK');
  26339. set->byteSize = 0;
  26340. set->fxMagic = vst_swap ('FBCh');
  26341. set->version = vst_swap (fxbVersionNum);
  26342. set->fxID = vst_swap (getUID());
  26343. set->fxVersion = vst_swap (getVersionNumber());
  26344. set->numPrograms = vst_swap (numPrograms);
  26345. set->chunkSize = vst_swap (chunk.getSize());
  26346. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26347. }
  26348. else
  26349. {
  26350. MemoryBlock chunk;
  26351. getChunkData (chunk, true, maxSizeMB);
  26352. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  26353. dest.setSize (totalLen, true);
  26354. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  26355. set->chunkMagic = vst_swap ('CcnK');
  26356. set->byteSize = 0;
  26357. set->fxMagic = vst_swap ('FPCh');
  26358. set->version = vst_swap (fxbVersionNum);
  26359. set->fxID = vst_swap (getUID());
  26360. set->fxVersion = vst_swap (getVersionNumber());
  26361. set->numPrograms = vst_swap (numPrograms);
  26362. set->chunkSize = vst_swap (chunk.getSize());
  26363. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  26364. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26365. }
  26366. }
  26367. else
  26368. {
  26369. if (isFXB)
  26370. {
  26371. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26372. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  26373. dest.setSize (len, true);
  26374. fxSet* const set = (fxSet*) dest.getData();
  26375. set->chunkMagic = vst_swap ('CcnK');
  26376. set->byteSize = 0;
  26377. set->fxMagic = vst_swap ('FxBk');
  26378. set->version = vst_swap (fxbVersionNum);
  26379. set->fxID = vst_swap (getUID());
  26380. set->fxVersion = vst_swap (getVersionNumber());
  26381. set->numPrograms = vst_swap (numPrograms);
  26382. const int oldProgram = getCurrentProgram();
  26383. MemoryBlock oldSettings;
  26384. createTempParameterStore (oldSettings);
  26385. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  26386. for (int i = 0; i < numPrograms; ++i)
  26387. {
  26388. if (i != oldProgram)
  26389. {
  26390. setCurrentProgram (i);
  26391. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  26392. }
  26393. }
  26394. setCurrentProgram (oldProgram);
  26395. restoreFromTempParameterStore (oldSettings);
  26396. }
  26397. else
  26398. {
  26399. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26400. dest.setSize (totalLen, true);
  26401. setParamsInProgramBlock ((fxProgram*) dest.getData());
  26402. }
  26403. }
  26404. return true;
  26405. }
  26406. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  26407. {
  26408. if (usesChunks())
  26409. {
  26410. void* data = 0;
  26411. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  26412. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  26413. {
  26414. mb.setSize (bytes);
  26415. mb.copyFrom (data, 0, bytes);
  26416. }
  26417. }
  26418. }
  26419. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  26420. {
  26421. if (size > 0 && usesChunks())
  26422. {
  26423. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  26424. if (! isPreset)
  26425. updateStoredProgramNames();
  26426. }
  26427. }
  26428. void VSTPluginInstance::timerCallback()
  26429. {
  26430. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  26431. stopTimer();
  26432. }
  26433. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  26434. {
  26435. const ScopedLock sl (lock);
  26436. ++insideVSTCallback;
  26437. int result = 0;
  26438. try
  26439. {
  26440. if (effect != 0)
  26441. {
  26442. #if JUCE_MAC
  26443. if (module->resFileId != 0)
  26444. UseResFile (module->resFileId);
  26445. CGrafPtr oldPort;
  26446. if (getActiveEditor() != 0)
  26447. {
  26448. int x = 0, y = 0;
  26449. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  26450. GetPort (&oldPort);
  26451. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  26452. SetOrigin (-x, -y);
  26453. }
  26454. #endif
  26455. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  26456. #if JUCE_MAC
  26457. if (getActiveEditor() != 0)
  26458. SetPort (oldPort);
  26459. module->resFileId = CurResFile();
  26460. #endif
  26461. --insideVSTCallback;
  26462. return result;
  26463. }
  26464. }
  26465. catch (...)
  26466. {
  26467. //char s[512];
  26468. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  26469. }
  26470. --insideVSTCallback;
  26471. return result;
  26472. }
  26473. // handles non plugin-specific callbacks..
  26474. static const int defaultVSTSampleRateValue = 16384;
  26475. static const int defaultVSTBlockSizeValue = 512;
  26476. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26477. {
  26478. (void) index;
  26479. (void) value;
  26480. (void) opt;
  26481. switch (opcode)
  26482. {
  26483. case audioMasterCanDo:
  26484. {
  26485. static const char* canDos[] = { "supplyIdle",
  26486. "sendVstEvents",
  26487. "sendVstMidiEvent",
  26488. "sendVstTimeInfo",
  26489. "receiveVstEvents",
  26490. "receiveVstMidiEvent",
  26491. "supportShell",
  26492. "shellCategory" };
  26493. for (int i = 0; i < numElementsInArray (canDos); ++i)
  26494. if (strcmp (canDos[i], (const char*) ptr) == 0)
  26495. return 1;
  26496. return 0;
  26497. }
  26498. case audioMasterVersion:
  26499. return 0x2400;
  26500. case audioMasterCurrentId:
  26501. return shellUIDToCreate;
  26502. case audioMasterGetNumAutomatableParameters:
  26503. return 0;
  26504. case audioMasterGetAutomationState:
  26505. return 1;
  26506. case audioMasterGetVendorVersion:
  26507. return 0x0101;
  26508. case audioMasterGetVendorString:
  26509. case audioMasterGetProductString:
  26510. {
  26511. String hostName ("Juce VST Host");
  26512. if (JUCEApplication::getInstance() != 0)
  26513. hostName = JUCEApplication::getInstance()->getApplicationName();
  26514. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  26515. }
  26516. break;
  26517. case audioMasterGetSampleRate:
  26518. return (VstIntPtr) defaultVSTSampleRateValue;
  26519. case audioMasterGetBlockSize:
  26520. return (VstIntPtr) defaultVSTBlockSizeValue;
  26521. case audioMasterSetOutputSampleRate:
  26522. return 0;
  26523. default:
  26524. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  26525. break;
  26526. }
  26527. return 0;
  26528. }
  26529. // handles callbacks for a specific plugin
  26530. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26531. {
  26532. switch (opcode)
  26533. {
  26534. case audioMasterAutomate:
  26535. sendParamChangeMessageToListeners (index, opt);
  26536. break;
  26537. case audioMasterProcessEvents:
  26538. handleMidiFromPlugin ((const VstEvents*) ptr);
  26539. break;
  26540. case audioMasterGetTime:
  26541. #ifdef _MSC_VER
  26542. #pragma warning (push)
  26543. #pragma warning (disable: 4311)
  26544. #endif
  26545. return (VstIntPtr) &vstHostTime;
  26546. #ifdef _MSC_VER
  26547. #pragma warning (pop)
  26548. #endif
  26549. break;
  26550. case audioMasterIdle:
  26551. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  26552. {
  26553. ++insideVSTCallback;
  26554. #if JUCE_MAC
  26555. if (getActiveEditor() != 0)
  26556. dispatch (effEditIdle, 0, 0, 0, 0);
  26557. #endif
  26558. juce_callAnyTimersSynchronously();
  26559. handleUpdateNowIfNeeded();
  26560. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  26561. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  26562. --insideVSTCallback;
  26563. }
  26564. break;
  26565. case audioMasterUpdateDisplay:
  26566. triggerAsyncUpdate();
  26567. break;
  26568. case audioMasterTempoAt:
  26569. // returns (10000 * bpm)
  26570. break;
  26571. case audioMasterNeedIdle:
  26572. startTimer (50);
  26573. break;
  26574. case audioMasterSizeWindow:
  26575. if (getActiveEditor() != 0)
  26576. getActiveEditor()->setSize (index, value);
  26577. return 1;
  26578. case audioMasterGetSampleRate:
  26579. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  26580. case audioMasterGetBlockSize:
  26581. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  26582. case audioMasterWantMidi:
  26583. wantsMidiMessages = true;
  26584. break;
  26585. case audioMasterGetDirectory:
  26586. #if JUCE_MAC
  26587. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  26588. #else
  26589. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  26590. #endif
  26591. case audioMasterGetAutomationState:
  26592. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  26593. break;
  26594. // none of these are handled (yet)..
  26595. case audioMasterBeginEdit:
  26596. case audioMasterEndEdit:
  26597. case audioMasterSetTime:
  26598. case audioMasterPinConnected:
  26599. case audioMasterGetParameterQuantization:
  26600. case audioMasterIOChanged:
  26601. case audioMasterGetInputLatency:
  26602. case audioMasterGetOutputLatency:
  26603. case audioMasterGetPreviousPlug:
  26604. case audioMasterGetNextPlug:
  26605. case audioMasterWillReplaceOrAccumulate:
  26606. case audioMasterGetCurrentProcessLevel:
  26607. case audioMasterOfflineStart:
  26608. case audioMasterOfflineRead:
  26609. case audioMasterOfflineWrite:
  26610. case audioMasterOfflineGetCurrentPass:
  26611. case audioMasterOfflineGetCurrentMetaPass:
  26612. case audioMasterVendorSpecific:
  26613. case audioMasterSetIcon:
  26614. case audioMasterGetLanguage:
  26615. case audioMasterOpenWindow:
  26616. case audioMasterCloseWindow:
  26617. break;
  26618. default:
  26619. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26620. }
  26621. return 0;
  26622. }
  26623. // entry point for all callbacks from the plugin
  26624. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  26625. {
  26626. try
  26627. {
  26628. if (effect != 0 && effect->resvd2 != 0)
  26629. {
  26630. return ((VSTPluginInstance*)(effect->resvd2))
  26631. ->handleCallback (opcode, index, value, ptr, opt);
  26632. }
  26633. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26634. }
  26635. catch (...)
  26636. {
  26637. return 0;
  26638. }
  26639. }
  26640. const String VSTPluginInstance::getVersion() const throw()
  26641. {
  26642. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  26643. String s;
  26644. if (v == 0 || v == -1)
  26645. v = getVersionNumber();
  26646. if (v != 0)
  26647. {
  26648. int versionBits[4];
  26649. int n = 0;
  26650. while (v != 0)
  26651. {
  26652. versionBits [n++] = (v & 0xff);
  26653. v >>= 8;
  26654. }
  26655. s << 'V';
  26656. while (n > 0)
  26657. {
  26658. s << versionBits [--n];
  26659. if (n > 0)
  26660. s << '.';
  26661. }
  26662. }
  26663. return s;
  26664. }
  26665. int VSTPluginInstance::getUID() const throw()
  26666. {
  26667. int uid = effect != 0 ? effect->uniqueID : 0;
  26668. if (uid == 0)
  26669. uid = module->file.hashCode();
  26670. return uid;
  26671. }
  26672. const String VSTPluginInstance::getCategory() const throw()
  26673. {
  26674. const char* result = 0;
  26675. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  26676. {
  26677. case kPlugCategEffect:
  26678. result = "Effect";
  26679. break;
  26680. case kPlugCategSynth:
  26681. result = "Synth";
  26682. break;
  26683. case kPlugCategAnalysis:
  26684. result = "Anaylsis";
  26685. break;
  26686. case kPlugCategMastering:
  26687. result = "Mastering";
  26688. break;
  26689. case kPlugCategSpacializer:
  26690. result = "Spacial";
  26691. break;
  26692. case kPlugCategRoomFx:
  26693. result = "Reverb";
  26694. break;
  26695. case kPlugSurroundFx:
  26696. result = "Surround";
  26697. break;
  26698. case kPlugCategRestoration:
  26699. result = "Restoration";
  26700. break;
  26701. case kPlugCategGenerator:
  26702. result = "Tone generation";
  26703. break;
  26704. default:
  26705. break;
  26706. }
  26707. return result;
  26708. }
  26709. float VSTPluginInstance::getParameter (int index)
  26710. {
  26711. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26712. {
  26713. try
  26714. {
  26715. const ScopedLock sl (lock);
  26716. return effect->getParameter (effect, index);
  26717. }
  26718. catch (...)
  26719. {
  26720. }
  26721. }
  26722. return 0.0f;
  26723. }
  26724. void VSTPluginInstance::setParameter (int index, float newValue)
  26725. {
  26726. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26727. {
  26728. try
  26729. {
  26730. const ScopedLock sl (lock);
  26731. if (effect->getParameter (effect, index) != newValue)
  26732. effect->setParameter (effect, index, newValue);
  26733. }
  26734. catch (...)
  26735. {
  26736. }
  26737. }
  26738. }
  26739. const String VSTPluginInstance::getParameterName (int index)
  26740. {
  26741. if (effect != 0)
  26742. {
  26743. jassert (index >= 0 && index < effect->numParams);
  26744. char nm [256];
  26745. zerostruct (nm);
  26746. dispatch (effGetParamName, index, 0, nm, 0);
  26747. return String (nm).trim();
  26748. }
  26749. return String::empty;
  26750. }
  26751. const String VSTPluginInstance::getParameterLabel (int index) const
  26752. {
  26753. if (effect != 0)
  26754. {
  26755. jassert (index >= 0 && index < effect->numParams);
  26756. char nm [256];
  26757. zerostruct (nm);
  26758. dispatch (effGetParamLabel, index, 0, nm, 0);
  26759. return String (nm).trim();
  26760. }
  26761. return String::empty;
  26762. }
  26763. const String VSTPluginInstance::getParameterText (int index)
  26764. {
  26765. if (effect != 0)
  26766. {
  26767. jassert (index >= 0 && index < effect->numParams);
  26768. char nm [256];
  26769. zerostruct (nm);
  26770. dispatch (effGetParamDisplay, index, 0, nm, 0);
  26771. return String (nm).trim();
  26772. }
  26773. return String::empty;
  26774. }
  26775. bool VSTPluginInstance::isParameterAutomatable (int index) const
  26776. {
  26777. if (effect != 0)
  26778. {
  26779. jassert (index >= 0 && index < effect->numParams);
  26780. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  26781. }
  26782. return false;
  26783. }
  26784. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  26785. {
  26786. dest.setSize (64 + 4 * getNumParameters());
  26787. dest.fillWith (0);
  26788. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  26789. float* const p = (float*) (((char*) dest.getData()) + 64);
  26790. for (int i = 0; i < getNumParameters(); ++i)
  26791. p[i] = getParameter(i);
  26792. }
  26793. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  26794. {
  26795. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  26796. float* p = (float*) (((char*) m.getData()) + 64);
  26797. for (int i = 0; i < getNumParameters(); ++i)
  26798. setParameter (i, p[i]);
  26799. }
  26800. void VSTPluginInstance::setCurrentProgram (int newIndex)
  26801. {
  26802. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  26803. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  26804. }
  26805. const String VSTPluginInstance::getProgramName (int index)
  26806. {
  26807. if (index == getCurrentProgram())
  26808. {
  26809. return getCurrentProgramName();
  26810. }
  26811. else if (effect != 0)
  26812. {
  26813. char nm [256];
  26814. zerostruct (nm);
  26815. if (dispatch (effGetProgramNameIndexed,
  26816. jlimit (0, getNumPrograms(), index),
  26817. -1, nm, 0) != 0)
  26818. {
  26819. return String (nm).trim();
  26820. }
  26821. }
  26822. return programNames [index];
  26823. }
  26824. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  26825. {
  26826. if (index == getCurrentProgram())
  26827. {
  26828. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  26829. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  26830. }
  26831. else
  26832. {
  26833. jassertfalse // xxx not implemented!
  26834. }
  26835. }
  26836. void VSTPluginInstance::updateStoredProgramNames()
  26837. {
  26838. if (effect != 0 && getNumPrograms() > 0)
  26839. {
  26840. char nm [256];
  26841. zerostruct (nm);
  26842. // only do this if the plugin can't use indexed names..
  26843. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  26844. {
  26845. const int oldProgram = getCurrentProgram();
  26846. MemoryBlock oldSettings;
  26847. createTempParameterStore (oldSettings);
  26848. for (int i = 0; i < getNumPrograms(); ++i)
  26849. {
  26850. setCurrentProgram (i);
  26851. getCurrentProgramName(); // (this updates the list)
  26852. }
  26853. setCurrentProgram (oldProgram);
  26854. restoreFromTempParameterStore (oldSettings);
  26855. }
  26856. }
  26857. }
  26858. const String VSTPluginInstance::getCurrentProgramName()
  26859. {
  26860. if (effect != 0)
  26861. {
  26862. char nm [256];
  26863. zerostruct (nm);
  26864. dispatch (effGetProgramName, 0, 0, nm, 0);
  26865. const int index = getCurrentProgram();
  26866. if (programNames[index].isEmpty())
  26867. {
  26868. while (programNames.size() < index)
  26869. programNames.add (String::empty);
  26870. programNames.set (index, String (nm).trim());
  26871. }
  26872. return String (nm).trim();
  26873. }
  26874. return String::empty;
  26875. }
  26876. const String VSTPluginInstance::getInputChannelName (const int index) const
  26877. {
  26878. if (index >= 0 && index < getNumInputChannels())
  26879. {
  26880. VstPinProperties pinProps;
  26881. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  26882. return String (pinProps.label, sizeof (pinProps.label));
  26883. }
  26884. return String::empty;
  26885. }
  26886. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  26887. {
  26888. if (index < 0 || index >= getNumInputChannels())
  26889. return false;
  26890. VstPinProperties pinProps;
  26891. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  26892. return (pinProps.flags & kVstPinIsStereo) != 0;
  26893. return true;
  26894. }
  26895. const String VSTPluginInstance::getOutputChannelName (const int index) const
  26896. {
  26897. if (index >= 0 && index < getNumOutputChannels())
  26898. {
  26899. VstPinProperties pinProps;
  26900. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  26901. return String (pinProps.label, sizeof (pinProps.label));
  26902. }
  26903. return String::empty;
  26904. }
  26905. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  26906. {
  26907. if (index < 0 || index >= getNumOutputChannels())
  26908. return false;
  26909. VstPinProperties pinProps;
  26910. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  26911. return (pinProps.flags & kVstPinIsStereo) != 0;
  26912. return true;
  26913. }
  26914. void VSTPluginInstance::setPower (const bool on)
  26915. {
  26916. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  26917. isPowerOn = on;
  26918. }
  26919. const int defaultMaxSizeMB = 64;
  26920. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  26921. {
  26922. saveToFXBFile (destData, true, defaultMaxSizeMB);
  26923. }
  26924. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26925. {
  26926. saveToFXBFile (destData, false, defaultMaxSizeMB);
  26927. }
  26928. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26929. {
  26930. loadFromFXBFile (data, sizeInBytes);
  26931. }
  26932. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26933. {
  26934. loadFromFXBFile (data, sizeInBytes);
  26935. }
  26936. VSTPluginFormat::VSTPluginFormat()
  26937. {
  26938. }
  26939. VSTPluginFormat::~VSTPluginFormat()
  26940. {
  26941. }
  26942. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26943. const String& fileOrIdentifier)
  26944. {
  26945. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26946. return;
  26947. PluginDescription desc;
  26948. desc.fileOrIdentifier = fileOrIdentifier;
  26949. desc.uid = 0;
  26950. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  26951. if (instance == 0)
  26952. return;
  26953. try
  26954. {
  26955. #if JUCE_MAC
  26956. if (instance->module->resFileId != 0)
  26957. UseResFile (instance->module->resFileId);
  26958. #endif
  26959. instance->fillInPluginDescription (desc);
  26960. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  26961. if (category != kPlugCategShell)
  26962. {
  26963. // Normal plugin...
  26964. results.add (new PluginDescription (desc));
  26965. ++insideVSTCallback;
  26966. instance->dispatch (effOpen, 0, 0, 0, 0);
  26967. --insideVSTCallback;
  26968. }
  26969. else
  26970. {
  26971. // It's a shell plugin, so iterate all the subtypes...
  26972. char shellEffectName [64];
  26973. for (;;)
  26974. {
  26975. zerostruct (shellEffectName);
  26976. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  26977. if (uid == 0)
  26978. {
  26979. break;
  26980. }
  26981. else
  26982. {
  26983. desc.uid = uid;
  26984. desc.name = shellEffectName;
  26985. bool alreadyThere = false;
  26986. for (int i = results.size(); --i >= 0;)
  26987. {
  26988. PluginDescription* const d = results.getUnchecked(i);
  26989. if (d->isDuplicateOf (desc))
  26990. {
  26991. alreadyThere = true;
  26992. break;
  26993. }
  26994. }
  26995. if (! alreadyThere)
  26996. results.add (new PluginDescription (desc));
  26997. }
  26998. }
  26999. }
  27000. }
  27001. catch (...)
  27002. {
  27003. // crashed while loading...
  27004. }
  27005. deleteAndZero (instance);
  27006. }
  27007. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27008. {
  27009. VSTPluginInstance* result = 0;
  27010. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27011. {
  27012. File file (desc.fileOrIdentifier);
  27013. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27014. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27015. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27016. if (module != 0)
  27017. {
  27018. shellUIDToCreate = desc.uid;
  27019. result = new VSTPluginInstance (module);
  27020. if (result->effect != 0)
  27021. {
  27022. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  27023. result->initialise();
  27024. }
  27025. else
  27026. {
  27027. deleteAndZero (result);
  27028. }
  27029. }
  27030. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27031. }
  27032. return result;
  27033. }
  27034. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27035. {
  27036. const File f (fileOrIdentifier);
  27037. #if JUCE_MAC
  27038. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  27039. return true;
  27040. #if JUCE_PPC
  27041. FSRef fileRef;
  27042. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27043. {
  27044. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27045. if (resFileId != -1)
  27046. {
  27047. const int numEffects = Count1Resources ('aEff');
  27048. CloseResFile (resFileId);
  27049. if (numEffects > 0)
  27050. return true;
  27051. }
  27052. }
  27053. #endif
  27054. return false;
  27055. #elif JUCE_WIN32
  27056. return f.existsAsFile()
  27057. && f.hasFileExtension (T(".dll"));
  27058. #elif JUCE_LINUX
  27059. return f.existsAsFile()
  27060. && f.hasFileExtension (T(".so"));
  27061. #endif
  27062. }
  27063. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27064. {
  27065. return fileOrIdentifier;
  27066. }
  27067. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27068. {
  27069. return File (desc.fileOrIdentifier).exists();
  27070. }
  27071. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27072. {
  27073. StringArray results;
  27074. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27075. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27076. return results;
  27077. }
  27078. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27079. {
  27080. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27081. // .component or .vst directories.
  27082. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27083. while (iter.next())
  27084. {
  27085. const File f (iter.getFile());
  27086. bool isPlugin = false;
  27087. if (fileMightContainThisPluginType (f.getFullPathName()))
  27088. {
  27089. isPlugin = true;
  27090. results.add (f.getFullPathName());
  27091. }
  27092. if (recursive && (! isPlugin) && f.isDirectory())
  27093. recursiveFileSearch (results, f, true);
  27094. }
  27095. }
  27096. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27097. {
  27098. #if JUCE_MAC
  27099. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27100. #elif JUCE_WIN32
  27101. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27102. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27103. #elif JUCE_LINUX
  27104. return FileSearchPath ("/usr/lib/vst");
  27105. #endif
  27106. }
  27107. END_JUCE_NAMESPACE
  27108. #endif
  27109. #undef log
  27110. #endif
  27111. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  27112. /********* End of inlined file: juce_VSTPluginFormat.mm *********/
  27113. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  27114. BEGIN_JUCE_NAMESPACE
  27115. AudioProcessor::AudioProcessor()
  27116. : playHead (0),
  27117. activeEditor (0),
  27118. sampleRate (0),
  27119. blockSize (0),
  27120. numInputChannels (0),
  27121. numOutputChannels (0),
  27122. latencySamples (0),
  27123. suspended (false),
  27124. nonRealtime (false)
  27125. {
  27126. }
  27127. AudioProcessor::~AudioProcessor()
  27128. {
  27129. // ooh, nasty - the editor should have been deleted before the filter
  27130. // that it refers to is deleted..
  27131. jassert (activeEditor == 0);
  27132. #ifdef JUCE_DEBUG
  27133. // This will fail if you've called beginParameterChangeGesture() for one
  27134. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27135. jassert (changingParams.countNumberOfSetBits() == 0);
  27136. #endif
  27137. }
  27138. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27139. {
  27140. playHead = newPlayHead;
  27141. }
  27142. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27143. {
  27144. const ScopedLock sl (listenerLock);
  27145. listeners.addIfNotAlreadyThere (newListener);
  27146. }
  27147. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27148. {
  27149. const ScopedLock sl (listenerLock);
  27150. listeners.removeValue (listenerToRemove);
  27151. }
  27152. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27153. const int numOuts,
  27154. const double sampleRate_,
  27155. const int blockSize_) throw()
  27156. {
  27157. numInputChannels = numIns;
  27158. numOutputChannels = numOuts;
  27159. sampleRate = sampleRate_;
  27160. blockSize = blockSize_;
  27161. }
  27162. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27163. {
  27164. nonRealtime = nonRealtime_;
  27165. }
  27166. void AudioProcessor::setLatencySamples (const int newLatency)
  27167. {
  27168. if (latencySamples != newLatency)
  27169. {
  27170. latencySamples = newLatency;
  27171. updateHostDisplay();
  27172. }
  27173. }
  27174. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27175. const float newValue)
  27176. {
  27177. setParameter (parameterIndex, newValue);
  27178. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27179. }
  27180. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27181. {
  27182. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27183. for (int i = listeners.size(); --i >= 0;)
  27184. {
  27185. listenerLock.enter();
  27186. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27187. listenerLock.exit();
  27188. if (l != 0)
  27189. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27190. }
  27191. }
  27192. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27193. {
  27194. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27195. #ifdef JUCE_DEBUG
  27196. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27197. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27198. jassert (! changingParams [parameterIndex]);
  27199. changingParams.setBit (parameterIndex);
  27200. #endif
  27201. for (int i = listeners.size(); --i >= 0;)
  27202. {
  27203. listenerLock.enter();
  27204. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27205. listenerLock.exit();
  27206. if (l != 0)
  27207. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27208. }
  27209. }
  27210. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27211. {
  27212. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27213. #ifdef JUCE_DEBUG
  27214. // This means you've called endParameterChangeGesture without having previously called
  27215. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27216. // calls matched correctly.
  27217. jassert (changingParams [parameterIndex]);
  27218. changingParams.clearBit (parameterIndex);
  27219. #endif
  27220. for (int i = listeners.size(); --i >= 0;)
  27221. {
  27222. listenerLock.enter();
  27223. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27224. listenerLock.exit();
  27225. if (l != 0)
  27226. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27227. }
  27228. }
  27229. void AudioProcessor::updateHostDisplay()
  27230. {
  27231. for (int i = listeners.size(); --i >= 0;)
  27232. {
  27233. listenerLock.enter();
  27234. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27235. listenerLock.exit();
  27236. if (l != 0)
  27237. l->audioProcessorChanged (this);
  27238. }
  27239. }
  27240. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27241. {
  27242. return true;
  27243. }
  27244. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27245. {
  27246. return false;
  27247. }
  27248. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27249. {
  27250. const ScopedLock sl (callbackLock);
  27251. suspended = shouldBeSuspended;
  27252. }
  27253. void AudioProcessor::reset()
  27254. {
  27255. }
  27256. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27257. {
  27258. const ScopedLock sl (callbackLock);
  27259. jassert (activeEditor == editor);
  27260. if (activeEditor == editor)
  27261. activeEditor = 0;
  27262. }
  27263. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27264. {
  27265. if (activeEditor != 0)
  27266. return activeEditor;
  27267. AudioProcessorEditor* const ed = createEditor();
  27268. if (ed != 0)
  27269. {
  27270. // you must give your editor comp a size before returning it..
  27271. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27272. const ScopedLock sl (callbackLock);
  27273. activeEditor = ed;
  27274. }
  27275. return ed;
  27276. }
  27277. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27278. {
  27279. getStateInformation (destData);
  27280. }
  27281. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27282. {
  27283. setStateInformation (data, sizeInBytes);
  27284. }
  27285. // magic number to identify memory blocks that we've stored as XML
  27286. const uint32 magicXmlNumber = 0x21324356;
  27287. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27288. JUCE_NAMESPACE::MemoryBlock& destData)
  27289. {
  27290. const String xmlString (xml.createDocument (String::empty, true, false));
  27291. const int stringLength = xmlString.length();
  27292. destData.setSize (stringLength + 10);
  27293. char* const d = (char*) destData.getData();
  27294. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  27295. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  27296. xmlString.copyToBuffer (d + 8, stringLength);
  27297. }
  27298. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27299. const int sizeInBytes)
  27300. {
  27301. if (sizeInBytes > 8
  27302. && littleEndianInt ((const char*) data) == magicXmlNumber)
  27303. {
  27304. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  27305. if (stringLength > 0)
  27306. {
  27307. XmlDocument doc (String (((const char*) data) + 8,
  27308. jmin ((sizeInBytes - 8), stringLength)));
  27309. return doc.getDocumentElement();
  27310. }
  27311. }
  27312. return 0;
  27313. }
  27314. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27315. {
  27316. }
  27317. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27318. {
  27319. }
  27320. END_JUCE_NAMESPACE
  27321. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  27322. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  27323. BEGIN_JUCE_NAMESPACE
  27324. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  27325. : owner (owner_)
  27326. {
  27327. // the filter must be valid..
  27328. jassert (owner != 0);
  27329. }
  27330. AudioProcessorEditor::~AudioProcessorEditor()
  27331. {
  27332. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  27333. // filter for some reason..
  27334. jassert (owner->getActiveEditor() != this);
  27335. }
  27336. END_JUCE_NAMESPACE
  27337. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  27338. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  27339. BEGIN_JUCE_NAMESPACE
  27340. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  27341. AudioProcessorGraph::Node::Node (const uint32 id_,
  27342. AudioProcessor* const processor_) throw()
  27343. : id (id_),
  27344. processor (processor_),
  27345. isPrepared (false)
  27346. {
  27347. jassert (processor_ != 0);
  27348. }
  27349. AudioProcessorGraph::Node::~Node()
  27350. {
  27351. delete processor;
  27352. }
  27353. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  27354. AudioProcessorGraph* const graph)
  27355. {
  27356. if (! isPrepared)
  27357. {
  27358. isPrepared = true;
  27359. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27360. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  27361. if (ioProc != 0)
  27362. ioProc->setParentGraph (graph);
  27363. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  27364. processor->getNumOutputChannels(),
  27365. sampleRate, blockSize);
  27366. processor->prepareToPlay (sampleRate, blockSize);
  27367. }
  27368. }
  27369. void AudioProcessorGraph::Node::unprepare()
  27370. {
  27371. if (isPrepared)
  27372. {
  27373. isPrepared = false;
  27374. processor->releaseResources();
  27375. }
  27376. }
  27377. AudioProcessorGraph::AudioProcessorGraph()
  27378. : lastNodeId (0),
  27379. renderingBuffers (1, 1),
  27380. currentAudioOutputBuffer (1, 1)
  27381. {
  27382. }
  27383. AudioProcessorGraph::~AudioProcessorGraph()
  27384. {
  27385. clearRenderingSequence();
  27386. clear();
  27387. }
  27388. const String AudioProcessorGraph::getName() const
  27389. {
  27390. return "Audio Graph";
  27391. }
  27392. void AudioProcessorGraph::clear()
  27393. {
  27394. nodes.clear();
  27395. connections.clear();
  27396. triggerAsyncUpdate();
  27397. }
  27398. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  27399. {
  27400. for (int i = nodes.size(); --i >= 0;)
  27401. if (nodes.getUnchecked(i)->id == nodeId)
  27402. return nodes.getUnchecked(i);
  27403. return 0;
  27404. }
  27405. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  27406. uint32 nodeId)
  27407. {
  27408. if (newProcessor == 0)
  27409. {
  27410. jassertfalse
  27411. return 0;
  27412. }
  27413. if (nodeId == 0)
  27414. {
  27415. nodeId = ++lastNodeId;
  27416. }
  27417. else
  27418. {
  27419. // you can't add a node with an id that already exists in the graph..
  27420. jassert (getNodeForId (nodeId) == 0);
  27421. removeNode (nodeId);
  27422. }
  27423. lastNodeId = nodeId;
  27424. Node* const n = new Node (nodeId, newProcessor);
  27425. nodes.add (n);
  27426. triggerAsyncUpdate();
  27427. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27428. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  27429. if (ioProc != 0)
  27430. ioProc->setParentGraph (this);
  27431. return n;
  27432. }
  27433. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  27434. {
  27435. disconnectNode (nodeId);
  27436. for (int i = nodes.size(); --i >= 0;)
  27437. {
  27438. if (nodes.getUnchecked(i)->id == nodeId)
  27439. {
  27440. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27441. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  27442. if (ioProc != 0)
  27443. ioProc->setParentGraph (0);
  27444. nodes.remove (i);
  27445. triggerAsyncUpdate();
  27446. return true;
  27447. }
  27448. }
  27449. return false;
  27450. }
  27451. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  27452. const int sourceChannelIndex,
  27453. const uint32 destNodeId,
  27454. const int destChannelIndex) const throw()
  27455. {
  27456. for (int i = connections.size(); --i >= 0;)
  27457. {
  27458. const Connection* const c = connections.getUnchecked(i);
  27459. if (c->sourceNodeId == sourceNodeId
  27460. && c->destNodeId == destNodeId
  27461. && c->sourceChannelIndex == sourceChannelIndex
  27462. && c->destChannelIndex == destChannelIndex)
  27463. {
  27464. return c;
  27465. }
  27466. }
  27467. return 0;
  27468. }
  27469. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  27470. const uint32 possibleDestNodeId) const throw()
  27471. {
  27472. for (int i = connections.size(); --i >= 0;)
  27473. {
  27474. const Connection* const c = connections.getUnchecked(i);
  27475. if (c->sourceNodeId == possibleSourceNodeId
  27476. && c->destNodeId == possibleDestNodeId)
  27477. {
  27478. return true;
  27479. }
  27480. }
  27481. return false;
  27482. }
  27483. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  27484. const int sourceChannelIndex,
  27485. const uint32 destNodeId,
  27486. const int destChannelIndex) const throw()
  27487. {
  27488. if (sourceChannelIndex < 0
  27489. || destChannelIndex < 0
  27490. || sourceNodeId == destNodeId
  27491. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  27492. return false;
  27493. const Node* const source = getNodeForId (sourceNodeId);
  27494. if (source == 0
  27495. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  27496. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  27497. return false;
  27498. const Node* const dest = getNodeForId (destNodeId);
  27499. if (dest == 0
  27500. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  27501. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  27502. return false;
  27503. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  27504. destNodeId, destChannelIndex) == 0;
  27505. }
  27506. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  27507. const int sourceChannelIndex,
  27508. const uint32 destNodeId,
  27509. const int destChannelIndex)
  27510. {
  27511. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  27512. return false;
  27513. Connection* const c = new Connection();
  27514. c->sourceNodeId = sourceNodeId;
  27515. c->sourceChannelIndex = sourceChannelIndex;
  27516. c->destNodeId = destNodeId;
  27517. c->destChannelIndex = destChannelIndex;
  27518. connections.add (c);
  27519. triggerAsyncUpdate();
  27520. return true;
  27521. }
  27522. void AudioProcessorGraph::removeConnection (const int index)
  27523. {
  27524. connections.remove (index);
  27525. triggerAsyncUpdate();
  27526. }
  27527. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  27528. const uint32 destNodeId, const int destChannelIndex)
  27529. {
  27530. bool doneAnything = false;
  27531. for (int i = connections.size(); --i >= 0;)
  27532. {
  27533. const Connection* const c = connections.getUnchecked(i);
  27534. if (c->sourceNodeId == sourceNodeId
  27535. && c->destNodeId == destNodeId
  27536. && c->sourceChannelIndex == sourceChannelIndex
  27537. && c->destChannelIndex == destChannelIndex)
  27538. {
  27539. removeConnection (i);
  27540. doneAnything = true;
  27541. triggerAsyncUpdate();
  27542. }
  27543. }
  27544. return doneAnything;
  27545. }
  27546. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  27547. {
  27548. bool doneAnything = false;
  27549. for (int i = connections.size(); --i >= 0;)
  27550. {
  27551. const Connection* const c = connections.getUnchecked(i);
  27552. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  27553. {
  27554. removeConnection (i);
  27555. doneAnything = true;
  27556. triggerAsyncUpdate();
  27557. }
  27558. }
  27559. return doneAnything;
  27560. }
  27561. bool AudioProcessorGraph::removeIllegalConnections()
  27562. {
  27563. bool doneAnything = false;
  27564. for (int i = connections.size(); --i >= 0;)
  27565. {
  27566. const Connection* const c = connections.getUnchecked(i);
  27567. const Node* const source = getNodeForId (c->sourceNodeId);
  27568. const Node* const dest = getNodeForId (c->destNodeId);
  27569. if (source == 0 || dest == 0
  27570. || (c->sourceChannelIndex != midiChannelIndex
  27571. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  27572. || (c->sourceChannelIndex == midiChannelIndex
  27573. && ! source->processor->producesMidi())
  27574. || (c->destChannelIndex != midiChannelIndex
  27575. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  27576. || (c->destChannelIndex == midiChannelIndex
  27577. && ! dest->processor->acceptsMidi()))
  27578. {
  27579. removeConnection (i);
  27580. doneAnything = true;
  27581. triggerAsyncUpdate();
  27582. }
  27583. }
  27584. return doneAnything;
  27585. }
  27586. namespace GraphRenderingOps
  27587. {
  27588. class AudioGraphRenderingOp
  27589. {
  27590. public:
  27591. AudioGraphRenderingOp() throw() {}
  27592. virtual ~AudioGraphRenderingOp() throw() {}
  27593. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  27594. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  27595. const int numSamples) throw() = 0;
  27596. juce_UseDebuggingNewOperator
  27597. };
  27598. class ClearChannelOp : public AudioGraphRenderingOp
  27599. {
  27600. public:
  27601. ClearChannelOp (const int channelNum_) throw()
  27602. : channelNum (channelNum_)
  27603. {}
  27604. ~ClearChannelOp() throw() {}
  27605. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27606. {
  27607. sharedBufferChans.clear (channelNum, 0, numSamples);
  27608. }
  27609. private:
  27610. const int channelNum;
  27611. ClearChannelOp (const ClearChannelOp&);
  27612. const ClearChannelOp& operator= (const ClearChannelOp&);
  27613. };
  27614. class CopyChannelOp : public AudioGraphRenderingOp
  27615. {
  27616. public:
  27617. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27618. : srcChannelNum (srcChannelNum_),
  27619. dstChannelNum (dstChannelNum_)
  27620. {}
  27621. ~CopyChannelOp() throw() {}
  27622. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27623. {
  27624. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27625. }
  27626. private:
  27627. const int srcChannelNum, dstChannelNum;
  27628. CopyChannelOp (const CopyChannelOp&);
  27629. const CopyChannelOp& operator= (const CopyChannelOp&);
  27630. };
  27631. class AddChannelOp : public AudioGraphRenderingOp
  27632. {
  27633. public:
  27634. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27635. : srcChannelNum (srcChannelNum_),
  27636. dstChannelNum (dstChannelNum_)
  27637. {}
  27638. ~AddChannelOp() throw() {}
  27639. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27640. {
  27641. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27642. }
  27643. private:
  27644. const int srcChannelNum, dstChannelNum;
  27645. AddChannelOp (const AddChannelOp&);
  27646. const AddChannelOp& operator= (const AddChannelOp&);
  27647. };
  27648. class ClearMidiBufferOp : public AudioGraphRenderingOp
  27649. {
  27650. public:
  27651. ClearMidiBufferOp (const int bufferNum_) throw()
  27652. : bufferNum (bufferNum_)
  27653. {}
  27654. ~ClearMidiBufferOp() throw() {}
  27655. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27656. {
  27657. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  27658. }
  27659. private:
  27660. const int bufferNum;
  27661. ClearMidiBufferOp (const ClearMidiBufferOp&);
  27662. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  27663. };
  27664. class CopyMidiBufferOp : public AudioGraphRenderingOp
  27665. {
  27666. public:
  27667. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27668. : srcBufferNum (srcBufferNum_),
  27669. dstBufferNum (dstBufferNum_)
  27670. {}
  27671. ~CopyMidiBufferOp() throw() {}
  27672. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27673. {
  27674. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  27675. }
  27676. private:
  27677. const int srcBufferNum, dstBufferNum;
  27678. CopyMidiBufferOp (const CopyMidiBufferOp&);
  27679. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  27680. };
  27681. class AddMidiBufferOp : public AudioGraphRenderingOp
  27682. {
  27683. public:
  27684. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27685. : srcBufferNum (srcBufferNum_),
  27686. dstBufferNum (dstBufferNum_)
  27687. {}
  27688. ~AddMidiBufferOp() throw() {}
  27689. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27690. {
  27691. sharedMidiBuffers.getUnchecked (dstBufferNum)
  27692. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  27693. }
  27694. private:
  27695. const int srcBufferNum, dstBufferNum;
  27696. AddMidiBufferOp (const AddMidiBufferOp&);
  27697. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  27698. };
  27699. class ProcessBufferOp : public AudioGraphRenderingOp
  27700. {
  27701. public:
  27702. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  27703. const Array <int>& audioChannelsToUse_,
  27704. const int totalChans_,
  27705. const int midiBufferToUse_) throw()
  27706. : node (node_),
  27707. processor (node_->processor),
  27708. audioChannelsToUse (audioChannelsToUse_),
  27709. totalChans (jmax (1, totalChans_)),
  27710. midiBufferToUse (midiBufferToUse_)
  27711. {
  27712. channels = (float**) juce_calloc (sizeof (float*) * totalChans);
  27713. while (audioChannelsToUse.size() < totalChans)
  27714. audioChannelsToUse.add (0);
  27715. }
  27716. ~ProcessBufferOp() throw()
  27717. {
  27718. juce_free (channels);
  27719. }
  27720. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27721. {
  27722. for (int i = totalChans; --i >= 0;)
  27723. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  27724. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  27725. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  27726. }
  27727. const AudioProcessorGraph::Node::Ptr node;
  27728. AudioProcessor* const processor;
  27729. private:
  27730. Array <int> audioChannelsToUse;
  27731. float** channels;
  27732. int totalChans;
  27733. int midiBufferToUse;
  27734. ProcessBufferOp (const ProcessBufferOp&);
  27735. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  27736. };
  27737. /** Used to calculate the correct sequence of rendering ops needed, based on
  27738. the best re-use of shared buffers at each stage.
  27739. */
  27740. class RenderingOpSequenceCalculator
  27741. {
  27742. public:
  27743. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  27744. const VoidArray& orderedNodes_,
  27745. VoidArray& renderingOps)
  27746. : graph (graph_),
  27747. orderedNodes (orderedNodes_)
  27748. {
  27749. nodeIds.add (-2); // first buffer is read-only zeros
  27750. channels.add (0);
  27751. midiNodeIds.add (-2);
  27752. for (int i = 0; i < orderedNodes.size(); ++i)
  27753. {
  27754. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  27755. renderingOps, i);
  27756. markAnyUnusedBuffersAsFree (i);
  27757. }
  27758. }
  27759. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  27760. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  27761. juce_UseDebuggingNewOperator
  27762. private:
  27763. AudioProcessorGraph& graph;
  27764. const VoidArray& orderedNodes;
  27765. Array <int> nodeIds, channels, midiNodeIds;
  27766. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  27767. VoidArray& renderingOps,
  27768. const int ourRenderingIndex)
  27769. {
  27770. const int numIns = node->processor->getNumInputChannels();
  27771. const int numOuts = node->processor->getNumOutputChannels();
  27772. const int totalChans = jmax (numIns, numOuts);
  27773. Array <int> audioChannelsToUse;
  27774. int midiBufferToUse = -1;
  27775. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  27776. {
  27777. // get a list of all the inputs to this node
  27778. Array <int> sourceNodes, sourceOutputChans;
  27779. for (int i = graph.getNumConnections(); --i >= 0;)
  27780. {
  27781. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27782. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  27783. {
  27784. sourceNodes.add (c->sourceNodeId);
  27785. sourceOutputChans.add (c->sourceChannelIndex);
  27786. }
  27787. }
  27788. int bufIndex = -1;
  27789. if (sourceNodes.size() == 0)
  27790. {
  27791. // unconnected input channel
  27792. if (inputChan >= numOuts)
  27793. {
  27794. bufIndex = getReadOnlyEmptyBuffer();
  27795. jassert (bufIndex >= 0);
  27796. }
  27797. else
  27798. {
  27799. bufIndex = getFreeBuffer (false);
  27800. renderingOps.add (new ClearChannelOp (bufIndex));
  27801. }
  27802. }
  27803. else if (sourceNodes.size() == 1)
  27804. {
  27805. // channel with a straightforward single input..
  27806. const int srcNode = sourceNodes.getUnchecked(0);
  27807. const int srcChan = sourceOutputChans.getUnchecked(0);
  27808. bufIndex = getBufferContaining (srcNode, srcChan);
  27809. if (bufIndex < 0)
  27810. {
  27811. // if not found, this is probably a feedback loop
  27812. bufIndex = getReadOnlyEmptyBuffer();
  27813. jassert (bufIndex >= 0);
  27814. }
  27815. if (inputChan < numOuts
  27816. && isBufferNeededLater (ourRenderingIndex,
  27817. inputChan,
  27818. srcNode, srcChan))
  27819. {
  27820. // can't mess up this channel because it's needed later by another node, so we
  27821. // need to use a copy of it..
  27822. const int newFreeBuffer = getFreeBuffer (false);
  27823. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  27824. bufIndex = newFreeBuffer;
  27825. }
  27826. }
  27827. else
  27828. {
  27829. // channel with a mix of several inputs..
  27830. // try to find a re-usable channel from our inputs..
  27831. int reusableInputIndex = -1;
  27832. for (int i = 0; i < sourceNodes.size(); ++i)
  27833. {
  27834. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  27835. sourceOutputChans.getUnchecked(i));
  27836. if (sourceBufIndex >= 0
  27837. && ! isBufferNeededLater (ourRenderingIndex,
  27838. inputChan,
  27839. sourceNodes.getUnchecked(i),
  27840. sourceOutputChans.getUnchecked(i)))
  27841. {
  27842. // we've found one of our input chans that can be re-used..
  27843. reusableInputIndex = i;
  27844. bufIndex = sourceBufIndex;
  27845. break;
  27846. }
  27847. }
  27848. if (reusableInputIndex < 0)
  27849. {
  27850. // can't re-use any of our input chans, so get a new one and copy everything into it..
  27851. bufIndex = getFreeBuffer (false);
  27852. jassert (bufIndex != 0);
  27853. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  27854. sourceOutputChans.getUnchecked (0));
  27855. if (srcIndex < 0)
  27856. {
  27857. // if not found, this is probably a feedback loop
  27858. renderingOps.add (new ClearChannelOp (bufIndex));
  27859. }
  27860. else
  27861. {
  27862. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  27863. }
  27864. reusableInputIndex = 0;
  27865. }
  27866. for (int j = 0; j < sourceNodes.size(); ++j)
  27867. {
  27868. if (j != reusableInputIndex)
  27869. {
  27870. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  27871. sourceOutputChans.getUnchecked(j));
  27872. if (srcIndex >= 0)
  27873. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  27874. }
  27875. }
  27876. }
  27877. jassert (bufIndex >= 0);
  27878. audioChannelsToUse.add (bufIndex);
  27879. if (inputChan < numOuts)
  27880. markBufferAsContaining (bufIndex, node->id, inputChan);
  27881. }
  27882. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  27883. {
  27884. const int bufIndex = getFreeBuffer (false);
  27885. jassert (bufIndex != 0);
  27886. audioChannelsToUse.add (bufIndex);
  27887. markBufferAsContaining (bufIndex, node->id, outputChan);
  27888. }
  27889. // Now the same thing for midi..
  27890. Array <int> midiSourceNodes;
  27891. for (int i = graph.getNumConnections(); --i >= 0;)
  27892. {
  27893. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27894. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  27895. midiSourceNodes.add (c->sourceNodeId);
  27896. }
  27897. if (midiSourceNodes.size() == 0)
  27898. {
  27899. // No midi inputs..
  27900. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  27901. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  27902. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  27903. }
  27904. else if (midiSourceNodes.size() == 1)
  27905. {
  27906. // One midi input..
  27907. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  27908. AudioProcessorGraph::midiChannelIndex);
  27909. if (midiBufferToUse >= 0)
  27910. {
  27911. if (isBufferNeededLater (ourRenderingIndex,
  27912. AudioProcessorGraph::midiChannelIndex,
  27913. midiSourceNodes.getUnchecked(0),
  27914. AudioProcessorGraph::midiChannelIndex))
  27915. {
  27916. // can't mess up this channel because it's needed later by another node, so we
  27917. // need to use a copy of it..
  27918. const int newFreeBuffer = getFreeBuffer (true);
  27919. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  27920. midiBufferToUse = newFreeBuffer;
  27921. }
  27922. }
  27923. else
  27924. {
  27925. // probably a feedback loop, so just use an empty one..
  27926. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  27927. }
  27928. }
  27929. else
  27930. {
  27931. // More than one midi input being mixed..
  27932. int reusableInputIndex = -1;
  27933. for (int i = 0; i < midiSourceNodes.size(); ++i)
  27934. {
  27935. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  27936. AudioProcessorGraph::midiChannelIndex);
  27937. if (sourceBufIndex >= 0
  27938. && ! isBufferNeededLater (ourRenderingIndex,
  27939. AudioProcessorGraph::midiChannelIndex,
  27940. midiSourceNodes.getUnchecked(i),
  27941. AudioProcessorGraph::midiChannelIndex))
  27942. {
  27943. // we've found one of our input buffers that can be re-used..
  27944. reusableInputIndex = i;
  27945. midiBufferToUse = sourceBufIndex;
  27946. break;
  27947. }
  27948. }
  27949. if (reusableInputIndex < 0)
  27950. {
  27951. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  27952. midiBufferToUse = getFreeBuffer (true);
  27953. jassert (midiBufferToUse >= 0);
  27954. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  27955. AudioProcessorGraph::midiChannelIndex);
  27956. if (srcIndex >= 0)
  27957. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  27958. else
  27959. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  27960. reusableInputIndex = 0;
  27961. }
  27962. for (int j = 0; j < midiSourceNodes.size(); ++j)
  27963. {
  27964. if (j != reusableInputIndex)
  27965. {
  27966. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  27967. AudioProcessorGraph::midiChannelIndex);
  27968. if (srcIndex >= 0)
  27969. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  27970. }
  27971. }
  27972. }
  27973. if (node->processor->producesMidi())
  27974. markBufferAsContaining (midiBufferToUse, node->id,
  27975. AudioProcessorGraph::midiChannelIndex);
  27976. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  27977. totalChans, midiBufferToUse));
  27978. }
  27979. int getFreeBuffer (const bool forMidi)
  27980. {
  27981. if (forMidi)
  27982. {
  27983. for (int i = 1; i < midiNodeIds.size(); ++i)
  27984. if (midiNodeIds.getUnchecked(i) < 0)
  27985. return i;
  27986. midiNodeIds.add (-1);
  27987. return midiNodeIds.size() - 1;
  27988. }
  27989. else
  27990. {
  27991. for (int i = 1; i < nodeIds.size(); ++i)
  27992. if (nodeIds.getUnchecked(i) < 0)
  27993. return i;
  27994. nodeIds.add (-1);
  27995. channels.add (0);
  27996. return nodeIds.size() - 1;
  27997. }
  27998. }
  27999. int getReadOnlyEmptyBuffer() const throw()
  28000. {
  28001. return 0;
  28002. }
  28003. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  28004. {
  28005. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28006. {
  28007. for (int i = midiNodeIds.size(); --i >= 0;)
  28008. if (midiNodeIds.getUnchecked(i) == nodeId)
  28009. return i;
  28010. }
  28011. else
  28012. {
  28013. for (int i = nodeIds.size(); --i >= 0;)
  28014. if (nodeIds.getUnchecked(i) == nodeId
  28015. && channels.getUnchecked(i) == outputChannel)
  28016. return i;
  28017. }
  28018. return -1;
  28019. }
  28020. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28021. {
  28022. int i;
  28023. for (i = 0; i < nodeIds.size(); ++i)
  28024. {
  28025. if (nodeIds.getUnchecked(i) >= 0
  28026. && ! isBufferNeededLater (stepIndex, -1,
  28027. nodeIds.getUnchecked(i),
  28028. channels.getUnchecked(i)))
  28029. {
  28030. nodeIds.set (i, -1);
  28031. }
  28032. }
  28033. for (i = 0; i < midiNodeIds.size(); ++i)
  28034. {
  28035. if (midiNodeIds.getUnchecked(i) >= 0
  28036. && ! isBufferNeededLater (stepIndex, -1,
  28037. midiNodeIds.getUnchecked(i),
  28038. AudioProcessorGraph::midiChannelIndex))
  28039. {
  28040. midiNodeIds.set (i, -1);
  28041. }
  28042. }
  28043. }
  28044. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28045. int inputChannelOfIndexToIgnore,
  28046. const int nodeId,
  28047. const int outputChanIndex) const throw()
  28048. {
  28049. while (stepIndexToSearchFrom < orderedNodes.size())
  28050. {
  28051. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28052. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28053. {
  28054. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28055. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28056. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28057. return true;
  28058. }
  28059. else
  28060. {
  28061. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28062. if (i != inputChannelOfIndexToIgnore
  28063. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28064. node->id, i) != 0)
  28065. return true;
  28066. }
  28067. inputChannelOfIndexToIgnore = -1;
  28068. ++stepIndexToSearchFrom;
  28069. }
  28070. return false;
  28071. }
  28072. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28073. {
  28074. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28075. {
  28076. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28077. midiNodeIds.set (bufferNum, nodeId);
  28078. }
  28079. else
  28080. {
  28081. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28082. nodeIds.set (bufferNum, nodeId);
  28083. channels.set (bufferNum, outputIndex);
  28084. }
  28085. }
  28086. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28087. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28088. };
  28089. }
  28090. void AudioProcessorGraph::clearRenderingSequence()
  28091. {
  28092. const ScopedLock sl (renderLock);
  28093. for (int i = renderingOps.size(); --i >= 0;)
  28094. {
  28095. GraphRenderingOps::AudioGraphRenderingOp* const r
  28096. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28097. renderingOps.remove (i);
  28098. delete r;
  28099. }
  28100. }
  28101. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28102. const uint32 possibleDestinationId,
  28103. const int recursionCheck) const throw()
  28104. {
  28105. if (recursionCheck > 0)
  28106. {
  28107. for (int i = connections.size(); --i >= 0;)
  28108. {
  28109. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28110. if (c->destNodeId == possibleDestinationId
  28111. && (c->sourceNodeId == possibleInputId
  28112. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28113. return true;
  28114. }
  28115. }
  28116. return false;
  28117. }
  28118. void AudioProcessorGraph::buildRenderingSequence()
  28119. {
  28120. VoidArray newRenderingOps;
  28121. int numRenderingBuffersNeeded = 2;
  28122. int numMidiBuffersNeeded = 1;
  28123. {
  28124. MessageManagerLock mml;
  28125. VoidArray orderedNodes;
  28126. int i;
  28127. for (i = 0; i < nodes.size(); ++i)
  28128. {
  28129. Node* const node = nodes.getUnchecked(i);
  28130. node->prepare (getSampleRate(), getBlockSize(), this);
  28131. int j = 0;
  28132. for (; j < orderedNodes.size(); ++j)
  28133. if (isAnInputTo (node->id,
  28134. ((Node*) orderedNodes.getUnchecked (j))->id,
  28135. nodes.size() + 1))
  28136. break;
  28137. orderedNodes.insert (j, node);
  28138. }
  28139. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28140. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28141. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28142. }
  28143. VoidArray oldRenderingOps (renderingOps);
  28144. {
  28145. // swap over to the new rendering sequence..
  28146. const ScopedLock sl (renderLock);
  28147. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28148. renderingBuffers.clear();
  28149. for (int i = midiBuffers.size(); --i >= 0;)
  28150. midiBuffers.getUnchecked(i)->clear();
  28151. while (midiBuffers.size() < numMidiBuffersNeeded)
  28152. midiBuffers.add (new MidiBuffer());
  28153. renderingOps = newRenderingOps;
  28154. }
  28155. for (int i = oldRenderingOps.size(); --i >= 0;)
  28156. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28157. }
  28158. void AudioProcessorGraph::handleAsyncUpdate()
  28159. {
  28160. buildRenderingSequence();
  28161. }
  28162. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28163. {
  28164. currentAudioInputBuffer = 0;
  28165. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28166. currentMidiInputBuffer = 0;
  28167. currentMidiOutputBuffer.clear();
  28168. clearRenderingSequence();
  28169. buildRenderingSequence();
  28170. }
  28171. void AudioProcessorGraph::releaseResources()
  28172. {
  28173. for (int i = 0; i < nodes.size(); ++i)
  28174. nodes.getUnchecked(i)->unprepare();
  28175. renderingBuffers.setSize (1, 1);
  28176. midiBuffers.clear();
  28177. currentAudioInputBuffer = 0;
  28178. currentAudioOutputBuffer.setSize (1, 1);
  28179. currentMidiInputBuffer = 0;
  28180. currentMidiOutputBuffer.clear();
  28181. }
  28182. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28183. {
  28184. const int numSamples = buffer.getNumSamples();
  28185. const ScopedLock sl (renderLock);
  28186. currentAudioInputBuffer = &buffer;
  28187. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28188. currentAudioOutputBuffer.clear();
  28189. currentMidiInputBuffer = &midiMessages;
  28190. currentMidiOutputBuffer.clear();
  28191. int i;
  28192. for (i = 0; i < renderingOps.size(); ++i)
  28193. {
  28194. GraphRenderingOps::AudioGraphRenderingOp* const op
  28195. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28196. op->perform (renderingBuffers, midiBuffers, numSamples);
  28197. }
  28198. for (i = 0; i < buffer.getNumChannels(); ++i)
  28199. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28200. }
  28201. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28202. {
  28203. return "Input " + String (channelIndex + 1);
  28204. }
  28205. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28206. {
  28207. return "Output " + String (channelIndex + 1);
  28208. }
  28209. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28210. {
  28211. return true;
  28212. }
  28213. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28214. {
  28215. return true;
  28216. }
  28217. bool AudioProcessorGraph::acceptsMidi() const
  28218. {
  28219. return true;
  28220. }
  28221. bool AudioProcessorGraph::producesMidi() const
  28222. {
  28223. return true;
  28224. }
  28225. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28226. {
  28227. }
  28228. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28229. {
  28230. }
  28231. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28232. : type (type_),
  28233. graph (0)
  28234. {
  28235. }
  28236. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28237. {
  28238. }
  28239. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28240. {
  28241. switch (type)
  28242. {
  28243. case audioOutputNode:
  28244. return "Audio Output";
  28245. case audioInputNode:
  28246. return "Audio Input";
  28247. case midiOutputNode:
  28248. return "Midi Output";
  28249. case midiInputNode:
  28250. return "Midi Input";
  28251. default:
  28252. break;
  28253. }
  28254. return String::empty;
  28255. }
  28256. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28257. {
  28258. d.name = getName();
  28259. d.uid = d.name.hashCode();
  28260. d.category = "I/O devices";
  28261. d.pluginFormatName = "Internal";
  28262. d.manufacturerName = "Raw Material Software";
  28263. d.version = "1.0";
  28264. d.isInstrument = false;
  28265. d.numInputChannels = getNumInputChannels();
  28266. if (type == audioOutputNode && graph != 0)
  28267. d.numInputChannels = graph->getNumInputChannels();
  28268. d.numOutputChannels = getNumOutputChannels();
  28269. if (type == audioInputNode && graph != 0)
  28270. d.numOutputChannels = graph->getNumOutputChannels();
  28271. }
  28272. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28273. {
  28274. jassert (graph != 0);
  28275. }
  28276. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28277. {
  28278. }
  28279. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28280. MidiBuffer& midiMessages)
  28281. {
  28282. jassert (graph != 0);
  28283. switch (type)
  28284. {
  28285. case audioOutputNode:
  28286. {
  28287. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28288. buffer.getNumChannels()); --i >= 0;)
  28289. {
  28290. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28291. }
  28292. break;
  28293. }
  28294. case audioInputNode:
  28295. {
  28296. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28297. buffer.getNumChannels()); --i >= 0;)
  28298. {
  28299. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28300. }
  28301. break;
  28302. }
  28303. case midiOutputNode:
  28304. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28305. break;
  28306. case midiInputNode:
  28307. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28308. break;
  28309. default:
  28310. break;
  28311. }
  28312. }
  28313. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  28314. {
  28315. return type == midiOutputNode;
  28316. }
  28317. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  28318. {
  28319. return type == midiInputNode;
  28320. }
  28321. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  28322. {
  28323. switch (type)
  28324. {
  28325. case audioOutputNode:
  28326. return "Output " + String (channelIndex + 1);
  28327. case midiOutputNode:
  28328. return "Midi Output";
  28329. default:
  28330. break;
  28331. }
  28332. return String::empty;
  28333. }
  28334. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  28335. {
  28336. switch (type)
  28337. {
  28338. case audioInputNode:
  28339. return "Input " + String (channelIndex + 1);
  28340. case midiInputNode:
  28341. return "Midi Input";
  28342. default:
  28343. break;
  28344. }
  28345. return String::empty;
  28346. }
  28347. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  28348. {
  28349. return type == audioInputNode || type == audioOutputNode;
  28350. }
  28351. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  28352. {
  28353. return isInputChannelStereoPair (index);
  28354. }
  28355. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  28356. {
  28357. return type == audioInputNode || type == midiInputNode;
  28358. }
  28359. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  28360. {
  28361. return type == audioOutputNode || type == midiOutputNode;
  28362. }
  28363. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  28364. {
  28365. return 0;
  28366. }
  28367. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  28368. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  28369. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  28370. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  28371. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  28372. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  28373. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  28374. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  28375. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  28376. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  28377. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  28378. {
  28379. }
  28380. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  28381. {
  28382. }
  28383. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  28384. {
  28385. graph = newGraph;
  28386. if (graph != 0)
  28387. {
  28388. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  28389. type == audioInputNode ? graph->getNumInputChannels() : 0,
  28390. getSampleRate(),
  28391. getBlockSize());
  28392. updateHostDisplay();
  28393. }
  28394. }
  28395. END_JUCE_NAMESPACE
  28396. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  28397. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28398. BEGIN_JUCE_NAMESPACE
  28399. AudioProcessorPlayer::AudioProcessorPlayer()
  28400. : processor (0),
  28401. sampleRate (0),
  28402. blockSize (0),
  28403. isPrepared (false),
  28404. numInputChans (0),
  28405. numOutputChans (0),
  28406. tempBuffer (1, 1)
  28407. {
  28408. }
  28409. AudioProcessorPlayer::~AudioProcessorPlayer()
  28410. {
  28411. setProcessor (0);
  28412. }
  28413. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  28414. {
  28415. if (processor != processorToPlay)
  28416. {
  28417. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  28418. {
  28419. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  28420. sampleRate, blockSize);
  28421. processorToPlay->prepareToPlay (sampleRate, blockSize);
  28422. }
  28423. lock.enter();
  28424. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  28425. processor = processorToPlay;
  28426. isPrepared = true;
  28427. lock.exit();
  28428. if (oldOne != 0)
  28429. oldOne->releaseResources();
  28430. }
  28431. }
  28432. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  28433. int numInputChannels,
  28434. float** outputChannelData,
  28435. int numOutputChannels,
  28436. int numSamples)
  28437. {
  28438. // these should have been prepared by audioDeviceAboutToStart()...
  28439. jassert (sampleRate > 0 && blockSize > 0);
  28440. incomingMidi.clear();
  28441. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  28442. int i, totalNumChans = 0;
  28443. if (numInputChannels > numOutputChannels)
  28444. {
  28445. // if there aren't enough output channels for the number of
  28446. // inputs, we need to create some temporary extra ones (can't
  28447. // use the input data in case it gets written to)
  28448. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  28449. false, false, true);
  28450. for (i = 0; i < numOutputChannels; ++i)
  28451. {
  28452. channels[totalNumChans] = outputChannelData[i];
  28453. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28454. ++totalNumChans;
  28455. }
  28456. for (i = numOutputChannels; i < numInputChannels; ++i)
  28457. {
  28458. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  28459. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28460. ++totalNumChans;
  28461. }
  28462. }
  28463. else
  28464. {
  28465. for (i = 0; i < numInputChannels; ++i)
  28466. {
  28467. channels[totalNumChans] = outputChannelData[i];
  28468. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28469. ++totalNumChans;
  28470. }
  28471. for (i = numInputChannels; i < numOutputChannels; ++i)
  28472. {
  28473. channels[totalNumChans] = outputChannelData[i];
  28474. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  28475. ++totalNumChans;
  28476. }
  28477. }
  28478. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  28479. const ScopedLock sl (lock);
  28480. if (processor != 0)
  28481. processor->processBlock (buffer, incomingMidi);
  28482. }
  28483. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  28484. {
  28485. const ScopedLock sl (lock);
  28486. sampleRate = device->getCurrentSampleRate();
  28487. blockSize = device->getCurrentBufferSizeSamples();
  28488. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  28489. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  28490. messageCollector.reset (sampleRate);
  28491. zeromem (channels, sizeof (channels));
  28492. if (processor != 0)
  28493. {
  28494. if (isPrepared)
  28495. processor->releaseResources();
  28496. AudioProcessor* const oldProcessor = processor;
  28497. setProcessor (0);
  28498. setProcessor (oldProcessor);
  28499. }
  28500. }
  28501. void AudioProcessorPlayer::audioDeviceStopped()
  28502. {
  28503. const ScopedLock sl (lock);
  28504. if (processor != 0 && isPrepared)
  28505. processor->releaseResources();
  28506. sampleRate = 0.0;
  28507. blockSize = 0;
  28508. isPrepared = false;
  28509. tempBuffer.setSize (1, 1);
  28510. }
  28511. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  28512. {
  28513. messageCollector.addMessageToQueue (message);
  28514. }
  28515. END_JUCE_NAMESPACE
  28516. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28517. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28518. BEGIN_JUCE_NAMESPACE
  28519. class ProcessorParameterPropertyComp : public PropertyComponent,
  28520. public AudioProcessorListener,
  28521. public AsyncUpdater
  28522. {
  28523. public:
  28524. ProcessorParameterPropertyComp (const String& name,
  28525. AudioProcessor* const owner_,
  28526. const int index_)
  28527. : PropertyComponent (name),
  28528. owner (owner_),
  28529. index (index_)
  28530. {
  28531. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  28532. owner_->addListener (this);
  28533. }
  28534. ~ProcessorParameterPropertyComp()
  28535. {
  28536. owner->removeListener (this);
  28537. deleteAllChildren();
  28538. }
  28539. void refresh()
  28540. {
  28541. slider->setValue (owner->getParameter (index), false);
  28542. }
  28543. void audioProcessorChanged (AudioProcessor*) {}
  28544. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  28545. {
  28546. if (parameterIndex == index)
  28547. triggerAsyncUpdate();
  28548. }
  28549. void handleAsyncUpdate()
  28550. {
  28551. refresh();
  28552. }
  28553. juce_UseDebuggingNewOperator
  28554. private:
  28555. AudioProcessor* const owner;
  28556. const int index;
  28557. Slider* slider;
  28558. class ParamSlider : public Slider
  28559. {
  28560. public:
  28561. ParamSlider (AudioProcessor* const owner_, const int index_)
  28562. : Slider (String::empty),
  28563. owner (owner_),
  28564. index (index_)
  28565. {
  28566. setRange (0.0, 1.0, 0.0);
  28567. setSliderStyle (Slider::LinearBar);
  28568. setTextBoxIsEditable (false);
  28569. setScrollWheelEnabled (false);
  28570. }
  28571. ~ParamSlider()
  28572. {
  28573. }
  28574. void valueChanged()
  28575. {
  28576. const float newVal = (float) getValue();
  28577. if (owner->getParameter (index) != newVal)
  28578. owner->setParameter (index, newVal);
  28579. }
  28580. const String getTextFromValue (double /*value*/)
  28581. {
  28582. return owner->getParameterText (index);
  28583. }
  28584. juce_UseDebuggingNewOperator
  28585. private:
  28586. AudioProcessor* const owner;
  28587. const int index;
  28588. };
  28589. };
  28590. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  28591. : AudioProcessorEditor (owner)
  28592. {
  28593. setOpaque (true);
  28594. addAndMakeVisible (panel = new PropertyPanel());
  28595. Array <PropertyComponent*> params;
  28596. const int numParams = owner->getNumParameters();
  28597. int totalHeight = 0;
  28598. for (int i = 0; i < numParams; ++i)
  28599. {
  28600. String name (owner->getParameterName (i));
  28601. if (name.trim().isEmpty())
  28602. name = "Unnamed";
  28603. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  28604. params.add (pc);
  28605. totalHeight += pc->getPreferredHeight();
  28606. }
  28607. panel->addProperties (params);
  28608. setSize (400, jlimit (25, 400, totalHeight));
  28609. }
  28610. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  28611. {
  28612. deleteAllChildren();
  28613. }
  28614. void GenericAudioProcessorEditor::paint (Graphics& g)
  28615. {
  28616. g.fillAll (Colours::white);
  28617. }
  28618. void GenericAudioProcessorEditor::resized()
  28619. {
  28620. panel->setSize (getWidth(), getHeight());
  28621. }
  28622. END_JUCE_NAMESPACE
  28623. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28624. /********* Start of inlined file: juce_Sampler.cpp *********/
  28625. BEGIN_JUCE_NAMESPACE
  28626. SamplerSound::SamplerSound (const String& name_,
  28627. AudioFormatReader& source,
  28628. const BitArray& midiNotes_,
  28629. const int midiNoteForNormalPitch,
  28630. const double attackTimeSecs,
  28631. const double releaseTimeSecs,
  28632. const double maxSampleLengthSeconds)
  28633. : name (name_),
  28634. midiNotes (midiNotes_),
  28635. midiRootNote (midiNoteForNormalPitch)
  28636. {
  28637. sourceSampleRate = source.sampleRate;
  28638. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  28639. {
  28640. data = 0;
  28641. length = 0;
  28642. attackSamples = 0;
  28643. releaseSamples = 0;
  28644. }
  28645. else
  28646. {
  28647. length = jmin ((int) source.lengthInSamples,
  28648. (int) (maxSampleLengthSeconds * sourceSampleRate));
  28649. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  28650. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  28651. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  28652. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  28653. }
  28654. }
  28655. SamplerSound::~SamplerSound()
  28656. {
  28657. delete data;
  28658. data = 0;
  28659. }
  28660. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  28661. {
  28662. return midiNotes [midiNoteNumber];
  28663. }
  28664. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  28665. {
  28666. return true;
  28667. }
  28668. SamplerVoice::SamplerVoice()
  28669. : pitchRatio (0.0),
  28670. sourceSamplePosition (0.0),
  28671. lgain (0.0f),
  28672. rgain (0.0f),
  28673. isInAttack (false),
  28674. isInRelease (false)
  28675. {
  28676. }
  28677. SamplerVoice::~SamplerVoice()
  28678. {
  28679. }
  28680. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  28681. {
  28682. return dynamic_cast <const SamplerSound*> (sound) != 0;
  28683. }
  28684. void SamplerVoice::startNote (const int midiNoteNumber,
  28685. const float velocity,
  28686. SynthesiserSound* s,
  28687. const int /*currentPitchWheelPosition*/)
  28688. {
  28689. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  28690. jassert (sound != 0); // this object can only play SamplerSounds!
  28691. if (sound != 0)
  28692. {
  28693. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  28694. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  28695. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  28696. sourceSamplePosition = 0.0;
  28697. lgain = velocity;
  28698. rgain = velocity;
  28699. isInAttack = (sound->attackSamples > 0);
  28700. isInRelease = false;
  28701. if (isInAttack)
  28702. {
  28703. attackReleaseLevel = 0.0f;
  28704. attackDelta = (float) (pitchRatio / sound->attackSamples);
  28705. }
  28706. else
  28707. {
  28708. attackReleaseLevel = 1.0f;
  28709. attackDelta = 0.0f;
  28710. }
  28711. if (sound->releaseSamples > 0)
  28712. {
  28713. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  28714. }
  28715. else
  28716. {
  28717. releaseDelta = 0.0f;
  28718. }
  28719. }
  28720. }
  28721. void SamplerVoice::stopNote (const bool allowTailOff)
  28722. {
  28723. if (allowTailOff)
  28724. {
  28725. isInAttack = false;
  28726. isInRelease = true;
  28727. }
  28728. else
  28729. {
  28730. clearCurrentNote();
  28731. }
  28732. }
  28733. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  28734. {
  28735. }
  28736. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  28737. const int /*newValue*/)
  28738. {
  28739. }
  28740. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  28741. {
  28742. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  28743. if (playingSound != 0)
  28744. {
  28745. const float* const inL = playingSound->data->getSampleData (0, 0);
  28746. const float* const inR = playingSound->data->getNumChannels() > 1
  28747. ? playingSound->data->getSampleData (1, 0) : 0;
  28748. float* outL = outputBuffer.getSampleData (0, startSample);
  28749. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  28750. while (--numSamples >= 0)
  28751. {
  28752. const int pos = (int) sourceSamplePosition;
  28753. const float alpha = (float) (sourceSamplePosition - pos);
  28754. const float invAlpha = 1.0f - alpha;
  28755. // just using a very simple linear interpolation here..
  28756. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  28757. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  28758. : l;
  28759. l *= lgain;
  28760. r *= rgain;
  28761. if (isInAttack)
  28762. {
  28763. l *= attackReleaseLevel;
  28764. r *= attackReleaseLevel;
  28765. attackReleaseLevel += attackDelta;
  28766. if (attackReleaseLevel >= 1.0f)
  28767. {
  28768. attackReleaseLevel = 1.0f;
  28769. isInAttack = false;
  28770. }
  28771. }
  28772. else if (isInRelease)
  28773. {
  28774. l *= attackReleaseLevel;
  28775. r *= attackReleaseLevel;
  28776. attackReleaseLevel += releaseDelta;
  28777. if (attackReleaseLevel <= 0.0f)
  28778. {
  28779. stopNote (false);
  28780. break;
  28781. }
  28782. }
  28783. if (outR != 0)
  28784. {
  28785. *outL++ += l;
  28786. *outR++ += r;
  28787. }
  28788. else
  28789. {
  28790. *outL++ += (l + r) * 0.5f;
  28791. }
  28792. sourceSamplePosition += pitchRatio;
  28793. if (sourceSamplePosition > playingSound->length)
  28794. {
  28795. stopNote (false);
  28796. break;
  28797. }
  28798. }
  28799. }
  28800. }
  28801. END_JUCE_NAMESPACE
  28802. /********* End of inlined file: juce_Sampler.cpp *********/
  28803. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  28804. BEGIN_JUCE_NAMESPACE
  28805. SynthesiserSound::SynthesiserSound()
  28806. {
  28807. }
  28808. SynthesiserSound::~SynthesiserSound()
  28809. {
  28810. }
  28811. SynthesiserVoice::SynthesiserVoice()
  28812. : currentSampleRate (44100.0),
  28813. currentlyPlayingNote (-1),
  28814. noteOnTime (0),
  28815. currentlyPlayingSound (0)
  28816. {
  28817. }
  28818. SynthesiserVoice::~SynthesiserVoice()
  28819. {
  28820. }
  28821. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  28822. {
  28823. return currentlyPlayingSound != 0
  28824. && currentlyPlayingSound->appliesToChannel (midiChannel);
  28825. }
  28826. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  28827. {
  28828. currentSampleRate = newRate;
  28829. }
  28830. void SynthesiserVoice::clearCurrentNote()
  28831. {
  28832. currentlyPlayingNote = -1;
  28833. currentlyPlayingSound = 0;
  28834. }
  28835. Synthesiser::Synthesiser()
  28836. : voices (2),
  28837. sounds (2),
  28838. sampleRate (0),
  28839. lastNoteOnCounter (0),
  28840. shouldStealNotes (true)
  28841. {
  28842. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  28843. lastPitchWheelValues[i] = 0x2000;
  28844. }
  28845. Synthesiser::~Synthesiser()
  28846. {
  28847. }
  28848. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  28849. {
  28850. const ScopedLock sl (lock);
  28851. return voices [index];
  28852. }
  28853. void Synthesiser::clearVoices()
  28854. {
  28855. const ScopedLock sl (lock);
  28856. voices.clear();
  28857. }
  28858. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  28859. {
  28860. const ScopedLock sl (lock);
  28861. voices.add (newVoice);
  28862. }
  28863. void Synthesiser::removeVoice (const int index)
  28864. {
  28865. const ScopedLock sl (lock);
  28866. voices.remove (index);
  28867. }
  28868. void Synthesiser::clearSounds()
  28869. {
  28870. const ScopedLock sl (lock);
  28871. sounds.clear();
  28872. }
  28873. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  28874. {
  28875. const ScopedLock sl (lock);
  28876. sounds.add (newSound);
  28877. }
  28878. void Synthesiser::removeSound (const int index)
  28879. {
  28880. const ScopedLock sl (lock);
  28881. sounds.remove (index);
  28882. }
  28883. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  28884. {
  28885. shouldStealNotes = shouldStealNotes_;
  28886. }
  28887. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  28888. {
  28889. if (sampleRate != newRate)
  28890. {
  28891. const ScopedLock sl (lock);
  28892. allNotesOff (0, false);
  28893. sampleRate = newRate;
  28894. for (int i = voices.size(); --i >= 0;)
  28895. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  28896. }
  28897. }
  28898. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  28899. const MidiBuffer& midiData,
  28900. int startSample,
  28901. int numSamples)
  28902. {
  28903. // must set the sample rate before using this!
  28904. jassert (sampleRate != 0);
  28905. const ScopedLock sl (lock);
  28906. MidiBuffer::Iterator midiIterator (midiData);
  28907. midiIterator.setNextSamplePosition (startSample);
  28908. MidiMessage m (0xf4, 0.0);
  28909. while (numSamples > 0)
  28910. {
  28911. int midiEventPos;
  28912. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  28913. && midiEventPos < startSample + numSamples;
  28914. const int numThisTime = useEvent ? midiEventPos - startSample
  28915. : numSamples;
  28916. if (numThisTime > 0)
  28917. {
  28918. for (int i = voices.size(); --i >= 0;)
  28919. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  28920. }
  28921. if (useEvent)
  28922. {
  28923. if (m.isNoteOn())
  28924. {
  28925. const int channel = m.getChannel();
  28926. noteOn (channel,
  28927. m.getNoteNumber(),
  28928. m.getFloatVelocity());
  28929. }
  28930. else if (m.isNoteOff())
  28931. {
  28932. noteOff (m.getChannel(),
  28933. m.getNoteNumber(),
  28934. true);
  28935. }
  28936. else if (m.isAllNotesOff() || m.isAllSoundOff())
  28937. {
  28938. allNotesOff (m.getChannel(), true);
  28939. }
  28940. else if (m.isPitchWheel())
  28941. {
  28942. const int channel = m.getChannel();
  28943. const int wheelPos = m.getPitchWheelValue();
  28944. lastPitchWheelValues [channel - 1] = wheelPos;
  28945. handlePitchWheel (channel, wheelPos);
  28946. }
  28947. else if (m.isController())
  28948. {
  28949. handleController (m.getChannel(),
  28950. m.getControllerNumber(),
  28951. m.getControllerValue());
  28952. }
  28953. }
  28954. startSample += numThisTime;
  28955. numSamples -= numThisTime;
  28956. }
  28957. }
  28958. void Synthesiser::noteOn (const int midiChannel,
  28959. const int midiNoteNumber,
  28960. const float velocity)
  28961. {
  28962. const ScopedLock sl (lock);
  28963. for (int i = sounds.size(); --i >= 0;)
  28964. {
  28965. SynthesiserSound* const sound = sounds.getUnchecked(i);
  28966. if (sound->appliesToNote (midiNoteNumber)
  28967. && sound->appliesToChannel (midiChannel))
  28968. {
  28969. startVoice (findFreeVoice (sound, shouldStealNotes),
  28970. sound, midiChannel, midiNoteNumber, velocity);
  28971. }
  28972. }
  28973. }
  28974. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  28975. SynthesiserSound* const sound,
  28976. const int midiChannel,
  28977. const int midiNoteNumber,
  28978. const float velocity)
  28979. {
  28980. if (voice != 0 && sound != 0)
  28981. {
  28982. if (voice->currentlyPlayingSound != 0)
  28983. voice->stopNote (false);
  28984. voice->startNote (midiNoteNumber,
  28985. velocity,
  28986. sound,
  28987. lastPitchWheelValues [midiChannel - 1]);
  28988. voice->currentlyPlayingNote = midiNoteNumber;
  28989. voice->noteOnTime = ++lastNoteOnCounter;
  28990. voice->currentlyPlayingSound = sound;
  28991. }
  28992. }
  28993. void Synthesiser::noteOff (const int midiChannel,
  28994. const int midiNoteNumber,
  28995. const bool allowTailOff)
  28996. {
  28997. const ScopedLock sl (lock);
  28998. for (int i = voices.size(); --i >= 0;)
  28999. {
  29000. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29001. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29002. {
  29003. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29004. if (sound != 0
  29005. && sound->appliesToNote (midiNoteNumber)
  29006. && sound->appliesToChannel (midiChannel))
  29007. {
  29008. voice->stopNote (allowTailOff);
  29009. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29010. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29011. }
  29012. }
  29013. }
  29014. }
  29015. void Synthesiser::allNotesOff (const int midiChannel,
  29016. const bool allowTailOff)
  29017. {
  29018. const ScopedLock sl (lock);
  29019. for (int i = voices.size(); --i >= 0;)
  29020. {
  29021. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29022. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29023. voice->stopNote (allowTailOff);
  29024. }
  29025. }
  29026. void Synthesiser::handlePitchWheel (const int midiChannel,
  29027. const int wheelValue)
  29028. {
  29029. const ScopedLock sl (lock);
  29030. for (int i = voices.size(); --i >= 0;)
  29031. {
  29032. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29033. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29034. {
  29035. voice->pitchWheelMoved (wheelValue);
  29036. }
  29037. }
  29038. }
  29039. void Synthesiser::handleController (const int midiChannel,
  29040. const int controllerNumber,
  29041. const int controllerValue)
  29042. {
  29043. const ScopedLock sl (lock);
  29044. for (int i = voices.size(); --i >= 0;)
  29045. {
  29046. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29047. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29048. voice->controllerMoved (controllerNumber, controllerValue);
  29049. }
  29050. }
  29051. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29052. const bool stealIfNoneAvailable) const
  29053. {
  29054. const ScopedLock sl (lock);
  29055. for (int i = voices.size(); --i >= 0;)
  29056. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29057. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29058. return voices.getUnchecked (i);
  29059. if (stealIfNoneAvailable)
  29060. {
  29061. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29062. SynthesiserVoice* oldest = 0;
  29063. for (int i = voices.size(); --i >= 0;)
  29064. {
  29065. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29066. if (voice->canPlaySound (soundToPlay)
  29067. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29068. oldest = voice;
  29069. }
  29070. jassert (oldest != 0);
  29071. return oldest;
  29072. }
  29073. return 0;
  29074. }
  29075. END_JUCE_NAMESPACE
  29076. /********* End of inlined file: juce_Synthesiser.cpp *********/
  29077. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  29078. BEGIN_JUCE_NAMESPACE
  29079. ActionBroadcaster::ActionBroadcaster() throw()
  29080. {
  29081. // are you trying to create this object before or after juce has been intialised??
  29082. jassert (MessageManager::instance != 0);
  29083. }
  29084. ActionBroadcaster::~ActionBroadcaster()
  29085. {
  29086. // all event-based objects must be deleted BEFORE juce is shut down!
  29087. jassert (MessageManager::instance != 0);
  29088. }
  29089. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29090. {
  29091. actionListenerList.addActionListener (listener);
  29092. }
  29093. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29094. {
  29095. jassert (actionListenerList.isValidMessageListener());
  29096. if (actionListenerList.isValidMessageListener())
  29097. actionListenerList.removeActionListener (listener);
  29098. }
  29099. void ActionBroadcaster::removeAllActionListeners()
  29100. {
  29101. actionListenerList.removeAllActionListeners();
  29102. }
  29103. void ActionBroadcaster::sendActionMessage (const String& message) const
  29104. {
  29105. actionListenerList.sendActionMessage (message);
  29106. }
  29107. END_JUCE_NAMESPACE
  29108. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  29109. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  29110. BEGIN_JUCE_NAMESPACE
  29111. // special message of our own with a string in it
  29112. class ActionMessage : public Message
  29113. {
  29114. public:
  29115. const String message;
  29116. ActionMessage (const String& messageText,
  29117. void* const listener_) throw()
  29118. : message (messageText)
  29119. {
  29120. pointerParameter = listener_;
  29121. }
  29122. ~ActionMessage() throw()
  29123. {
  29124. }
  29125. private:
  29126. ActionMessage (const ActionMessage&);
  29127. const ActionMessage& operator= (const ActionMessage&);
  29128. };
  29129. ActionListenerList::ActionListenerList() throw()
  29130. {
  29131. }
  29132. ActionListenerList::~ActionListenerList() throw()
  29133. {
  29134. }
  29135. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29136. {
  29137. const ScopedLock sl (actionListenerLock_);
  29138. jassert (listener != 0);
  29139. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29140. if (listener != 0)
  29141. actionListeners_.add (listener);
  29142. }
  29143. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29144. {
  29145. const ScopedLock sl (actionListenerLock_);
  29146. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29147. actionListeners_.removeValue (listener);
  29148. }
  29149. void ActionListenerList::removeAllActionListeners() throw()
  29150. {
  29151. const ScopedLock sl (actionListenerLock_);
  29152. actionListeners_.clear();
  29153. }
  29154. void ActionListenerList::sendActionMessage (const String& message) const
  29155. {
  29156. const ScopedLock sl (actionListenerLock_);
  29157. for (int i = actionListeners_.size(); --i >= 0;)
  29158. {
  29159. postMessage (new ActionMessage (message,
  29160. (ActionListener*) actionListeners_.getUnchecked(i)));
  29161. }
  29162. }
  29163. void ActionListenerList::handleMessage (const Message& message)
  29164. {
  29165. const ActionMessage& am = (const ActionMessage&) message;
  29166. if (actionListeners_.contains (am.pointerParameter))
  29167. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  29168. }
  29169. END_JUCE_NAMESPACE
  29170. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  29171. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  29172. BEGIN_JUCE_NAMESPACE
  29173. AsyncUpdater::AsyncUpdater() throw()
  29174. : asyncMessagePending (false)
  29175. {
  29176. internalAsyncHandler.owner = this;
  29177. }
  29178. AsyncUpdater::~AsyncUpdater()
  29179. {
  29180. }
  29181. void AsyncUpdater::triggerAsyncUpdate() throw()
  29182. {
  29183. if (! asyncMessagePending)
  29184. {
  29185. asyncMessagePending = true;
  29186. internalAsyncHandler.postMessage (new Message());
  29187. }
  29188. }
  29189. void AsyncUpdater::cancelPendingUpdate() throw()
  29190. {
  29191. asyncMessagePending = false;
  29192. }
  29193. void AsyncUpdater::handleUpdateNowIfNeeded()
  29194. {
  29195. if (asyncMessagePending)
  29196. {
  29197. asyncMessagePending = false;
  29198. handleAsyncUpdate();
  29199. }
  29200. }
  29201. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29202. {
  29203. owner->handleUpdateNowIfNeeded();
  29204. }
  29205. END_JUCE_NAMESPACE
  29206. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  29207. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  29208. BEGIN_JUCE_NAMESPACE
  29209. ChangeBroadcaster::ChangeBroadcaster() throw()
  29210. {
  29211. // are you trying to create this object before or after juce has been intialised??
  29212. jassert (MessageManager::instance != 0);
  29213. }
  29214. ChangeBroadcaster::~ChangeBroadcaster()
  29215. {
  29216. // all event-based objects must be deleted BEFORE juce is shut down!
  29217. jassert (MessageManager::instance != 0);
  29218. }
  29219. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29220. {
  29221. changeListenerList.addChangeListener (listener);
  29222. }
  29223. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29224. {
  29225. jassert (changeListenerList.isValidMessageListener());
  29226. if (changeListenerList.isValidMessageListener())
  29227. changeListenerList.removeChangeListener (listener);
  29228. }
  29229. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29230. {
  29231. changeListenerList.removeAllChangeListeners();
  29232. }
  29233. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29234. {
  29235. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29236. }
  29237. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29238. {
  29239. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29240. }
  29241. void ChangeBroadcaster::dispatchPendingMessages()
  29242. {
  29243. changeListenerList.dispatchPendingMessages();
  29244. }
  29245. END_JUCE_NAMESPACE
  29246. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  29247. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  29248. BEGIN_JUCE_NAMESPACE
  29249. ChangeListenerList::ChangeListenerList() throw()
  29250. : lastChangedObject (0),
  29251. messagePending (false)
  29252. {
  29253. }
  29254. ChangeListenerList::~ChangeListenerList() throw()
  29255. {
  29256. }
  29257. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29258. {
  29259. const ScopedLock sl (lock);
  29260. jassert (listener != 0);
  29261. if (listener != 0)
  29262. listeners.add (listener);
  29263. }
  29264. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29265. {
  29266. const ScopedLock sl (lock);
  29267. listeners.removeValue (listener);
  29268. }
  29269. void ChangeListenerList::removeAllChangeListeners() throw()
  29270. {
  29271. const ScopedLock sl (lock);
  29272. listeners.clear();
  29273. }
  29274. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29275. {
  29276. const ScopedLock sl (lock);
  29277. if ((! messagePending) && (listeners.size() > 0))
  29278. {
  29279. lastChangedObject = objectThatHasChanged;
  29280. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29281. messagePending = true;
  29282. }
  29283. }
  29284. void ChangeListenerList::handleMessage (const Message& message)
  29285. {
  29286. sendSynchronousChangeMessage (message.pointerParameter);
  29287. }
  29288. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29289. {
  29290. const ScopedLock sl (lock);
  29291. messagePending = false;
  29292. for (int i = listeners.size(); --i >= 0;)
  29293. {
  29294. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  29295. {
  29296. const ScopedUnlock tempUnlocker (lock);
  29297. l->changeListenerCallback (objectThatHasChanged);
  29298. }
  29299. i = jmin (i, listeners.size());
  29300. }
  29301. }
  29302. void ChangeListenerList::dispatchPendingMessages()
  29303. {
  29304. if (messagePending)
  29305. sendSynchronousChangeMessage (lastChangedObject);
  29306. }
  29307. END_JUCE_NAMESPACE
  29308. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  29309. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  29310. BEGIN_JUCE_NAMESPACE
  29311. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  29312. const uint32 magicMessageHeaderNumber)
  29313. : Thread ("Juce IPC connection"),
  29314. socket (0),
  29315. pipe (0),
  29316. callbackConnectionState (false),
  29317. useMessageThread (callbacksOnMessageThread),
  29318. magicMessageHeader (magicMessageHeaderNumber),
  29319. pipeReceiveMessageTimeout (-1)
  29320. {
  29321. }
  29322. InterprocessConnection::~InterprocessConnection()
  29323. {
  29324. callbackConnectionState = false;
  29325. disconnect();
  29326. }
  29327. bool InterprocessConnection::connectToSocket (const String& hostName,
  29328. const int portNumber,
  29329. const int timeOutMillisecs)
  29330. {
  29331. disconnect();
  29332. const ScopedLock sl (pipeAndSocketLock);
  29333. socket = new StreamingSocket();
  29334. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  29335. {
  29336. connectionMadeInt();
  29337. startThread();
  29338. return true;
  29339. }
  29340. else
  29341. {
  29342. deleteAndZero (socket);
  29343. return false;
  29344. }
  29345. }
  29346. bool InterprocessConnection::connectToPipe (const String& pipeName,
  29347. const int pipeReceiveMessageTimeoutMs)
  29348. {
  29349. disconnect();
  29350. NamedPipe* const newPipe = new NamedPipe();
  29351. if (newPipe->openExisting (pipeName))
  29352. {
  29353. const ScopedLock sl (pipeAndSocketLock);
  29354. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29355. initialiseWithPipe (newPipe);
  29356. return true;
  29357. }
  29358. else
  29359. {
  29360. delete newPipe;
  29361. return false;
  29362. }
  29363. }
  29364. bool InterprocessConnection::createPipe (const String& pipeName,
  29365. const int pipeReceiveMessageTimeoutMs)
  29366. {
  29367. disconnect();
  29368. NamedPipe* const newPipe = new NamedPipe();
  29369. if (newPipe->createNewPipe (pipeName))
  29370. {
  29371. const ScopedLock sl (pipeAndSocketLock);
  29372. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29373. initialiseWithPipe (newPipe);
  29374. return true;
  29375. }
  29376. else
  29377. {
  29378. delete newPipe;
  29379. return false;
  29380. }
  29381. }
  29382. void InterprocessConnection::disconnect()
  29383. {
  29384. if (socket != 0)
  29385. socket->close();
  29386. if (pipe != 0)
  29387. {
  29388. pipe->cancelPendingReads();
  29389. pipe->close();
  29390. }
  29391. stopThread (4000);
  29392. {
  29393. const ScopedLock sl (pipeAndSocketLock);
  29394. deleteAndZero (socket);
  29395. deleteAndZero (pipe);
  29396. }
  29397. connectionLostInt();
  29398. }
  29399. bool InterprocessConnection::isConnected() const
  29400. {
  29401. const ScopedLock sl (pipeAndSocketLock);
  29402. return ((socket != 0 && socket->isConnected())
  29403. || (pipe != 0 && pipe->isOpen()))
  29404. && isThreadRunning();
  29405. }
  29406. const String InterprocessConnection::getConnectedHostName() const
  29407. {
  29408. if (pipe != 0)
  29409. {
  29410. return "localhost";
  29411. }
  29412. else if (socket != 0)
  29413. {
  29414. if (! socket->isLocal())
  29415. return socket->getHostName();
  29416. return "localhost";
  29417. }
  29418. return String::empty;
  29419. }
  29420. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  29421. {
  29422. uint32 messageHeader[2];
  29423. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  29424. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  29425. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  29426. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  29427. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  29428. int bytesWritten = 0;
  29429. const ScopedLock sl (pipeAndSocketLock);
  29430. if (socket != 0)
  29431. {
  29432. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  29433. }
  29434. else if (pipe != 0)
  29435. {
  29436. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  29437. }
  29438. if (bytesWritten < 0)
  29439. {
  29440. // error..
  29441. return false;
  29442. }
  29443. return (bytesWritten == messageData.getSize());
  29444. }
  29445. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  29446. {
  29447. jassert (socket == 0);
  29448. socket = socket_;
  29449. connectionMadeInt();
  29450. startThread();
  29451. }
  29452. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  29453. {
  29454. jassert (pipe == 0);
  29455. pipe = pipe_;
  29456. connectionMadeInt();
  29457. startThread();
  29458. }
  29459. const int messageMagicNumber = 0xb734128b;
  29460. void InterprocessConnection::handleMessage (const Message& message)
  29461. {
  29462. if (message.intParameter1 == messageMagicNumber)
  29463. {
  29464. switch (message.intParameter2)
  29465. {
  29466. case 0:
  29467. {
  29468. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  29469. messageReceived (*data);
  29470. delete data;
  29471. break;
  29472. }
  29473. case 1:
  29474. connectionMade();
  29475. break;
  29476. case 2:
  29477. connectionLost();
  29478. break;
  29479. }
  29480. }
  29481. }
  29482. void InterprocessConnection::connectionMadeInt()
  29483. {
  29484. if (! callbackConnectionState)
  29485. {
  29486. callbackConnectionState = true;
  29487. if (useMessageThread)
  29488. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  29489. else
  29490. connectionMade();
  29491. }
  29492. }
  29493. void InterprocessConnection::connectionLostInt()
  29494. {
  29495. if (callbackConnectionState)
  29496. {
  29497. callbackConnectionState = false;
  29498. if (useMessageThread)
  29499. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  29500. else
  29501. connectionLost();
  29502. }
  29503. }
  29504. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  29505. {
  29506. jassert (callbackConnectionState);
  29507. if (useMessageThread)
  29508. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  29509. else
  29510. messageReceived (data);
  29511. }
  29512. bool InterprocessConnection::readNextMessageInt()
  29513. {
  29514. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  29515. uint32 messageHeader[2];
  29516. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  29517. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  29518. if (bytes == sizeof (messageHeader)
  29519. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  29520. {
  29521. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  29522. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  29523. {
  29524. MemoryBlock messageData (bytesInMessage, true);
  29525. int bytesRead = 0;
  29526. while (bytesRead < bytesInMessage)
  29527. {
  29528. if (threadShouldExit())
  29529. return false;
  29530. const int numThisTime = jmin (bytesInMessage, 65536);
  29531. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime, true)
  29532. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  29533. pipeReceiveMessageTimeout);
  29534. if (bytesIn <= 0)
  29535. break;
  29536. bytesRead += bytesIn;
  29537. }
  29538. if (bytesRead >= 0)
  29539. deliverDataInt (messageData);
  29540. }
  29541. }
  29542. else if (bytes < 0)
  29543. {
  29544. {
  29545. const ScopedLock sl (pipeAndSocketLock);
  29546. deleteAndZero (socket);
  29547. }
  29548. connectionLostInt();
  29549. return false;
  29550. }
  29551. return true;
  29552. }
  29553. void InterprocessConnection::run()
  29554. {
  29555. while (! threadShouldExit())
  29556. {
  29557. if (socket != 0)
  29558. {
  29559. const int ready = socket->waitUntilReady (true, 0);
  29560. if (ready < 0)
  29561. {
  29562. {
  29563. const ScopedLock sl (pipeAndSocketLock);
  29564. deleteAndZero (socket);
  29565. }
  29566. connectionLostInt();
  29567. break;
  29568. }
  29569. else if (ready > 0)
  29570. {
  29571. if (! readNextMessageInt())
  29572. break;
  29573. }
  29574. else
  29575. {
  29576. Thread::sleep (2);
  29577. }
  29578. }
  29579. else if (pipe != 0)
  29580. {
  29581. if (! pipe->isOpen())
  29582. {
  29583. {
  29584. const ScopedLock sl (pipeAndSocketLock);
  29585. deleteAndZero (pipe);
  29586. }
  29587. connectionLostInt();
  29588. break;
  29589. }
  29590. else
  29591. {
  29592. if (! readNextMessageInt())
  29593. break;
  29594. }
  29595. }
  29596. else
  29597. {
  29598. break;
  29599. }
  29600. }
  29601. }
  29602. END_JUCE_NAMESPACE
  29603. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  29604. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29605. BEGIN_JUCE_NAMESPACE
  29606. InterprocessConnectionServer::InterprocessConnectionServer()
  29607. : Thread ("Juce IPC server"),
  29608. socket (0)
  29609. {
  29610. }
  29611. InterprocessConnectionServer::~InterprocessConnectionServer()
  29612. {
  29613. stop();
  29614. }
  29615. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  29616. {
  29617. stop();
  29618. socket = new StreamingSocket();
  29619. if (socket->createListener (portNumber))
  29620. {
  29621. startThread();
  29622. return true;
  29623. }
  29624. deleteAndZero (socket);
  29625. return false;
  29626. }
  29627. void InterprocessConnectionServer::stop()
  29628. {
  29629. signalThreadShouldExit();
  29630. if (socket != 0)
  29631. socket->close();
  29632. stopThread (4000);
  29633. deleteAndZero (socket);
  29634. }
  29635. void InterprocessConnectionServer::run()
  29636. {
  29637. while ((! threadShouldExit()) && socket != 0)
  29638. {
  29639. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  29640. if (clientSocket != 0)
  29641. {
  29642. InterprocessConnection* newConnection = createConnectionObject();
  29643. if (newConnection != 0)
  29644. {
  29645. newConnection->initialiseWithSocket (clientSocket);
  29646. }
  29647. else
  29648. {
  29649. delete clientSocket;
  29650. }
  29651. }
  29652. }
  29653. }
  29654. END_JUCE_NAMESPACE
  29655. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29656. /********* Start of inlined file: juce_Message.cpp *********/
  29657. BEGIN_JUCE_NAMESPACE
  29658. Message::Message() throw()
  29659. {
  29660. }
  29661. Message::~Message() throw()
  29662. {
  29663. }
  29664. Message::Message (const int intParameter1_,
  29665. const int intParameter2_,
  29666. const int intParameter3_,
  29667. void* const pointerParameter_) throw()
  29668. : intParameter1 (intParameter1_),
  29669. intParameter2 (intParameter2_),
  29670. intParameter3 (intParameter3_),
  29671. pointerParameter (pointerParameter_)
  29672. {
  29673. }
  29674. END_JUCE_NAMESPACE
  29675. /********* End of inlined file: juce_Message.cpp *********/
  29676. /********* Start of inlined file: juce_MessageListener.cpp *********/
  29677. BEGIN_JUCE_NAMESPACE
  29678. MessageListener::MessageListener() throw()
  29679. {
  29680. // are you trying to create a messagelistener before or after juce has been intialised??
  29681. jassert (MessageManager::instance != 0);
  29682. if (MessageManager::instance != 0)
  29683. MessageManager::instance->messageListeners.add (this);
  29684. }
  29685. MessageListener::~MessageListener()
  29686. {
  29687. if (MessageManager::instance != 0)
  29688. MessageManager::instance->messageListeners.removeValue (this);
  29689. }
  29690. void MessageListener::postMessage (Message* const message) const throw()
  29691. {
  29692. message->messageRecipient = const_cast <MessageListener*> (this);
  29693. if (MessageManager::instance == 0)
  29694. MessageManager::getInstance();
  29695. MessageManager::instance->postMessageToQueue (message);
  29696. }
  29697. bool MessageListener::isValidMessageListener() const throw()
  29698. {
  29699. return (MessageManager::instance != 0)
  29700. && MessageManager::instance->messageListeners.contains (this);
  29701. }
  29702. END_JUCE_NAMESPACE
  29703. /********* End of inlined file: juce_MessageListener.cpp *********/
  29704. /********* Start of inlined file: juce_MessageManager.cpp *********/
  29705. BEGIN_JUCE_NAMESPACE
  29706. // platform-specific functions..
  29707. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  29708. bool juce_postMessageToSystemQueue (void* message);
  29709. MessageManager* MessageManager::instance = 0;
  29710. static const int quitMessageId = 0xfffff321;
  29711. MessageManager::MessageManager() throw()
  29712. : broadcastListeners (0),
  29713. quitMessagePosted (false),
  29714. quitMessageReceived (false),
  29715. threadWithLock (0)
  29716. {
  29717. messageThreadId = Thread::getCurrentThreadId();
  29718. }
  29719. MessageManager::~MessageManager() throw()
  29720. {
  29721. deleteAndZero (broadcastListeners);
  29722. doPlatformSpecificShutdown();
  29723. jassert (instance == this);
  29724. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  29725. }
  29726. MessageManager* MessageManager::getInstance() throw()
  29727. {
  29728. if (instance == 0)
  29729. {
  29730. instance = new MessageManager();
  29731. doPlatformSpecificInitialisation();
  29732. }
  29733. return instance;
  29734. }
  29735. void MessageManager::postMessageToQueue (Message* const message)
  29736. {
  29737. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  29738. delete message;
  29739. }
  29740. CallbackMessage::CallbackMessage() throw() {}
  29741. CallbackMessage::~CallbackMessage() throw() {}
  29742. void CallbackMessage::post()
  29743. {
  29744. if (MessageManager::instance != 0)
  29745. MessageManager::instance->postCallbackMessage (this);
  29746. }
  29747. void MessageManager::postCallbackMessage (Message* const message)
  29748. {
  29749. message->messageRecipient = 0;
  29750. postMessageToQueue (message);
  29751. }
  29752. // not for public use..
  29753. void MessageManager::deliverMessage (void* message)
  29754. {
  29755. Message* const m = (Message*) message;
  29756. MessageListener* const recipient = m->messageRecipient;
  29757. JUCE_TRY
  29758. {
  29759. if (messageListeners.contains (recipient))
  29760. {
  29761. recipient->handleMessage (*m);
  29762. }
  29763. else if (recipient == 0)
  29764. {
  29765. if (m->intParameter1 == quitMessageId)
  29766. {
  29767. quitMessageReceived = true;
  29768. }
  29769. else if (dynamic_cast <CallbackMessage*> (m) != 0)
  29770. {
  29771. (dynamic_cast <CallbackMessage*> (m))->messageCallback();
  29772. }
  29773. }
  29774. }
  29775. JUCE_CATCH_EXCEPTION
  29776. delete m;
  29777. }
  29778. #if ! JUCE_MAC
  29779. void MessageManager::runDispatchLoop()
  29780. {
  29781. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29782. runDispatchLoopUntil (-1);
  29783. }
  29784. void MessageManager::stopDispatchLoop()
  29785. {
  29786. Message* const m = new Message (quitMessageId, 0, 0, 0);
  29787. m->messageRecipient = 0;
  29788. postMessageToQueue (m);
  29789. quitMessagePosted = true;
  29790. }
  29791. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  29792. {
  29793. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29794. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  29795. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  29796. && ! quitMessageReceived)
  29797. {
  29798. JUCE_TRY
  29799. {
  29800. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  29801. {
  29802. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  29803. if (msToWait > 0)
  29804. Thread::sleep (jmin (5, msToWait));
  29805. }
  29806. }
  29807. JUCE_CATCH_EXCEPTION
  29808. }
  29809. return ! quitMessageReceived;
  29810. }
  29811. #endif
  29812. void MessageManager::deliverBroadcastMessage (const String& value)
  29813. {
  29814. if (broadcastListeners != 0)
  29815. broadcastListeners->sendActionMessage (value);
  29816. }
  29817. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  29818. {
  29819. if (broadcastListeners == 0)
  29820. broadcastListeners = new ActionListenerList();
  29821. broadcastListeners->addActionListener (listener);
  29822. }
  29823. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  29824. {
  29825. if (broadcastListeners != 0)
  29826. broadcastListeners->removeActionListener (listener);
  29827. }
  29828. bool MessageManager::isThisTheMessageThread() const throw()
  29829. {
  29830. return Thread::getCurrentThreadId() == messageThreadId;
  29831. }
  29832. void MessageManager::setCurrentMessageThread (const Thread::ThreadID threadId) throw()
  29833. {
  29834. messageThreadId = threadId;
  29835. }
  29836. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  29837. {
  29838. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  29839. return thisThread == messageThreadId || thisThread == threadWithLock;
  29840. }
  29841. /* The only safe way to lock the message thread while another thread does
  29842. some work is by posting a special message, whose purpose is to tie up the event
  29843. loop until the other thread has finished its business.
  29844. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  29845. get locked before making an event callback, because if the same OS lock gets indirectly
  29846. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  29847. in Cocoa).
  29848. */
  29849. class SharedLockingEvents : public ReferenceCountedObject
  29850. {
  29851. public:
  29852. SharedLockingEvents() throw() {}
  29853. ~SharedLockingEvents() {}
  29854. /* This class just holds a couple of events to communicate between the MMLockMessage
  29855. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  29856. this shared data must be kept in a separate, ref-counted container. */
  29857. WaitableEvent lockedEvent, releaseEvent;
  29858. };
  29859. class MMLockMessage : public CallbackMessage
  29860. {
  29861. public:
  29862. MMLockMessage (SharedLockingEvents* const events_) throw()
  29863. : events (events_)
  29864. {}
  29865. ~MMLockMessage() throw() {}
  29866. ReferenceCountedObjectPtr <SharedLockingEvents> events;
  29867. void messageCallback()
  29868. {
  29869. events->lockedEvent.signal();
  29870. events->releaseEvent.wait();
  29871. }
  29872. juce_UseDebuggingNewOperator
  29873. MMLockMessage (const MMLockMessage&);
  29874. const MMLockMessage& operator= (const MMLockMessage&);
  29875. };
  29876. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  29877. : locked (false),
  29878. needsUnlocking (false)
  29879. {
  29880. init (threadToCheck, 0);
  29881. }
  29882. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  29883. : locked (false),
  29884. needsUnlocking (false)
  29885. {
  29886. init (0, jobToCheckForExitSignal);
  29887. }
  29888. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  29889. {
  29890. if (MessageManager::instance != 0)
  29891. {
  29892. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  29893. {
  29894. locked = true; // either we're on the message thread, or this is a re-entrant call.
  29895. }
  29896. else
  29897. {
  29898. if (threadToCheck == 0 && job == 0)
  29899. {
  29900. MessageManager::instance->lockingLock.enter();
  29901. }
  29902. else
  29903. {
  29904. while (! MessageManager::instance->lockingLock.tryEnter())
  29905. {
  29906. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  29907. || (job != 0 && job->shouldExit()))
  29908. return;
  29909. Thread::sleep (1);
  29910. }
  29911. }
  29912. SharedLockingEvents* const events = new SharedLockingEvents();
  29913. sharedEvents = events;
  29914. events->incReferenceCount();
  29915. (new MMLockMessage (events))->post();
  29916. while (! events->lockedEvent.wait (50))
  29917. {
  29918. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  29919. || (job != 0 && job->shouldExit()))
  29920. {
  29921. events->releaseEvent.signal();
  29922. events->decReferenceCount();
  29923. MessageManager::instance->lockingLock.exit();
  29924. return;
  29925. }
  29926. }
  29927. jassert (MessageManager::instance->threadWithLock == 0);
  29928. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  29929. locked = true;
  29930. needsUnlocking = true;
  29931. }
  29932. }
  29933. }
  29934. MessageManagerLock::~MessageManagerLock() throw()
  29935. {
  29936. if (needsUnlocking && MessageManager::instance != 0)
  29937. {
  29938. jassert (MessageManager::instance->currentThreadHasLockedMessageManager());
  29939. ((SharedLockingEvents*) sharedEvents)->releaseEvent.signal();
  29940. ((SharedLockingEvents*) sharedEvents)->decReferenceCount();
  29941. MessageManager::instance->threadWithLock = 0;
  29942. MessageManager::instance->lockingLock.exit();
  29943. }
  29944. }
  29945. END_JUCE_NAMESPACE
  29946. /********* End of inlined file: juce_MessageManager.cpp *********/
  29947. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  29948. BEGIN_JUCE_NAMESPACE
  29949. class InternalMultiTimerCallback : public Timer
  29950. {
  29951. public:
  29952. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  29953. : timerId (timerId_),
  29954. owner (owner_)
  29955. {
  29956. }
  29957. ~InternalMultiTimerCallback()
  29958. {
  29959. }
  29960. void timerCallback()
  29961. {
  29962. owner.timerCallback (timerId);
  29963. }
  29964. const int timerId;
  29965. private:
  29966. MultiTimer& owner;
  29967. };
  29968. MultiTimer::MultiTimer() throw()
  29969. {
  29970. }
  29971. MultiTimer::MultiTimer (const MultiTimer&) throw()
  29972. {
  29973. }
  29974. MultiTimer::~MultiTimer()
  29975. {
  29976. const ScopedLock sl (timerListLock);
  29977. for (int i = timers.size(); --i >= 0;)
  29978. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29979. timers.clear();
  29980. }
  29981. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  29982. {
  29983. const ScopedLock sl (timerListLock);
  29984. for (int i = timers.size(); --i >= 0;)
  29985. {
  29986. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29987. if (t->timerId == timerId)
  29988. {
  29989. t->startTimer (intervalInMilliseconds);
  29990. return;
  29991. }
  29992. }
  29993. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  29994. timers.add (newTimer);
  29995. newTimer->startTimer (intervalInMilliseconds);
  29996. }
  29997. void MultiTimer::stopTimer (const int timerId) throw()
  29998. {
  29999. const ScopedLock sl (timerListLock);
  30000. for (int i = timers.size(); --i >= 0;)
  30001. {
  30002. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30003. if (t->timerId == timerId)
  30004. t->stopTimer();
  30005. }
  30006. }
  30007. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30008. {
  30009. const ScopedLock sl (timerListLock);
  30010. for (int i = timers.size(); --i >= 0;)
  30011. {
  30012. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30013. if (t->timerId == timerId)
  30014. return t->isTimerRunning();
  30015. }
  30016. return false;
  30017. }
  30018. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30019. {
  30020. const ScopedLock sl (timerListLock);
  30021. for (int i = timers.size(); --i >= 0;)
  30022. {
  30023. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30024. if (t->timerId == timerId)
  30025. return t->getTimerInterval();
  30026. }
  30027. return 0;
  30028. }
  30029. END_JUCE_NAMESPACE
  30030. /********* End of inlined file: juce_MultiTimer.cpp *********/
  30031. /********* Start of inlined file: juce_Timer.cpp *********/
  30032. BEGIN_JUCE_NAMESPACE
  30033. class InternalTimerThread : private Thread,
  30034. private MessageListener,
  30035. private DeletedAtShutdown,
  30036. private AsyncUpdater
  30037. {
  30038. private:
  30039. friend class Timer;
  30040. static InternalTimerThread* instance;
  30041. static CriticalSection lock;
  30042. Timer* volatile firstTimer;
  30043. bool volatile callbackNeeded;
  30044. InternalTimerThread (const InternalTimerThread&);
  30045. const InternalTimerThread& operator= (const InternalTimerThread&);
  30046. void addTimer (Timer* const t) throw()
  30047. {
  30048. #ifdef JUCE_DEBUG
  30049. Timer* tt = firstTimer;
  30050. while (tt != 0)
  30051. {
  30052. // trying to add a timer that's already here - shouldn't get to this point,
  30053. // so if you get this assertion, let me know!
  30054. jassert (tt != t);
  30055. tt = tt->next;
  30056. }
  30057. jassert (t->previous == 0 && t->next == 0);
  30058. #endif
  30059. Timer* i = firstTimer;
  30060. if (i == 0 || i->countdownMs > t->countdownMs)
  30061. {
  30062. t->next = firstTimer;
  30063. firstTimer = t;
  30064. }
  30065. else
  30066. {
  30067. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30068. i = i->next;
  30069. jassert (i != 0);
  30070. t->next = i->next;
  30071. t->previous = i;
  30072. i->next = t;
  30073. }
  30074. if (t->next != 0)
  30075. t->next->previous = t;
  30076. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30077. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30078. notify();
  30079. }
  30080. void removeTimer (Timer* const t) throw()
  30081. {
  30082. #ifdef JUCE_DEBUG
  30083. Timer* tt = firstTimer;
  30084. bool found = false;
  30085. while (tt != 0)
  30086. {
  30087. if (tt == t)
  30088. {
  30089. found = true;
  30090. break;
  30091. }
  30092. tt = tt->next;
  30093. }
  30094. // trying to remove a timer that's not here - shouldn't get to this point,
  30095. // so if you get this assertion, let me know!
  30096. jassert (found);
  30097. #endif
  30098. if (t->previous != 0)
  30099. {
  30100. jassert (firstTimer != t);
  30101. t->previous->next = t->next;
  30102. }
  30103. else
  30104. {
  30105. jassert (firstTimer == t);
  30106. firstTimer = t->next;
  30107. }
  30108. if (t->next != 0)
  30109. t->next->previous = t->previous;
  30110. t->next = 0;
  30111. t->previous = 0;
  30112. }
  30113. void decrementAllCounters (const int numMillisecs) const
  30114. {
  30115. Timer* t = firstTimer;
  30116. while (t != 0)
  30117. {
  30118. t->countdownMs -= numMillisecs;
  30119. t = t->next;
  30120. }
  30121. }
  30122. void handleAsyncUpdate()
  30123. {
  30124. startThread (7);
  30125. }
  30126. public:
  30127. InternalTimerThread()
  30128. : Thread ("Juce Timer"),
  30129. firstTimer (0),
  30130. callbackNeeded (false)
  30131. {
  30132. triggerAsyncUpdate();
  30133. }
  30134. ~InternalTimerThread() throw()
  30135. {
  30136. stopThread (4000);
  30137. jassert (instance == this || instance == 0);
  30138. if (instance == this)
  30139. instance = 0;
  30140. }
  30141. void run()
  30142. {
  30143. uint32 lastTime = Time::getMillisecondCounter();
  30144. while (! threadShouldExit())
  30145. {
  30146. uint32 now = Time::getMillisecondCounter();
  30147. if (now <= lastTime)
  30148. {
  30149. wait (2);
  30150. continue;
  30151. }
  30152. const int elapsed = now - lastTime;
  30153. lastTime = now;
  30154. lock.enter();
  30155. decrementAllCounters (elapsed);
  30156. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  30157. : 1000;
  30158. lock.exit();
  30159. if (timeUntilFirstTimer <= 0)
  30160. {
  30161. callbackNeeded = true;
  30162. postMessage (new Message());
  30163. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  30164. // so this is how long to wait before assuming the message has been lost and trying again.
  30165. const uint32 messageDeliveryTimeout = now + 2000;
  30166. while (callbackNeeded)
  30167. {
  30168. wait (4);
  30169. if (threadShouldExit())
  30170. return;
  30171. now = Time::getMillisecondCounter();
  30172. if (now > messageDeliveryTimeout)
  30173. break;
  30174. }
  30175. }
  30176. else
  30177. {
  30178. // don't wait for too long because running this loop also helps keep the
  30179. // Time::getApproximateMillisecondTimer value stay up-to-date
  30180. wait (jlimit (1, 50, timeUntilFirstTimer));
  30181. }
  30182. }
  30183. }
  30184. void handleMessage (const Message&)
  30185. {
  30186. const ScopedLock sl (lock);
  30187. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30188. {
  30189. Timer* const t = firstTimer;
  30190. t->countdownMs = t->periodMs;
  30191. removeTimer (t);
  30192. addTimer (t);
  30193. const ScopedUnlock ul (lock);
  30194. JUCE_TRY
  30195. {
  30196. t->timerCallback();
  30197. }
  30198. JUCE_CATCH_EXCEPTION
  30199. }
  30200. callbackNeeded = false;
  30201. }
  30202. static void callAnyTimersSynchronously()
  30203. {
  30204. if (InternalTimerThread::instance != 0)
  30205. {
  30206. const Message m;
  30207. InternalTimerThread::instance->handleMessage (m);
  30208. }
  30209. }
  30210. static inline void add (Timer* const tim) throw()
  30211. {
  30212. if (instance == 0)
  30213. instance = new InternalTimerThread();
  30214. const ScopedLock sl (instance->lock);
  30215. instance->addTimer (tim);
  30216. }
  30217. static inline void remove (Timer* const tim) throw()
  30218. {
  30219. if (instance != 0)
  30220. {
  30221. const ScopedLock sl (instance->lock);
  30222. instance->removeTimer (tim);
  30223. }
  30224. }
  30225. static inline void resetCounter (Timer* const tim,
  30226. const int newCounter) throw()
  30227. {
  30228. if (instance != 0)
  30229. {
  30230. tim->countdownMs = newCounter;
  30231. tim->periodMs = newCounter;
  30232. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30233. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30234. {
  30235. const ScopedLock sl (instance->lock);
  30236. instance->removeTimer (tim);
  30237. instance->addTimer (tim);
  30238. }
  30239. }
  30240. }
  30241. };
  30242. InternalTimerThread* InternalTimerThread::instance = 0;
  30243. CriticalSection InternalTimerThread::lock;
  30244. void juce_callAnyTimersSynchronously()
  30245. {
  30246. InternalTimerThread::callAnyTimersSynchronously();
  30247. }
  30248. #ifdef JUCE_DEBUG
  30249. static SortedSet <Timer*> activeTimers;
  30250. #endif
  30251. Timer::Timer() throw()
  30252. : countdownMs (0),
  30253. periodMs (0),
  30254. previous (0),
  30255. next (0)
  30256. {
  30257. #ifdef JUCE_DEBUG
  30258. activeTimers.add (this);
  30259. #endif
  30260. }
  30261. Timer::Timer (const Timer&) throw()
  30262. : countdownMs (0),
  30263. periodMs (0),
  30264. previous (0),
  30265. next (0)
  30266. {
  30267. #ifdef JUCE_DEBUG
  30268. activeTimers.add (this);
  30269. #endif
  30270. }
  30271. Timer::~Timer()
  30272. {
  30273. stopTimer();
  30274. #ifdef JUCE_DEBUG
  30275. activeTimers.removeValue (this);
  30276. #endif
  30277. }
  30278. void Timer::startTimer (const int interval) throw()
  30279. {
  30280. const ScopedLock sl (InternalTimerThread::lock);
  30281. #ifdef JUCE_DEBUG
  30282. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30283. jassert (activeTimers.contains (this));
  30284. #endif
  30285. if (periodMs == 0)
  30286. {
  30287. countdownMs = interval;
  30288. periodMs = jmax (1, interval);
  30289. InternalTimerThread::add (this);
  30290. }
  30291. else
  30292. {
  30293. InternalTimerThread::resetCounter (this, interval);
  30294. }
  30295. }
  30296. void Timer::stopTimer() throw()
  30297. {
  30298. const ScopedLock sl (InternalTimerThread::lock);
  30299. #ifdef JUCE_DEBUG
  30300. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30301. jassert (activeTimers.contains (this));
  30302. #endif
  30303. if (periodMs > 0)
  30304. {
  30305. InternalTimerThread::remove (this);
  30306. periodMs = 0;
  30307. }
  30308. }
  30309. END_JUCE_NAMESPACE
  30310. /********* End of inlined file: juce_Timer.cpp *********/
  30311. /********* Start of inlined file: juce_Component.cpp *********/
  30312. BEGIN_JUCE_NAMESPACE
  30313. Component* Component::componentUnderMouse = 0;
  30314. Component* Component::currentlyFocusedComponent = 0;
  30315. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  30316. static Array <int> modalReturnValues (4);
  30317. static const int customCommandMessage = 0x7fff0001;
  30318. static const int exitModalStateMessage = 0x7fff0002;
  30319. // these are also used by ComponentPeer
  30320. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  30321. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  30322. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  30323. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  30324. int juce_LastMousePosX = 0;
  30325. int juce_LastMousePosY = 0;
  30326. int juce_MouseClickCounter = 0;
  30327. bool juce_MouseHasMovedSignificantlySincePressed = false;
  30328. static int countMouseClicks() throw()
  30329. {
  30330. int numClicks = 0;
  30331. if (juce_recentMouseDownTimes[0] != 0)
  30332. {
  30333. if (! juce_MouseHasMovedSignificantlySincePressed)
  30334. ++numClicks;
  30335. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  30336. {
  30337. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  30338. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  30339. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  30340. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  30341. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  30342. {
  30343. ++numClicks;
  30344. }
  30345. else
  30346. {
  30347. break;
  30348. }
  30349. }
  30350. }
  30351. return numClicks;
  30352. }
  30353. static int unboundedMouseOffsetX = 0;
  30354. static int unboundedMouseOffsetY = 0;
  30355. static bool isUnboundedMouseModeOn = false;
  30356. static bool isCursorVisibleUntilOffscreen;
  30357. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30358. static uint32 nextComponentUID = 0;
  30359. Component::Component() throw()
  30360. : parentComponent_ (0),
  30361. componentUID (++nextComponentUID),
  30362. numDeepMouseListeners (0),
  30363. childComponentList_ (16),
  30364. lookAndFeel_ (0),
  30365. effect_ (0),
  30366. bufferedImage_ (0),
  30367. mouseListeners_ (0),
  30368. keyListeners_ (0),
  30369. componentListeners_ (0),
  30370. propertySet_ (0),
  30371. componentFlags_ (0)
  30372. {
  30373. }
  30374. Component::Component (const String& name) throw()
  30375. : componentName_ (name),
  30376. parentComponent_ (0),
  30377. componentUID (++nextComponentUID),
  30378. numDeepMouseListeners (0),
  30379. childComponentList_ (16),
  30380. lookAndFeel_ (0),
  30381. effect_ (0),
  30382. bufferedImage_ (0),
  30383. mouseListeners_ (0),
  30384. keyListeners_ (0),
  30385. componentListeners_ (0),
  30386. propertySet_ (0),
  30387. componentFlags_ (0)
  30388. {
  30389. }
  30390. Component::~Component()
  30391. {
  30392. if (parentComponent_ != 0)
  30393. {
  30394. parentComponent_->removeChildComponent (this);
  30395. }
  30396. else if ((currentlyFocusedComponent == this)
  30397. || isParentOf (currentlyFocusedComponent))
  30398. {
  30399. giveAwayFocus();
  30400. }
  30401. if (componentUnderMouse == this)
  30402. componentUnderMouse = 0;
  30403. if (flags.hasHeavyweightPeerFlag)
  30404. removeFromDesktop();
  30405. modalComponentStack.removeValue (this);
  30406. for (int i = childComponentList_.size(); --i >= 0;)
  30407. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  30408. delete bufferedImage_;
  30409. delete mouseListeners_;
  30410. delete keyListeners_;
  30411. delete componentListeners_;
  30412. delete propertySet_;
  30413. }
  30414. void Component::setName (const String& name)
  30415. {
  30416. // if component methods are being called from threads other than the message
  30417. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30418. checkMessageManagerIsLocked
  30419. if (componentName_ != name)
  30420. {
  30421. componentName_ = name;
  30422. if (flags.hasHeavyweightPeerFlag)
  30423. {
  30424. ComponentPeer* const peer = getPeer();
  30425. jassert (peer != 0);
  30426. if (peer != 0)
  30427. peer->setTitle (name);
  30428. }
  30429. if (componentListeners_ != 0)
  30430. {
  30431. const ComponentDeletionWatcher deletionChecker (this);
  30432. for (int i = componentListeners_->size(); --i >= 0;)
  30433. {
  30434. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30435. ->componentNameChanged (*this);
  30436. if (deletionChecker.hasBeenDeleted())
  30437. return;
  30438. i = jmin (i, componentListeners_->size());
  30439. }
  30440. }
  30441. }
  30442. }
  30443. void Component::setVisible (bool shouldBeVisible)
  30444. {
  30445. if (flags.visibleFlag != shouldBeVisible)
  30446. {
  30447. // if component methods are being called from threads other than the message
  30448. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30449. checkMessageManagerIsLocked
  30450. const ComponentDeletionWatcher deletionChecker (this);
  30451. flags.visibleFlag = shouldBeVisible;
  30452. internalRepaint (0, 0, getWidth(), getHeight());
  30453. sendFakeMouseMove();
  30454. if (! shouldBeVisible)
  30455. {
  30456. if (currentlyFocusedComponent == this
  30457. || isParentOf (currentlyFocusedComponent))
  30458. {
  30459. if (parentComponent_ != 0)
  30460. parentComponent_->grabKeyboardFocus();
  30461. else
  30462. giveAwayFocus();
  30463. }
  30464. }
  30465. sendVisibilityChangeMessage();
  30466. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  30467. {
  30468. ComponentPeer* const peer = getPeer();
  30469. jassert (peer != 0);
  30470. if (peer != 0)
  30471. {
  30472. peer->setVisible (shouldBeVisible);
  30473. internalHierarchyChanged();
  30474. }
  30475. }
  30476. }
  30477. }
  30478. void Component::visibilityChanged()
  30479. {
  30480. }
  30481. void Component::sendVisibilityChangeMessage()
  30482. {
  30483. const ComponentDeletionWatcher deletionChecker (this);
  30484. visibilityChanged();
  30485. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  30486. {
  30487. for (int i = componentListeners_->size(); --i >= 0;)
  30488. {
  30489. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30490. ->componentVisibilityChanged (*this);
  30491. if (deletionChecker.hasBeenDeleted())
  30492. return;
  30493. i = jmin (i, componentListeners_->size());
  30494. }
  30495. }
  30496. }
  30497. bool Component::isShowing() const throw()
  30498. {
  30499. if (flags.visibleFlag)
  30500. {
  30501. if (parentComponent_ != 0)
  30502. {
  30503. return parentComponent_->isShowing();
  30504. }
  30505. else
  30506. {
  30507. const ComponentPeer* const peer = getPeer();
  30508. return peer != 0 && ! peer->isMinimised();
  30509. }
  30510. }
  30511. return false;
  30512. }
  30513. class FadeOutProxyComponent : public Component,
  30514. public Timer
  30515. {
  30516. public:
  30517. FadeOutProxyComponent (Component* comp,
  30518. const int fadeLengthMs,
  30519. const int deltaXToMove,
  30520. const int deltaYToMove,
  30521. const float scaleFactorAtEnd)
  30522. : lastTime (0),
  30523. alpha (1.0f),
  30524. scale (1.0f)
  30525. {
  30526. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  30527. setBounds (comp->getBounds());
  30528. comp->getParentComponent()->addAndMakeVisible (this);
  30529. toBehind (comp);
  30530. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  30531. centreX = comp->getX() + comp->getWidth() * 0.5f;
  30532. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  30533. centreY = comp->getY() + comp->getHeight() * 0.5f;
  30534. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  30535. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  30536. setInterceptsMouseClicks (false, false);
  30537. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  30538. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  30539. }
  30540. ~FadeOutProxyComponent()
  30541. {
  30542. delete image;
  30543. }
  30544. void paint (Graphics& g)
  30545. {
  30546. g.setOpacity (alpha);
  30547. g.drawImage (image,
  30548. 0, 0, getWidth(), getHeight(),
  30549. 0, 0, image->getWidth(), image->getHeight());
  30550. }
  30551. void timerCallback()
  30552. {
  30553. const uint32 now = Time::getMillisecondCounter();
  30554. if (lastTime == 0)
  30555. lastTime = now;
  30556. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  30557. lastTime = now;
  30558. alpha += alphaChangePerMs * msPassed;
  30559. if (alpha > 0)
  30560. {
  30561. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  30562. {
  30563. centreX += xChangePerMs * msPassed;
  30564. centreY += yChangePerMs * msPassed;
  30565. scale += scaleChangePerMs * msPassed;
  30566. const int w = roundFloatToInt (image->getWidth() * scale);
  30567. const int h = roundFloatToInt (image->getHeight() * scale);
  30568. setBounds (roundFloatToInt (centreX) - w / 2,
  30569. roundFloatToInt (centreY) - h / 2,
  30570. w, h);
  30571. }
  30572. repaint();
  30573. }
  30574. else
  30575. {
  30576. delete this;
  30577. }
  30578. }
  30579. juce_UseDebuggingNewOperator
  30580. private:
  30581. Image* image;
  30582. uint32 lastTime;
  30583. float alpha, alphaChangePerMs;
  30584. float centreX, xChangePerMs;
  30585. float centreY, yChangePerMs;
  30586. float scale, scaleChangePerMs;
  30587. FadeOutProxyComponent (const FadeOutProxyComponent&);
  30588. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  30589. };
  30590. void Component::fadeOutComponent (const int millisecondsToFade,
  30591. const int deltaXToMove,
  30592. const int deltaYToMove,
  30593. const float scaleFactorAtEnd)
  30594. {
  30595. //xxx won't work for comps without parents
  30596. if (isShowing() && millisecondsToFade > 0)
  30597. new FadeOutProxyComponent (this, millisecondsToFade,
  30598. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  30599. setVisible (false);
  30600. }
  30601. bool Component::isValidComponent() const throw()
  30602. {
  30603. return (this != 0) && isValidMessageListener();
  30604. }
  30605. void* Component::getWindowHandle() const throw()
  30606. {
  30607. const ComponentPeer* const peer = getPeer();
  30608. if (peer != 0)
  30609. return peer->getNativeHandle();
  30610. return 0;
  30611. }
  30612. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  30613. {
  30614. // if component methods are being called from threads other than the message
  30615. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30616. checkMessageManagerIsLocked
  30617. if (! isOpaque())
  30618. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  30619. int currentStyleFlags = 0;
  30620. // don't use getPeer(), so that we only get the peer that's specifically
  30621. // for this comp, and not for one of its parents.
  30622. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  30623. if (peer != 0)
  30624. currentStyleFlags = peer->getStyleFlags();
  30625. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  30626. {
  30627. const ComponentDeletionWatcher deletionChecker (this);
  30628. #if JUCE_LINUX
  30629. // it's wise to give the component a non-zero size before
  30630. // putting it on the desktop, as X windows get confused by this, and
  30631. // a (1, 1) minimum size is enforced here.
  30632. setSize (jmax (1, getWidth()),
  30633. jmax (1, getHeight()));
  30634. #endif
  30635. int x = 0, y = 0;
  30636. relativePositionToGlobal (x, y);
  30637. bool wasFullscreen = false;
  30638. bool wasMinimised = false;
  30639. ComponentBoundsConstrainer* currentConstainer = 0;
  30640. Rectangle oldNonFullScreenBounds;
  30641. if (peer != 0)
  30642. {
  30643. wasFullscreen = peer->isFullScreen();
  30644. wasMinimised = peer->isMinimised();
  30645. currentConstainer = peer->getConstrainer();
  30646. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  30647. removeFromDesktop();
  30648. setTopLeftPosition (x, y);
  30649. }
  30650. if (parentComponent_ != 0)
  30651. parentComponent_->removeChildComponent (this);
  30652. if (! deletionChecker.hasBeenDeleted())
  30653. {
  30654. flags.hasHeavyweightPeerFlag = true;
  30655. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  30656. Desktop::getInstance().addDesktopComponent (this);
  30657. bounds_.setPosition (x, y);
  30658. peer->setBounds (x, y, getWidth(), getHeight(), false);
  30659. peer->setVisible (isVisible());
  30660. if (wasFullscreen)
  30661. {
  30662. peer->setFullScreen (true);
  30663. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  30664. }
  30665. if (wasMinimised)
  30666. peer->setMinimised (true);
  30667. if (isAlwaysOnTop())
  30668. peer->setAlwaysOnTop (true);
  30669. peer->setConstrainer (currentConstainer);
  30670. repaint();
  30671. }
  30672. internalHierarchyChanged();
  30673. }
  30674. }
  30675. void Component::removeFromDesktop()
  30676. {
  30677. // if component methods are being called from threads other than the message
  30678. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30679. checkMessageManagerIsLocked
  30680. if (flags.hasHeavyweightPeerFlag)
  30681. {
  30682. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30683. flags.hasHeavyweightPeerFlag = false;
  30684. jassert (peer != 0);
  30685. delete peer;
  30686. Desktop::getInstance().removeDesktopComponent (this);
  30687. }
  30688. }
  30689. bool Component::isOnDesktop() const throw()
  30690. {
  30691. return flags.hasHeavyweightPeerFlag;
  30692. }
  30693. void Component::userTriedToCloseWindow()
  30694. {
  30695. /* This means that the user's trying to get rid of your window with the 'close window' system
  30696. menu option (on windows) or possibly the task manager - you should really handle this
  30697. and delete or hide your component in an appropriate way.
  30698. If you want to ignore the event and don't want to trigger this assertion, just override
  30699. this method and do nothing.
  30700. */
  30701. jassertfalse
  30702. }
  30703. void Component::minimisationStateChanged (bool)
  30704. {
  30705. }
  30706. void Component::setOpaque (const bool shouldBeOpaque) throw()
  30707. {
  30708. if (shouldBeOpaque != flags.opaqueFlag)
  30709. {
  30710. flags.opaqueFlag = shouldBeOpaque;
  30711. if (flags.hasHeavyweightPeerFlag)
  30712. {
  30713. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30714. if (peer != 0)
  30715. {
  30716. // to make it recreate the heavyweight window
  30717. addToDesktop (peer->getStyleFlags());
  30718. }
  30719. }
  30720. repaint();
  30721. }
  30722. }
  30723. bool Component::isOpaque() const throw()
  30724. {
  30725. return flags.opaqueFlag;
  30726. }
  30727. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  30728. {
  30729. if (shouldBeBuffered != flags.bufferToImageFlag)
  30730. {
  30731. deleteAndZero (bufferedImage_);
  30732. flags.bufferToImageFlag = shouldBeBuffered;
  30733. }
  30734. }
  30735. void Component::toFront (const bool setAsForeground)
  30736. {
  30737. // if component methods are being called from threads other than the message
  30738. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30739. checkMessageManagerIsLocked
  30740. if (flags.hasHeavyweightPeerFlag)
  30741. {
  30742. ComponentPeer* const peer = getPeer();
  30743. if (peer != 0)
  30744. {
  30745. peer->toFront (setAsForeground);
  30746. if (setAsForeground && ! hasKeyboardFocus (true))
  30747. grabKeyboardFocus();
  30748. }
  30749. }
  30750. else if (parentComponent_ != 0)
  30751. {
  30752. if (parentComponent_->childComponentList_.getLast() != this)
  30753. {
  30754. const int index = parentComponent_->childComponentList_.indexOf (this);
  30755. if (index >= 0)
  30756. {
  30757. int insertIndex = -1;
  30758. if (! flags.alwaysOnTopFlag)
  30759. {
  30760. insertIndex = parentComponent_->childComponentList_.size() - 1;
  30761. while (insertIndex > 0
  30762. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30763. {
  30764. --insertIndex;
  30765. }
  30766. }
  30767. if (index != insertIndex)
  30768. {
  30769. parentComponent_->childComponentList_.move (index, insertIndex);
  30770. sendFakeMouseMove();
  30771. repaintParent();
  30772. }
  30773. }
  30774. }
  30775. if (setAsForeground)
  30776. {
  30777. internalBroughtToFront();
  30778. grabKeyboardFocus();
  30779. }
  30780. }
  30781. }
  30782. void Component::toBehind (Component* const other)
  30783. {
  30784. if (other != 0)
  30785. {
  30786. // the two components must belong to the same parent..
  30787. jassert (parentComponent_ == other->parentComponent_);
  30788. if (parentComponent_ != 0)
  30789. {
  30790. const int index = parentComponent_->childComponentList_.indexOf (this);
  30791. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  30792. if (index >= 0
  30793. && otherIndex >= 0
  30794. && index != otherIndex - 1
  30795. && other != this)
  30796. {
  30797. if (index < otherIndex)
  30798. --otherIndex;
  30799. parentComponent_->childComponentList_.move (index, otherIndex);
  30800. sendFakeMouseMove();
  30801. repaintParent();
  30802. }
  30803. }
  30804. else if (isOnDesktop())
  30805. {
  30806. jassert (other->isOnDesktop());
  30807. if (other->isOnDesktop())
  30808. {
  30809. ComponentPeer* const us = getPeer();
  30810. ComponentPeer* const them = other->getPeer();
  30811. jassert (us != 0 && them != 0);
  30812. if (us != 0 && them != 0)
  30813. us->toBehind (them);
  30814. }
  30815. }
  30816. }
  30817. }
  30818. void Component::toBack()
  30819. {
  30820. if (isOnDesktop())
  30821. {
  30822. jassertfalse //xxx need to add this to native window
  30823. }
  30824. else if (parentComponent_ != 0
  30825. && parentComponent_->childComponentList_.getFirst() != this)
  30826. {
  30827. const int index = parentComponent_->childComponentList_.indexOf (this);
  30828. if (index > 0)
  30829. {
  30830. int insertIndex = 0;
  30831. if (flags.alwaysOnTopFlag)
  30832. {
  30833. while (insertIndex < parentComponent_->childComponentList_.size()
  30834. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30835. {
  30836. ++insertIndex;
  30837. }
  30838. }
  30839. if (index != insertIndex)
  30840. {
  30841. parentComponent_->childComponentList_.move (index, insertIndex);
  30842. sendFakeMouseMove();
  30843. repaintParent();
  30844. }
  30845. }
  30846. }
  30847. }
  30848. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  30849. {
  30850. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  30851. {
  30852. flags.alwaysOnTopFlag = shouldStayOnTop;
  30853. if (isOnDesktop())
  30854. {
  30855. ComponentPeer* const peer = getPeer();
  30856. jassert (peer != 0);
  30857. if (peer != 0)
  30858. {
  30859. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  30860. {
  30861. // some kinds of peer can't change their always-on-top status, so
  30862. // for these, we'll need to create a new window
  30863. const int oldFlags = peer->getStyleFlags();
  30864. removeFromDesktop();
  30865. addToDesktop (oldFlags);
  30866. }
  30867. }
  30868. }
  30869. if (shouldStayOnTop)
  30870. toFront (false);
  30871. internalHierarchyChanged();
  30872. }
  30873. }
  30874. bool Component::isAlwaysOnTop() const throw()
  30875. {
  30876. return flags.alwaysOnTopFlag;
  30877. }
  30878. int Component::proportionOfWidth (const float proportion) const throw()
  30879. {
  30880. return roundDoubleToInt (proportion * bounds_.getWidth());
  30881. }
  30882. int Component::proportionOfHeight (const float proportion) const throw()
  30883. {
  30884. return roundDoubleToInt (proportion * bounds_.getHeight());
  30885. }
  30886. int Component::getParentWidth() const throw()
  30887. {
  30888. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  30889. : getParentMonitorArea().getWidth();
  30890. }
  30891. int Component::getParentHeight() const throw()
  30892. {
  30893. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  30894. : getParentMonitorArea().getHeight();
  30895. }
  30896. int Component::getScreenX() const throw()
  30897. {
  30898. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  30899. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  30900. : getX());
  30901. }
  30902. int Component::getScreenY() const throw()
  30903. {
  30904. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  30905. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  30906. : getY());
  30907. }
  30908. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  30909. {
  30910. const Component* c = this;
  30911. do
  30912. {
  30913. if (c->flags.hasHeavyweightPeerFlag)
  30914. {
  30915. c->getPeer()->relativePositionToGlobal (x, y);
  30916. break;
  30917. }
  30918. x += c->getX();
  30919. y += c->getY();
  30920. c = c->parentComponent_;
  30921. }
  30922. while (c != 0);
  30923. }
  30924. void Component::globalPositionToRelative (int& x, int& y) const throw()
  30925. {
  30926. if (flags.hasHeavyweightPeerFlag)
  30927. {
  30928. getPeer()->globalPositionToRelative (x, y);
  30929. }
  30930. else
  30931. {
  30932. if (parentComponent_ != 0)
  30933. parentComponent_->globalPositionToRelative (x, y);
  30934. x -= getX();
  30935. y -= getY();
  30936. }
  30937. }
  30938. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  30939. {
  30940. if (targetComponent != 0)
  30941. {
  30942. const Component* c = this;
  30943. do
  30944. {
  30945. if (c == targetComponent)
  30946. return;
  30947. if (c->flags.hasHeavyweightPeerFlag)
  30948. {
  30949. c->getPeer()->relativePositionToGlobal (x, y);
  30950. break;
  30951. }
  30952. x += c->getX();
  30953. y += c->getY();
  30954. c = c->parentComponent_;
  30955. }
  30956. while (c != 0);
  30957. targetComponent->globalPositionToRelative (x, y);
  30958. }
  30959. }
  30960. void Component::setBounds (int x, int y, int w, int h)
  30961. {
  30962. // if component methods are being called from threads other than the message
  30963. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30964. checkMessageManagerIsLocked
  30965. if (w < 0) w = 0;
  30966. if (h < 0) h = 0;
  30967. const bool wasResized = (getWidth() != w || getHeight() != h);
  30968. const bool wasMoved = (getX() != x || getY() != y);
  30969. #ifdef JUCE_DEBUG
  30970. // It's a very bad idea to try to resize a window during its paint() method!
  30971. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  30972. #endif
  30973. if (wasMoved || wasResized)
  30974. {
  30975. if (flags.visibleFlag)
  30976. {
  30977. // send a fake mouse move to trigger enter/exit messages if needed..
  30978. sendFakeMouseMove();
  30979. if (! flags.hasHeavyweightPeerFlag)
  30980. repaintParent();
  30981. }
  30982. bounds_.setBounds (x, y, w, h);
  30983. if (wasResized)
  30984. repaint();
  30985. else if (! flags.hasHeavyweightPeerFlag)
  30986. repaintParent();
  30987. if (flags.hasHeavyweightPeerFlag)
  30988. {
  30989. ComponentPeer* const peer = getPeer();
  30990. if (peer != 0)
  30991. {
  30992. if (wasMoved && wasResized)
  30993. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  30994. else if (wasMoved)
  30995. peer->setPosition (getX(), getY());
  30996. else if (wasResized)
  30997. peer->setSize (getWidth(), getHeight());
  30998. }
  30999. }
  31000. sendMovedResizedMessages (wasMoved, wasResized);
  31001. }
  31002. }
  31003. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31004. {
  31005. JUCE_TRY
  31006. {
  31007. if (wasMoved)
  31008. moved();
  31009. if (wasResized)
  31010. {
  31011. resized();
  31012. for (int i = childComponentList_.size(); --i >= 0;)
  31013. {
  31014. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31015. i = jmin (i, childComponentList_.size());
  31016. }
  31017. }
  31018. if (parentComponent_ != 0)
  31019. parentComponent_->childBoundsChanged (this);
  31020. if (componentListeners_ != 0)
  31021. {
  31022. const ComponentDeletionWatcher deletionChecker (this);
  31023. for (int i = componentListeners_->size(); --i >= 0;)
  31024. {
  31025. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31026. ->componentMovedOrResized (*this, wasMoved, wasResized);
  31027. if (deletionChecker.hasBeenDeleted())
  31028. return;
  31029. i = jmin (i, componentListeners_->size());
  31030. }
  31031. }
  31032. }
  31033. JUCE_CATCH_EXCEPTION
  31034. }
  31035. void Component::setSize (const int w, const int h)
  31036. {
  31037. setBounds (getX(), getY(), w, h);
  31038. }
  31039. void Component::setTopLeftPosition (const int x, const int y)
  31040. {
  31041. setBounds (x, y, getWidth(), getHeight());
  31042. }
  31043. void Component::setTopRightPosition (const int x, const int y)
  31044. {
  31045. setTopLeftPosition (x - getWidth(), y);
  31046. }
  31047. void Component::setBounds (const Rectangle& r)
  31048. {
  31049. setBounds (r.getX(),
  31050. r.getY(),
  31051. r.getWidth(),
  31052. r.getHeight());
  31053. }
  31054. void Component::setBoundsRelative (const float x, const float y,
  31055. const float w, const float h)
  31056. {
  31057. const int pw = getParentWidth();
  31058. const int ph = getParentHeight();
  31059. setBounds (roundFloatToInt (x * pw),
  31060. roundFloatToInt (y * ph),
  31061. roundFloatToInt (w * pw),
  31062. roundFloatToInt (h * ph));
  31063. }
  31064. void Component::setCentrePosition (const int x, const int y)
  31065. {
  31066. setTopLeftPosition (x - getWidth() / 2,
  31067. y - getHeight() / 2);
  31068. }
  31069. void Component::setCentreRelative (const float x, const float y)
  31070. {
  31071. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  31072. roundFloatToInt (getParentHeight() * y));
  31073. }
  31074. void Component::centreWithSize (const int width, const int height)
  31075. {
  31076. setBounds ((getParentWidth() - width) / 2,
  31077. (getParentHeight() - height) / 2,
  31078. width,
  31079. height);
  31080. }
  31081. void Component::setBoundsInset (const BorderSize& borders)
  31082. {
  31083. setBounds (borders.getLeft(),
  31084. borders.getTop(),
  31085. getParentWidth() - (borders.getLeftAndRight()),
  31086. getParentHeight() - (borders.getTopAndBottom()));
  31087. }
  31088. void Component::setBoundsToFit (int x, int y, int width, int height,
  31089. const Justification& justification,
  31090. const bool onlyReduceInSize)
  31091. {
  31092. // it's no good calling this method unless both the component and
  31093. // target rectangle have a finite size.
  31094. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31095. if (getWidth() > 0 && getHeight() > 0
  31096. && width > 0 && height > 0)
  31097. {
  31098. int newW, newH;
  31099. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31100. {
  31101. newW = getWidth();
  31102. newH = getHeight();
  31103. }
  31104. else
  31105. {
  31106. const double imageRatio = getHeight() / (double) getWidth();
  31107. const double targetRatio = height / (double) width;
  31108. if (imageRatio <= targetRatio)
  31109. {
  31110. newW = width;
  31111. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  31112. }
  31113. else
  31114. {
  31115. newH = height;
  31116. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  31117. }
  31118. }
  31119. if (newW > 0 && newH > 0)
  31120. {
  31121. int newX, newY;
  31122. justification.applyToRectangle (newX, newY, newW, newH,
  31123. x, y, width, height);
  31124. setBounds (newX, newY, newW, newH);
  31125. }
  31126. }
  31127. }
  31128. bool Component::hitTest (int x, int y)
  31129. {
  31130. if (! flags.ignoresMouseClicksFlag)
  31131. return true;
  31132. if (flags.allowChildMouseClicksFlag)
  31133. {
  31134. for (int i = getNumChildComponents(); --i >= 0;)
  31135. {
  31136. Component* const c = getChildComponent (i);
  31137. if (c->isVisible()
  31138. && c->bounds_.contains (x, y)
  31139. && c->hitTest (x - c->getX(),
  31140. y - c->getY()))
  31141. {
  31142. return true;
  31143. }
  31144. }
  31145. }
  31146. return false;
  31147. }
  31148. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31149. const bool allowClicksOnChildComponents) throw()
  31150. {
  31151. flags.ignoresMouseClicksFlag = ! allowClicks;
  31152. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31153. }
  31154. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31155. bool& allowsClicksOnChildComponents) const throw()
  31156. {
  31157. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31158. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31159. }
  31160. bool Component::contains (const int x, const int y)
  31161. {
  31162. if (((unsigned int) x) < (unsigned int) getWidth()
  31163. && ((unsigned int) y) < (unsigned int) getHeight()
  31164. && hitTest (x, y))
  31165. {
  31166. if (parentComponent_ != 0)
  31167. {
  31168. return parentComponent_->contains (x + getX(),
  31169. y + getY());
  31170. }
  31171. else if (flags.hasHeavyweightPeerFlag)
  31172. {
  31173. const ComponentPeer* const peer = getPeer();
  31174. if (peer != 0)
  31175. return peer->contains (x, y, true);
  31176. }
  31177. }
  31178. return false;
  31179. }
  31180. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31181. {
  31182. if (! contains (x, y))
  31183. return false;
  31184. Component* p = this;
  31185. while (p->parentComponent_ != 0)
  31186. {
  31187. x += p->getX();
  31188. y += p->getY();
  31189. p = p->parentComponent_;
  31190. }
  31191. const Component* const c = p->getComponentAt (x, y);
  31192. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31193. }
  31194. Component* Component::getComponentAt (const int x, const int y)
  31195. {
  31196. if (flags.visibleFlag
  31197. && ((unsigned int) x) < (unsigned int) getWidth()
  31198. && ((unsigned int) y) < (unsigned int) getHeight()
  31199. && hitTest (x, y))
  31200. {
  31201. for (int i = childComponentList_.size(); --i >= 0;)
  31202. {
  31203. Component* const child = childComponentList_.getUnchecked(i);
  31204. Component* const c = child->getComponentAt (x - child->getX(),
  31205. y - child->getY());
  31206. if (c != 0)
  31207. return c;
  31208. }
  31209. return this;
  31210. }
  31211. return 0;
  31212. }
  31213. void Component::addChildComponent (Component* const child, int zOrder)
  31214. {
  31215. // if component methods are being called from threads other than the message
  31216. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31217. checkMessageManagerIsLocked
  31218. if (child != 0 && child->parentComponent_ != this)
  31219. {
  31220. if (child->parentComponent_ != 0)
  31221. child->parentComponent_->removeChildComponent (child);
  31222. else
  31223. child->removeFromDesktop();
  31224. child->parentComponent_ = this;
  31225. if (child->isVisible())
  31226. child->repaintParent();
  31227. if (! child->isAlwaysOnTop())
  31228. {
  31229. if (zOrder < 0 || zOrder > childComponentList_.size())
  31230. zOrder = childComponentList_.size();
  31231. while (zOrder > 0)
  31232. {
  31233. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31234. break;
  31235. --zOrder;
  31236. }
  31237. }
  31238. childComponentList_.insert (zOrder, child);
  31239. child->internalHierarchyChanged();
  31240. internalChildrenChanged();
  31241. }
  31242. }
  31243. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31244. {
  31245. if (child != 0)
  31246. {
  31247. child->setVisible (true);
  31248. addChildComponent (child, zOrder);
  31249. }
  31250. }
  31251. void Component::removeChildComponent (Component* const child)
  31252. {
  31253. removeChildComponent (childComponentList_.indexOf (child));
  31254. }
  31255. Component* Component::removeChildComponent (const int index)
  31256. {
  31257. // if component methods are being called from threads other than the message
  31258. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31259. checkMessageManagerIsLocked
  31260. Component* const child = childComponentList_ [index];
  31261. if (child != 0)
  31262. {
  31263. sendFakeMouseMove();
  31264. child->repaintParent();
  31265. childComponentList_.remove (index);
  31266. child->parentComponent_ = 0;
  31267. JUCE_TRY
  31268. {
  31269. if ((currentlyFocusedComponent == child)
  31270. || child->isParentOf (currentlyFocusedComponent))
  31271. {
  31272. // get rid first to force the grabKeyboardFocus to change to us.
  31273. giveAwayFocus();
  31274. grabKeyboardFocus();
  31275. }
  31276. }
  31277. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31278. catch (const std::exception& e)
  31279. {
  31280. currentlyFocusedComponent = 0;
  31281. Desktop::getInstance().triggerFocusCallback();
  31282. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31283. }
  31284. catch (...)
  31285. {
  31286. currentlyFocusedComponent = 0;
  31287. Desktop::getInstance().triggerFocusCallback();
  31288. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31289. }
  31290. #endif
  31291. child->internalHierarchyChanged();
  31292. internalChildrenChanged();
  31293. }
  31294. return child;
  31295. }
  31296. void Component::removeAllChildren()
  31297. {
  31298. for (int i = childComponentList_.size(); --i >= 0;)
  31299. removeChildComponent (i);
  31300. }
  31301. void Component::deleteAllChildren()
  31302. {
  31303. for (int i = childComponentList_.size(); --i >= 0;)
  31304. delete (removeChildComponent (i));
  31305. }
  31306. int Component::getNumChildComponents() const throw()
  31307. {
  31308. return childComponentList_.size();
  31309. }
  31310. Component* Component::getChildComponent (const int index) const throw()
  31311. {
  31312. return childComponentList_ [index];
  31313. }
  31314. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31315. {
  31316. return childComponentList_.indexOf (const_cast <Component*> (child));
  31317. }
  31318. Component* Component::getTopLevelComponent() const throw()
  31319. {
  31320. const Component* comp = this;
  31321. while (comp->parentComponent_ != 0)
  31322. comp = comp->parentComponent_;
  31323. return (Component*) comp;
  31324. }
  31325. bool Component::isParentOf (const Component* possibleChild) const throw()
  31326. {
  31327. while (possibleChild->isValidComponent())
  31328. {
  31329. possibleChild = possibleChild->parentComponent_;
  31330. if (possibleChild == this)
  31331. return true;
  31332. }
  31333. return false;
  31334. }
  31335. void Component::parentHierarchyChanged()
  31336. {
  31337. }
  31338. void Component::childrenChanged()
  31339. {
  31340. }
  31341. void Component::internalChildrenChanged()
  31342. {
  31343. const ComponentDeletionWatcher deletionChecker (this);
  31344. const bool hasListeners = componentListeners_ != 0;
  31345. childrenChanged();
  31346. if (hasListeners)
  31347. {
  31348. if (deletionChecker.hasBeenDeleted())
  31349. return;
  31350. for (int i = componentListeners_->size(); --i >= 0;)
  31351. {
  31352. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31353. ->componentChildrenChanged (*this);
  31354. if (deletionChecker.hasBeenDeleted())
  31355. return;
  31356. i = jmin (i, componentListeners_->size());
  31357. }
  31358. }
  31359. }
  31360. void Component::internalHierarchyChanged()
  31361. {
  31362. parentHierarchyChanged();
  31363. const ComponentDeletionWatcher deletionChecker (this);
  31364. if (componentListeners_ != 0)
  31365. {
  31366. for (int i = componentListeners_->size(); --i >= 0;)
  31367. {
  31368. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31369. ->componentParentHierarchyChanged (*this);
  31370. if (deletionChecker.hasBeenDeleted())
  31371. return;
  31372. i = jmin (i, componentListeners_->size());
  31373. }
  31374. }
  31375. for (int i = childComponentList_.size(); --i >= 0;)
  31376. {
  31377. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  31378. // you really shouldn't delete the parent component during a callback telling you
  31379. // that it's changed..
  31380. jassert (! deletionChecker.hasBeenDeleted());
  31381. if (deletionChecker.hasBeenDeleted())
  31382. return;
  31383. i = jmin (i, childComponentList_.size());
  31384. }
  31385. }
  31386. void* Component::runModalLoopCallback (void* userData)
  31387. {
  31388. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  31389. }
  31390. int Component::runModalLoop()
  31391. {
  31392. if (! MessageManager::getInstance()->isThisTheMessageThread())
  31393. {
  31394. // use a callback so this can be called from non-gui threads
  31395. return (int) (pointer_sized_int)
  31396. MessageManager::getInstance()
  31397. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  31398. }
  31399. Component* const prevFocused = getCurrentlyFocusedComponent();
  31400. ComponentDeletionWatcher* deletionChecker = 0;
  31401. if (prevFocused != 0)
  31402. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  31403. if (! isCurrentlyModal())
  31404. enterModalState();
  31405. JUCE_TRY
  31406. {
  31407. while (flags.currentlyModalFlag && flags.visibleFlag)
  31408. {
  31409. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  31410. break;
  31411. // check whether this component was deleted during the last message
  31412. if (! isValidMessageListener())
  31413. break;
  31414. }
  31415. }
  31416. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31417. catch (const std::exception& e)
  31418. {
  31419. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31420. return 0;
  31421. }
  31422. catch (...)
  31423. {
  31424. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31425. return 0;
  31426. }
  31427. #endif
  31428. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31429. int returnValue = 0;
  31430. if (modalIndex >= 0)
  31431. {
  31432. modalComponentReturnValueKeys.remove (modalIndex);
  31433. returnValue = modalReturnValues.remove (modalIndex);
  31434. }
  31435. modalComponentStack.removeValue (this);
  31436. if (deletionChecker != 0)
  31437. {
  31438. if (! deletionChecker->hasBeenDeleted())
  31439. prevFocused->grabKeyboardFocus();
  31440. delete deletionChecker;
  31441. }
  31442. return returnValue;
  31443. }
  31444. void Component::enterModalState (const bool takeKeyboardFocus)
  31445. {
  31446. // if component methods are being called from threads other than the message
  31447. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31448. checkMessageManagerIsLocked
  31449. // Check for an attempt to make a component modal when it already is!
  31450. // This can cause nasty problems..
  31451. jassert (! flags.currentlyModalFlag);
  31452. if (! isCurrentlyModal())
  31453. {
  31454. modalComponentStack.add (this);
  31455. modalComponentReturnValueKeys.add (this);
  31456. modalReturnValues.add (0);
  31457. flags.currentlyModalFlag = true;
  31458. setVisible (true);
  31459. if (takeKeyboardFocus)
  31460. grabKeyboardFocus();
  31461. }
  31462. }
  31463. void Component::exitModalState (const int returnValue)
  31464. {
  31465. if (isCurrentlyModal())
  31466. {
  31467. if (MessageManager::getInstance()->isThisTheMessageThread())
  31468. {
  31469. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31470. if (modalIndex >= 0)
  31471. {
  31472. modalReturnValues.set (modalIndex, returnValue);
  31473. }
  31474. else
  31475. {
  31476. modalComponentReturnValueKeys.add (this);
  31477. modalReturnValues.add (returnValue);
  31478. }
  31479. modalComponentStack.removeValue (this);
  31480. flags.currentlyModalFlag = false;
  31481. bringModalComponentToFront();
  31482. }
  31483. else
  31484. {
  31485. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  31486. }
  31487. }
  31488. }
  31489. bool Component::isCurrentlyModal() const throw()
  31490. {
  31491. return flags.currentlyModalFlag
  31492. && getCurrentlyModalComponent() == this;
  31493. }
  31494. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  31495. {
  31496. Component* const mc = getCurrentlyModalComponent();
  31497. return mc != 0
  31498. && mc != this
  31499. && (! mc->isParentOf (this))
  31500. && ! mc->canModalEventBeSentToComponent (this);
  31501. }
  31502. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  31503. {
  31504. return modalComponentStack.size();
  31505. }
  31506. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  31507. {
  31508. Component* const c = (Component*) (modalComponentStack [modalComponentStack.size() - index - 1]);
  31509. return c->isValidComponent() ? c : 0;
  31510. }
  31511. void Component::bringModalComponentToFront()
  31512. {
  31513. ComponentPeer* lastOne = 0;
  31514. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  31515. {
  31516. Component* const c = getCurrentlyModalComponent (i);
  31517. if (c == 0)
  31518. break;
  31519. ComponentPeer* peer = c->getPeer();
  31520. if (peer != 0 && peer != lastOne)
  31521. {
  31522. if (lastOne == 0)
  31523. {
  31524. peer->toFront (true);
  31525. peer->grabFocus();
  31526. }
  31527. else
  31528. peer->toBehind (lastOne);
  31529. lastOne = peer;
  31530. }
  31531. }
  31532. }
  31533. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  31534. {
  31535. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  31536. }
  31537. bool Component::isBroughtToFrontOnMouseClick() const throw()
  31538. {
  31539. return flags.bringToFrontOnClickFlag;
  31540. }
  31541. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  31542. {
  31543. cursor_ = cursor;
  31544. if (flags.visibleFlag)
  31545. {
  31546. int mx, my;
  31547. getMouseXYRelative (mx, my);
  31548. if (flags.draggingFlag || reallyContains (mx, my, false))
  31549. {
  31550. internalUpdateMouseCursor (false);
  31551. }
  31552. }
  31553. }
  31554. const MouseCursor Component::getMouseCursor()
  31555. {
  31556. return cursor_;
  31557. }
  31558. void Component::updateMouseCursor() const throw()
  31559. {
  31560. sendFakeMouseMove();
  31561. }
  31562. void Component::internalUpdateMouseCursor (bool forcedUpdate) throw()
  31563. {
  31564. ComponentPeer* const peer = getPeer();
  31565. if (peer != 0)
  31566. {
  31567. MouseCursor mc (getMouseCursor());
  31568. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  31569. || unboundedMouseOffsetY != 0
  31570. || ! isCursorVisibleUntilOffscreen))
  31571. {
  31572. mc = MouseCursor::NoCursor;
  31573. forcedUpdate = true;
  31574. }
  31575. static void* currentCursorHandle = 0;
  31576. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  31577. {
  31578. currentCursorHandle = mc.getHandle();
  31579. mc.showInWindow (peer);
  31580. }
  31581. }
  31582. }
  31583. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  31584. {
  31585. flags.repaintOnMouseActivityFlag = shouldRepaint;
  31586. }
  31587. void Component::repaintParent() throw()
  31588. {
  31589. if (flags.visibleFlag)
  31590. internalRepaint (0, 0, getWidth(), getHeight());
  31591. }
  31592. void Component::repaint() throw()
  31593. {
  31594. repaint (0, 0, getWidth(), getHeight());
  31595. }
  31596. void Component::repaint (const int x, const int y,
  31597. const int w, const int h) throw()
  31598. {
  31599. deleteAndZero (bufferedImage_);
  31600. if (flags.visibleFlag)
  31601. internalRepaint (x, y, w, h);
  31602. }
  31603. void Component::internalRepaint (int x, int y, int w, int h)
  31604. {
  31605. // if component methods are being called from threads other than the message
  31606. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31607. checkMessageManagerIsLocked
  31608. if (x < 0)
  31609. {
  31610. w += x;
  31611. x = 0;
  31612. }
  31613. if (x + w > getWidth())
  31614. w = getWidth() - x;
  31615. if (w > 0)
  31616. {
  31617. if (y < 0)
  31618. {
  31619. h += y;
  31620. y = 0;
  31621. }
  31622. if (y + h > getHeight())
  31623. h = getHeight() - y;
  31624. if (h > 0)
  31625. {
  31626. if (parentComponent_ != 0)
  31627. {
  31628. x += getX();
  31629. y += getY();
  31630. if (parentComponent_->flags.visibleFlag)
  31631. parentComponent_->internalRepaint (x, y, w, h);
  31632. }
  31633. else if (flags.hasHeavyweightPeerFlag)
  31634. {
  31635. ComponentPeer* const peer = getPeer();
  31636. if (peer != 0)
  31637. peer->repaint (x, y, w, h);
  31638. }
  31639. }
  31640. }
  31641. }
  31642. void Component::paintEntireComponent (Graphics& originalContext)
  31643. {
  31644. jassert (! originalContext.isClipEmpty());
  31645. #ifdef JUCE_DEBUG
  31646. flags.isInsidePaintCall = true;
  31647. #endif
  31648. Graphics* g = &originalContext;
  31649. Image* effectImage = 0;
  31650. if (effect_ != 0)
  31651. {
  31652. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31653. getWidth(), getHeight(),
  31654. ! flags.opaqueFlag);
  31655. g = new Graphics (*effectImage);
  31656. }
  31657. g->saveState();
  31658. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  31659. if (! g->isClipEmpty())
  31660. {
  31661. if (bufferedImage_ != 0)
  31662. {
  31663. g->setColour (Colours::black);
  31664. g->drawImageAt (bufferedImage_, 0, 0);
  31665. }
  31666. else
  31667. {
  31668. if (flags.bufferToImageFlag)
  31669. {
  31670. if (bufferedImage_ == 0)
  31671. {
  31672. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31673. getWidth(), getHeight(), ! flags.opaqueFlag);
  31674. Graphics imG (*bufferedImage_);
  31675. paint (imG);
  31676. }
  31677. g->setColour (Colours::black);
  31678. g->drawImageAt (bufferedImage_, 0, 0);
  31679. }
  31680. else
  31681. {
  31682. paint (*g);
  31683. g->resetToDefaultState();
  31684. }
  31685. }
  31686. }
  31687. g->restoreState();
  31688. for (int i = 0; i < childComponentList_.size(); ++i)
  31689. {
  31690. Component* const child = childComponentList_.getUnchecked (i);
  31691. if (child->isVisible())
  31692. {
  31693. g->saveState();
  31694. if (g->reduceClipRegion (child->getX(), child->getY(),
  31695. child->getWidth(), child->getHeight()))
  31696. {
  31697. for (int j = i + 1; j < childComponentList_.size(); ++j)
  31698. {
  31699. const Component* const sibling = childComponentList_.getUnchecked (j);
  31700. if (sibling->flags.opaqueFlag && sibling->isVisible())
  31701. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  31702. sibling->getWidth(), sibling->getHeight());
  31703. }
  31704. if (! g->isClipEmpty())
  31705. {
  31706. g->setOrigin (child->getX(), child->getY());
  31707. child->paintEntireComponent (*g);
  31708. }
  31709. }
  31710. g->restoreState();
  31711. }
  31712. }
  31713. JUCE_TRY
  31714. {
  31715. g->saveState();
  31716. paintOverChildren (*g);
  31717. g->restoreState();
  31718. }
  31719. JUCE_CATCH_EXCEPTION
  31720. if (effect_ != 0)
  31721. {
  31722. delete g;
  31723. effect_->applyEffect (*effectImage, originalContext);
  31724. delete effectImage;
  31725. }
  31726. #ifdef JUCE_DEBUG
  31727. flags.isInsidePaintCall = false;
  31728. #endif
  31729. }
  31730. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  31731. const bool clipImageToComponentBounds)
  31732. {
  31733. Rectangle r (areaToGrab);
  31734. if (clipImageToComponentBounds)
  31735. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  31736. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31737. jmax (1, r.getWidth()),
  31738. jmax (1, r.getHeight()),
  31739. true);
  31740. Graphics imageContext (*componentImage);
  31741. imageContext.setOrigin (-r.getX(),
  31742. -r.getY());
  31743. paintEntireComponent (imageContext);
  31744. return componentImage;
  31745. }
  31746. void Component::setComponentEffect (ImageEffectFilter* const effect)
  31747. {
  31748. if (effect_ != effect)
  31749. {
  31750. effect_ = effect;
  31751. repaint();
  31752. }
  31753. }
  31754. LookAndFeel& Component::getLookAndFeel() const throw()
  31755. {
  31756. const Component* c = this;
  31757. do
  31758. {
  31759. if (c->lookAndFeel_ != 0)
  31760. return *(c->lookAndFeel_);
  31761. c = c->parentComponent_;
  31762. }
  31763. while (c != 0);
  31764. return LookAndFeel::getDefaultLookAndFeel();
  31765. }
  31766. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  31767. {
  31768. if (lookAndFeel_ != newLookAndFeel)
  31769. {
  31770. lookAndFeel_ = newLookAndFeel;
  31771. sendLookAndFeelChange();
  31772. }
  31773. }
  31774. void Component::lookAndFeelChanged()
  31775. {
  31776. }
  31777. void Component::sendLookAndFeelChange()
  31778. {
  31779. repaint();
  31780. lookAndFeelChanged();
  31781. // (it's not a great idea to do anything that would delete this component
  31782. // during the lookAndFeelChanged() callback)
  31783. jassert (isValidComponent());
  31784. const ComponentDeletionWatcher deletionChecker (this);
  31785. for (int i = childComponentList_.size(); --i >= 0;)
  31786. {
  31787. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  31788. if (deletionChecker.hasBeenDeleted())
  31789. return;
  31790. i = jmin (i, childComponentList_.size());
  31791. }
  31792. }
  31793. static const String getColourPropertyName (const int colourId) throw()
  31794. {
  31795. String s;
  31796. s.preallocateStorage (18);
  31797. s << T("jcclr_") << colourId;
  31798. return s;
  31799. }
  31800. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  31801. {
  31802. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  31803. inheritFromParent,
  31804. String::empty));
  31805. if (customColour.isNotEmpty())
  31806. return Colour (customColour.getIntValue());
  31807. return getLookAndFeel().findColour (colourId);
  31808. }
  31809. bool Component::isColourSpecified (const int colourId) const throw()
  31810. {
  31811. return getComponentProperty (getColourPropertyName (colourId),
  31812. false,
  31813. String::empty).isNotEmpty();
  31814. }
  31815. void Component::removeColour (const int colourId)
  31816. {
  31817. if (isColourSpecified (colourId))
  31818. {
  31819. removeComponentProperty (getColourPropertyName (colourId));
  31820. colourChanged();
  31821. }
  31822. }
  31823. void Component::setColour (const int colourId, const Colour& colour)
  31824. {
  31825. const String colourName (getColourPropertyName (colourId));
  31826. const String customColour (getComponentProperty (colourName, false, String::empty));
  31827. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  31828. {
  31829. setComponentProperty (colourName, colour);
  31830. colourChanged();
  31831. }
  31832. }
  31833. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  31834. {
  31835. if (propertySet_ != 0)
  31836. {
  31837. const StringPairArray& props = propertySet_->getAllProperties();
  31838. const StringArray& keys = props.getAllKeys();
  31839. for (int i = 0; i < keys.size(); ++i)
  31840. {
  31841. if (keys[i].startsWith (T("jcclr_")))
  31842. {
  31843. target.setComponentProperty (keys[i],
  31844. props.getAllValues() [i]);
  31845. }
  31846. }
  31847. target.colourChanged();
  31848. }
  31849. }
  31850. void Component::colourChanged()
  31851. {
  31852. }
  31853. const Rectangle Component::getUnclippedArea() const
  31854. {
  31855. int x = 0, y = 0, w = getWidth(), h = getHeight();
  31856. Component* p = parentComponent_;
  31857. int px = getX();
  31858. int py = getY();
  31859. while (p != 0)
  31860. {
  31861. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  31862. return Rectangle();
  31863. px += p->getX();
  31864. py += p->getY();
  31865. p = p->parentComponent_;
  31866. }
  31867. return Rectangle (x, y, w, h);
  31868. }
  31869. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  31870. const int deltaX, const int deltaY) const throw()
  31871. {
  31872. for (int i = childComponentList_.size(); --i >= 0;)
  31873. {
  31874. const Component* const c = childComponentList_.getUnchecked(i);
  31875. if (c->isVisible())
  31876. {
  31877. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31878. if (! newClip.isEmpty())
  31879. {
  31880. if (c->isOpaque())
  31881. {
  31882. g.excludeClipRegion (deltaX + newClip.getX(),
  31883. deltaY + newClip.getY(),
  31884. newClip.getWidth(),
  31885. newClip.getHeight());
  31886. }
  31887. else
  31888. {
  31889. newClip.translate (-c->getX(), -c->getY());
  31890. c->clipObscuredRegions (g, newClip,
  31891. c->getX() + deltaX,
  31892. c->getY() + deltaY);
  31893. }
  31894. }
  31895. }
  31896. }
  31897. }
  31898. void Component::getVisibleArea (RectangleList& result,
  31899. const bool includeSiblings) const
  31900. {
  31901. result.clear();
  31902. const Rectangle unclipped (getUnclippedArea());
  31903. if (! unclipped.isEmpty())
  31904. {
  31905. result.add (unclipped);
  31906. if (includeSiblings)
  31907. {
  31908. const Component* const c = getTopLevelComponent();
  31909. int x = 0, y = 0;
  31910. c->relativePositionToOtherComponent (this, x, y);
  31911. c->subtractObscuredRegions (result, x, y,
  31912. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  31913. this);
  31914. }
  31915. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  31916. result.consolidate();
  31917. }
  31918. }
  31919. void Component::subtractObscuredRegions (RectangleList& result,
  31920. const int deltaX,
  31921. const int deltaY,
  31922. const Rectangle& clipRect,
  31923. const Component* const compToAvoid) const throw()
  31924. {
  31925. for (int i = childComponentList_.size(); --i >= 0;)
  31926. {
  31927. const Component* const c = childComponentList_.getUnchecked(i);
  31928. if (c != compToAvoid && c->isVisible())
  31929. {
  31930. if (c->isOpaque())
  31931. {
  31932. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  31933. childBounds.translate (deltaX, deltaY);
  31934. result.subtract (childBounds);
  31935. }
  31936. else
  31937. {
  31938. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31939. newClip.translate (-c->getX(), -c->getY());
  31940. c->subtractObscuredRegions (result,
  31941. c->getX() + deltaX,
  31942. c->getY() + deltaY,
  31943. newClip,
  31944. compToAvoid);
  31945. }
  31946. }
  31947. }
  31948. }
  31949. void Component::mouseEnter (const MouseEvent&)
  31950. {
  31951. // base class does nothing
  31952. }
  31953. void Component::mouseExit (const MouseEvent&)
  31954. {
  31955. // base class does nothing
  31956. }
  31957. void Component::mouseDown (const MouseEvent&)
  31958. {
  31959. // base class does nothing
  31960. }
  31961. void Component::mouseUp (const MouseEvent&)
  31962. {
  31963. // base class does nothing
  31964. }
  31965. void Component::mouseDrag (const MouseEvent&)
  31966. {
  31967. // base class does nothing
  31968. }
  31969. void Component::mouseMove (const MouseEvent&)
  31970. {
  31971. // base class does nothing
  31972. }
  31973. void Component::mouseDoubleClick (const MouseEvent&)
  31974. {
  31975. // base class does nothing
  31976. }
  31977. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  31978. {
  31979. // the base class just passes this event up to its parent..
  31980. if (parentComponent_ != 0)
  31981. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  31982. wheelIncrementX, wheelIncrementY);
  31983. }
  31984. void Component::resized()
  31985. {
  31986. // base class does nothing
  31987. }
  31988. void Component::moved()
  31989. {
  31990. // base class does nothing
  31991. }
  31992. void Component::childBoundsChanged (Component*)
  31993. {
  31994. // base class does nothing
  31995. }
  31996. void Component::parentSizeChanged()
  31997. {
  31998. // base class does nothing
  31999. }
  32000. void Component::addComponentListener (ComponentListener* const newListener) throw()
  32001. {
  32002. if (componentListeners_ == 0)
  32003. componentListeners_ = new VoidArray (4);
  32004. componentListeners_->addIfNotAlreadyThere (newListener);
  32005. }
  32006. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  32007. {
  32008. jassert (isValidComponent());
  32009. if (componentListeners_ != 0)
  32010. componentListeners_->removeValue (listenerToRemove);
  32011. }
  32012. void Component::inputAttemptWhenModal()
  32013. {
  32014. bringModalComponentToFront();
  32015. getLookAndFeel().playAlertSound();
  32016. }
  32017. bool Component::canModalEventBeSentToComponent (const Component*)
  32018. {
  32019. return false;
  32020. }
  32021. void Component::internalModalInputAttempt()
  32022. {
  32023. Component* const current = getCurrentlyModalComponent();
  32024. if (current != 0)
  32025. current->inputAttemptWhenModal();
  32026. }
  32027. void Component::paint (Graphics&)
  32028. {
  32029. // all painting is done in the subclasses
  32030. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32031. }
  32032. void Component::paintOverChildren (Graphics&)
  32033. {
  32034. // all painting is done in the subclasses
  32035. }
  32036. void Component::handleMessage (const Message& message)
  32037. {
  32038. if (message.intParameter1 == exitModalStateMessage)
  32039. {
  32040. exitModalState (message.intParameter2);
  32041. }
  32042. else if (message.intParameter1 == customCommandMessage)
  32043. {
  32044. handleCommandMessage (message.intParameter2);
  32045. }
  32046. }
  32047. void Component::postCommandMessage (const int commandId) throw()
  32048. {
  32049. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32050. }
  32051. void Component::handleCommandMessage (int)
  32052. {
  32053. // used by subclasses
  32054. }
  32055. void Component::addMouseListener (MouseListener* const newListener,
  32056. const bool wantsEventsForAllNestedChildComponents) throw()
  32057. {
  32058. // if component methods are being called from threads other than the message
  32059. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32060. checkMessageManagerIsLocked
  32061. if (mouseListeners_ == 0)
  32062. mouseListeners_ = new VoidArray (4);
  32063. if (! mouseListeners_->contains (newListener))
  32064. {
  32065. if (wantsEventsForAllNestedChildComponents)
  32066. {
  32067. mouseListeners_->insert (0, newListener);
  32068. ++numDeepMouseListeners;
  32069. }
  32070. else
  32071. {
  32072. mouseListeners_->add (newListener);
  32073. }
  32074. }
  32075. }
  32076. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  32077. {
  32078. // if component methods are being called from threads other than the message
  32079. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32080. checkMessageManagerIsLocked
  32081. if (mouseListeners_ != 0)
  32082. {
  32083. const int index = mouseListeners_->indexOf (listenerToRemove);
  32084. if (index >= 0)
  32085. {
  32086. if (index < numDeepMouseListeners)
  32087. --numDeepMouseListeners;
  32088. mouseListeners_->remove (index);
  32089. }
  32090. }
  32091. }
  32092. void Component::internalMouseEnter (int x, int y, int64 time)
  32093. {
  32094. if (isCurrentlyBlockedByAnotherModalComponent())
  32095. {
  32096. // if something else is modal, always just show a normal mouse cursor
  32097. if (componentUnderMouse == this)
  32098. {
  32099. ComponentPeer* const peer = getPeer();
  32100. if (peer != 0)
  32101. {
  32102. MouseCursor mc (MouseCursor::NormalCursor);
  32103. mc.showInWindow (peer);
  32104. }
  32105. }
  32106. return;
  32107. }
  32108. if (! flags.mouseInsideFlag)
  32109. {
  32110. flags.mouseInsideFlag = true;
  32111. flags.mouseOverFlag = true;
  32112. flags.draggingFlag = false;
  32113. if (isValidComponent())
  32114. {
  32115. const ComponentDeletionWatcher deletionChecker (this);
  32116. if (flags.repaintOnMouseActivityFlag)
  32117. repaint();
  32118. const MouseEvent me (x, y,
  32119. ModifierKeys::getCurrentModifiers(),
  32120. this,
  32121. Time (time),
  32122. x, y,
  32123. Time (time),
  32124. 0, false);
  32125. mouseEnter (me);
  32126. if (deletionChecker.hasBeenDeleted())
  32127. return;
  32128. Desktop::getInstance().resetTimer();
  32129. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32130. {
  32131. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  32132. if (deletionChecker.hasBeenDeleted())
  32133. return;
  32134. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32135. }
  32136. if (mouseListeners_ != 0)
  32137. {
  32138. for (int i = mouseListeners_->size(); --i >= 0;)
  32139. {
  32140. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  32141. if (deletionChecker.hasBeenDeleted())
  32142. return;
  32143. i = jmin (i, mouseListeners_->size());
  32144. }
  32145. }
  32146. const Component* p = parentComponent_;
  32147. while (p != 0)
  32148. {
  32149. const ComponentDeletionWatcher parentDeletionChecker (p);
  32150. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32151. {
  32152. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  32153. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32154. return;
  32155. i = jmin (i, p->numDeepMouseListeners);
  32156. }
  32157. p = p->parentComponent_;
  32158. }
  32159. }
  32160. }
  32161. if (componentUnderMouse == this)
  32162. internalUpdateMouseCursor (true);
  32163. }
  32164. void Component::internalMouseExit (int x, int y, int64 time)
  32165. {
  32166. const ComponentDeletionWatcher deletionChecker (this);
  32167. if (flags.draggingFlag)
  32168. {
  32169. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  32170. if (deletionChecker.hasBeenDeleted())
  32171. return;
  32172. }
  32173. enableUnboundedMouseMovement (false);
  32174. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32175. {
  32176. flags.mouseInsideFlag = false;
  32177. flags.mouseOverFlag = false;
  32178. flags.draggingFlag = false;
  32179. if (flags.repaintOnMouseActivityFlag)
  32180. repaint();
  32181. const MouseEvent me (x, y,
  32182. ModifierKeys::getCurrentModifiers(),
  32183. this,
  32184. Time (time),
  32185. x, y,
  32186. Time (time),
  32187. 0, false);
  32188. mouseExit (me);
  32189. if (deletionChecker.hasBeenDeleted())
  32190. return;
  32191. Desktop::getInstance().resetTimer();
  32192. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32193. {
  32194. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  32195. if (deletionChecker.hasBeenDeleted())
  32196. return;
  32197. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32198. }
  32199. if (mouseListeners_ != 0)
  32200. {
  32201. for (int i = mouseListeners_->size(); --i >= 0;)
  32202. {
  32203. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32204. if (deletionChecker.hasBeenDeleted())
  32205. return;
  32206. i = jmin (i, mouseListeners_->size());
  32207. }
  32208. }
  32209. const Component* p = parentComponent_;
  32210. while (p != 0)
  32211. {
  32212. const ComponentDeletionWatcher parentDeletionChecker (p);
  32213. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32214. {
  32215. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  32216. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32217. return;
  32218. i = jmin (i, p->numDeepMouseListeners);
  32219. }
  32220. p = p->parentComponent_;
  32221. }
  32222. }
  32223. }
  32224. class InternalDragRepeater : public Timer
  32225. {
  32226. public:
  32227. InternalDragRepeater()
  32228. {}
  32229. ~InternalDragRepeater()
  32230. {}
  32231. void timerCallback()
  32232. {
  32233. Component* const c = Component::getComponentUnderMouse();
  32234. if (c != 0 && c->isMouseButtonDown())
  32235. {
  32236. int x, y;
  32237. c->getMouseXYRelative (x, y);
  32238. // the offsets have been added on, so must be taken off before calling the
  32239. // drag.. otherwise they'll be added twice
  32240. x -= unboundedMouseOffsetX;
  32241. y -= unboundedMouseOffsetY;
  32242. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  32243. }
  32244. }
  32245. juce_UseDebuggingNewOperator
  32246. };
  32247. static InternalDragRepeater* dragRepeater = 0;
  32248. void Component::beginDragAutoRepeat (const int interval)
  32249. {
  32250. if (interval > 0)
  32251. {
  32252. if (dragRepeater == 0)
  32253. dragRepeater = new InternalDragRepeater();
  32254. if (dragRepeater->getTimerInterval() != interval)
  32255. dragRepeater->startTimer (interval);
  32256. }
  32257. else
  32258. {
  32259. deleteAndZero (dragRepeater);
  32260. }
  32261. }
  32262. void Component::internalMouseDown (const int x, const int y)
  32263. {
  32264. const ComponentDeletionWatcher deletionChecker (this);
  32265. if (isCurrentlyBlockedByAnotherModalComponent())
  32266. {
  32267. internalModalInputAttempt();
  32268. if (deletionChecker.hasBeenDeleted())
  32269. return;
  32270. // If processing the input attempt has exited the modal loop, we'll allow the event
  32271. // to be delivered..
  32272. if (isCurrentlyBlockedByAnotherModalComponent())
  32273. {
  32274. // allow blocked mouse-events to go to global listeners..
  32275. const MouseEvent me (x, y,
  32276. ModifierKeys::getCurrentModifiers(),
  32277. this,
  32278. Time (juce_recentMouseDownTimes[0]),
  32279. x, y,
  32280. Time (juce_recentMouseDownTimes[0]),
  32281. countMouseClicks(),
  32282. false);
  32283. Desktop::getInstance().resetTimer();
  32284. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32285. {
  32286. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32287. if (deletionChecker.hasBeenDeleted())
  32288. return;
  32289. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32290. }
  32291. return;
  32292. }
  32293. }
  32294. {
  32295. Component* c = this;
  32296. while (c != 0)
  32297. {
  32298. if (c->isBroughtToFrontOnMouseClick())
  32299. {
  32300. c->toFront (true);
  32301. if (deletionChecker.hasBeenDeleted())
  32302. return;
  32303. }
  32304. c = c->parentComponent_;
  32305. }
  32306. }
  32307. if (! flags.dontFocusOnMouseClickFlag)
  32308. grabFocusInternal (focusChangedByMouseClick);
  32309. if (! deletionChecker.hasBeenDeleted())
  32310. {
  32311. flags.draggingFlag = true;
  32312. flags.mouseOverFlag = true;
  32313. if (flags.repaintOnMouseActivityFlag)
  32314. repaint();
  32315. const MouseEvent me (x, y,
  32316. ModifierKeys::getCurrentModifiers(),
  32317. this,
  32318. Time (juce_recentMouseDownTimes[0]),
  32319. x, y,
  32320. Time (juce_recentMouseDownTimes[0]),
  32321. countMouseClicks(),
  32322. false);
  32323. mouseDown (me);
  32324. if (deletionChecker.hasBeenDeleted())
  32325. return;
  32326. Desktop::getInstance().resetTimer();
  32327. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32328. {
  32329. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32330. if (deletionChecker.hasBeenDeleted())
  32331. return;
  32332. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32333. }
  32334. if (mouseListeners_ != 0)
  32335. {
  32336. for (int i = mouseListeners_->size(); --i >= 0;)
  32337. {
  32338. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32339. if (deletionChecker.hasBeenDeleted())
  32340. return;
  32341. i = jmin (i, mouseListeners_->size());
  32342. }
  32343. }
  32344. const Component* p = parentComponent_;
  32345. while (p != 0)
  32346. {
  32347. const ComponentDeletionWatcher parentDeletionChecker (p);
  32348. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32349. {
  32350. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  32351. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32352. return;
  32353. i = jmin (i, p->numDeepMouseListeners);
  32354. }
  32355. p = p->parentComponent_;
  32356. }
  32357. }
  32358. }
  32359. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  32360. {
  32361. if (isValidComponent() && flags.draggingFlag)
  32362. {
  32363. flags.draggingFlag = false;
  32364. deleteAndZero (dragRepeater);
  32365. x += unboundedMouseOffsetX;
  32366. y += unboundedMouseOffsetY;
  32367. juce_LastMousePosX = x;
  32368. juce_LastMousePosY = y;
  32369. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32370. const ComponentDeletionWatcher deletionChecker (this);
  32371. if (flags.repaintOnMouseActivityFlag)
  32372. repaint();
  32373. int mdx = juce_recentMouseDownX[0];
  32374. int mdy = juce_recentMouseDownY[0];
  32375. globalPositionToRelative (mdx, mdy);
  32376. const MouseEvent me (x, y,
  32377. oldModifiers,
  32378. this,
  32379. Time (time),
  32380. mdx, mdy,
  32381. Time (juce_recentMouseDownTimes [0]),
  32382. countMouseClicks(),
  32383. juce_MouseHasMovedSignificantlySincePressed
  32384. || juce_recentMouseDownTimes[0] + 300 < time);
  32385. mouseUp (me);
  32386. if (deletionChecker.hasBeenDeleted())
  32387. return;
  32388. Desktop::getInstance().resetTimer();
  32389. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32390. {
  32391. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  32392. if (deletionChecker.hasBeenDeleted())
  32393. return;
  32394. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32395. }
  32396. if (mouseListeners_ != 0)
  32397. {
  32398. for (int i = mouseListeners_->size(); --i >= 0;)
  32399. {
  32400. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32401. if (deletionChecker.hasBeenDeleted())
  32402. return;
  32403. i = jmin (i, mouseListeners_->size());
  32404. }
  32405. }
  32406. {
  32407. const Component* p = parentComponent_;
  32408. while (p != 0)
  32409. {
  32410. const ComponentDeletionWatcher parentDeletionChecker (p);
  32411. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32412. {
  32413. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  32414. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32415. return;
  32416. i = jmin (i, p->numDeepMouseListeners);
  32417. }
  32418. p = p->parentComponent_;
  32419. }
  32420. }
  32421. // check for double-click
  32422. if (me.getNumberOfClicks() >= 2)
  32423. {
  32424. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32425. mouseDoubleClick (me);
  32426. int i;
  32427. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32428. {
  32429. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  32430. if (deletionChecker.hasBeenDeleted())
  32431. return;
  32432. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32433. }
  32434. for (i = numListeners; --i >= 0;)
  32435. {
  32436. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  32437. return;
  32438. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32439. if (ml != 0)
  32440. ml->mouseDoubleClick (me);
  32441. }
  32442. if (deletionChecker.hasBeenDeleted())
  32443. return;
  32444. const Component* p = parentComponent_;
  32445. while (p != 0)
  32446. {
  32447. const ComponentDeletionWatcher parentDeletionChecker (p);
  32448. for (i = p->numDeepMouseListeners; --i >= 0;)
  32449. {
  32450. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  32451. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32452. return;
  32453. i = jmin (i, p->numDeepMouseListeners);
  32454. }
  32455. p = p->parentComponent_;
  32456. }
  32457. }
  32458. }
  32459. enableUnboundedMouseMovement (false);
  32460. }
  32461. void Component::internalMouseDrag (int x, int y, const int64 time)
  32462. {
  32463. if (isValidComponent() && flags.draggingFlag)
  32464. {
  32465. flags.mouseOverFlag = reallyContains (x, y, false);
  32466. x += unboundedMouseOffsetX;
  32467. y += unboundedMouseOffsetY;
  32468. juce_LastMousePosX = x;
  32469. juce_LastMousePosY = y;
  32470. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32471. juce_MouseHasMovedSignificantlySincePressed
  32472. = juce_MouseHasMovedSignificantlySincePressed
  32473. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  32474. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  32475. const ComponentDeletionWatcher deletionChecker (this);
  32476. int mdx = juce_recentMouseDownX[0];
  32477. int mdy = juce_recentMouseDownY[0];
  32478. globalPositionToRelative (mdx, mdy);
  32479. const MouseEvent me (x, y,
  32480. ModifierKeys::getCurrentModifiers(),
  32481. this,
  32482. Time (time),
  32483. mdx, mdy,
  32484. Time (juce_recentMouseDownTimes[0]),
  32485. countMouseClicks(),
  32486. juce_MouseHasMovedSignificantlySincePressed
  32487. || juce_recentMouseDownTimes[0] + 300 < time);
  32488. mouseDrag (me);
  32489. if (deletionChecker.hasBeenDeleted())
  32490. return;
  32491. Desktop::getInstance().resetTimer();
  32492. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32493. {
  32494. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  32495. if (deletionChecker.hasBeenDeleted())
  32496. return;
  32497. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32498. }
  32499. if (mouseListeners_ != 0)
  32500. {
  32501. for (int i = mouseListeners_->size(); --i >= 0;)
  32502. {
  32503. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  32504. if (deletionChecker.hasBeenDeleted())
  32505. return;
  32506. i = jmin (i, mouseListeners_->size());
  32507. }
  32508. }
  32509. const Component* p = parentComponent_;
  32510. while (p != 0)
  32511. {
  32512. const ComponentDeletionWatcher parentDeletionChecker (p);
  32513. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32514. {
  32515. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  32516. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32517. return;
  32518. i = jmin (i, p->numDeepMouseListeners);
  32519. }
  32520. p = p->parentComponent_;
  32521. }
  32522. if (this == componentUnderMouse)
  32523. {
  32524. if (isUnboundedMouseModeOn)
  32525. {
  32526. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  32527. int mx, my;
  32528. Desktop::getMousePosition (mx, my);
  32529. if (! screenArea.contains (mx, my))
  32530. {
  32531. int deltaX = 0, deltaY = 0;
  32532. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  32533. deltaX = getScreenX() + getWidth() / 2 - mx;
  32534. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  32535. deltaY = getScreenY() + getHeight() / 2 - my;
  32536. unboundedMouseOffsetX -= deltaX;
  32537. unboundedMouseOffsetY -= deltaY;
  32538. Desktop::setMousePosition (mx + deltaX,
  32539. my + deltaY);
  32540. }
  32541. else if (isCursorVisibleUntilOffscreen
  32542. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  32543. && screenArea.contains (mx + unboundedMouseOffsetX,
  32544. my + unboundedMouseOffsetY))
  32545. {
  32546. mx += unboundedMouseOffsetX;
  32547. my += unboundedMouseOffsetY;
  32548. unboundedMouseOffsetX = 0;
  32549. unboundedMouseOffsetY = 0;
  32550. Desktop::setMousePosition (mx, my);
  32551. }
  32552. }
  32553. internalUpdateMouseCursor (false);
  32554. }
  32555. }
  32556. }
  32557. void Component::internalMouseMove (const int x, const int y, const int64 time)
  32558. {
  32559. const ComponentDeletionWatcher deletionChecker (this);
  32560. if (isValidComponent())
  32561. {
  32562. const MouseEvent me (x, y,
  32563. ModifierKeys::getCurrentModifiers(),
  32564. this,
  32565. Time (time),
  32566. x, y,
  32567. Time (time),
  32568. 0, false);
  32569. if (isCurrentlyBlockedByAnotherModalComponent())
  32570. {
  32571. // allow blocked mouse-events to go to global listeners..
  32572. Desktop::getInstance().sendMouseMove();
  32573. }
  32574. else
  32575. {
  32576. if (this == componentUnderMouse)
  32577. internalUpdateMouseCursor (false);
  32578. flags.mouseOverFlag = true;
  32579. mouseMove (me);
  32580. if (deletionChecker.hasBeenDeleted())
  32581. return;
  32582. Desktop::getInstance().resetTimer();
  32583. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32584. {
  32585. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  32586. if (deletionChecker.hasBeenDeleted())
  32587. return;
  32588. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32589. }
  32590. if (mouseListeners_ != 0)
  32591. {
  32592. for (int i = mouseListeners_->size(); --i >= 0;)
  32593. {
  32594. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  32595. if (deletionChecker.hasBeenDeleted())
  32596. return;
  32597. i = jmin (i, mouseListeners_->size());
  32598. }
  32599. }
  32600. const Component* p = parentComponent_;
  32601. while (p != 0)
  32602. {
  32603. const ComponentDeletionWatcher parentDeletionChecker (p);
  32604. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32605. {
  32606. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  32607. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32608. return;
  32609. i = jmin (i, p->numDeepMouseListeners);
  32610. }
  32611. p = p->parentComponent_;
  32612. }
  32613. }
  32614. }
  32615. }
  32616. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  32617. {
  32618. const ComponentDeletionWatcher deletionChecker (this);
  32619. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  32620. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  32621. int mx, my;
  32622. getMouseXYRelative (mx, my);
  32623. const MouseEvent me (mx, my,
  32624. ModifierKeys::getCurrentModifiers(),
  32625. this,
  32626. Time (time),
  32627. mx, my,
  32628. Time (time),
  32629. 0, false);
  32630. if (isCurrentlyBlockedByAnotherModalComponent())
  32631. {
  32632. // allow blocked mouse-events to go to global listeners..
  32633. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32634. {
  32635. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32636. if (deletionChecker.hasBeenDeleted())
  32637. return;
  32638. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32639. }
  32640. }
  32641. else
  32642. {
  32643. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32644. if (deletionChecker.hasBeenDeleted())
  32645. return;
  32646. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32647. {
  32648. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32649. if (deletionChecker.hasBeenDeleted())
  32650. return;
  32651. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32652. }
  32653. if (mouseListeners_ != 0)
  32654. {
  32655. for (int i = mouseListeners_->size(); --i >= 0;)
  32656. {
  32657. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32658. if (deletionChecker.hasBeenDeleted())
  32659. return;
  32660. i = jmin (i, mouseListeners_->size());
  32661. }
  32662. }
  32663. const Component* p = parentComponent_;
  32664. while (p != 0)
  32665. {
  32666. const ComponentDeletionWatcher parentDeletionChecker (p);
  32667. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32668. {
  32669. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32670. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32671. return;
  32672. i = jmin (i, p->numDeepMouseListeners);
  32673. }
  32674. p = p->parentComponent_;
  32675. }
  32676. sendFakeMouseMove();
  32677. }
  32678. }
  32679. void Component::sendFakeMouseMove() const
  32680. {
  32681. ComponentPeer* const peer = getPeer();
  32682. if (peer != 0)
  32683. peer->sendFakeMouseMove();
  32684. }
  32685. void Component::broughtToFront()
  32686. {
  32687. }
  32688. void Component::internalBroughtToFront()
  32689. {
  32690. if (isValidComponent())
  32691. {
  32692. if (flags.hasHeavyweightPeerFlag)
  32693. Desktop::getInstance().componentBroughtToFront (this);
  32694. const ComponentDeletionWatcher deletionChecker (this);
  32695. broughtToFront();
  32696. if (deletionChecker.hasBeenDeleted())
  32697. return;
  32698. if (componentListeners_ != 0)
  32699. {
  32700. for (int i = componentListeners_->size(); --i >= 0;)
  32701. {
  32702. ((ComponentListener*) componentListeners_->getUnchecked (i))
  32703. ->componentBroughtToFront (*this);
  32704. if (deletionChecker.hasBeenDeleted())
  32705. return;
  32706. i = jmin (i, componentListeners_->size());
  32707. }
  32708. }
  32709. // when brought to the front and there's a modal component blocking this one,
  32710. // we need to bring the modal one to the front instead..
  32711. Component* const cm = getCurrentlyModalComponent();
  32712. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  32713. bringModalComponentToFront();
  32714. }
  32715. }
  32716. void Component::focusGained (FocusChangeType)
  32717. {
  32718. // base class does nothing
  32719. }
  32720. void Component::internalFocusGain (const FocusChangeType cause)
  32721. {
  32722. const ComponentDeletionWatcher deletionChecker (this);
  32723. focusGained (cause);
  32724. if (! deletionChecker.hasBeenDeleted())
  32725. internalChildFocusChange (cause);
  32726. }
  32727. void Component::focusLost (FocusChangeType)
  32728. {
  32729. // base class does nothing
  32730. }
  32731. void Component::internalFocusLoss (const FocusChangeType cause)
  32732. {
  32733. const ComponentDeletionWatcher deletionChecker (this);
  32734. focusLost (focusChangedDirectly);
  32735. if (! deletionChecker.hasBeenDeleted())
  32736. internalChildFocusChange (cause);
  32737. }
  32738. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  32739. {
  32740. // base class does nothing
  32741. }
  32742. void Component::internalChildFocusChange (FocusChangeType cause)
  32743. {
  32744. const bool childIsNowFocused = hasKeyboardFocus (true);
  32745. if (flags.childCompFocusedFlag != childIsNowFocused)
  32746. {
  32747. flags.childCompFocusedFlag = childIsNowFocused;
  32748. const ComponentDeletionWatcher deletionChecker (this);
  32749. focusOfChildComponentChanged (cause);
  32750. if (deletionChecker.hasBeenDeleted())
  32751. return;
  32752. }
  32753. if (parentComponent_ != 0)
  32754. parentComponent_->internalChildFocusChange (cause);
  32755. }
  32756. bool Component::isEnabled() const throw()
  32757. {
  32758. return (! flags.isDisabledFlag)
  32759. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  32760. }
  32761. void Component::setEnabled (const bool shouldBeEnabled)
  32762. {
  32763. if (flags.isDisabledFlag == shouldBeEnabled)
  32764. {
  32765. flags.isDisabledFlag = ! shouldBeEnabled;
  32766. // if any parent components are disabled, setting our flag won't make a difference,
  32767. // so no need to send a change message
  32768. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  32769. sendEnablementChangeMessage();
  32770. }
  32771. }
  32772. void Component::sendEnablementChangeMessage()
  32773. {
  32774. const ComponentDeletionWatcher deletionChecker (this);
  32775. enablementChanged();
  32776. if (deletionChecker.hasBeenDeleted())
  32777. return;
  32778. for (int i = getNumChildComponents(); --i >= 0;)
  32779. {
  32780. Component* const c = getChildComponent (i);
  32781. if (c != 0)
  32782. {
  32783. c->sendEnablementChangeMessage();
  32784. if (deletionChecker.hasBeenDeleted())
  32785. return;
  32786. }
  32787. }
  32788. }
  32789. void Component::enablementChanged()
  32790. {
  32791. }
  32792. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  32793. {
  32794. flags.wantsFocusFlag = wantsFocus;
  32795. }
  32796. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  32797. {
  32798. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  32799. }
  32800. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  32801. {
  32802. return ! flags.dontFocusOnMouseClickFlag;
  32803. }
  32804. bool Component::getWantsKeyboardFocus() const throw()
  32805. {
  32806. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  32807. }
  32808. void Component::setFocusContainer (const bool isFocusContainer) throw()
  32809. {
  32810. flags.isFocusContainerFlag = isFocusContainer;
  32811. }
  32812. bool Component::isFocusContainer() const throw()
  32813. {
  32814. return flags.isFocusContainerFlag;
  32815. }
  32816. int Component::getExplicitFocusOrder() const throw()
  32817. {
  32818. return getComponentPropertyInt (T("_jexfo"), false, 0);
  32819. }
  32820. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  32821. {
  32822. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  32823. }
  32824. KeyboardFocusTraverser* Component::createFocusTraverser()
  32825. {
  32826. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  32827. return new KeyboardFocusTraverser();
  32828. return parentComponent_->createFocusTraverser();
  32829. }
  32830. void Component::takeKeyboardFocus (const FocusChangeType cause)
  32831. {
  32832. // give the focus to this component
  32833. if (currentlyFocusedComponent != this)
  32834. {
  32835. JUCE_TRY
  32836. {
  32837. // get the focus onto our desktop window
  32838. ComponentPeer* const peer = getPeer();
  32839. if (peer != 0)
  32840. {
  32841. const ComponentDeletionWatcher deletionChecker (this);
  32842. peer->grabFocus();
  32843. if (peer->isFocused() && currentlyFocusedComponent != this)
  32844. {
  32845. Component* const componentLosingFocus = currentlyFocusedComponent;
  32846. currentlyFocusedComponent = this;
  32847. Desktop::getInstance().triggerFocusCallback();
  32848. // call this after setting currentlyFocusedComponent so that the one that's
  32849. // losing it has a chance to see where focus is going
  32850. if (componentLosingFocus->isValidComponent())
  32851. componentLosingFocus->internalFocusLoss (cause);
  32852. if (currentlyFocusedComponent == this)
  32853. {
  32854. focusGained (cause);
  32855. if (! deletionChecker.hasBeenDeleted())
  32856. internalChildFocusChange (cause);
  32857. }
  32858. }
  32859. }
  32860. }
  32861. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32862. catch (const std::exception& e)
  32863. {
  32864. currentlyFocusedComponent = 0;
  32865. Desktop::getInstance().triggerFocusCallback();
  32866. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32867. }
  32868. catch (...)
  32869. {
  32870. currentlyFocusedComponent = 0;
  32871. Desktop::getInstance().triggerFocusCallback();
  32872. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32873. }
  32874. #endif
  32875. }
  32876. }
  32877. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  32878. {
  32879. if (isShowing())
  32880. {
  32881. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  32882. {
  32883. takeKeyboardFocus (cause);
  32884. }
  32885. else
  32886. {
  32887. if (isParentOf (currentlyFocusedComponent)
  32888. && currentlyFocusedComponent->isShowing())
  32889. {
  32890. // do nothing if the focused component is actually a child of ours..
  32891. }
  32892. else
  32893. {
  32894. // find the default child component..
  32895. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32896. if (traverser != 0)
  32897. {
  32898. Component* const defaultComp = traverser->getDefaultComponent (this);
  32899. delete traverser;
  32900. if (defaultComp != 0)
  32901. {
  32902. defaultComp->grabFocusInternal (cause, false);
  32903. return;
  32904. }
  32905. }
  32906. if (canTryParent && parentComponent_ != 0)
  32907. {
  32908. // if no children want it and we're allowed to try our parent comp,
  32909. // then pass up to parent, which will try our siblings.
  32910. parentComponent_->grabFocusInternal (cause, true);
  32911. }
  32912. }
  32913. }
  32914. }
  32915. }
  32916. void Component::grabKeyboardFocus()
  32917. {
  32918. // if component methods are being called from threads other than the message
  32919. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32920. checkMessageManagerIsLocked
  32921. grabFocusInternal (focusChangedDirectly);
  32922. }
  32923. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  32924. {
  32925. // if component methods are being called from threads other than the message
  32926. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32927. checkMessageManagerIsLocked
  32928. if (parentComponent_ != 0)
  32929. {
  32930. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32931. if (traverser != 0)
  32932. {
  32933. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  32934. : traverser->getPreviousComponent (this);
  32935. delete traverser;
  32936. if (nextComp != 0)
  32937. {
  32938. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32939. {
  32940. const ComponentDeletionWatcher deletionChecker (nextComp);
  32941. internalModalInputAttempt();
  32942. if (deletionChecker.hasBeenDeleted()
  32943. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32944. return;
  32945. }
  32946. nextComp->grabFocusInternal (focusChangedByTabKey);
  32947. return;
  32948. }
  32949. }
  32950. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  32951. }
  32952. }
  32953. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  32954. {
  32955. return (currentlyFocusedComponent == this)
  32956. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  32957. }
  32958. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  32959. {
  32960. return currentlyFocusedComponent;
  32961. }
  32962. void Component::giveAwayFocus()
  32963. {
  32964. // use a copy so we can clear the value before the call
  32965. Component* const componentLosingFocus = currentlyFocusedComponent;
  32966. currentlyFocusedComponent = 0;
  32967. Desktop::getInstance().triggerFocusCallback();
  32968. if (componentLosingFocus->isValidComponent())
  32969. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  32970. }
  32971. bool Component::isMouseOver() const throw()
  32972. {
  32973. return flags.mouseOverFlag;
  32974. }
  32975. bool Component::isMouseButtonDown() const throw()
  32976. {
  32977. return flags.draggingFlag;
  32978. }
  32979. bool Component::isMouseOverOrDragging() const throw()
  32980. {
  32981. return flags.mouseOverFlag || flags.draggingFlag;
  32982. }
  32983. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  32984. {
  32985. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  32986. }
  32987. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  32988. {
  32989. Desktop::getMousePosition (mx, my);
  32990. globalPositionToRelative (mx, my);
  32991. mx += unboundedMouseOffsetX;
  32992. my += unboundedMouseOffsetY;
  32993. }
  32994. void Component::enableUnboundedMouseMovement (bool enable,
  32995. bool keepCursorVisibleUntilOffscreen) throw()
  32996. {
  32997. enable = enable && isMouseButtonDown();
  32998. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  32999. if (enable != isUnboundedMouseModeOn)
  33000. {
  33001. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  33002. || unboundedMouseOffsetX != 0
  33003. || unboundedMouseOffsetY != 0))
  33004. {
  33005. // when released, return the mouse to within the component's bounds
  33006. int mx, my;
  33007. getMouseXYRelative (mx, my);
  33008. mx = jlimit (0, getWidth(), mx);
  33009. my = jlimit (0, getHeight(), my);
  33010. relativePositionToGlobal (mx, my);
  33011. Desktop::setMousePosition (mx, my);
  33012. }
  33013. isUnboundedMouseModeOn = enable;
  33014. unboundedMouseOffsetX = 0;
  33015. unboundedMouseOffsetY = 0;
  33016. internalUpdateMouseCursor (true);
  33017. }
  33018. }
  33019. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  33020. {
  33021. return componentUnderMouse;
  33022. }
  33023. const Rectangle Component::getParentMonitorArea() const throw()
  33024. {
  33025. int centreX = getWidth() / 2;
  33026. int centreY = getHeight() / 2;
  33027. relativePositionToGlobal (centreX, centreY);
  33028. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  33029. }
  33030. void Component::addKeyListener (KeyListener* const newListener) throw()
  33031. {
  33032. if (keyListeners_ == 0)
  33033. keyListeners_ = new VoidArray (4);
  33034. keyListeners_->addIfNotAlreadyThere (newListener);
  33035. }
  33036. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  33037. {
  33038. if (keyListeners_ != 0)
  33039. keyListeners_->removeValue (listenerToRemove);
  33040. }
  33041. bool Component::keyPressed (const KeyPress&)
  33042. {
  33043. return false;
  33044. }
  33045. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33046. {
  33047. return false;
  33048. }
  33049. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33050. {
  33051. if (parentComponent_ != 0)
  33052. parentComponent_->modifierKeysChanged (modifiers);
  33053. }
  33054. void Component::internalModifierKeysChanged()
  33055. {
  33056. sendFakeMouseMove();
  33057. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33058. }
  33059. ComponentPeer* Component::getPeer() const throw()
  33060. {
  33061. if (flags.hasHeavyweightPeerFlag)
  33062. return ComponentPeer::getPeerFor (this);
  33063. else if (parentComponent_ != 0)
  33064. return parentComponent_->getPeer();
  33065. else
  33066. return 0;
  33067. }
  33068. const String Component::getComponentProperty (const String& keyName,
  33069. const bool useParentComponentIfNotFound,
  33070. const String& defaultReturnValue) const throw()
  33071. {
  33072. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33073. return propertySet_->getValue (keyName, defaultReturnValue);
  33074. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33075. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  33076. return defaultReturnValue;
  33077. }
  33078. int Component::getComponentPropertyInt (const String& keyName,
  33079. const bool useParentComponentIfNotFound,
  33080. const int defaultReturnValue) const throw()
  33081. {
  33082. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33083. return propertySet_->getIntValue (keyName, defaultReturnValue);
  33084. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33085. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  33086. return defaultReturnValue;
  33087. }
  33088. double Component::getComponentPropertyDouble (const String& keyName,
  33089. const bool useParentComponentIfNotFound,
  33090. const double defaultReturnValue) const throw()
  33091. {
  33092. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33093. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  33094. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33095. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  33096. return defaultReturnValue;
  33097. }
  33098. bool Component::getComponentPropertyBool (const String& keyName,
  33099. const bool useParentComponentIfNotFound,
  33100. const bool defaultReturnValue) const throw()
  33101. {
  33102. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33103. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  33104. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33105. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  33106. return defaultReturnValue;
  33107. }
  33108. const Colour Component::getComponentPropertyColour (const String& keyName,
  33109. const bool useParentComponentIfNotFound,
  33110. const Colour& defaultReturnValue) const throw()
  33111. {
  33112. return Colour ((uint32) getComponentPropertyInt (keyName,
  33113. useParentComponentIfNotFound,
  33114. defaultReturnValue.getARGB()));
  33115. }
  33116. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  33117. {
  33118. if (propertySet_ == 0)
  33119. propertySet_ = new PropertySet();
  33120. propertySet_->setValue (keyName, value);
  33121. }
  33122. void Component::setComponentProperty (const String& keyName, const int value) throw()
  33123. {
  33124. if (propertySet_ == 0)
  33125. propertySet_ = new PropertySet();
  33126. propertySet_->setValue (keyName, value);
  33127. }
  33128. void Component::setComponentProperty (const String& keyName, const double value) throw()
  33129. {
  33130. if (propertySet_ == 0)
  33131. propertySet_ = new PropertySet();
  33132. propertySet_->setValue (keyName, value);
  33133. }
  33134. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  33135. {
  33136. if (propertySet_ == 0)
  33137. propertySet_ = new PropertySet();
  33138. propertySet_->setValue (keyName, value);
  33139. }
  33140. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  33141. {
  33142. setComponentProperty (keyName, (int) colour.getARGB());
  33143. }
  33144. void Component::removeComponentProperty (const String& keyName) throw()
  33145. {
  33146. if (propertySet_ != 0)
  33147. propertySet_->removeValue (keyName);
  33148. }
  33149. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  33150. : componentToWatch (componentToWatch_),
  33151. componentUID (componentToWatch_->getComponentUID())
  33152. {
  33153. // not possible to check on an already-deleted object..
  33154. jassert (componentToWatch_->isValidComponent());
  33155. }
  33156. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  33157. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  33158. {
  33159. return ! (componentToWatch->isValidComponent()
  33160. && componentToWatch->getComponentUID() == componentUID);
  33161. }
  33162. const Component* ComponentDeletionWatcher::getComponent() const throw()
  33163. {
  33164. return hasBeenDeleted() ? 0 : componentToWatch;
  33165. }
  33166. END_JUCE_NAMESPACE
  33167. /********* End of inlined file: juce_Component.cpp *********/
  33168. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  33169. BEGIN_JUCE_NAMESPACE
  33170. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  33171. {
  33172. }
  33173. void ComponentListener::componentBroughtToFront (Component&)
  33174. {
  33175. }
  33176. void ComponentListener::componentVisibilityChanged (Component&)
  33177. {
  33178. }
  33179. void ComponentListener::componentChildrenChanged (Component&)
  33180. {
  33181. }
  33182. void ComponentListener::componentParentHierarchyChanged (Component&)
  33183. {
  33184. }
  33185. void ComponentListener::componentNameChanged (Component&)
  33186. {
  33187. }
  33188. END_JUCE_NAMESPACE
  33189. /********* End of inlined file: juce_ComponentListener.cpp *********/
  33190. /********* Start of inlined file: juce_Desktop.cpp *********/
  33191. BEGIN_JUCE_NAMESPACE
  33192. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  33193. const bool clipToWorkArea) throw();
  33194. static Desktop* juce_desktopInstance = 0;
  33195. Desktop::Desktop() throw()
  33196. : mouseListeners (2),
  33197. desktopComponents (4),
  33198. monitorCoordsClipped (2),
  33199. monitorCoordsUnclipped (2),
  33200. lastMouseX (0),
  33201. lastMouseY (0),
  33202. kioskModeComponent (0)
  33203. {
  33204. refreshMonitorSizes();
  33205. }
  33206. Desktop::~Desktop() throw()
  33207. {
  33208. jassert (juce_desktopInstance == this);
  33209. juce_desktopInstance = 0;
  33210. // doh! If you don't delete all your windows before exiting, you're going to
  33211. // be leaking memory!
  33212. jassert (desktopComponents.size() == 0);
  33213. }
  33214. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  33215. {
  33216. if (juce_desktopInstance == 0)
  33217. juce_desktopInstance = new Desktop();
  33218. return *juce_desktopInstance;
  33219. }
  33220. void Desktop::refreshMonitorSizes() throw()
  33221. {
  33222. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  33223. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  33224. monitorCoordsClipped.clear();
  33225. monitorCoordsUnclipped.clear();
  33226. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33227. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33228. jassert (monitorCoordsClipped.size() > 0
  33229. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33230. if (oldClipped != monitorCoordsClipped
  33231. || oldUnclipped != monitorCoordsUnclipped)
  33232. {
  33233. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33234. {
  33235. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33236. if (p != 0)
  33237. p->handleScreenSizeChange();
  33238. }
  33239. }
  33240. }
  33241. int Desktop::getNumDisplayMonitors() const throw()
  33242. {
  33243. return monitorCoordsClipped.size();
  33244. }
  33245. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33246. {
  33247. return clippedToWorkArea ? monitorCoordsClipped [index]
  33248. : monitorCoordsUnclipped [index];
  33249. }
  33250. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33251. {
  33252. RectangleList rl;
  33253. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33254. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33255. return rl;
  33256. }
  33257. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33258. {
  33259. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33260. }
  33261. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  33262. {
  33263. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  33264. double bestDistance = 1.0e10;
  33265. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33266. {
  33267. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33268. if (rect.contains (cx, cy))
  33269. return rect;
  33270. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  33271. (double) (rect.getCentreY() - cy));
  33272. if (distance < bestDistance)
  33273. {
  33274. bestDistance = distance;
  33275. best = rect;
  33276. }
  33277. }
  33278. return best;
  33279. }
  33280. int Desktop::getNumComponents() const throw()
  33281. {
  33282. return desktopComponents.size();
  33283. }
  33284. Component* Desktop::getComponent (const int index) const throw()
  33285. {
  33286. return (Component*) desktopComponents [index];
  33287. }
  33288. Component* Desktop::findComponentAt (const int screenX,
  33289. const int screenY) const
  33290. {
  33291. for (int i = desktopComponents.size(); --i >= 0;)
  33292. {
  33293. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  33294. int x = screenX, y = screenY;
  33295. c->globalPositionToRelative (x, y);
  33296. if (c->contains (x, y))
  33297. return c->getComponentAt (x, y);
  33298. }
  33299. return 0;
  33300. }
  33301. void Desktop::addDesktopComponent (Component* const c) throw()
  33302. {
  33303. jassert (c != 0);
  33304. jassert (! desktopComponents.contains (c));
  33305. desktopComponents.addIfNotAlreadyThere (c);
  33306. }
  33307. void Desktop::removeDesktopComponent (Component* const c) throw()
  33308. {
  33309. desktopComponents.removeValue (c);
  33310. }
  33311. void Desktop::componentBroughtToFront (Component* const c) throw()
  33312. {
  33313. const int index = desktopComponents.indexOf (c);
  33314. jassert (index >= 0);
  33315. if (index >= 0)
  33316. desktopComponents.move (index, -1);
  33317. }
  33318. // from Component.cpp
  33319. extern int juce_recentMouseDownX [4];
  33320. extern int juce_recentMouseDownY [4];
  33321. extern int juce_MouseClickCounter;
  33322. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  33323. {
  33324. x = juce_recentMouseDownX [0];
  33325. y = juce_recentMouseDownY [0];
  33326. }
  33327. int Desktop::getMouseButtonClickCounter() throw()
  33328. {
  33329. return juce_MouseClickCounter;
  33330. }
  33331. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  33332. {
  33333. jassert (listener != 0);
  33334. if (listener != 0)
  33335. {
  33336. mouseListeners.add (listener);
  33337. resetTimer();
  33338. }
  33339. }
  33340. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  33341. {
  33342. mouseListeners.removeValue (listener);
  33343. resetTimer();
  33344. }
  33345. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  33346. {
  33347. jassert (listener != 0);
  33348. if (listener != 0)
  33349. focusListeners.add (listener);
  33350. }
  33351. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  33352. {
  33353. focusListeners.removeValue (listener);
  33354. }
  33355. void Desktop::triggerFocusCallback() throw()
  33356. {
  33357. triggerAsyncUpdate();
  33358. }
  33359. void Desktop::handleAsyncUpdate()
  33360. {
  33361. for (int i = focusListeners.size(); --i >= 0;)
  33362. {
  33363. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  33364. i = jmin (i, focusListeners.size());
  33365. }
  33366. }
  33367. void Desktop::timerCallback()
  33368. {
  33369. int x, y;
  33370. getMousePosition (x, y);
  33371. if (lastMouseX != x || lastMouseY != y)
  33372. sendMouseMove();
  33373. }
  33374. void Desktop::sendMouseMove()
  33375. {
  33376. if (mouseListeners.size() > 0)
  33377. {
  33378. startTimer (20);
  33379. int x, y;
  33380. getMousePosition (x, y);
  33381. lastMouseX = x;
  33382. lastMouseY = y;
  33383. Component* const target = findComponentAt (x, y);
  33384. if (target != 0)
  33385. {
  33386. target->globalPositionToRelative (x, y);
  33387. ComponentDeletionWatcher deletionChecker (target);
  33388. const MouseEvent me (x, y,
  33389. ModifierKeys::getCurrentModifiers(),
  33390. target,
  33391. Time::getCurrentTime(),
  33392. x, y,
  33393. Time::getCurrentTime(),
  33394. 0, false);
  33395. for (int i = mouseListeners.size(); --i >= 0;)
  33396. {
  33397. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  33398. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  33399. else
  33400. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  33401. if (deletionChecker.hasBeenDeleted())
  33402. return;
  33403. i = jmin (i, mouseListeners.size());
  33404. }
  33405. }
  33406. }
  33407. }
  33408. void Desktop::resetTimer() throw()
  33409. {
  33410. if (mouseListeners.size() == 0)
  33411. stopTimer();
  33412. else
  33413. startTimer (100);
  33414. getMousePosition (lastMouseX, lastMouseY);
  33415. }
  33416. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33417. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33418. {
  33419. if (kioskModeComponent != componentToUse)
  33420. {
  33421. // agh! Don't delete a component without first stopping it being the kiosk comp
  33422. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33423. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33424. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33425. if (kioskModeComponent->isValidComponent())
  33426. {
  33427. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33428. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33429. }
  33430. kioskModeComponent = componentToUse;
  33431. if (kioskModeComponent != 0)
  33432. {
  33433. jassert (kioskModeComponent->isValidComponent());
  33434. // Only components that are already on the desktop can be put into kiosk mode!
  33435. jassert (kioskModeComponent->isOnDesktop());
  33436. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33437. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33438. }
  33439. }
  33440. }
  33441. END_JUCE_NAMESPACE
  33442. /********* End of inlined file: juce_Desktop.cpp *********/
  33443. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  33444. BEGIN_JUCE_NAMESPACE
  33445. ArrowButton::ArrowButton (const String& name,
  33446. float arrowDirectionInRadians,
  33447. const Colour& arrowColour)
  33448. : Button (name),
  33449. colour (arrowColour)
  33450. {
  33451. path.lineTo (0.0f, 1.0f);
  33452. path.lineTo (1.0f, 0.5f);
  33453. path.closeSubPath();
  33454. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33455. 0.5f, 0.5f));
  33456. setComponentEffect (&shadow);
  33457. buttonStateChanged();
  33458. }
  33459. ArrowButton::~ArrowButton()
  33460. {
  33461. }
  33462. void ArrowButton::paintButton (Graphics& g,
  33463. bool /*isMouseOverButton*/,
  33464. bool /*isButtonDown*/)
  33465. {
  33466. g.setColour (colour);
  33467. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33468. (float) offset,
  33469. (float) (getWidth() - 3),
  33470. (float) (getHeight() - 3),
  33471. false));
  33472. }
  33473. void ArrowButton::buttonStateChanged()
  33474. {
  33475. offset = (isDown()) ? 1 : 0;
  33476. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33477. 0.3f, -1, 0);
  33478. }
  33479. END_JUCE_NAMESPACE
  33480. /********* End of inlined file: juce_ArrowButton.cpp *********/
  33481. /********* Start of inlined file: juce_Button.cpp *********/
  33482. BEGIN_JUCE_NAMESPACE
  33483. Button::Button (const String& name)
  33484. : Component (name),
  33485. shortcuts (2),
  33486. keySource (0),
  33487. text (name),
  33488. buttonListeners (2),
  33489. repeatTimer (0),
  33490. buttonPressTime (0),
  33491. lastTimeCallbackTime (0),
  33492. commandManagerToUse (0),
  33493. autoRepeatDelay (-1),
  33494. autoRepeatSpeed (0),
  33495. autoRepeatMinimumDelay (-1),
  33496. radioGroupId (0),
  33497. commandID (0),
  33498. connectedEdgeFlags (0),
  33499. buttonState (buttonNormal),
  33500. isOn (false),
  33501. clickTogglesState (false),
  33502. needsToRelease (false),
  33503. needsRepainting (false),
  33504. isKeyDown (false),
  33505. triggerOnMouseDown (false),
  33506. generateTooltip (false)
  33507. {
  33508. setWantsKeyboardFocus (true);
  33509. }
  33510. Button::~Button()
  33511. {
  33512. if (commandManagerToUse != 0)
  33513. commandManagerToUse->removeListener (this);
  33514. delete repeatTimer;
  33515. clearShortcuts();
  33516. }
  33517. void Button::setButtonText (const String& newText) throw()
  33518. {
  33519. if (text != newText)
  33520. {
  33521. text = newText;
  33522. repaint();
  33523. }
  33524. }
  33525. void Button::setTooltip (const String& newTooltip)
  33526. {
  33527. SettableTooltipClient::setTooltip (newTooltip);
  33528. generateTooltip = false;
  33529. }
  33530. const String Button::getTooltip()
  33531. {
  33532. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33533. {
  33534. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33535. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33536. for (int i = 0; i < keyPresses.size(); ++i)
  33537. {
  33538. const String key (keyPresses.getReference(i).getTextDescription());
  33539. if (key.length() == 1)
  33540. tt << " [shortcut: '" << key << "']";
  33541. else
  33542. tt << " [" << key << ']';
  33543. }
  33544. return tt;
  33545. }
  33546. return SettableTooltipClient::getTooltip();
  33547. }
  33548. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  33549. {
  33550. if (connectedEdgeFlags != connectedEdgeFlags_)
  33551. {
  33552. connectedEdgeFlags = connectedEdgeFlags_;
  33553. repaint();
  33554. }
  33555. }
  33556. void Button::setToggleState (const bool shouldBeOn,
  33557. const bool sendChangeNotification)
  33558. {
  33559. if (shouldBeOn != isOn)
  33560. {
  33561. const ComponentDeletionWatcher deletionWatcher (this);
  33562. isOn = shouldBeOn;
  33563. repaint();
  33564. if (sendChangeNotification)
  33565. sendClickMessage (ModifierKeys());
  33566. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  33567. turnOffOtherButtonsInGroup (sendChangeNotification);
  33568. }
  33569. }
  33570. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33571. {
  33572. clickTogglesState = shouldToggle;
  33573. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33574. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33575. // it is that this button represents, and the button will update its state to reflect this
  33576. // in the applicationCommandListChanged() method.
  33577. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33578. }
  33579. bool Button::getClickingTogglesState() const throw()
  33580. {
  33581. return clickTogglesState;
  33582. }
  33583. void Button::setRadioGroupId (const int newGroupId)
  33584. {
  33585. if (radioGroupId != newGroupId)
  33586. {
  33587. radioGroupId = newGroupId;
  33588. if (isOn)
  33589. turnOffOtherButtonsInGroup (true);
  33590. }
  33591. }
  33592. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33593. {
  33594. Component* const p = getParentComponent();
  33595. if (p != 0 && radioGroupId != 0)
  33596. {
  33597. const ComponentDeletionWatcher deletionWatcher (this);
  33598. for (int i = p->getNumChildComponents(); --i >= 0;)
  33599. {
  33600. Component* const c = p->getChildComponent (i);
  33601. if (c != this)
  33602. {
  33603. Button* const b = dynamic_cast <Button*> (c);
  33604. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33605. {
  33606. b->setToggleState (false, sendChangeNotification);
  33607. if (deletionWatcher.hasBeenDeleted())
  33608. return;
  33609. }
  33610. }
  33611. }
  33612. }
  33613. }
  33614. void Button::enablementChanged()
  33615. {
  33616. updateState (0);
  33617. repaint();
  33618. }
  33619. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  33620. {
  33621. ButtonState state = buttonNormal;
  33622. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33623. {
  33624. int mx, my;
  33625. if (e == 0)
  33626. {
  33627. getMouseXYRelative (mx, my);
  33628. }
  33629. else
  33630. {
  33631. const MouseEvent e2 (e->getEventRelativeTo (this));
  33632. mx = e2.x;
  33633. my = e2.y;
  33634. }
  33635. const bool over = reallyContains (mx, my, true);
  33636. const bool down = isMouseButtonDown();
  33637. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33638. state = buttonDown;
  33639. else if (over)
  33640. state = buttonOver;
  33641. }
  33642. setState (state);
  33643. return state;
  33644. }
  33645. void Button::setState (const ButtonState newState)
  33646. {
  33647. if (buttonState != newState)
  33648. {
  33649. buttonState = newState;
  33650. repaint();
  33651. if (buttonState == buttonDown)
  33652. {
  33653. buttonPressTime = Time::getApproximateMillisecondCounter();
  33654. lastTimeCallbackTime = buttonPressTime;
  33655. }
  33656. sendStateMessage();
  33657. }
  33658. }
  33659. bool Button::isDown() const throw()
  33660. {
  33661. return buttonState == buttonDown;
  33662. }
  33663. bool Button::isOver() const throw()
  33664. {
  33665. return buttonState != buttonNormal;
  33666. }
  33667. void Button::buttonStateChanged()
  33668. {
  33669. }
  33670. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  33671. {
  33672. const uint32 now = Time::getApproximateMillisecondCounter();
  33673. return now > buttonPressTime ? now - buttonPressTime : 0;
  33674. }
  33675. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  33676. {
  33677. triggerOnMouseDown = isTriggeredOnMouseDown;
  33678. }
  33679. void Button::clicked()
  33680. {
  33681. }
  33682. void Button::clicked (const ModifierKeys& /*modifiers*/)
  33683. {
  33684. clicked();
  33685. }
  33686. static const int clickMessageId = 0x2f3f4f99;
  33687. void Button::triggerClick()
  33688. {
  33689. postCommandMessage (clickMessageId);
  33690. }
  33691. void Button::internalClickCallback (const ModifierKeys& modifiers)
  33692. {
  33693. if (clickTogglesState)
  33694. setToggleState ((radioGroupId != 0) || ! isOn, false);
  33695. sendClickMessage (modifiers);
  33696. }
  33697. void Button::flashButtonState() throw()
  33698. {
  33699. if (isEnabled())
  33700. {
  33701. needsToRelease = true;
  33702. setState (buttonDown);
  33703. getRepeatTimer().startTimer (100);
  33704. }
  33705. }
  33706. void Button::handleCommandMessage (int commandId)
  33707. {
  33708. if (commandId == clickMessageId)
  33709. {
  33710. if (isEnabled())
  33711. {
  33712. flashButtonState();
  33713. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33714. }
  33715. }
  33716. else
  33717. {
  33718. Component::handleCommandMessage (commandId);
  33719. }
  33720. }
  33721. void Button::addButtonListener (ButtonListener* const newListener) throw()
  33722. {
  33723. jassert (newListener != 0);
  33724. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  33725. if (newListener != 0)
  33726. buttonListeners.add (newListener);
  33727. }
  33728. void Button::removeButtonListener (ButtonListener* const listener) throw()
  33729. {
  33730. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  33731. buttonListeners.removeValue (listener);
  33732. }
  33733. void Button::sendClickMessage (const ModifierKeys& modifiers)
  33734. {
  33735. const ComponentDeletionWatcher cdw (this);
  33736. if (commandManagerToUse != 0 && commandID != 0)
  33737. {
  33738. ApplicationCommandTarget::InvocationInfo info (commandID);
  33739. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  33740. info.originatingComponent = this;
  33741. commandManagerToUse->invoke (info, true);
  33742. }
  33743. clicked (modifiers);
  33744. if (! cdw.hasBeenDeleted())
  33745. {
  33746. for (int i = buttonListeners.size(); --i >= 0;)
  33747. {
  33748. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33749. if (bl != 0)
  33750. {
  33751. bl->buttonClicked (this);
  33752. if (cdw.hasBeenDeleted())
  33753. return;
  33754. }
  33755. }
  33756. }
  33757. }
  33758. void Button::sendStateMessage()
  33759. {
  33760. const ComponentDeletionWatcher cdw (this);
  33761. buttonStateChanged();
  33762. if (cdw.hasBeenDeleted())
  33763. return;
  33764. for (int i = buttonListeners.size(); --i >= 0;)
  33765. {
  33766. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33767. if (bl != 0)
  33768. {
  33769. bl->buttonStateChanged (this);
  33770. if (cdw.hasBeenDeleted())
  33771. return;
  33772. }
  33773. }
  33774. }
  33775. void Button::paint (Graphics& g)
  33776. {
  33777. if (needsToRelease && isEnabled())
  33778. {
  33779. needsToRelease = false;
  33780. needsRepainting = true;
  33781. }
  33782. paintButton (g, isOver(), isDown());
  33783. }
  33784. void Button::mouseEnter (const MouseEvent& e)
  33785. {
  33786. updateState (&e);
  33787. }
  33788. void Button::mouseExit (const MouseEvent& e)
  33789. {
  33790. updateState (&e);
  33791. }
  33792. void Button::mouseDown (const MouseEvent& e)
  33793. {
  33794. updateState (&e);
  33795. if (isDown())
  33796. {
  33797. if (autoRepeatDelay >= 0)
  33798. getRepeatTimer().startTimer (autoRepeatDelay);
  33799. if (triggerOnMouseDown)
  33800. internalClickCallback (e.mods);
  33801. }
  33802. }
  33803. void Button::mouseUp (const MouseEvent& e)
  33804. {
  33805. const bool wasDown = isDown();
  33806. updateState (&e);
  33807. if (wasDown && isOver() && ! triggerOnMouseDown)
  33808. internalClickCallback (e.mods);
  33809. }
  33810. void Button::mouseDrag (const MouseEvent& e)
  33811. {
  33812. const ButtonState oldState = buttonState;
  33813. updateState (&e);
  33814. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  33815. getRepeatTimer().startTimer (autoRepeatSpeed);
  33816. }
  33817. void Button::focusGained (FocusChangeType)
  33818. {
  33819. updateState (0);
  33820. repaint();
  33821. }
  33822. void Button::focusLost (FocusChangeType)
  33823. {
  33824. updateState (0);
  33825. repaint();
  33826. }
  33827. void Button::setVisible (bool shouldBeVisible)
  33828. {
  33829. if (shouldBeVisible != isVisible())
  33830. {
  33831. Component::setVisible (shouldBeVisible);
  33832. if (! shouldBeVisible)
  33833. needsToRelease = false;
  33834. updateState (0);
  33835. }
  33836. else
  33837. {
  33838. Component::setVisible (shouldBeVisible);
  33839. }
  33840. }
  33841. void Button::parentHierarchyChanged()
  33842. {
  33843. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  33844. if (newKeySource != keySource)
  33845. {
  33846. if (keySource->isValidComponent())
  33847. keySource->removeKeyListener (this);
  33848. keySource = newKeySource;
  33849. if (keySource->isValidComponent())
  33850. keySource->addKeyListener (this);
  33851. }
  33852. }
  33853. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  33854. const int commandID_,
  33855. const bool generateTooltip_)
  33856. {
  33857. commandID = commandID_;
  33858. generateTooltip = generateTooltip_;
  33859. if (commandManagerToUse != commandManagerToUse_)
  33860. {
  33861. if (commandManagerToUse != 0)
  33862. commandManagerToUse->removeListener (this);
  33863. commandManagerToUse = commandManagerToUse_;
  33864. if (commandManagerToUse != 0)
  33865. commandManagerToUse->addListener (this);
  33866. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33867. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33868. // it is that this button represents, and the button will update its state to reflect this
  33869. // in the applicationCommandListChanged() method.
  33870. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33871. }
  33872. if (commandManagerToUse != 0)
  33873. applicationCommandListChanged();
  33874. else
  33875. setEnabled (true);
  33876. }
  33877. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  33878. {
  33879. if (info.commandID == commandID
  33880. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  33881. {
  33882. flashButtonState();
  33883. }
  33884. }
  33885. void Button::applicationCommandListChanged()
  33886. {
  33887. if (commandManagerToUse != 0)
  33888. {
  33889. ApplicationCommandInfo info (0);
  33890. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  33891. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  33892. if (target != 0)
  33893. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  33894. }
  33895. }
  33896. void Button::addShortcut (const KeyPress& key)
  33897. {
  33898. if (key.isValid())
  33899. {
  33900. jassert (! isRegisteredForShortcut (key)); // already registered!
  33901. shortcuts.add (key);
  33902. parentHierarchyChanged();
  33903. }
  33904. }
  33905. void Button::clearShortcuts()
  33906. {
  33907. shortcuts.clear();
  33908. parentHierarchyChanged();
  33909. }
  33910. bool Button::isShortcutPressed() const throw()
  33911. {
  33912. if (! isCurrentlyBlockedByAnotherModalComponent())
  33913. {
  33914. for (int i = shortcuts.size(); --i >= 0;)
  33915. if (shortcuts.getReference(i).isCurrentlyDown())
  33916. return true;
  33917. }
  33918. return false;
  33919. }
  33920. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  33921. {
  33922. for (int i = shortcuts.size(); --i >= 0;)
  33923. if (key == shortcuts.getReference(i))
  33924. return true;
  33925. return false;
  33926. }
  33927. bool Button::keyStateChanged (const bool, Component*)
  33928. {
  33929. if (! isEnabled())
  33930. return false;
  33931. const bool wasDown = isKeyDown;
  33932. isKeyDown = isShortcutPressed();
  33933. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  33934. getRepeatTimer().startTimer (autoRepeatDelay);
  33935. updateState (0);
  33936. if (isEnabled() && wasDown && ! isKeyDown)
  33937. {
  33938. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33939. // (return immediately - this button may now have been deleted)
  33940. return true;
  33941. }
  33942. return wasDown || isKeyDown;
  33943. }
  33944. bool Button::keyPressed (const KeyPress&, Component*)
  33945. {
  33946. // returning true will avoid forwarding events for keys that we're using as shortcuts
  33947. return isShortcutPressed();
  33948. }
  33949. bool Button::keyPressed (const KeyPress& key)
  33950. {
  33951. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  33952. {
  33953. triggerClick();
  33954. return true;
  33955. }
  33956. return false;
  33957. }
  33958. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  33959. const int repeatMillisecs,
  33960. const int minimumDelayInMillisecs) throw()
  33961. {
  33962. autoRepeatDelay = initialDelayMillisecs;
  33963. autoRepeatSpeed = repeatMillisecs;
  33964. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  33965. }
  33966. void Button::repeatTimerCallback() throw()
  33967. {
  33968. if (needsRepainting)
  33969. {
  33970. getRepeatTimer().stopTimer();
  33971. updateState (0);
  33972. needsRepainting = false;
  33973. }
  33974. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  33975. {
  33976. int repeatSpeed = autoRepeatSpeed;
  33977. if (autoRepeatMinimumDelay >= 0)
  33978. {
  33979. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  33980. timeHeldDown *= timeHeldDown;
  33981. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  33982. }
  33983. repeatSpeed = jmax (1, repeatSpeed);
  33984. getRepeatTimer().startTimer (repeatSpeed);
  33985. const uint32 now = Time::getApproximateMillisecondCounter();
  33986. const int numTimesToCallback
  33987. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  33988. lastTimeCallbackTime = now;
  33989. const ComponentDeletionWatcher cdw (this);
  33990. for (int i = numTimesToCallback; --i >= 0;)
  33991. {
  33992. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33993. if (cdw.hasBeenDeleted() || ! isDown())
  33994. return;
  33995. }
  33996. }
  33997. else if (! needsToRelease)
  33998. {
  33999. getRepeatTimer().stopTimer();
  34000. }
  34001. }
  34002. class InternalButtonRepeatTimer : public Timer
  34003. {
  34004. public:
  34005. InternalButtonRepeatTimer (Button& owner_) throw()
  34006. : owner (owner_)
  34007. {
  34008. }
  34009. ~InternalButtonRepeatTimer()
  34010. {
  34011. }
  34012. void timerCallback()
  34013. {
  34014. owner.repeatTimerCallback();
  34015. }
  34016. private:
  34017. Button& owner;
  34018. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  34019. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  34020. };
  34021. Timer& Button::getRepeatTimer() throw()
  34022. {
  34023. if (repeatTimer == 0)
  34024. repeatTimer = new InternalButtonRepeatTimer (*this);
  34025. return *repeatTimer;
  34026. }
  34027. END_JUCE_NAMESPACE
  34028. /********* End of inlined file: juce_Button.cpp *********/
  34029. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  34030. BEGIN_JUCE_NAMESPACE
  34031. DrawableButton::DrawableButton (const String& name,
  34032. const DrawableButton::ButtonStyle buttonStyle)
  34033. : Button (name),
  34034. style (buttonStyle),
  34035. normalImage (0),
  34036. overImage (0),
  34037. downImage (0),
  34038. disabledImage (0),
  34039. normalImageOn (0),
  34040. overImageOn (0),
  34041. downImageOn (0),
  34042. disabledImageOn (0),
  34043. edgeIndent (3)
  34044. {
  34045. if (buttonStyle == ImageOnButtonBackground)
  34046. {
  34047. backgroundOff = Colour (0xffbbbbff);
  34048. backgroundOn = Colour (0xff3333ff);
  34049. }
  34050. else
  34051. {
  34052. backgroundOff = Colours::transparentBlack;
  34053. backgroundOn = Colour (0xaabbbbff);
  34054. }
  34055. }
  34056. DrawableButton::~DrawableButton()
  34057. {
  34058. deleteImages();
  34059. }
  34060. void DrawableButton::deleteImages()
  34061. {
  34062. deleteAndZero (normalImage);
  34063. deleteAndZero (overImage);
  34064. deleteAndZero (downImage);
  34065. deleteAndZero (disabledImage);
  34066. deleteAndZero (normalImageOn);
  34067. deleteAndZero (overImageOn);
  34068. deleteAndZero (downImageOn);
  34069. deleteAndZero (disabledImageOn);
  34070. }
  34071. void DrawableButton::setImages (const Drawable* normal,
  34072. const Drawable* over,
  34073. const Drawable* down,
  34074. const Drawable* disabled,
  34075. const Drawable* normalOn,
  34076. const Drawable* overOn,
  34077. const Drawable* downOn,
  34078. const Drawable* disabledOn)
  34079. {
  34080. deleteImages();
  34081. jassert (normal != 0); // you really need to give it at least a normal image..
  34082. if (normal != 0)
  34083. normalImage = normal->createCopy();
  34084. if (over != 0)
  34085. overImage = over->createCopy();
  34086. if (down != 0)
  34087. downImage = down->createCopy();
  34088. if (disabled != 0)
  34089. disabledImage = disabled->createCopy();
  34090. if (normalOn != 0)
  34091. normalImageOn = normalOn->createCopy();
  34092. if (overOn != 0)
  34093. overImageOn = overOn->createCopy();
  34094. if (downOn != 0)
  34095. downImageOn = downOn->createCopy();
  34096. if (disabledOn != 0)
  34097. disabledImageOn = disabledOn->createCopy();
  34098. repaint();
  34099. }
  34100. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34101. {
  34102. if (style != newStyle)
  34103. {
  34104. style = newStyle;
  34105. repaint();
  34106. }
  34107. }
  34108. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34109. const Colour& toggledOnColour)
  34110. {
  34111. if (backgroundOff != toggledOffColour
  34112. || backgroundOn != toggledOnColour)
  34113. {
  34114. backgroundOff = toggledOffColour;
  34115. backgroundOn = toggledOnColour;
  34116. repaint();
  34117. }
  34118. }
  34119. const Colour& DrawableButton::getBackgroundColour() const throw()
  34120. {
  34121. return getToggleState() ? backgroundOn
  34122. : backgroundOff;
  34123. }
  34124. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34125. {
  34126. edgeIndent = numPixelsIndent;
  34127. repaint();
  34128. }
  34129. void DrawableButton::paintButton (Graphics& g,
  34130. bool isMouseOverButton,
  34131. bool isButtonDown)
  34132. {
  34133. Rectangle imageSpace;
  34134. if (style == ImageOnButtonBackground)
  34135. {
  34136. const int insetX = getWidth() / 4;
  34137. const int insetY = getHeight() / 4;
  34138. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34139. getLookAndFeel().drawButtonBackground (g, *this,
  34140. getBackgroundColour(),
  34141. isMouseOverButton,
  34142. isButtonDown);
  34143. }
  34144. else
  34145. {
  34146. g.fillAll (getBackgroundColour());
  34147. const int textH = (style == ImageAboveTextLabel)
  34148. ? jmin (16, proportionOfHeight (0.25f))
  34149. : 0;
  34150. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34151. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34152. imageSpace.setBounds (indentX, indentY,
  34153. getWidth() - indentX * 2,
  34154. getHeight() - indentY * 2 - textH);
  34155. if (textH > 0)
  34156. {
  34157. g.setFont ((float) textH);
  34158. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34159. g.drawFittedText (getButtonText(),
  34160. 2, getHeight() - textH - 1,
  34161. getWidth() - 4, textH,
  34162. Justification::centred, 1);
  34163. }
  34164. }
  34165. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34166. g.setOpacity (1.0f);
  34167. const Drawable* imageToDraw = 0;
  34168. if (isEnabled())
  34169. {
  34170. imageToDraw = getCurrentImage();
  34171. }
  34172. else
  34173. {
  34174. imageToDraw = getToggleState() ? disabledImageOn
  34175. : disabledImage;
  34176. if (imageToDraw == 0)
  34177. {
  34178. g.setOpacity (0.4f);
  34179. imageToDraw = getNormalImage();
  34180. }
  34181. }
  34182. if (imageToDraw != 0)
  34183. {
  34184. if (style == ImageRaw)
  34185. {
  34186. imageToDraw->draw (g);
  34187. }
  34188. else
  34189. {
  34190. imageToDraw->drawWithin (g,
  34191. imageSpace.getX(),
  34192. imageSpace.getY(),
  34193. imageSpace.getWidth(),
  34194. imageSpace.getHeight(),
  34195. RectanglePlacement::centred);
  34196. }
  34197. }
  34198. }
  34199. const Drawable* DrawableButton::getCurrentImage() const throw()
  34200. {
  34201. if (isDown())
  34202. return getDownImage();
  34203. if (isOver())
  34204. return getOverImage();
  34205. return getNormalImage();
  34206. }
  34207. const Drawable* DrawableButton::getNormalImage() const throw()
  34208. {
  34209. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34210. : normalImage;
  34211. }
  34212. const Drawable* DrawableButton::getOverImage() const throw()
  34213. {
  34214. const Drawable* d = normalImage;
  34215. if (getToggleState())
  34216. {
  34217. if (overImageOn != 0)
  34218. d = overImageOn;
  34219. else if (normalImageOn != 0)
  34220. d = normalImageOn;
  34221. else if (overImage != 0)
  34222. d = overImage;
  34223. }
  34224. else
  34225. {
  34226. if (overImage != 0)
  34227. d = overImage;
  34228. }
  34229. return d;
  34230. }
  34231. const Drawable* DrawableButton::getDownImage() const throw()
  34232. {
  34233. const Drawable* d = normalImage;
  34234. if (getToggleState())
  34235. {
  34236. if (downImageOn != 0)
  34237. d = downImageOn;
  34238. else if (overImageOn != 0)
  34239. d = overImageOn;
  34240. else if (normalImageOn != 0)
  34241. d = normalImageOn;
  34242. else if (downImage != 0)
  34243. d = downImage;
  34244. else
  34245. d = getOverImage();
  34246. }
  34247. else
  34248. {
  34249. if (downImage != 0)
  34250. d = downImage;
  34251. else
  34252. d = getOverImage();
  34253. }
  34254. return d;
  34255. }
  34256. END_JUCE_NAMESPACE
  34257. /********* End of inlined file: juce_DrawableButton.cpp *********/
  34258. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  34259. BEGIN_JUCE_NAMESPACE
  34260. HyperlinkButton::HyperlinkButton (const String& linkText,
  34261. const URL& linkURL)
  34262. : Button (linkText),
  34263. url (linkURL),
  34264. font (14.0f, Font::underlined),
  34265. resizeFont (true),
  34266. justification (Justification::centred)
  34267. {
  34268. setMouseCursor (MouseCursor::PointingHandCursor);
  34269. setTooltip (linkURL.toString (false));
  34270. }
  34271. HyperlinkButton::~HyperlinkButton()
  34272. {
  34273. }
  34274. void HyperlinkButton::setFont (const Font& newFont,
  34275. const bool resizeToMatchComponentHeight,
  34276. const Justification& justificationType)
  34277. {
  34278. font = newFont;
  34279. resizeFont = resizeToMatchComponentHeight;
  34280. justification = justificationType;
  34281. repaint();
  34282. }
  34283. void HyperlinkButton::setURL (const URL& newURL) throw()
  34284. {
  34285. url = newURL;
  34286. setTooltip (newURL.toString (false));
  34287. }
  34288. const Font HyperlinkButton::getFontToUse() const
  34289. {
  34290. Font f (font);
  34291. if (resizeFont)
  34292. f.setHeight (getHeight() * 0.7f);
  34293. return f;
  34294. }
  34295. void HyperlinkButton::changeWidthToFitText()
  34296. {
  34297. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34298. }
  34299. void HyperlinkButton::colourChanged()
  34300. {
  34301. repaint();
  34302. }
  34303. void HyperlinkButton::clicked()
  34304. {
  34305. if (url.isWellFormed())
  34306. url.launchInDefaultBrowser();
  34307. }
  34308. void HyperlinkButton::paintButton (Graphics& g,
  34309. bool isMouseOverButton,
  34310. bool isButtonDown)
  34311. {
  34312. const Colour textColour (findColour (textColourId));
  34313. if (isEnabled())
  34314. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34315. : textColour);
  34316. else
  34317. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34318. g.setFont (getFontToUse());
  34319. g.drawText (getButtonText(),
  34320. 2, 0, getWidth() - 2, getHeight(),
  34321. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34322. true);
  34323. }
  34324. END_JUCE_NAMESPACE
  34325. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  34326. /********* Start of inlined file: juce_ImageButton.cpp *********/
  34327. BEGIN_JUCE_NAMESPACE
  34328. ImageButton::ImageButton (const String& text_)
  34329. : Button (text_),
  34330. scaleImageToFit (true),
  34331. preserveProportions (true),
  34332. alphaThreshold (0),
  34333. imageX (0),
  34334. imageY (0),
  34335. imageW (0),
  34336. imageH (0),
  34337. normalImage (0),
  34338. overImage (0),
  34339. downImage (0)
  34340. {
  34341. }
  34342. ImageButton::~ImageButton()
  34343. {
  34344. deleteImages();
  34345. }
  34346. void ImageButton::deleteImages()
  34347. {
  34348. if (normalImage != 0)
  34349. {
  34350. if (ImageCache::isImageInCache (normalImage))
  34351. ImageCache::release (normalImage);
  34352. else
  34353. delete normalImage;
  34354. }
  34355. if (overImage != 0)
  34356. {
  34357. if (ImageCache::isImageInCache (overImage))
  34358. ImageCache::release (overImage);
  34359. else
  34360. delete overImage;
  34361. }
  34362. if (downImage != 0)
  34363. {
  34364. if (ImageCache::isImageInCache (downImage))
  34365. ImageCache::release (downImage);
  34366. else
  34367. delete downImage;
  34368. }
  34369. }
  34370. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34371. const bool rescaleImagesWhenButtonSizeChanges,
  34372. const bool preserveImageProportions,
  34373. Image* const normalImage_,
  34374. const float imageOpacityWhenNormal,
  34375. const Colour& overlayColourWhenNormal,
  34376. Image* const overImage_,
  34377. const float imageOpacityWhenOver,
  34378. const Colour& overlayColourWhenOver,
  34379. Image* const downImage_,
  34380. const float imageOpacityWhenDown,
  34381. const Colour& overlayColourWhenDown,
  34382. const float hitTestAlphaThreshold)
  34383. {
  34384. deleteImages();
  34385. normalImage = normalImage_;
  34386. overImage = overImage_;
  34387. downImage = downImage_;
  34388. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34389. {
  34390. imageW = normalImage->getWidth();
  34391. imageH = normalImage->getHeight();
  34392. setSize (imageW, imageH);
  34393. }
  34394. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34395. preserveProportions = preserveImageProportions;
  34396. normalOpacity = imageOpacityWhenNormal;
  34397. normalOverlay = overlayColourWhenNormal;
  34398. overOpacity = imageOpacityWhenOver;
  34399. overOverlay = overlayColourWhenOver;
  34400. downOpacity = imageOpacityWhenDown;
  34401. downOverlay = overlayColourWhenDown;
  34402. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  34403. repaint();
  34404. }
  34405. Image* ImageButton::getCurrentImage() const
  34406. {
  34407. if (isDown() || getToggleState())
  34408. return getDownImage();
  34409. if (isOver())
  34410. return getOverImage();
  34411. return getNormalImage();
  34412. }
  34413. Image* ImageButton::getNormalImage() const throw()
  34414. {
  34415. return normalImage;
  34416. }
  34417. Image* ImageButton::getOverImage() const throw()
  34418. {
  34419. return (overImage != 0) ? overImage
  34420. : normalImage;
  34421. }
  34422. Image* ImageButton::getDownImage() const throw()
  34423. {
  34424. return (downImage != 0) ? downImage
  34425. : getOverImage();
  34426. }
  34427. void ImageButton::paintButton (Graphics& g,
  34428. bool isMouseOverButton,
  34429. bool isButtonDown)
  34430. {
  34431. if (! isEnabled())
  34432. {
  34433. isMouseOverButton = false;
  34434. isButtonDown = false;
  34435. }
  34436. Image* const im = getCurrentImage();
  34437. if (im != 0)
  34438. {
  34439. const int iw = im->getWidth();
  34440. const int ih = im->getHeight();
  34441. imageW = getWidth();
  34442. imageH = getHeight();
  34443. imageX = (imageW - iw) >> 1;
  34444. imageY = (imageH - ih) >> 1;
  34445. if (scaleImageToFit)
  34446. {
  34447. if (preserveProportions)
  34448. {
  34449. int newW, newH;
  34450. const float imRatio = ih / (float)iw;
  34451. const float destRatio = imageH / (float)imageW;
  34452. if (imRatio > destRatio)
  34453. {
  34454. newW = roundFloatToInt (imageH / imRatio);
  34455. newH = imageH;
  34456. }
  34457. else
  34458. {
  34459. newW = imageW;
  34460. newH = roundFloatToInt (imageW * imRatio);
  34461. }
  34462. imageX = (imageW - newW) / 2;
  34463. imageY = (imageH - newH) / 2;
  34464. imageW = newW;
  34465. imageH = newH;
  34466. }
  34467. else
  34468. {
  34469. imageX = 0;
  34470. imageY = 0;
  34471. }
  34472. }
  34473. if (! scaleImageToFit)
  34474. {
  34475. imageW = iw;
  34476. imageH = ih;
  34477. }
  34478. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34479. isButtonDown ? downOverlay
  34480. : (isMouseOverButton ? overOverlay
  34481. : normalOverlay),
  34482. isButtonDown ? downOpacity
  34483. : (isMouseOverButton ? overOpacity
  34484. : normalOpacity),
  34485. *this);
  34486. }
  34487. }
  34488. bool ImageButton::hitTest (int x, int y)
  34489. {
  34490. if (alphaThreshold == 0)
  34491. return true;
  34492. Image* const im = getCurrentImage();
  34493. return im == 0
  34494. || (imageW > 0 && imageH > 0
  34495. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34496. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34497. }
  34498. END_JUCE_NAMESPACE
  34499. /********* End of inlined file: juce_ImageButton.cpp *********/
  34500. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  34501. BEGIN_JUCE_NAMESPACE
  34502. ShapeButton::ShapeButton (const String& text,
  34503. const Colour& normalColour_,
  34504. const Colour& overColour_,
  34505. const Colour& downColour_)
  34506. : Button (text),
  34507. normalColour (normalColour_),
  34508. overColour (overColour_),
  34509. downColour (downColour_),
  34510. maintainShapeProportions (false),
  34511. outlineWidth (0.0f)
  34512. {
  34513. }
  34514. ShapeButton::~ShapeButton()
  34515. {
  34516. }
  34517. void ShapeButton::setColours (const Colour& newNormalColour,
  34518. const Colour& newOverColour,
  34519. const Colour& newDownColour)
  34520. {
  34521. normalColour = newNormalColour;
  34522. overColour = newOverColour;
  34523. downColour = newDownColour;
  34524. }
  34525. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34526. const float newOutlineWidth)
  34527. {
  34528. outlineColour = newOutlineColour;
  34529. outlineWidth = newOutlineWidth;
  34530. }
  34531. void ShapeButton::setShape (const Path& newShape,
  34532. const bool resizeNowToFitThisShape,
  34533. const bool maintainShapeProportions_,
  34534. const bool hasShadow)
  34535. {
  34536. shape = newShape;
  34537. maintainShapeProportions = maintainShapeProportions_;
  34538. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34539. setComponentEffect ((hasShadow) ? &shadow : 0);
  34540. if (resizeNowToFitThisShape)
  34541. {
  34542. float x, y, w, h;
  34543. shape.getBounds (x, y, w, h);
  34544. shape.applyTransform (AffineTransform::translation (-x, -y));
  34545. if (hasShadow)
  34546. {
  34547. w += 4.0f;
  34548. h += 4.0f;
  34549. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  34550. }
  34551. setSize (1 + (int) (w + outlineWidth),
  34552. 1 + (int) (h + outlineWidth));
  34553. }
  34554. }
  34555. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34556. {
  34557. if (! isEnabled())
  34558. {
  34559. isMouseOverButton = false;
  34560. isButtonDown = false;
  34561. }
  34562. g.setColour ((isButtonDown) ? downColour
  34563. : (isMouseOverButton) ? overColour
  34564. : normalColour);
  34565. int w = getWidth();
  34566. int h = getHeight();
  34567. if (getComponentEffect() != 0)
  34568. {
  34569. w -= 4;
  34570. h -= 4;
  34571. }
  34572. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34573. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34574. w - offset - outlineWidth,
  34575. h - offset - outlineWidth,
  34576. maintainShapeProportions));
  34577. g.fillPath (shape, trans);
  34578. if (outlineWidth > 0.0f)
  34579. {
  34580. g.setColour (outlineColour);
  34581. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34582. }
  34583. }
  34584. END_JUCE_NAMESPACE
  34585. /********* End of inlined file: juce_ShapeButton.cpp *********/
  34586. /********* Start of inlined file: juce_TextButton.cpp *********/
  34587. BEGIN_JUCE_NAMESPACE
  34588. TextButton::TextButton (const String& name,
  34589. const String& toolTip)
  34590. : Button (name)
  34591. {
  34592. setTooltip (toolTip);
  34593. }
  34594. TextButton::~TextButton()
  34595. {
  34596. }
  34597. void TextButton::paintButton (Graphics& g,
  34598. bool isMouseOverButton,
  34599. bool isButtonDown)
  34600. {
  34601. getLookAndFeel().drawButtonBackground (g, *this,
  34602. findColour (getToggleState() ? buttonOnColourId
  34603. : buttonColourId),
  34604. isMouseOverButton,
  34605. isButtonDown);
  34606. getLookAndFeel().drawButtonText (g, *this,
  34607. isMouseOverButton,
  34608. isButtonDown);
  34609. }
  34610. void TextButton::colourChanged()
  34611. {
  34612. repaint();
  34613. }
  34614. const Font TextButton::getFont()
  34615. {
  34616. return Font (jmin (15.0f, getHeight() * 0.6f));
  34617. }
  34618. void TextButton::changeWidthToFitText (const int newHeight)
  34619. {
  34620. if (newHeight >= 0)
  34621. setSize (jmax (1, getWidth()), newHeight);
  34622. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34623. getHeight());
  34624. }
  34625. END_JUCE_NAMESPACE
  34626. /********* End of inlined file: juce_TextButton.cpp *********/
  34627. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  34628. BEGIN_JUCE_NAMESPACE
  34629. ToggleButton::ToggleButton (const String& buttonText)
  34630. : Button (buttonText)
  34631. {
  34632. setClickingTogglesState (true);
  34633. }
  34634. ToggleButton::~ToggleButton()
  34635. {
  34636. }
  34637. void ToggleButton::paintButton (Graphics& g,
  34638. bool isMouseOverButton,
  34639. bool isButtonDown)
  34640. {
  34641. getLookAndFeel().drawToggleButton (g, *this,
  34642. isMouseOverButton,
  34643. isButtonDown);
  34644. }
  34645. void ToggleButton::changeWidthToFitText()
  34646. {
  34647. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34648. }
  34649. void ToggleButton::colourChanged()
  34650. {
  34651. repaint();
  34652. }
  34653. END_JUCE_NAMESPACE
  34654. /********* End of inlined file: juce_ToggleButton.cpp *********/
  34655. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  34656. BEGIN_JUCE_NAMESPACE
  34657. ToolbarButton::ToolbarButton (const int itemId_,
  34658. const String& buttonText,
  34659. Drawable* const normalImage_,
  34660. Drawable* const toggledOnImage_)
  34661. : ToolbarItemComponent (itemId_, buttonText, true),
  34662. normalImage (normalImage_),
  34663. toggledOnImage (toggledOnImage_)
  34664. {
  34665. }
  34666. ToolbarButton::~ToolbarButton()
  34667. {
  34668. delete normalImage;
  34669. delete toggledOnImage;
  34670. }
  34671. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34672. bool /*isToolbarVertical*/,
  34673. int& preferredSize,
  34674. int& minSize, int& maxSize)
  34675. {
  34676. preferredSize = minSize = maxSize = toolbarDepth;
  34677. return true;
  34678. }
  34679. void ToolbarButton::paintButtonArea (Graphics& g,
  34680. int width, int height,
  34681. bool /*isMouseOver*/,
  34682. bool /*isMouseDown*/)
  34683. {
  34684. Drawable* d = normalImage;
  34685. if (getToggleState() && toggledOnImage != 0)
  34686. d = toggledOnImage;
  34687. if (! isEnabled())
  34688. {
  34689. Image im (Image::ARGB, width, height, true);
  34690. Graphics g2 (im);
  34691. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  34692. im.desaturate();
  34693. g.drawImageAt (&im, 0, 0);
  34694. }
  34695. else
  34696. {
  34697. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  34698. }
  34699. }
  34700. void ToolbarButton::contentAreaChanged (const Rectangle&)
  34701. {
  34702. }
  34703. END_JUCE_NAMESPACE
  34704. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  34705. /********* Start of inlined file: juce_ComboBox.cpp *********/
  34706. BEGIN_JUCE_NAMESPACE
  34707. ComboBox::ComboBox (const String& name)
  34708. : Component (name),
  34709. items (4),
  34710. currentIndex (-1),
  34711. isButtonDown (false),
  34712. separatorPending (false),
  34713. menuActive (false),
  34714. listeners (2),
  34715. label (0)
  34716. {
  34717. noChoicesMessage = TRANS("(no choices)");
  34718. setRepaintsOnMouseActivity (true);
  34719. lookAndFeelChanged();
  34720. }
  34721. ComboBox::~ComboBox()
  34722. {
  34723. if (menuActive)
  34724. PopupMenu::dismissAllActiveMenus();
  34725. deleteAllChildren();
  34726. }
  34727. void ComboBox::setEditableText (const bool isEditable)
  34728. {
  34729. label->setEditable (isEditable, isEditable, false);
  34730. setWantsKeyboardFocus (! isEditable);
  34731. resized();
  34732. }
  34733. bool ComboBox::isTextEditable() const throw()
  34734. {
  34735. return label->isEditable();
  34736. }
  34737. void ComboBox::setJustificationType (const Justification& justification) throw()
  34738. {
  34739. label->setJustificationType (justification);
  34740. }
  34741. const Justification ComboBox::getJustificationType() const throw()
  34742. {
  34743. return label->getJustificationType();
  34744. }
  34745. void ComboBox::setTooltip (const String& newTooltip)
  34746. {
  34747. SettableTooltipClient::setTooltip (newTooltip);
  34748. label->setTooltip (newTooltip);
  34749. }
  34750. void ComboBox::addItem (const String& newItemText,
  34751. const int newItemId) throw()
  34752. {
  34753. // you can't add empty strings to the list..
  34754. jassert (newItemText.isNotEmpty());
  34755. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  34756. jassert (newItemId != 0);
  34757. // you shouldn't use duplicate item IDs!
  34758. jassert (getItemForId (newItemId) == 0);
  34759. if (newItemText.isNotEmpty() && newItemId != 0)
  34760. {
  34761. if (separatorPending)
  34762. {
  34763. separatorPending = false;
  34764. ItemInfo* const item = new ItemInfo();
  34765. item->itemId = 0;
  34766. item->isEnabled = false;
  34767. item->isHeading = false;
  34768. items.add (item);
  34769. }
  34770. ItemInfo* const item = new ItemInfo();
  34771. item->name = newItemText;
  34772. item->itemId = newItemId;
  34773. item->isEnabled = true;
  34774. item->isHeading = false;
  34775. items.add (item);
  34776. }
  34777. }
  34778. void ComboBox::addSeparator() throw()
  34779. {
  34780. separatorPending = (items.size() > 0);
  34781. }
  34782. void ComboBox::addSectionHeading (const String& headingName) throw()
  34783. {
  34784. // you can't add empty strings to the list..
  34785. jassert (headingName.isNotEmpty());
  34786. if (headingName.isNotEmpty())
  34787. {
  34788. if (separatorPending)
  34789. {
  34790. separatorPending = false;
  34791. ItemInfo* const item = new ItemInfo();
  34792. item->itemId = 0;
  34793. item->isEnabled = false;
  34794. item->isHeading = false;
  34795. items.add (item);
  34796. }
  34797. ItemInfo* const item = new ItemInfo();
  34798. item->name = headingName;
  34799. item->itemId = 0;
  34800. item->isEnabled = true;
  34801. item->isHeading = true;
  34802. items.add (item);
  34803. }
  34804. }
  34805. void ComboBox::setItemEnabled (const int itemId,
  34806. const bool isEnabled) throw()
  34807. {
  34808. ItemInfo* const item = getItemForId (itemId);
  34809. if (item != 0)
  34810. item->isEnabled = isEnabled;
  34811. }
  34812. void ComboBox::changeItemText (const int itemId,
  34813. const String& newText) throw()
  34814. {
  34815. ItemInfo* const item = getItemForId (itemId);
  34816. jassert (item != 0);
  34817. if (item != 0)
  34818. item->name = newText;
  34819. }
  34820. void ComboBox::clear (const bool dontSendChangeMessage)
  34821. {
  34822. items.clear();
  34823. separatorPending = false;
  34824. if (! label->isEditable())
  34825. setSelectedItemIndex (-1, dontSendChangeMessage);
  34826. }
  34827. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  34828. {
  34829. jassert (itemId != 0);
  34830. if (itemId != 0)
  34831. {
  34832. for (int i = items.size(); --i >= 0;)
  34833. if (items.getUnchecked(i)->itemId == itemId)
  34834. return items.getUnchecked(i);
  34835. }
  34836. return 0;
  34837. }
  34838. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  34839. {
  34840. int n = 0;
  34841. for (int i = 0; i < items.size(); ++i)
  34842. {
  34843. ItemInfo* const item = items.getUnchecked(i);
  34844. if (item->isRealItem())
  34845. {
  34846. if (n++ == index)
  34847. return item;
  34848. }
  34849. }
  34850. return 0;
  34851. }
  34852. int ComboBox::getNumItems() const throw()
  34853. {
  34854. int n = 0;
  34855. for (int i = items.size(); --i >= 0;)
  34856. {
  34857. ItemInfo* const item = items.getUnchecked(i);
  34858. if (item->isRealItem())
  34859. ++n;
  34860. }
  34861. return n;
  34862. }
  34863. const String ComboBox::getItemText (const int index) const throw()
  34864. {
  34865. ItemInfo* const item = getItemForIndex (index);
  34866. if (item != 0)
  34867. return item->name;
  34868. return String::empty;
  34869. }
  34870. int ComboBox::getItemId (const int index) const throw()
  34871. {
  34872. ItemInfo* const item = getItemForIndex (index);
  34873. return (item != 0) ? item->itemId : 0;
  34874. }
  34875. bool ComboBox::ItemInfo::isSeparator() const throw()
  34876. {
  34877. return name.isEmpty();
  34878. }
  34879. bool ComboBox::ItemInfo::isRealItem() const throw()
  34880. {
  34881. return ! (isHeading || name.isEmpty());
  34882. }
  34883. int ComboBox::getSelectedItemIndex() const throw()
  34884. {
  34885. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  34886. ? currentIndex
  34887. : -1;
  34888. }
  34889. void ComboBox::setSelectedItemIndex (const int index,
  34890. const bool dontSendChangeMessage) throw()
  34891. {
  34892. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  34893. {
  34894. if (((unsigned int) index) < (unsigned int) getNumItems())
  34895. currentIndex = index;
  34896. else
  34897. currentIndex = -1;
  34898. label->setText (getItemText (currentIndex), false);
  34899. if (! dontSendChangeMessage)
  34900. triggerAsyncUpdate();
  34901. }
  34902. }
  34903. void ComboBox::setSelectedId (const int newItemId,
  34904. const bool dontSendChangeMessage) throw()
  34905. {
  34906. for (int i = getNumItems(); --i >= 0;)
  34907. {
  34908. if (getItemId(i) == newItemId)
  34909. {
  34910. setSelectedItemIndex (i, dontSendChangeMessage);
  34911. break;
  34912. }
  34913. }
  34914. }
  34915. int ComboBox::getSelectedId() const throw()
  34916. {
  34917. const ItemInfo* const item = getItemForIndex (currentIndex);
  34918. return (item != 0 && getText() == item->name)
  34919. ? item->itemId
  34920. : 0;
  34921. }
  34922. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  34923. {
  34924. jassert (listener != 0);
  34925. if (listener != 0)
  34926. listeners.add (listener);
  34927. }
  34928. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  34929. {
  34930. listeners.removeValue (listener);
  34931. }
  34932. void ComboBox::handleAsyncUpdate()
  34933. {
  34934. for (int i = listeners.size(); --i >= 0;)
  34935. {
  34936. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  34937. i = jmin (i, listeners.size());
  34938. }
  34939. }
  34940. const String ComboBox::getText() const throw()
  34941. {
  34942. return label->getText();
  34943. }
  34944. void ComboBox::setText (const String& newText,
  34945. const bool dontSendChangeMessage) throw()
  34946. {
  34947. for (int i = items.size(); --i >= 0;)
  34948. {
  34949. ItemInfo* const item = items.getUnchecked(i);
  34950. if (item->isRealItem()
  34951. && item->name == newText)
  34952. {
  34953. setSelectedId (item->itemId, dontSendChangeMessage);
  34954. return;
  34955. }
  34956. }
  34957. currentIndex = -1;
  34958. if (label->getText() != newText)
  34959. {
  34960. label->setText (newText, false);
  34961. if (! dontSendChangeMessage)
  34962. triggerAsyncUpdate();
  34963. }
  34964. repaint();
  34965. }
  34966. void ComboBox::showEditor()
  34967. {
  34968. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  34969. label->showEditor();
  34970. }
  34971. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  34972. {
  34973. textWhenNothingSelected = newMessage;
  34974. repaint();
  34975. }
  34976. const String ComboBox::getTextWhenNothingSelected() const throw()
  34977. {
  34978. return textWhenNothingSelected;
  34979. }
  34980. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  34981. {
  34982. noChoicesMessage = newMessage;
  34983. }
  34984. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  34985. {
  34986. return noChoicesMessage;
  34987. }
  34988. void ComboBox::paint (Graphics& g)
  34989. {
  34990. getLookAndFeel().drawComboBox (g,
  34991. getWidth(),
  34992. getHeight(),
  34993. isButtonDown,
  34994. label->getRight(),
  34995. 0,
  34996. getWidth() - label->getRight(),
  34997. getHeight(),
  34998. *this);
  34999. if (textWhenNothingSelected.isNotEmpty()
  35000. && label->getText().isEmpty()
  35001. && ! label->isBeingEdited())
  35002. {
  35003. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  35004. g.setFont (label->getFont());
  35005. g.drawFittedText (textWhenNothingSelected,
  35006. label->getX() + 2, label->getY() + 1,
  35007. label->getWidth() - 4, label->getHeight() - 2,
  35008. label->getJustificationType(),
  35009. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  35010. }
  35011. }
  35012. void ComboBox::resized()
  35013. {
  35014. if (getHeight() > 0 && getWidth() > 0)
  35015. getLookAndFeel().positionComboBoxText (*this, *label);
  35016. }
  35017. void ComboBox::enablementChanged()
  35018. {
  35019. repaint();
  35020. }
  35021. void ComboBox::lookAndFeelChanged()
  35022. {
  35023. repaint();
  35024. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  35025. if (label != 0)
  35026. {
  35027. newLabel->setEditable (label->isEditable());
  35028. newLabel->setJustificationType (label->getJustificationType());
  35029. newLabel->setTooltip (label->getTooltip());
  35030. newLabel->setText (label->getText(), false);
  35031. }
  35032. delete label;
  35033. label = newLabel;
  35034. addAndMakeVisible (newLabel);
  35035. newLabel->addListener (this);
  35036. newLabel->addMouseListener (this, false);
  35037. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  35038. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  35039. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  35040. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35041. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  35042. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35043. resized();
  35044. }
  35045. void ComboBox::colourChanged()
  35046. {
  35047. lookAndFeelChanged();
  35048. }
  35049. bool ComboBox::keyPressed (const KeyPress& key)
  35050. {
  35051. bool used = false;
  35052. if (key.isKeyCode (KeyPress::upKey)
  35053. || key.isKeyCode (KeyPress::leftKey))
  35054. {
  35055. setSelectedItemIndex (jmax (0, currentIndex - 1));
  35056. used = true;
  35057. }
  35058. else if (key.isKeyCode (KeyPress::downKey)
  35059. || key.isKeyCode (KeyPress::rightKey))
  35060. {
  35061. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  35062. used = true;
  35063. }
  35064. else if (key.isKeyCode (KeyPress::returnKey))
  35065. {
  35066. showPopup();
  35067. used = true;
  35068. }
  35069. return used;
  35070. }
  35071. bool ComboBox::keyStateChanged (const bool isKeyDown)
  35072. {
  35073. // only forward key events that aren't used by this component
  35074. return isKeyDown
  35075. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  35076. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  35077. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  35078. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  35079. }
  35080. void ComboBox::focusGained (FocusChangeType)
  35081. {
  35082. repaint();
  35083. }
  35084. void ComboBox::focusLost (FocusChangeType)
  35085. {
  35086. repaint();
  35087. }
  35088. void ComboBox::labelTextChanged (Label*)
  35089. {
  35090. triggerAsyncUpdate();
  35091. }
  35092. void ComboBox::showPopup()
  35093. {
  35094. if (! menuActive)
  35095. {
  35096. const int currentId = getSelectedId();
  35097. ComponentDeletionWatcher deletionWatcher (this);
  35098. PopupMenu menu;
  35099. menu.setLookAndFeel (&getLookAndFeel());
  35100. for (int i = 0; i < items.size(); ++i)
  35101. {
  35102. const ItemInfo* const item = items.getUnchecked(i);
  35103. if (item->isSeparator())
  35104. menu.addSeparator();
  35105. else if (item->isHeading)
  35106. menu.addSectionHeader (item->name);
  35107. else
  35108. menu.addItem (item->itemId, item->name,
  35109. item->isEnabled, item->itemId == currentId);
  35110. }
  35111. if (items.size() == 0)
  35112. menu.addItem (1, noChoicesMessage, false);
  35113. const int itemHeight = jlimit (12, 24, getHeight());
  35114. menuActive = true;
  35115. const int resultId = menu.showAt (this, currentId,
  35116. getWidth(), 1, itemHeight);
  35117. if (deletionWatcher.hasBeenDeleted())
  35118. return;
  35119. menuActive = false;
  35120. if (resultId != 0)
  35121. setSelectedId (resultId);
  35122. }
  35123. }
  35124. void ComboBox::mouseDown (const MouseEvent& e)
  35125. {
  35126. beginDragAutoRepeat (300);
  35127. isButtonDown = isEnabled();
  35128. if (isButtonDown
  35129. && (e.eventComponent == this || ! label->isEditable()))
  35130. {
  35131. showPopup();
  35132. }
  35133. }
  35134. void ComboBox::mouseDrag (const MouseEvent& e)
  35135. {
  35136. beginDragAutoRepeat (50);
  35137. if (isButtonDown && ! e.mouseWasClicked())
  35138. showPopup();
  35139. }
  35140. void ComboBox::mouseUp (const MouseEvent& e2)
  35141. {
  35142. if (isButtonDown)
  35143. {
  35144. isButtonDown = false;
  35145. repaint();
  35146. const MouseEvent e (e2.getEventRelativeTo (this));
  35147. if (reallyContains (e.x, e.y, true)
  35148. && (e2.eventComponent == this || ! label->isEditable()))
  35149. {
  35150. showPopup();
  35151. }
  35152. }
  35153. }
  35154. END_JUCE_NAMESPACE
  35155. /********* End of inlined file: juce_ComboBox.cpp *********/
  35156. /********* Start of inlined file: juce_Label.cpp *********/
  35157. BEGIN_JUCE_NAMESPACE
  35158. Label::Label (const String& componentName,
  35159. const String& labelText)
  35160. : Component (componentName),
  35161. text (labelText),
  35162. font (15.0f),
  35163. justification (Justification::centredLeft),
  35164. editor (0),
  35165. listeners (2),
  35166. ownerComponent (0),
  35167. deletionWatcher (0),
  35168. horizontalBorderSize (3),
  35169. verticalBorderSize (1),
  35170. minimumHorizontalScale (0.7f),
  35171. editSingleClick (false),
  35172. editDoubleClick (false),
  35173. lossOfFocusDiscardsChanges (false)
  35174. {
  35175. setColour (TextEditor::textColourId, Colours::black);
  35176. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35177. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35178. }
  35179. Label::~Label()
  35180. {
  35181. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35182. ownerComponent->removeComponentListener (this);
  35183. deleteAndZero (deletionWatcher);
  35184. if (editor != 0)
  35185. delete editor;
  35186. }
  35187. void Label::setText (const String& newText,
  35188. const bool broadcastChangeMessage)
  35189. {
  35190. hideEditor (true);
  35191. if (text != newText)
  35192. {
  35193. text = newText;
  35194. repaint();
  35195. textWasChanged();
  35196. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35197. componentMovedOrResized (*ownerComponent, true, true);
  35198. if (broadcastChangeMessage)
  35199. callChangeListeners();
  35200. }
  35201. }
  35202. const String Label::getText (const bool returnActiveEditorContents) const throw()
  35203. {
  35204. return (returnActiveEditorContents && isBeingEdited())
  35205. ? editor->getText()
  35206. : text;
  35207. }
  35208. void Label::setFont (const Font& newFont) throw()
  35209. {
  35210. font = newFont;
  35211. repaint();
  35212. }
  35213. const Font& Label::getFont() const throw()
  35214. {
  35215. return font;
  35216. }
  35217. void Label::setEditable (const bool editOnSingleClick,
  35218. const bool editOnDoubleClick,
  35219. const bool lossOfFocusDiscardsChanges_) throw()
  35220. {
  35221. editSingleClick = editOnSingleClick;
  35222. editDoubleClick = editOnDoubleClick;
  35223. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  35224. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  35225. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  35226. }
  35227. void Label::setJustificationType (const Justification& justification_) throw()
  35228. {
  35229. justification = justification_;
  35230. repaint();
  35231. }
  35232. void Label::setBorderSize (int h, int v)
  35233. {
  35234. horizontalBorderSize = h;
  35235. verticalBorderSize = v;
  35236. repaint();
  35237. }
  35238. void Label::attachToComponent (Component* owner,
  35239. const bool onLeft)
  35240. {
  35241. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35242. ownerComponent->removeComponentListener (this);
  35243. deleteAndZero (deletionWatcher);
  35244. ownerComponent = owner;
  35245. leftOfOwnerComp = onLeft;
  35246. if (ownerComponent != 0)
  35247. {
  35248. deletionWatcher = new ComponentDeletionWatcher (owner);
  35249. setVisible (owner->isVisible());
  35250. ownerComponent->addComponentListener (this);
  35251. componentParentHierarchyChanged (*ownerComponent);
  35252. componentMovedOrResized (*ownerComponent, true, true);
  35253. }
  35254. }
  35255. void Label::componentMovedOrResized (Component& component,
  35256. bool /*wasMoved*/,
  35257. bool /*wasResized*/)
  35258. {
  35259. if (leftOfOwnerComp)
  35260. {
  35261. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  35262. component.getHeight());
  35263. setTopRightPosition (component.getX(), component.getY());
  35264. }
  35265. else
  35266. {
  35267. setSize (component.getWidth(),
  35268. 8 + roundFloatToInt (getFont().getHeight()));
  35269. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  35270. }
  35271. }
  35272. void Label::componentParentHierarchyChanged (Component& component)
  35273. {
  35274. if (component.getParentComponent() != 0)
  35275. component.getParentComponent()->addChildComponent (this);
  35276. }
  35277. void Label::componentVisibilityChanged (Component& component)
  35278. {
  35279. setVisible (component.isVisible());
  35280. }
  35281. void Label::textWasEdited()
  35282. {
  35283. }
  35284. void Label::textWasChanged()
  35285. {
  35286. }
  35287. void Label::showEditor()
  35288. {
  35289. if (editor == 0)
  35290. {
  35291. addAndMakeVisible (editor = createEditorComponent());
  35292. editor->setText (getText(), false);
  35293. editor->addListener (this);
  35294. editor->grabKeyboardFocus();
  35295. editor->setHighlightedRegion (0, text.length());
  35296. editor->addListener (this);
  35297. resized();
  35298. repaint();
  35299. editorShown (editor);
  35300. enterModalState();
  35301. editor->grabKeyboardFocus();
  35302. }
  35303. }
  35304. void Label::editorShown (TextEditor* editorComponent)
  35305. {
  35306. }
  35307. void Label::editorAboutToBeHidden (TextEditor* editorComponent)
  35308. {
  35309. }
  35310. bool Label::updateFromTextEditorContents()
  35311. {
  35312. jassert (editor != 0);
  35313. const String newText (editor->getText());
  35314. if (text != newText)
  35315. {
  35316. text = newText;
  35317. repaint();
  35318. textWasChanged();
  35319. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35320. componentMovedOrResized (*ownerComponent, true, true);
  35321. return true;
  35322. }
  35323. return false;
  35324. }
  35325. void Label::hideEditor (const bool discardCurrentEditorContents)
  35326. {
  35327. if (editor != 0)
  35328. {
  35329. editorAboutToBeHidden (editor);
  35330. const bool changed = (! discardCurrentEditorContents)
  35331. && updateFromTextEditorContents();
  35332. deleteAndZero (editor);
  35333. repaint();
  35334. if (changed)
  35335. textWasEdited();
  35336. exitModalState (0);
  35337. if (changed && isValidComponent())
  35338. callChangeListeners();
  35339. }
  35340. }
  35341. void Label::inputAttemptWhenModal()
  35342. {
  35343. if (editor != 0)
  35344. {
  35345. if (lossOfFocusDiscardsChanges)
  35346. textEditorEscapeKeyPressed (*editor);
  35347. else
  35348. textEditorReturnKeyPressed (*editor);
  35349. }
  35350. }
  35351. bool Label::isBeingEdited() const throw()
  35352. {
  35353. return editor != 0;
  35354. }
  35355. TextEditor* Label::createEditorComponent()
  35356. {
  35357. TextEditor* const ed = new TextEditor (getName());
  35358. ed->setFont (font);
  35359. // copy these colours from our own settings..
  35360. const int cols[] = { TextEditor::backgroundColourId,
  35361. TextEditor::textColourId,
  35362. TextEditor::highlightColourId,
  35363. TextEditor::highlightedTextColourId,
  35364. TextEditor::caretColourId,
  35365. TextEditor::outlineColourId,
  35366. TextEditor::focusedOutlineColourId,
  35367. TextEditor::shadowColourId };
  35368. for (int i = 0; i < numElementsInArray (cols); ++i)
  35369. ed->setColour (cols[i], findColour (cols[i]));
  35370. return ed;
  35371. }
  35372. void Label::paint (Graphics& g)
  35373. {
  35374. getLookAndFeel().drawLabel (g, *this);
  35375. }
  35376. void Label::mouseUp (const MouseEvent& e)
  35377. {
  35378. if (editSingleClick
  35379. && e.mouseWasClicked()
  35380. && contains (e.x, e.y)
  35381. && ! e.mods.isPopupMenu())
  35382. {
  35383. showEditor();
  35384. }
  35385. }
  35386. void Label::mouseDoubleClick (const MouseEvent& e)
  35387. {
  35388. if (editDoubleClick && ! e.mods.isPopupMenu())
  35389. showEditor();
  35390. }
  35391. void Label::resized()
  35392. {
  35393. if (editor != 0)
  35394. editor->setBoundsInset (BorderSize (0));
  35395. }
  35396. void Label::focusGained (FocusChangeType cause)
  35397. {
  35398. if (editSingleClick && cause == focusChangedByTabKey)
  35399. showEditor();
  35400. }
  35401. void Label::enablementChanged()
  35402. {
  35403. repaint();
  35404. }
  35405. void Label::colourChanged()
  35406. {
  35407. repaint();
  35408. }
  35409. void Label::setMinimumHorizontalScale (const float newScale)
  35410. {
  35411. if (minimumHorizontalScale != newScale)
  35412. {
  35413. minimumHorizontalScale = newScale;
  35414. repaint();
  35415. }
  35416. }
  35417. // We'll use a custom focus traverser here to make sure focus goes from the
  35418. // text editor to another component rather than back to the label itself.
  35419. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  35420. {
  35421. public:
  35422. LabelKeyboardFocusTraverser() {}
  35423. Component* getNextComponent (Component* current)
  35424. {
  35425. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  35426. ? current->getParentComponent() : current);
  35427. }
  35428. Component* getPreviousComponent (Component* current)
  35429. {
  35430. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  35431. ? current->getParentComponent() : current);
  35432. }
  35433. };
  35434. KeyboardFocusTraverser* Label::createFocusTraverser()
  35435. {
  35436. return new LabelKeyboardFocusTraverser();
  35437. }
  35438. void Label::addListener (LabelListener* const listener) throw()
  35439. {
  35440. jassert (listener != 0);
  35441. if (listener != 0)
  35442. listeners.add (listener);
  35443. }
  35444. void Label::removeListener (LabelListener* const listener) throw()
  35445. {
  35446. listeners.removeValue (listener);
  35447. }
  35448. void Label::callChangeListeners()
  35449. {
  35450. for (int i = listeners.size(); --i >= 0;)
  35451. {
  35452. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  35453. i = jmin (i, listeners.size());
  35454. }
  35455. }
  35456. void Label::textEditorTextChanged (TextEditor& ed)
  35457. {
  35458. if (editor != 0)
  35459. {
  35460. jassert (&ed == editor);
  35461. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  35462. {
  35463. if (lossOfFocusDiscardsChanges)
  35464. textEditorEscapeKeyPressed (ed);
  35465. else
  35466. textEditorReturnKeyPressed (ed);
  35467. }
  35468. }
  35469. }
  35470. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  35471. {
  35472. if (editor != 0)
  35473. {
  35474. jassert (&ed == editor);
  35475. (void) ed;
  35476. const bool changed = updateFromTextEditorContents();
  35477. hideEditor (true);
  35478. if (changed)
  35479. {
  35480. textWasEdited();
  35481. if (isValidComponent())
  35482. callChangeListeners();
  35483. }
  35484. }
  35485. }
  35486. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  35487. {
  35488. if (editor != 0)
  35489. {
  35490. jassert (&ed == editor);
  35491. (void) ed;
  35492. editor->setText (text, false);
  35493. hideEditor (true);
  35494. }
  35495. }
  35496. void Label::textEditorFocusLost (TextEditor& ed)
  35497. {
  35498. textEditorTextChanged (ed);
  35499. }
  35500. END_JUCE_NAMESPACE
  35501. /********* End of inlined file: juce_Label.cpp *********/
  35502. /********* Start of inlined file: juce_ListBox.cpp *********/
  35503. BEGIN_JUCE_NAMESPACE
  35504. class ListBoxRowComponent : public Component
  35505. {
  35506. public:
  35507. ListBoxRowComponent (ListBox& owner_)
  35508. : owner (owner_),
  35509. row (-1),
  35510. selected (false),
  35511. isDragging (false)
  35512. {
  35513. }
  35514. ~ListBoxRowComponent()
  35515. {
  35516. deleteAllChildren();
  35517. }
  35518. void paint (Graphics& g)
  35519. {
  35520. if (owner.getModel() != 0)
  35521. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  35522. }
  35523. void update (const int row_, const bool selected_)
  35524. {
  35525. if (row != row_ || selected != selected_)
  35526. {
  35527. repaint();
  35528. row = row_;
  35529. selected = selected_;
  35530. }
  35531. if (owner.getModel() != 0)
  35532. {
  35533. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  35534. if (customComp != 0)
  35535. {
  35536. addAndMakeVisible (customComp);
  35537. customComp->setBounds (0, 0, getWidth(), getHeight());
  35538. for (int i = getNumChildComponents(); --i >= 0;)
  35539. if (getChildComponent (i) != customComp)
  35540. delete getChildComponent (i);
  35541. }
  35542. else
  35543. {
  35544. deleteAllChildren();
  35545. }
  35546. }
  35547. }
  35548. void mouseDown (const MouseEvent& e)
  35549. {
  35550. isDragging = false;
  35551. selectRowOnMouseUp = false;
  35552. if (isEnabled())
  35553. {
  35554. if (! selected)
  35555. {
  35556. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35557. if (owner.getModel() != 0)
  35558. owner.getModel()->listBoxItemClicked (row, e);
  35559. }
  35560. else
  35561. {
  35562. selectRowOnMouseUp = true;
  35563. }
  35564. }
  35565. }
  35566. void mouseUp (const MouseEvent& e)
  35567. {
  35568. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  35569. {
  35570. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35571. if (owner.getModel() != 0)
  35572. owner.getModel()->listBoxItemClicked (row, e);
  35573. }
  35574. }
  35575. void mouseDoubleClick (const MouseEvent& e)
  35576. {
  35577. if (owner.getModel() != 0 && isEnabled())
  35578. owner.getModel()->listBoxItemDoubleClicked (row, e);
  35579. }
  35580. void mouseDrag (const MouseEvent& e)
  35581. {
  35582. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  35583. {
  35584. const SparseSet <int> selectedRows (owner.getSelectedRows());
  35585. if (selectedRows.size() > 0)
  35586. {
  35587. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  35588. if (dragDescription.isNotEmpty())
  35589. {
  35590. isDragging = true;
  35591. DragAndDropContainer* const dragContainer
  35592. = DragAndDropContainer::findParentDragContainerFor (this);
  35593. if (dragContainer != 0)
  35594. {
  35595. Image* dragImage = owner.createSnapshotOfSelectedRows();
  35596. dragImage->multiplyAllAlphas (0.6f);
  35597. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  35598. }
  35599. else
  35600. {
  35601. // to be able to do a drag-and-drop operation, the listbox needs to
  35602. // be inside a component which is also a DragAndDropContainer.
  35603. jassertfalse
  35604. }
  35605. }
  35606. }
  35607. }
  35608. }
  35609. void resized()
  35610. {
  35611. if (getNumChildComponents() > 0)
  35612. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  35613. }
  35614. juce_UseDebuggingNewOperator
  35615. bool neededFlag;
  35616. private:
  35617. ListBox& owner;
  35618. int row;
  35619. bool selected, isDragging, selectRowOnMouseUp;
  35620. ListBoxRowComponent (const ListBoxRowComponent&);
  35621. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  35622. };
  35623. class ListViewport : public Viewport
  35624. {
  35625. public:
  35626. int firstIndex, firstWholeIndex, lastWholeIndex;
  35627. bool hasUpdated;
  35628. ListViewport (ListBox& owner_)
  35629. : owner (owner_)
  35630. {
  35631. setWantsKeyboardFocus (false);
  35632. setViewedComponent (new Component());
  35633. getViewedComponent()->addMouseListener (this, false);
  35634. getViewedComponent()->setWantsKeyboardFocus (false);
  35635. }
  35636. ~ListViewport()
  35637. {
  35638. getViewedComponent()->removeMouseListener (this);
  35639. getViewedComponent()->deleteAllChildren();
  35640. }
  35641. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  35642. {
  35643. return (ListBoxRowComponent*) getViewedComponent()
  35644. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  35645. }
  35646. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  35647. {
  35648. const int index = getIndexOfChildComponent (rowComponent);
  35649. const int num = getViewedComponent()->getNumChildComponents();
  35650. for (int i = num; --i >= 0;)
  35651. if (((firstIndex + i) % jmax (1, num)) == index)
  35652. return firstIndex + i;
  35653. return -1;
  35654. }
  35655. Component* getComponentForRowIfOnscreen (const int row) const throw()
  35656. {
  35657. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  35658. ? getComponentForRow (row) : 0;
  35659. }
  35660. void visibleAreaChanged (int, int, int, int)
  35661. {
  35662. updateVisibleArea (true);
  35663. if (owner.getModel() != 0)
  35664. owner.getModel()->listWasScrolled();
  35665. }
  35666. void updateVisibleArea (const bool makeSureItUpdatesContent)
  35667. {
  35668. hasUpdated = false;
  35669. const int newX = getViewedComponent()->getX();
  35670. int newY = getViewedComponent()->getY();
  35671. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  35672. const int newH = owner.totalItems * owner.getRowHeight();
  35673. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  35674. newY = getMaximumVisibleHeight() - newH;
  35675. getViewedComponent()->setBounds (newX, newY, newW, newH);
  35676. if (makeSureItUpdatesContent && ! hasUpdated)
  35677. updateContents();
  35678. }
  35679. void updateContents()
  35680. {
  35681. hasUpdated = true;
  35682. const int rowHeight = owner.getRowHeight();
  35683. if (rowHeight > 0)
  35684. {
  35685. const int y = getViewPositionY();
  35686. const int w = getViewedComponent()->getWidth();
  35687. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  35688. while (numNeeded > getViewedComponent()->getNumChildComponents())
  35689. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  35690. jassert (numNeeded >= 0);
  35691. while (numNeeded < getViewedComponent()->getNumChildComponents())
  35692. {
  35693. Component* const rowToRemove
  35694. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  35695. delete rowToRemove;
  35696. }
  35697. firstIndex = y / rowHeight;
  35698. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  35699. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  35700. for (int i = 0; i < numNeeded; ++i)
  35701. {
  35702. const int row = i + firstIndex;
  35703. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  35704. if (rowComp != 0)
  35705. {
  35706. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  35707. rowComp->update (row, owner.isRowSelected (row));
  35708. }
  35709. }
  35710. }
  35711. if (owner.headerComponent != 0)
  35712. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  35713. owner.outlineThickness,
  35714. jmax (owner.getWidth() - owner.outlineThickness * 2,
  35715. getViewedComponent()->getWidth()),
  35716. owner.headerComponent->getHeight());
  35717. }
  35718. void paint (Graphics& g)
  35719. {
  35720. if (isOpaque())
  35721. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  35722. }
  35723. bool keyPressed (const KeyPress& key)
  35724. {
  35725. if (key.isKeyCode (KeyPress::upKey)
  35726. || key.isKeyCode (KeyPress::downKey)
  35727. || key.isKeyCode (KeyPress::pageUpKey)
  35728. || key.isKeyCode (KeyPress::pageDownKey)
  35729. || key.isKeyCode (KeyPress::homeKey)
  35730. || key.isKeyCode (KeyPress::endKey))
  35731. {
  35732. // we want to avoid these keypresses going to the viewport, and instead allow
  35733. // them to pass up to our listbox..
  35734. return false;
  35735. }
  35736. return Viewport::keyPressed (key);
  35737. }
  35738. juce_UseDebuggingNewOperator
  35739. private:
  35740. ListBox& owner;
  35741. ListViewport (const ListViewport&);
  35742. const ListViewport& operator= (const ListViewport&);
  35743. };
  35744. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  35745. : Component (name),
  35746. model (model_),
  35747. headerComponent (0),
  35748. totalItems (0),
  35749. rowHeight (22),
  35750. minimumRowWidth (0),
  35751. outlineThickness (0),
  35752. lastRowSelected (-1),
  35753. mouseMoveSelects (false),
  35754. multipleSelection (false),
  35755. hasDoneInitialUpdate (false)
  35756. {
  35757. addAndMakeVisible (viewport = new ListViewport (*this));
  35758. setWantsKeyboardFocus (true);
  35759. }
  35760. ListBox::~ListBox()
  35761. {
  35762. deleteAllChildren();
  35763. }
  35764. void ListBox::setModel (ListBoxModel* const newModel)
  35765. {
  35766. if (model != newModel)
  35767. {
  35768. model = newModel;
  35769. updateContent();
  35770. }
  35771. }
  35772. void ListBox::setMultipleSelectionEnabled (bool b)
  35773. {
  35774. multipleSelection = b;
  35775. }
  35776. void ListBox::setMouseMoveSelectsRows (bool b)
  35777. {
  35778. mouseMoveSelects = b;
  35779. if (b)
  35780. addMouseListener (this, true);
  35781. }
  35782. void ListBox::paint (Graphics& g)
  35783. {
  35784. if (! hasDoneInitialUpdate)
  35785. updateContent();
  35786. g.fillAll (findColour (backgroundColourId));
  35787. }
  35788. void ListBox::paintOverChildren (Graphics& g)
  35789. {
  35790. if (outlineThickness > 0)
  35791. {
  35792. g.setColour (findColour (outlineColourId));
  35793. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  35794. }
  35795. }
  35796. void ListBox::resized()
  35797. {
  35798. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  35799. outlineThickness,
  35800. outlineThickness,
  35801. outlineThickness));
  35802. viewport->setSingleStepSizes (20, getRowHeight());
  35803. viewport->updateVisibleArea (false);
  35804. }
  35805. void ListBox::visibilityChanged()
  35806. {
  35807. viewport->updateVisibleArea (true);
  35808. }
  35809. Viewport* ListBox::getViewport() const throw()
  35810. {
  35811. return viewport;
  35812. }
  35813. void ListBox::updateContent()
  35814. {
  35815. hasDoneInitialUpdate = true;
  35816. totalItems = (model != 0) ? model->getNumRows() : 0;
  35817. bool selectionChanged = false;
  35818. if (selected [selected.size() - 1] >= totalItems)
  35819. {
  35820. selected.removeRange (totalItems, INT_MAX - totalItems);
  35821. lastRowSelected = getSelectedRow (0);
  35822. selectionChanged = true;
  35823. }
  35824. viewport->updateVisibleArea (isVisible());
  35825. viewport->resized();
  35826. if (selectionChanged && model != 0)
  35827. model->selectedRowsChanged (lastRowSelected);
  35828. }
  35829. void ListBox::selectRow (const int row,
  35830. bool dontScroll,
  35831. bool deselectOthersFirst)
  35832. {
  35833. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  35834. }
  35835. void ListBox::selectRowInternal (const int row,
  35836. bool dontScroll,
  35837. bool deselectOthersFirst,
  35838. bool isMouseClick)
  35839. {
  35840. if (! multipleSelection)
  35841. deselectOthersFirst = true;
  35842. if ((! isRowSelected (row))
  35843. || (deselectOthersFirst && getNumSelectedRows() > 1))
  35844. {
  35845. if (((unsigned int) row) < (unsigned int) totalItems)
  35846. {
  35847. if (deselectOthersFirst)
  35848. selected.clear();
  35849. selected.addRange (row, 1);
  35850. if (getHeight() == 0 || getWidth() == 0)
  35851. dontScroll = true;
  35852. viewport->hasUpdated = false;
  35853. if (row < viewport->firstWholeIndex && ! dontScroll)
  35854. {
  35855. viewport->setViewPosition (viewport->getViewPositionX(),
  35856. row * getRowHeight());
  35857. }
  35858. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  35859. {
  35860. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  35861. if (row >= lastRowSelected + rowsOnScreen
  35862. && rowsOnScreen < totalItems - 1
  35863. && ! isMouseClick)
  35864. {
  35865. viewport->setViewPosition (viewport->getViewPositionX(),
  35866. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  35867. * getRowHeight());
  35868. }
  35869. else
  35870. {
  35871. viewport->setViewPosition (viewport->getViewPositionX(),
  35872. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  35873. }
  35874. }
  35875. if (! viewport->hasUpdated)
  35876. viewport->updateContents();
  35877. lastRowSelected = row;
  35878. model->selectedRowsChanged (row);
  35879. }
  35880. else
  35881. {
  35882. if (deselectOthersFirst)
  35883. deselectAllRows();
  35884. }
  35885. }
  35886. }
  35887. void ListBox::deselectRow (const int row)
  35888. {
  35889. if (selected.contains (row))
  35890. {
  35891. selected.removeRange (row, 1);
  35892. if (row == lastRowSelected)
  35893. lastRowSelected = getSelectedRow (0);
  35894. viewport->updateContents();
  35895. model->selectedRowsChanged (lastRowSelected);
  35896. }
  35897. }
  35898. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  35899. const bool sendNotificationEventToModel)
  35900. {
  35901. selected = setOfRowsToBeSelected;
  35902. selected.removeRange (totalItems, INT_MAX - totalItems);
  35903. if (! isRowSelected (lastRowSelected))
  35904. lastRowSelected = getSelectedRow (0);
  35905. viewport->updateContents();
  35906. if ((model != 0) && sendNotificationEventToModel)
  35907. model->selectedRowsChanged (lastRowSelected);
  35908. }
  35909. const SparseSet<int> ListBox::getSelectedRows() const
  35910. {
  35911. return selected;
  35912. }
  35913. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  35914. {
  35915. if (multipleSelection && (firstRow != lastRow))
  35916. {
  35917. const int numRows = totalItems - 1;
  35918. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  35919. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  35920. selected.addRange (jmin (firstRow, lastRow),
  35921. abs (firstRow - lastRow) + 1);
  35922. selected.removeRange (lastRow, 1);
  35923. }
  35924. selectRowInternal (lastRow, false, false, true);
  35925. }
  35926. void ListBox::flipRowSelection (const int row)
  35927. {
  35928. if (isRowSelected (row))
  35929. deselectRow (row);
  35930. else
  35931. selectRowInternal (row, false, false, true);
  35932. }
  35933. void ListBox::deselectAllRows()
  35934. {
  35935. if (! selected.isEmpty())
  35936. {
  35937. selected.clear();
  35938. lastRowSelected = -1;
  35939. viewport->updateContents();
  35940. if (model != 0)
  35941. model->selectedRowsChanged (lastRowSelected);
  35942. }
  35943. }
  35944. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  35945. const ModifierKeys& mods)
  35946. {
  35947. if (multipleSelection && mods.isCommandDown())
  35948. {
  35949. flipRowSelection (row);
  35950. }
  35951. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  35952. {
  35953. selectRangeOfRows (lastRowSelected, row);
  35954. }
  35955. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  35956. {
  35957. selectRowInternal (row, false, true, true);
  35958. }
  35959. }
  35960. int ListBox::getNumSelectedRows() const
  35961. {
  35962. return selected.size();
  35963. }
  35964. int ListBox::getSelectedRow (const int index) const
  35965. {
  35966. return (((unsigned int) index) < (unsigned int) selected.size())
  35967. ? selected [index] : -1;
  35968. }
  35969. bool ListBox::isRowSelected (const int row) const
  35970. {
  35971. return selected.contains (row);
  35972. }
  35973. int ListBox::getLastRowSelected() const
  35974. {
  35975. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  35976. }
  35977. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  35978. {
  35979. if (((unsigned int) x) < (unsigned int) getWidth())
  35980. {
  35981. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  35982. if (((unsigned int) row) < (unsigned int) totalItems)
  35983. return row;
  35984. }
  35985. return -1;
  35986. }
  35987. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  35988. {
  35989. if (((unsigned int) x) < (unsigned int) getWidth())
  35990. {
  35991. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  35992. return jlimit (0, totalItems, row);
  35993. }
  35994. return -1;
  35995. }
  35996. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  35997. {
  35998. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  35999. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  36000. }
  36001. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  36002. {
  36003. return viewport->getRowNumberOfComponent (rowComponent);
  36004. }
  36005. const Rectangle ListBox::getRowPosition (const int rowNumber,
  36006. const bool relativeToComponentTopLeft) const throw()
  36007. {
  36008. const int rowHeight = getRowHeight();
  36009. int y = viewport->getY() + rowHeight * rowNumber;
  36010. if (relativeToComponentTopLeft)
  36011. y -= viewport->getViewPositionY();
  36012. return Rectangle (viewport->getX(), y,
  36013. viewport->getViewedComponent()->getWidth(), rowHeight);
  36014. }
  36015. void ListBox::setVerticalPosition (const double proportion)
  36016. {
  36017. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36018. viewport->setViewPosition (viewport->getViewPositionX(),
  36019. jmax (0, roundDoubleToInt (proportion * offscreen)));
  36020. }
  36021. double ListBox::getVerticalPosition() const
  36022. {
  36023. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36024. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  36025. : 0;
  36026. }
  36027. int ListBox::getVisibleRowWidth() const throw()
  36028. {
  36029. return viewport->getViewWidth();
  36030. }
  36031. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  36032. {
  36033. if (row < viewport->firstWholeIndex)
  36034. {
  36035. viewport->setViewPosition (viewport->getViewPositionX(),
  36036. row * getRowHeight());
  36037. }
  36038. else if (row >= viewport->lastWholeIndex)
  36039. {
  36040. viewport->setViewPosition (viewport->getViewPositionX(),
  36041. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  36042. }
  36043. }
  36044. bool ListBox::keyPressed (const KeyPress& key)
  36045. {
  36046. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  36047. const bool multiple = multipleSelection
  36048. && (lastRowSelected >= 0)
  36049. && (key.getModifiers().isShiftDown()
  36050. || key.getModifiers().isCtrlDown()
  36051. || key.getModifiers().isCommandDown());
  36052. if (key.isKeyCode (KeyPress::upKey))
  36053. {
  36054. if (multiple)
  36055. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  36056. else
  36057. selectRow (jmax (0, lastRowSelected - 1));
  36058. }
  36059. else if (key.isKeyCode (KeyPress::returnKey)
  36060. && isRowSelected (lastRowSelected))
  36061. {
  36062. if (model != 0)
  36063. model->returnKeyPressed (lastRowSelected);
  36064. }
  36065. else if (key.isKeyCode (KeyPress::pageUpKey))
  36066. {
  36067. if (multiple)
  36068. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  36069. else
  36070. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  36071. }
  36072. else if (key.isKeyCode (KeyPress::pageDownKey))
  36073. {
  36074. if (multiple)
  36075. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  36076. else
  36077. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  36078. }
  36079. else if (key.isKeyCode (KeyPress::homeKey))
  36080. {
  36081. if (multiple && key.getModifiers().isShiftDown())
  36082. selectRangeOfRows (lastRowSelected, 0);
  36083. else
  36084. selectRow (0);
  36085. }
  36086. else if (key.isKeyCode (KeyPress::endKey))
  36087. {
  36088. if (multiple && key.getModifiers().isShiftDown())
  36089. selectRangeOfRows (lastRowSelected, totalItems - 1);
  36090. else
  36091. selectRow (totalItems - 1);
  36092. }
  36093. else if (key.isKeyCode (KeyPress::downKey))
  36094. {
  36095. if (multiple)
  36096. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  36097. else
  36098. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  36099. }
  36100. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  36101. && isRowSelected (lastRowSelected))
  36102. {
  36103. if (model != 0)
  36104. model->deleteKeyPressed (lastRowSelected);
  36105. }
  36106. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  36107. {
  36108. selectRangeOfRows (0, INT_MAX);
  36109. }
  36110. else
  36111. {
  36112. return false;
  36113. }
  36114. return true;
  36115. }
  36116. bool ListBox::keyStateChanged (const bool isKeyDown)
  36117. {
  36118. return isKeyDown
  36119. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  36120. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  36121. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  36122. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  36123. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  36124. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  36125. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  36126. }
  36127. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36128. {
  36129. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  36130. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  36131. }
  36132. void ListBox::mouseMove (const MouseEvent& e)
  36133. {
  36134. if (mouseMoveSelects)
  36135. {
  36136. const MouseEvent e2 (e.getEventRelativeTo (this));
  36137. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  36138. lastMouseX = e2.x;
  36139. lastMouseY = e2.y;
  36140. }
  36141. }
  36142. void ListBox::mouseExit (const MouseEvent& e)
  36143. {
  36144. mouseMove (e);
  36145. }
  36146. void ListBox::mouseUp (const MouseEvent& e)
  36147. {
  36148. if (e.mouseWasClicked() && model != 0)
  36149. model->backgroundClicked();
  36150. }
  36151. void ListBox::setRowHeight (const int newHeight)
  36152. {
  36153. rowHeight = jmax (1, newHeight);
  36154. viewport->setSingleStepSizes (20, rowHeight);
  36155. updateContent();
  36156. }
  36157. int ListBox::getNumRowsOnScreen() const throw()
  36158. {
  36159. return viewport->getMaximumVisibleHeight() / rowHeight;
  36160. }
  36161. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  36162. {
  36163. minimumRowWidth = newMinimumWidth;
  36164. updateContent();
  36165. }
  36166. int ListBox::getVisibleContentWidth() const throw()
  36167. {
  36168. return viewport->getMaximumVisibleWidth();
  36169. }
  36170. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  36171. {
  36172. return viewport->getVerticalScrollBar();
  36173. }
  36174. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  36175. {
  36176. return viewport->getHorizontalScrollBar();
  36177. }
  36178. void ListBox::colourChanged()
  36179. {
  36180. setOpaque (findColour (backgroundColourId).isOpaque());
  36181. viewport->setOpaque (isOpaque());
  36182. repaint();
  36183. }
  36184. void ListBox::setOutlineThickness (const int outlineThickness_)
  36185. {
  36186. outlineThickness = outlineThickness_;
  36187. resized();
  36188. }
  36189. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  36190. {
  36191. if (headerComponent != newHeaderComponent)
  36192. {
  36193. if (headerComponent != 0)
  36194. delete headerComponent;
  36195. headerComponent = newHeaderComponent;
  36196. addAndMakeVisible (newHeaderComponent);
  36197. ListBox::resized();
  36198. }
  36199. }
  36200. void ListBox::repaintRow (const int rowNumber) throw()
  36201. {
  36202. const Rectangle r (getRowPosition (rowNumber, true));
  36203. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  36204. }
  36205. Image* ListBox::createSnapshotOfSelectedRows()
  36206. {
  36207. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  36208. Graphics g (*snapshot);
  36209. const int firstRow = getRowContainingPosition (0, 0);
  36210. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  36211. {
  36212. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  36213. if (rowComp != 0 && isRowSelected (firstRow + i))
  36214. {
  36215. g.saveState();
  36216. int x = 0, y = 0;
  36217. rowComp->relativePositionToOtherComponent (this, x, y);
  36218. g.setOrigin (x, y);
  36219. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  36220. rowComp->paintEntireComponent (g);
  36221. g.restoreState();
  36222. }
  36223. }
  36224. return snapshot;
  36225. }
  36226. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  36227. {
  36228. (void) existingComponentToUpdate;
  36229. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36230. return 0;
  36231. }
  36232. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  36233. {
  36234. }
  36235. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  36236. {
  36237. }
  36238. void ListBoxModel::backgroundClicked()
  36239. {
  36240. }
  36241. void ListBoxModel::selectedRowsChanged (int)
  36242. {
  36243. }
  36244. void ListBoxModel::deleteKeyPressed (int)
  36245. {
  36246. }
  36247. void ListBoxModel::returnKeyPressed (int)
  36248. {
  36249. }
  36250. void ListBoxModel::listWasScrolled()
  36251. {
  36252. }
  36253. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36254. {
  36255. return String::empty;
  36256. }
  36257. END_JUCE_NAMESPACE
  36258. /********* End of inlined file: juce_ListBox.cpp *********/
  36259. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  36260. BEGIN_JUCE_NAMESPACE
  36261. ProgressBar::ProgressBar (double& progress_)
  36262. : progress (progress_),
  36263. displayPercentage (true),
  36264. lastCallbackTime (0)
  36265. {
  36266. currentValue = jlimit (0.0, 1.0, progress);
  36267. }
  36268. ProgressBar::~ProgressBar()
  36269. {
  36270. }
  36271. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  36272. {
  36273. displayPercentage = shouldDisplayPercentage;
  36274. repaint();
  36275. }
  36276. void ProgressBar::setTextToDisplay (const String& text)
  36277. {
  36278. displayPercentage = false;
  36279. displayedMessage = text;
  36280. }
  36281. void ProgressBar::lookAndFeelChanged()
  36282. {
  36283. setOpaque (findColour (backgroundColourId).isOpaque());
  36284. }
  36285. void ProgressBar::colourChanged()
  36286. {
  36287. lookAndFeelChanged();
  36288. }
  36289. void ProgressBar::paint (Graphics& g)
  36290. {
  36291. String text;
  36292. if (displayPercentage)
  36293. {
  36294. if (currentValue >= 0 && currentValue <= 1.0)
  36295. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  36296. }
  36297. else
  36298. {
  36299. text = displayedMessage;
  36300. }
  36301. getLookAndFeel().drawProgressBar (g, *this,
  36302. getWidth(), getHeight(),
  36303. currentValue, text);
  36304. }
  36305. void ProgressBar::visibilityChanged()
  36306. {
  36307. if (isVisible())
  36308. startTimer (30);
  36309. else
  36310. stopTimer();
  36311. }
  36312. void ProgressBar::timerCallback()
  36313. {
  36314. double newProgress = progress;
  36315. if (currentValue != newProgress
  36316. || newProgress < 0 || newProgress >= 1.0
  36317. || currentMessage != displayedMessage)
  36318. {
  36319. if (currentValue < newProgress
  36320. && newProgress >= 0 && newProgress < 1.0
  36321. && currentValue >= 0 && currentValue < 1.0)
  36322. {
  36323. const uint32 now = Time::getMillisecondCounter();
  36324. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  36325. lastCallbackTime = now;
  36326. newProgress = jmin (currentValue + 0.00018 * timeSinceLastCallback,
  36327. newProgress);
  36328. }
  36329. currentValue = newProgress;
  36330. currentMessage = displayedMessage;
  36331. repaint();
  36332. }
  36333. }
  36334. END_JUCE_NAMESPACE
  36335. /********* End of inlined file: juce_ProgressBar.cpp *********/
  36336. /********* Start of inlined file: juce_Slider.cpp *********/
  36337. BEGIN_JUCE_NAMESPACE
  36338. class SliderPopupDisplayComponent : public BubbleComponent
  36339. {
  36340. public:
  36341. SliderPopupDisplayComponent (Slider* const owner_)
  36342. : owner (owner_),
  36343. font (15.0f, Font::bold)
  36344. {
  36345. setAlwaysOnTop (true);
  36346. }
  36347. ~SliderPopupDisplayComponent()
  36348. {
  36349. }
  36350. void paintContent (Graphics& g, int w, int h)
  36351. {
  36352. g.setFont (font);
  36353. g.setColour (Colours::black);
  36354. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  36355. }
  36356. void getContentSize (int& w, int& h)
  36357. {
  36358. w = font.getStringWidth (text) + 18;
  36359. h = (int) (font.getHeight() * 1.6f);
  36360. }
  36361. void updatePosition (const String& newText)
  36362. {
  36363. if (text != newText)
  36364. {
  36365. text = newText;
  36366. repaint();
  36367. }
  36368. BubbleComponent::setPosition (owner);
  36369. }
  36370. juce_UseDebuggingNewOperator
  36371. private:
  36372. Slider* owner;
  36373. Font font;
  36374. String text;
  36375. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  36376. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  36377. };
  36378. Slider::Slider (const String& name)
  36379. : Component (name),
  36380. listeners (2),
  36381. currentValue (0.0),
  36382. valueMin (0.0),
  36383. valueMax (0.0),
  36384. minimum (0),
  36385. maximum (10),
  36386. interval (0),
  36387. skewFactor (1.0),
  36388. velocityModeSensitivity (1.0),
  36389. velocityModeOffset (0.0),
  36390. velocityModeThreshold (1),
  36391. rotaryStart (float_Pi * 1.2f),
  36392. rotaryEnd (float_Pi * 2.8f),
  36393. numDecimalPlaces (7),
  36394. sliderRegionStart (0),
  36395. sliderRegionSize (1),
  36396. sliderBeingDragged (-1),
  36397. pixelsForFullDragExtent (250),
  36398. style (LinearHorizontal),
  36399. textBoxPos (TextBoxLeft),
  36400. textBoxWidth (80),
  36401. textBoxHeight (20),
  36402. incDecButtonMode (incDecButtonsNotDraggable),
  36403. editableText (true),
  36404. doubleClickToValue (false),
  36405. isVelocityBased (false),
  36406. userKeyOverridesVelocity (true),
  36407. rotaryStop (true),
  36408. incDecButtonsSideBySide (false),
  36409. sendChangeOnlyOnRelease (false),
  36410. popupDisplayEnabled (false),
  36411. menuEnabled (false),
  36412. menuShown (false),
  36413. scrollWheelEnabled (true),
  36414. snapsToMousePos (true),
  36415. valueBox (0),
  36416. incButton (0),
  36417. decButton (0),
  36418. popupDisplay (0),
  36419. parentForPopupDisplay (0)
  36420. {
  36421. setWantsKeyboardFocus (false);
  36422. setRepaintsOnMouseActivity (true);
  36423. lookAndFeelChanged();
  36424. updateText();
  36425. }
  36426. Slider::~Slider()
  36427. {
  36428. deleteAndZero (popupDisplay);
  36429. deleteAllChildren();
  36430. }
  36431. void Slider::handleAsyncUpdate()
  36432. {
  36433. cancelPendingUpdate();
  36434. for (int i = listeners.size(); --i >= 0;)
  36435. {
  36436. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  36437. i = jmin (i, listeners.size());
  36438. }
  36439. }
  36440. void Slider::sendDragStart()
  36441. {
  36442. startedDragging();
  36443. for (int i = listeners.size(); --i >= 0;)
  36444. {
  36445. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  36446. i = jmin (i, listeners.size());
  36447. }
  36448. }
  36449. void Slider::sendDragEnd()
  36450. {
  36451. stoppedDragging();
  36452. sliderBeingDragged = -1;
  36453. for (int i = listeners.size(); --i >= 0;)
  36454. {
  36455. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  36456. i = jmin (i, listeners.size());
  36457. }
  36458. }
  36459. void Slider::addListener (SliderListener* const listener) throw()
  36460. {
  36461. jassert (listener != 0);
  36462. if (listener != 0)
  36463. listeners.add (listener);
  36464. }
  36465. void Slider::removeListener (SliderListener* const listener) throw()
  36466. {
  36467. listeners.removeValue (listener);
  36468. }
  36469. void Slider::setSliderStyle (const SliderStyle newStyle)
  36470. {
  36471. if (style != newStyle)
  36472. {
  36473. style = newStyle;
  36474. repaint();
  36475. lookAndFeelChanged();
  36476. }
  36477. }
  36478. void Slider::setRotaryParameters (const float startAngleRadians,
  36479. const float endAngleRadians,
  36480. const bool stopAtEnd)
  36481. {
  36482. // make sure the values are sensible..
  36483. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  36484. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  36485. jassert (rotaryStart < rotaryEnd);
  36486. rotaryStart = startAngleRadians;
  36487. rotaryEnd = endAngleRadians;
  36488. rotaryStop = stopAtEnd;
  36489. }
  36490. void Slider::setVelocityBasedMode (const bool velBased) throw()
  36491. {
  36492. isVelocityBased = velBased;
  36493. }
  36494. void Slider::setVelocityModeParameters (const double sensitivity,
  36495. const int threshold,
  36496. const double offset,
  36497. const bool userCanPressKeyToSwapMode) throw()
  36498. {
  36499. jassert (threshold >= 0);
  36500. jassert (sensitivity > 0);
  36501. jassert (offset >= 0);
  36502. velocityModeSensitivity = sensitivity;
  36503. velocityModeOffset = offset;
  36504. velocityModeThreshold = threshold;
  36505. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  36506. }
  36507. void Slider::setSkewFactor (const double factor) throw()
  36508. {
  36509. skewFactor = factor;
  36510. }
  36511. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  36512. {
  36513. if (maximum > minimum)
  36514. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  36515. / (maximum - minimum));
  36516. }
  36517. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  36518. {
  36519. jassert (distanceForFullScaleDrag > 0);
  36520. pixelsForFullDragExtent = distanceForFullScaleDrag;
  36521. }
  36522. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  36523. {
  36524. if (incDecButtonMode != mode)
  36525. {
  36526. incDecButtonMode = mode;
  36527. lookAndFeelChanged();
  36528. }
  36529. }
  36530. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  36531. const bool isReadOnly,
  36532. const int textEntryBoxWidth,
  36533. const int textEntryBoxHeight)
  36534. {
  36535. textBoxPos = newPosition;
  36536. editableText = ! isReadOnly;
  36537. textBoxWidth = textEntryBoxWidth;
  36538. textBoxHeight = textEntryBoxHeight;
  36539. repaint();
  36540. lookAndFeelChanged();
  36541. }
  36542. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  36543. {
  36544. editableText = shouldBeEditable;
  36545. if (valueBox != 0)
  36546. valueBox->setEditable (shouldBeEditable && isEnabled());
  36547. }
  36548. void Slider::showTextBox()
  36549. {
  36550. jassert (editableText); // this should probably be avoided in read-only sliders.
  36551. if (valueBox != 0)
  36552. valueBox->showEditor();
  36553. }
  36554. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  36555. {
  36556. if (valueBox != 0)
  36557. {
  36558. valueBox->hideEditor (discardCurrentEditorContents);
  36559. if (discardCurrentEditorContents)
  36560. updateText();
  36561. }
  36562. }
  36563. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  36564. {
  36565. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  36566. }
  36567. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  36568. {
  36569. snapsToMousePos = shouldSnapToMouse;
  36570. }
  36571. void Slider::setPopupDisplayEnabled (const bool enabled,
  36572. Component* const parentComponentToUse) throw()
  36573. {
  36574. popupDisplayEnabled = enabled;
  36575. parentForPopupDisplay = parentComponentToUse;
  36576. }
  36577. void Slider::colourChanged()
  36578. {
  36579. lookAndFeelChanged();
  36580. }
  36581. void Slider::lookAndFeelChanged()
  36582. {
  36583. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  36584. : getTextFromValue (currentValue));
  36585. deleteAllChildren();
  36586. valueBox = 0;
  36587. LookAndFeel& lf = getLookAndFeel();
  36588. if (textBoxPos != NoTextBox)
  36589. {
  36590. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  36591. valueBox->setWantsKeyboardFocus (false);
  36592. valueBox->setText (previousTextBoxContent, false);
  36593. valueBox->setEditable (editableText && isEnabled());
  36594. valueBox->addListener (this);
  36595. if (style == LinearBar)
  36596. valueBox->addMouseListener (this, false);
  36597. valueBox->setTooltip (getTooltip());
  36598. }
  36599. if (style == IncDecButtons)
  36600. {
  36601. addAndMakeVisible (incButton = lf.createSliderButton (true));
  36602. incButton->addButtonListener (this);
  36603. addAndMakeVisible (decButton = lf.createSliderButton (false));
  36604. decButton->addButtonListener (this);
  36605. if (incDecButtonMode != incDecButtonsNotDraggable)
  36606. {
  36607. incButton->addMouseListener (this, false);
  36608. decButton->addMouseListener (this, false);
  36609. }
  36610. else
  36611. {
  36612. incButton->setRepeatSpeed (300, 100, 20);
  36613. incButton->addMouseListener (decButton, false);
  36614. decButton->setRepeatSpeed (300, 100, 20);
  36615. decButton->addMouseListener (incButton, false);
  36616. }
  36617. incButton->setTooltip (getTooltip());
  36618. decButton->setTooltip (getTooltip());
  36619. }
  36620. setComponentEffect (lf.getSliderEffect());
  36621. resized();
  36622. repaint();
  36623. }
  36624. void Slider::setRange (const double newMin,
  36625. const double newMax,
  36626. const double newInt)
  36627. {
  36628. if (minimum != newMin
  36629. || maximum != newMax
  36630. || interval != newInt)
  36631. {
  36632. minimum = newMin;
  36633. maximum = newMax;
  36634. interval = newInt;
  36635. // figure out the number of DPs needed to display all values at this
  36636. // interval setting.
  36637. numDecimalPlaces = 7;
  36638. if (newInt != 0)
  36639. {
  36640. int v = abs ((int) (newInt * 10000000));
  36641. while ((v % 10) == 0)
  36642. {
  36643. --numDecimalPlaces;
  36644. v /= 10;
  36645. }
  36646. }
  36647. // keep the current values inside the new range..
  36648. if (style != TwoValueHorizontal && style != TwoValueVertical)
  36649. {
  36650. setValue (currentValue, false, false);
  36651. }
  36652. else
  36653. {
  36654. setMinValue (getMinValue(), false, false);
  36655. setMaxValue (getMaxValue(), false, false);
  36656. }
  36657. updateText();
  36658. }
  36659. }
  36660. void Slider::triggerChangeMessage (const bool synchronous)
  36661. {
  36662. if (synchronous)
  36663. handleAsyncUpdate();
  36664. else
  36665. triggerAsyncUpdate();
  36666. valueChanged();
  36667. }
  36668. double Slider::getValue() const throw()
  36669. {
  36670. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  36671. // methods to get the two values.
  36672. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36673. return currentValue;
  36674. }
  36675. void Slider::setValue (double newValue,
  36676. const bool sendUpdateMessage,
  36677. const bool sendMessageSynchronously)
  36678. {
  36679. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  36680. // methods to set the two values.
  36681. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36682. newValue = constrainedValue (newValue);
  36683. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  36684. {
  36685. jassert (valueMin <= valueMax);
  36686. newValue = jlimit (valueMin, valueMax, newValue);
  36687. }
  36688. if (currentValue != newValue)
  36689. {
  36690. if (valueBox != 0)
  36691. valueBox->hideEditor (true);
  36692. currentValue = newValue;
  36693. updateText();
  36694. repaint();
  36695. if (popupDisplay != 0)
  36696. {
  36697. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  36698. popupDisplay->repaint();
  36699. }
  36700. if (sendUpdateMessage)
  36701. triggerChangeMessage (sendMessageSynchronously);
  36702. }
  36703. }
  36704. double Slider::getMinValue() const throw()
  36705. {
  36706. // The minimum value only applies to sliders that are in two- or three-value mode.
  36707. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36708. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36709. return valueMin;
  36710. }
  36711. double Slider::getMaxValue() const throw()
  36712. {
  36713. // The maximum value only applies to sliders that are in two- or three-value mode.
  36714. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36715. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36716. return valueMax;
  36717. }
  36718. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36719. {
  36720. // The minimum value only applies to sliders that are in two- or three-value mode.
  36721. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36722. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36723. newValue = constrainedValue (newValue);
  36724. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36725. {
  36726. if (allowNudgingOfOtherValues && newValue > valueMax)
  36727. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36728. newValue = jmin (valueMax, newValue);
  36729. }
  36730. else
  36731. {
  36732. if (allowNudgingOfOtherValues && newValue > currentValue)
  36733. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36734. newValue = jmin (currentValue, newValue);
  36735. }
  36736. if (valueMin != newValue)
  36737. {
  36738. valueMin = newValue;
  36739. repaint();
  36740. if (popupDisplay != 0)
  36741. {
  36742. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  36743. popupDisplay->repaint();
  36744. }
  36745. if (sendUpdateMessage)
  36746. triggerChangeMessage (sendMessageSynchronously);
  36747. }
  36748. }
  36749. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36750. {
  36751. // The maximum value only applies to sliders that are in two- or three-value mode.
  36752. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36753. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36754. newValue = constrainedValue (newValue);
  36755. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36756. {
  36757. if (allowNudgingOfOtherValues && newValue < valueMin)
  36758. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36759. newValue = jmax (valueMin, newValue);
  36760. }
  36761. else
  36762. {
  36763. if (allowNudgingOfOtherValues && newValue < currentValue)
  36764. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36765. newValue = jmax (currentValue, newValue);
  36766. }
  36767. if (valueMax != newValue)
  36768. {
  36769. valueMax = newValue;
  36770. repaint();
  36771. if (popupDisplay != 0)
  36772. {
  36773. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  36774. popupDisplay->repaint();
  36775. }
  36776. if (sendUpdateMessage)
  36777. triggerChangeMessage (sendMessageSynchronously);
  36778. }
  36779. }
  36780. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  36781. const double valueToSetOnDoubleClick) throw()
  36782. {
  36783. doubleClickToValue = isDoubleClickEnabled;
  36784. doubleClickReturnValue = valueToSetOnDoubleClick;
  36785. }
  36786. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  36787. {
  36788. isEnabled_ = doubleClickToValue;
  36789. return doubleClickReturnValue;
  36790. }
  36791. void Slider::updateText()
  36792. {
  36793. if (valueBox != 0)
  36794. valueBox->setText (getTextFromValue (currentValue), false);
  36795. }
  36796. void Slider::setTextValueSuffix (const String& suffix)
  36797. {
  36798. if (textSuffix != suffix)
  36799. {
  36800. textSuffix = suffix;
  36801. updateText();
  36802. }
  36803. }
  36804. const String Slider::getTextFromValue (double v)
  36805. {
  36806. if (numDecimalPlaces > 0)
  36807. return String (v, numDecimalPlaces) + textSuffix;
  36808. else
  36809. return String (roundDoubleToInt (v)) + textSuffix;
  36810. }
  36811. double Slider::getValueFromText (const String& text)
  36812. {
  36813. String t (text.trimStart());
  36814. if (t.endsWith (textSuffix))
  36815. t = t.substring (0, t.length() - textSuffix.length());
  36816. while (t.startsWithChar (T('+')))
  36817. t = t.substring (1).trimStart();
  36818. return t.initialSectionContainingOnly (T("0123456789.,-"))
  36819. .getDoubleValue();
  36820. }
  36821. double Slider::proportionOfLengthToValue (double proportion)
  36822. {
  36823. if (skewFactor != 1.0 && proportion > 0.0)
  36824. proportion = exp (log (proportion) / skewFactor);
  36825. return minimum + (maximum - minimum) * proportion;
  36826. }
  36827. double Slider::valueToProportionOfLength (double value)
  36828. {
  36829. const double n = (value - minimum) / (maximum - minimum);
  36830. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  36831. }
  36832. double Slider::snapValue (double attemptedValue, const bool)
  36833. {
  36834. return attemptedValue;
  36835. }
  36836. void Slider::startedDragging()
  36837. {
  36838. }
  36839. void Slider::stoppedDragging()
  36840. {
  36841. }
  36842. void Slider::valueChanged()
  36843. {
  36844. }
  36845. void Slider::enablementChanged()
  36846. {
  36847. repaint();
  36848. }
  36849. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  36850. {
  36851. menuEnabled = menuEnabled_;
  36852. }
  36853. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  36854. {
  36855. scrollWheelEnabled = enabled;
  36856. }
  36857. void Slider::labelTextChanged (Label* label)
  36858. {
  36859. const double newValue = snapValue (getValueFromText (label->getText()), false);
  36860. if (getValue() != newValue)
  36861. {
  36862. sendDragStart();
  36863. setValue (newValue, true, true);
  36864. sendDragEnd();
  36865. }
  36866. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  36867. }
  36868. void Slider::buttonClicked (Button* button)
  36869. {
  36870. if (style == IncDecButtons)
  36871. {
  36872. sendDragStart();
  36873. if (button == incButton)
  36874. setValue (snapValue (getValue() + interval, false), true, true);
  36875. else if (button == decButton)
  36876. setValue (snapValue (getValue() - interval, false), true, true);
  36877. sendDragEnd();
  36878. }
  36879. }
  36880. double Slider::constrainedValue (double value) const throw()
  36881. {
  36882. if (interval > 0)
  36883. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  36884. if (value <= minimum || maximum <= minimum)
  36885. value = minimum;
  36886. else if (value >= maximum)
  36887. value = maximum;
  36888. return value;
  36889. }
  36890. float Slider::getLinearSliderPos (const double value)
  36891. {
  36892. double sliderPosProportional;
  36893. if (maximum > minimum)
  36894. {
  36895. if (value < minimum)
  36896. {
  36897. sliderPosProportional = 0.0;
  36898. }
  36899. else if (value > maximum)
  36900. {
  36901. sliderPosProportional = 1.0;
  36902. }
  36903. else
  36904. {
  36905. sliderPosProportional = valueToProportionOfLength (value);
  36906. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  36907. }
  36908. }
  36909. else
  36910. {
  36911. sliderPosProportional = 0.5;
  36912. }
  36913. if (isVertical() || style == IncDecButtons)
  36914. sliderPosProportional = 1.0 - sliderPosProportional;
  36915. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  36916. }
  36917. bool Slider::isHorizontal() const throw()
  36918. {
  36919. return style == LinearHorizontal
  36920. || style == LinearBar
  36921. || style == TwoValueHorizontal
  36922. || style == ThreeValueHorizontal;
  36923. }
  36924. bool Slider::isVertical() const throw()
  36925. {
  36926. return style == LinearVertical
  36927. || style == TwoValueVertical
  36928. || style == ThreeValueVertical;
  36929. }
  36930. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  36931. {
  36932. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  36933. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  36934. }
  36935. float Slider::getPositionOfValue (const double value)
  36936. {
  36937. if (isHorizontal() || isVertical())
  36938. {
  36939. return getLinearSliderPos (value);
  36940. }
  36941. else
  36942. {
  36943. jassertfalse // not a valid call on a slider that doesn't work linearly!
  36944. return 0.0f;
  36945. }
  36946. }
  36947. void Slider::paint (Graphics& g)
  36948. {
  36949. if (style != IncDecButtons)
  36950. {
  36951. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  36952. {
  36953. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  36954. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  36955. getLookAndFeel().drawRotarySlider (g,
  36956. sliderRect.getX(),
  36957. sliderRect.getY(),
  36958. sliderRect.getWidth(),
  36959. sliderRect.getHeight(),
  36960. sliderPos,
  36961. rotaryStart, rotaryEnd,
  36962. *this);
  36963. }
  36964. else
  36965. {
  36966. getLookAndFeel().drawLinearSlider (g,
  36967. sliderRect.getX(),
  36968. sliderRect.getY(),
  36969. sliderRect.getWidth(),
  36970. sliderRect.getHeight(),
  36971. getLinearSliderPos (currentValue),
  36972. getLinearSliderPos (valueMin),
  36973. getLinearSliderPos (valueMax),
  36974. style,
  36975. *this);
  36976. }
  36977. if (style == LinearBar && valueBox == 0)
  36978. {
  36979. g.setColour (findColour (Slider::textBoxOutlineColourId));
  36980. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  36981. }
  36982. }
  36983. }
  36984. void Slider::resized()
  36985. {
  36986. int minXSpace = 0;
  36987. int minYSpace = 0;
  36988. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  36989. minXSpace = 30;
  36990. else
  36991. minYSpace = 15;
  36992. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  36993. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  36994. if (style == LinearBar)
  36995. {
  36996. if (valueBox != 0)
  36997. valueBox->setBounds (0, 0, getWidth(), getHeight());
  36998. }
  36999. else
  37000. {
  37001. if (textBoxPos == NoTextBox)
  37002. {
  37003. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  37004. }
  37005. else if (textBoxPos == TextBoxLeft)
  37006. {
  37007. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  37008. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  37009. }
  37010. else if (textBoxPos == TextBoxRight)
  37011. {
  37012. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  37013. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  37014. }
  37015. else if (textBoxPos == TextBoxAbove)
  37016. {
  37017. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  37018. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  37019. }
  37020. else if (textBoxPos == TextBoxBelow)
  37021. {
  37022. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  37023. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  37024. }
  37025. }
  37026. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  37027. if (style == LinearBar)
  37028. {
  37029. const int barIndent = 1;
  37030. sliderRegionStart = barIndent;
  37031. sliderRegionSize = getWidth() - barIndent * 2;
  37032. sliderRect.setBounds (sliderRegionStart, barIndent,
  37033. sliderRegionSize, getHeight() - barIndent * 2);
  37034. }
  37035. else if (isHorizontal())
  37036. {
  37037. sliderRegionStart = sliderRect.getX() + indent;
  37038. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  37039. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  37040. sliderRegionSize, sliderRect.getHeight());
  37041. }
  37042. else if (isVertical())
  37043. {
  37044. sliderRegionStart = sliderRect.getY() + indent;
  37045. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  37046. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  37047. sliderRect.getWidth(), sliderRegionSize);
  37048. }
  37049. else
  37050. {
  37051. sliderRegionStart = 0;
  37052. sliderRegionSize = 100;
  37053. }
  37054. if (style == IncDecButtons)
  37055. {
  37056. Rectangle buttonRect (sliderRect);
  37057. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  37058. buttonRect.expand (-2, 0);
  37059. else
  37060. buttonRect.expand (0, -2);
  37061. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  37062. if (incDecButtonsSideBySide)
  37063. {
  37064. decButton->setBounds (buttonRect.getX(),
  37065. buttonRect.getY(),
  37066. buttonRect.getWidth() / 2,
  37067. buttonRect.getHeight());
  37068. decButton->setConnectedEdges (Button::ConnectedOnRight);
  37069. incButton->setBounds (buttonRect.getCentreX(),
  37070. buttonRect.getY(),
  37071. buttonRect.getWidth() / 2,
  37072. buttonRect.getHeight());
  37073. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  37074. }
  37075. else
  37076. {
  37077. incButton->setBounds (buttonRect.getX(),
  37078. buttonRect.getY(),
  37079. buttonRect.getWidth(),
  37080. buttonRect.getHeight() / 2);
  37081. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  37082. decButton->setBounds (buttonRect.getX(),
  37083. buttonRect.getCentreY(),
  37084. buttonRect.getWidth(),
  37085. buttonRect.getHeight() / 2);
  37086. decButton->setConnectedEdges (Button::ConnectedOnTop);
  37087. }
  37088. }
  37089. }
  37090. void Slider::focusOfChildComponentChanged (FocusChangeType)
  37091. {
  37092. repaint();
  37093. }
  37094. void Slider::mouseDown (const MouseEvent& e)
  37095. {
  37096. mouseWasHidden = false;
  37097. incDecDragged = false;
  37098. mouseXWhenLastDragged = e.x;
  37099. mouseYWhenLastDragged = e.y;
  37100. mouseDragStartX = e.getMouseDownX();
  37101. mouseDragStartY = e.getMouseDownY();
  37102. if (isEnabled())
  37103. {
  37104. if (e.mods.isPopupMenu() && menuEnabled)
  37105. {
  37106. menuShown = true;
  37107. PopupMenu m;
  37108. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  37109. m.addSeparator();
  37110. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37111. {
  37112. PopupMenu rotaryMenu;
  37113. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  37114. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  37115. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  37116. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  37117. }
  37118. const int r = m.show();
  37119. if (r == 1)
  37120. {
  37121. setVelocityBasedMode (! isVelocityBased);
  37122. }
  37123. else if (r == 2)
  37124. {
  37125. setSliderStyle (Rotary);
  37126. }
  37127. else if (r == 3)
  37128. {
  37129. setSliderStyle (RotaryHorizontalDrag);
  37130. }
  37131. else if (r == 4)
  37132. {
  37133. setSliderStyle (RotaryVerticalDrag);
  37134. }
  37135. }
  37136. else if (maximum > minimum)
  37137. {
  37138. menuShown = false;
  37139. if (valueBox != 0)
  37140. valueBox->hideEditor (true);
  37141. sliderBeingDragged = 0;
  37142. if (style == TwoValueHorizontal
  37143. || style == TwoValueVertical
  37144. || style == ThreeValueHorizontal
  37145. || style == ThreeValueVertical)
  37146. {
  37147. const float mousePos = (float) (isVertical() ? e.y : e.x);
  37148. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  37149. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  37150. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  37151. if (style == TwoValueHorizontal || style == TwoValueVertical)
  37152. {
  37153. if (maxPosDistance <= minPosDistance)
  37154. sliderBeingDragged = 2;
  37155. else
  37156. sliderBeingDragged = 1;
  37157. }
  37158. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  37159. {
  37160. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  37161. sliderBeingDragged = 1;
  37162. else if (normalPosDistance >= maxPosDistance)
  37163. sliderBeingDragged = 2;
  37164. }
  37165. }
  37166. minMaxDiff = valueMax - valueMin;
  37167. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  37168. * valueToProportionOfLength (currentValue);
  37169. if (sliderBeingDragged == 2)
  37170. valueWhenLastDragged = valueMax;
  37171. else if (sliderBeingDragged == 1)
  37172. valueWhenLastDragged = valueMin;
  37173. else
  37174. valueWhenLastDragged = currentValue;
  37175. valueOnMouseDown = valueWhenLastDragged;
  37176. if (popupDisplayEnabled)
  37177. {
  37178. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  37179. popupDisplay = popup;
  37180. if (parentForPopupDisplay != 0)
  37181. {
  37182. parentForPopupDisplay->addChildComponent (popup);
  37183. }
  37184. else
  37185. {
  37186. popup->addToDesktop (0);
  37187. }
  37188. popup->setVisible (true);
  37189. }
  37190. sendDragStart();
  37191. mouseDrag (e);
  37192. }
  37193. }
  37194. }
  37195. void Slider::mouseUp (const MouseEvent&)
  37196. {
  37197. if (isEnabled()
  37198. && (! menuShown)
  37199. && (maximum > minimum)
  37200. && (style != IncDecButtons || incDecDragged))
  37201. {
  37202. restoreMouseIfHidden();
  37203. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  37204. triggerChangeMessage (false);
  37205. sendDragEnd();
  37206. deleteAndZero (popupDisplay);
  37207. if (style == IncDecButtons)
  37208. {
  37209. incButton->setState (Button::buttonNormal);
  37210. decButton->setState (Button::buttonNormal);
  37211. }
  37212. }
  37213. }
  37214. void Slider::restoreMouseIfHidden()
  37215. {
  37216. if (mouseWasHidden)
  37217. {
  37218. mouseWasHidden = false;
  37219. Component* c = Component::getComponentUnderMouse();
  37220. if (c == 0)
  37221. c = this;
  37222. c->enableUnboundedMouseMovement (false);
  37223. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  37224. : ((sliderBeingDragged == 1) ? getMinValue()
  37225. : currentValue);
  37226. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37227. {
  37228. int x, y, downX, downY;
  37229. Desktop::getMousePosition (x, y);
  37230. Desktop::getLastMouseDownPosition (downX, downY);
  37231. if (style == RotaryHorizontalDrag)
  37232. {
  37233. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  37234. x = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downX);
  37235. y = downY;
  37236. }
  37237. else
  37238. {
  37239. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  37240. x = downX;
  37241. y = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downY);
  37242. }
  37243. Desktop::setMousePosition (x, y);
  37244. }
  37245. else
  37246. {
  37247. const int pixelPos = (int) getLinearSliderPos (pos);
  37248. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  37249. int y = isVertical() ? pixelPos : (getHeight() / 2);
  37250. relativePositionToGlobal (x, y);
  37251. Desktop::setMousePosition (x, y);
  37252. }
  37253. }
  37254. }
  37255. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  37256. {
  37257. if (isEnabled()
  37258. && style != IncDecButtons
  37259. && style != Rotary
  37260. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  37261. {
  37262. restoreMouseIfHidden();
  37263. }
  37264. }
  37265. static double smallestAngleBetween (double a1, double a2)
  37266. {
  37267. return jmin (fabs (a1 - a2),
  37268. fabs (a1 + double_Pi * 2.0 - a2),
  37269. fabs (a2 + double_Pi * 2.0 - a1));
  37270. }
  37271. void Slider::mouseDrag (const MouseEvent& e)
  37272. {
  37273. if (isEnabled()
  37274. && (! menuShown)
  37275. && (maximum > minimum))
  37276. {
  37277. if (style == Rotary)
  37278. {
  37279. int dx = e.x - sliderRect.getCentreX();
  37280. int dy = e.y - sliderRect.getCentreY();
  37281. if (dx * dx + dy * dy > 25)
  37282. {
  37283. double angle = atan2 ((double) dx, (double) -dy);
  37284. while (angle < 0.0)
  37285. angle += double_Pi * 2.0;
  37286. if (rotaryStop && ! e.mouseWasClicked())
  37287. {
  37288. if (fabs (angle - lastAngle) > double_Pi)
  37289. {
  37290. if (angle >= lastAngle)
  37291. angle -= double_Pi * 2.0;
  37292. else
  37293. angle += double_Pi * 2.0;
  37294. }
  37295. if (angle >= lastAngle)
  37296. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  37297. else
  37298. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  37299. }
  37300. else
  37301. {
  37302. while (angle < rotaryStart)
  37303. angle += double_Pi * 2.0;
  37304. if (angle > rotaryEnd)
  37305. {
  37306. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  37307. angle = rotaryStart;
  37308. else
  37309. angle = rotaryEnd;
  37310. }
  37311. }
  37312. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  37313. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  37314. lastAngle = angle;
  37315. }
  37316. }
  37317. else
  37318. {
  37319. if (style == LinearBar && e.mouseWasClicked()
  37320. && valueBox != 0 && valueBox->isEditable())
  37321. return;
  37322. if (style == IncDecButtons && ! incDecDragged)
  37323. {
  37324. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  37325. return;
  37326. incDecDragged = true;
  37327. mouseDragStartX = e.x;
  37328. mouseDragStartY = e.y;
  37329. }
  37330. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  37331. : false))
  37332. || ((maximum - minimum) / sliderRegionSize < interval))
  37333. {
  37334. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  37335. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  37336. if (style == RotaryHorizontalDrag
  37337. || style == RotaryVerticalDrag
  37338. || style == IncDecButtons
  37339. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  37340. && ! snapsToMousePos))
  37341. {
  37342. const int mouseDiff = (style == RotaryHorizontalDrag
  37343. || style == LinearHorizontal
  37344. || style == LinearBar
  37345. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37346. ? e.x - mouseDragStartX
  37347. : mouseDragStartY - e.y;
  37348. double newPos = valueToProportionOfLength (valueOnMouseDown)
  37349. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  37350. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  37351. if (style == IncDecButtons)
  37352. {
  37353. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  37354. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  37355. }
  37356. }
  37357. else
  37358. {
  37359. if (isVertical())
  37360. scaledMousePos = 1.0 - scaledMousePos;
  37361. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  37362. }
  37363. }
  37364. else
  37365. {
  37366. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  37367. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37368. ? e.x - mouseXWhenLastDragged
  37369. : e.y - mouseYWhenLastDragged;
  37370. const double maxSpeed = jmax (200, sliderRegionSize);
  37371. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  37372. if (speed != 0)
  37373. {
  37374. speed = 0.2 * velocityModeSensitivity
  37375. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  37376. + jmax (0.0, (double) (speed - velocityModeThreshold))
  37377. / maxSpeed))));
  37378. if (mouseDiff < 0)
  37379. speed = -speed;
  37380. if (isVertical() || style == RotaryVerticalDrag
  37381. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  37382. speed = -speed;
  37383. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  37384. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  37385. e.originalComponent->enableUnboundedMouseMovement (true, false);
  37386. mouseWasHidden = true;
  37387. }
  37388. }
  37389. }
  37390. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  37391. if (sliderBeingDragged == 0)
  37392. {
  37393. setValue (snapValue (valueWhenLastDragged, true),
  37394. ! sendChangeOnlyOnRelease, true);
  37395. }
  37396. else if (sliderBeingDragged == 1)
  37397. {
  37398. setMinValue (snapValue (valueWhenLastDragged, true),
  37399. ! sendChangeOnlyOnRelease, false, true);
  37400. if (e.mods.isShiftDown())
  37401. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  37402. else
  37403. minMaxDiff = valueMax - valueMin;
  37404. }
  37405. else
  37406. {
  37407. jassert (sliderBeingDragged == 2);
  37408. setMaxValue (snapValue (valueWhenLastDragged, true),
  37409. ! sendChangeOnlyOnRelease, false, true);
  37410. if (e.mods.isShiftDown())
  37411. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  37412. else
  37413. minMaxDiff = valueMax - valueMin;
  37414. }
  37415. mouseXWhenLastDragged = e.x;
  37416. mouseYWhenLastDragged = e.y;
  37417. }
  37418. }
  37419. void Slider::mouseDoubleClick (const MouseEvent&)
  37420. {
  37421. if (doubleClickToValue
  37422. && isEnabled()
  37423. && style != IncDecButtons
  37424. && minimum <= doubleClickReturnValue
  37425. && maximum >= doubleClickReturnValue)
  37426. {
  37427. sendDragStart();
  37428. setValue (doubleClickReturnValue, true, true);
  37429. sendDragEnd();
  37430. }
  37431. }
  37432. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37433. {
  37434. if (scrollWheelEnabled && isEnabled()
  37435. && style != TwoValueHorizontal
  37436. && style != TwoValueVertical)
  37437. {
  37438. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  37439. {
  37440. if (valueBox != 0)
  37441. valueBox->hideEditor (false);
  37442. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  37443. const double currentPos = valueToProportionOfLength (currentValue);
  37444. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  37445. double delta = (newValue != currentValue)
  37446. ? jmax (fabs (newValue - currentValue), interval) : 0;
  37447. if (currentValue > newValue)
  37448. delta = -delta;
  37449. sendDragStart();
  37450. setValue (snapValue (currentValue + delta, false), true, true);
  37451. sendDragEnd();
  37452. }
  37453. }
  37454. else
  37455. {
  37456. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37457. }
  37458. }
  37459. void SliderListener::sliderDragStarted (Slider*)
  37460. {
  37461. }
  37462. void SliderListener::sliderDragEnded (Slider*)
  37463. {
  37464. }
  37465. END_JUCE_NAMESPACE
  37466. /********* End of inlined file: juce_Slider.cpp *********/
  37467. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  37468. BEGIN_JUCE_NAMESPACE
  37469. class DragOverlayComp : public Component
  37470. {
  37471. public:
  37472. DragOverlayComp (Image* const image_)
  37473. : image (image_)
  37474. {
  37475. image->multiplyAllAlphas (0.8f);
  37476. setAlwaysOnTop (true);
  37477. }
  37478. ~DragOverlayComp()
  37479. {
  37480. delete image;
  37481. }
  37482. void paint (Graphics& g)
  37483. {
  37484. g.drawImageAt (image, 0, 0);
  37485. }
  37486. private:
  37487. Image* image;
  37488. DragOverlayComp (const DragOverlayComp&);
  37489. const DragOverlayComp& operator= (const DragOverlayComp&);
  37490. };
  37491. TableHeaderComponent::TableHeaderComponent()
  37492. : listeners (2),
  37493. dragOverlayComp (0),
  37494. columnsChanged (false),
  37495. columnsResized (false),
  37496. sortChanged (false),
  37497. menuActive (true),
  37498. stretchToFit (false),
  37499. columnIdBeingResized (0),
  37500. columnIdBeingDragged (0),
  37501. columnIdUnderMouse (0),
  37502. lastDeliberateWidth (0)
  37503. {
  37504. }
  37505. TableHeaderComponent::~TableHeaderComponent()
  37506. {
  37507. delete dragOverlayComp;
  37508. }
  37509. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  37510. {
  37511. menuActive = hasMenu;
  37512. }
  37513. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  37514. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  37515. {
  37516. if (onlyCountVisibleColumns)
  37517. {
  37518. int num = 0;
  37519. for (int i = columns.size(); --i >= 0;)
  37520. if (columns.getUnchecked(i)->isVisible())
  37521. ++num;
  37522. return num;
  37523. }
  37524. else
  37525. {
  37526. return columns.size();
  37527. }
  37528. }
  37529. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  37530. {
  37531. const ColumnInfo* const ci = getInfoForId (columnId);
  37532. return ci != 0 ? ci->name : String::empty;
  37533. }
  37534. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  37535. {
  37536. ColumnInfo* const ci = getInfoForId (columnId);
  37537. if (ci != 0 && ci->name != newName)
  37538. {
  37539. ci->name = newName;
  37540. sendColumnsChanged();
  37541. }
  37542. }
  37543. void TableHeaderComponent::addColumn (const String& columnName,
  37544. const int columnId,
  37545. const int width,
  37546. const int minimumWidth,
  37547. const int maximumWidth,
  37548. const int propertyFlags,
  37549. const int insertIndex)
  37550. {
  37551. // can't have a duplicate or null ID!
  37552. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  37553. jassert (width > 0);
  37554. ColumnInfo* const ci = new ColumnInfo();
  37555. ci->name = columnName;
  37556. ci->id = columnId;
  37557. ci->width = width;
  37558. ci->lastDeliberateWidth = width;
  37559. ci->minimumWidth = minimumWidth;
  37560. ci->maximumWidth = maximumWidth;
  37561. if (ci->maximumWidth < 0)
  37562. ci->maximumWidth = INT_MAX;
  37563. jassert (ci->maximumWidth >= ci->minimumWidth);
  37564. ci->propertyFlags = propertyFlags;
  37565. columns.insert (insertIndex, ci);
  37566. sendColumnsChanged();
  37567. }
  37568. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  37569. {
  37570. const int index = getIndexOfColumnId (columnIdToRemove, false);
  37571. if (index >= 0)
  37572. {
  37573. columns.remove (index);
  37574. sortChanged = true;
  37575. sendColumnsChanged();
  37576. }
  37577. }
  37578. void TableHeaderComponent::removeAllColumns()
  37579. {
  37580. if (columns.size() > 0)
  37581. {
  37582. columns.clear();
  37583. sendColumnsChanged();
  37584. }
  37585. }
  37586. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  37587. {
  37588. const int currentIndex = getIndexOfColumnId (columnId, false);
  37589. newIndex = visibleIndexToTotalIndex (newIndex);
  37590. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  37591. {
  37592. columns.move (currentIndex, newIndex);
  37593. sendColumnsChanged();
  37594. }
  37595. }
  37596. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  37597. {
  37598. ColumnInfo* const ci = getInfoForId (columnId);
  37599. if (ci != 0 && ci->width != newWidth)
  37600. {
  37601. const int numColumns = getNumColumns (true);
  37602. ci->lastDeliberateWidth = ci->width
  37603. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  37604. if (stretchToFit)
  37605. {
  37606. const int index = getIndexOfColumnId (columnId, true) + 1;
  37607. if (((unsigned int) index) < (unsigned int) numColumns)
  37608. {
  37609. const int x = getColumnPosition (index).getX();
  37610. if (lastDeliberateWidth == 0)
  37611. lastDeliberateWidth = getTotalWidth();
  37612. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  37613. }
  37614. }
  37615. repaint();
  37616. columnsResized = true;
  37617. triggerAsyncUpdate();
  37618. }
  37619. }
  37620. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  37621. {
  37622. int n = 0;
  37623. for (int i = 0; i < columns.size(); ++i)
  37624. {
  37625. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  37626. {
  37627. if (columns.getUnchecked(i)->id == columnId)
  37628. return n;
  37629. ++n;
  37630. }
  37631. }
  37632. return -1;
  37633. }
  37634. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  37635. {
  37636. if (onlyCountVisibleColumns)
  37637. index = visibleIndexToTotalIndex (index);
  37638. const ColumnInfo* const ci = columns [index];
  37639. return (ci != 0) ? ci->id : 0;
  37640. }
  37641. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  37642. {
  37643. int x = 0, width = 0, n = 0;
  37644. for (int i = 0; i < columns.size(); ++i)
  37645. {
  37646. x += width;
  37647. if (columns.getUnchecked(i)->isVisible())
  37648. {
  37649. width = columns.getUnchecked(i)->width;
  37650. if (n++ == index)
  37651. break;
  37652. }
  37653. else
  37654. {
  37655. width = 0;
  37656. }
  37657. }
  37658. return Rectangle (x, 0, width, getHeight());
  37659. }
  37660. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  37661. {
  37662. if (xToFind >= 0)
  37663. {
  37664. int x = 0;
  37665. for (int i = 0; i < columns.size(); ++i)
  37666. {
  37667. const ColumnInfo* const ci = columns.getUnchecked(i);
  37668. if (ci->isVisible())
  37669. {
  37670. x += ci->width;
  37671. if (xToFind < x)
  37672. return ci->id;
  37673. }
  37674. }
  37675. }
  37676. return 0;
  37677. }
  37678. int TableHeaderComponent::getTotalWidth() const throw()
  37679. {
  37680. int w = 0;
  37681. for (int i = columns.size(); --i >= 0;)
  37682. if (columns.getUnchecked(i)->isVisible())
  37683. w += columns.getUnchecked(i)->width;
  37684. return w;
  37685. }
  37686. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  37687. {
  37688. stretchToFit = shouldStretchToFit;
  37689. lastDeliberateWidth = getTotalWidth();
  37690. resized();
  37691. }
  37692. bool TableHeaderComponent::isStretchToFitActive() const throw()
  37693. {
  37694. return stretchToFit;
  37695. }
  37696. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  37697. {
  37698. if (stretchToFit && getWidth() > 0
  37699. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  37700. {
  37701. lastDeliberateWidth = targetTotalWidth;
  37702. resizeColumnsToFit (0, targetTotalWidth);
  37703. }
  37704. }
  37705. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  37706. {
  37707. targetTotalWidth = jmax (targetTotalWidth, 0);
  37708. StretchableObjectResizer sor;
  37709. int i;
  37710. for (i = firstColumnIndex; i < columns.size(); ++i)
  37711. {
  37712. ColumnInfo* const ci = columns.getUnchecked(i);
  37713. if (ci->isVisible())
  37714. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  37715. }
  37716. sor.resizeToFit (targetTotalWidth);
  37717. int visIndex = 0;
  37718. for (i = firstColumnIndex; i < columns.size(); ++i)
  37719. {
  37720. ColumnInfo* const ci = columns.getUnchecked(i);
  37721. if (ci->isVisible())
  37722. {
  37723. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  37724. (int) floor (sor.getItemSize (visIndex++)));
  37725. if (newWidth != ci->width)
  37726. {
  37727. ci->width = newWidth;
  37728. repaint();
  37729. columnsResized = true;
  37730. triggerAsyncUpdate();
  37731. }
  37732. }
  37733. }
  37734. }
  37735. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  37736. {
  37737. ColumnInfo* const ci = getInfoForId (columnId);
  37738. if (ci != 0 && shouldBeVisible != ci->isVisible())
  37739. {
  37740. if (shouldBeVisible)
  37741. ci->propertyFlags |= visible;
  37742. else
  37743. ci->propertyFlags &= ~visible;
  37744. sendColumnsChanged();
  37745. resized();
  37746. }
  37747. }
  37748. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  37749. {
  37750. const ColumnInfo* const ci = getInfoForId (columnId);
  37751. return ci != 0 && ci->isVisible();
  37752. }
  37753. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  37754. {
  37755. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  37756. {
  37757. for (int i = columns.size(); --i >= 0;)
  37758. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  37759. ColumnInfo* const ci = getInfoForId (columnId);
  37760. if (ci != 0)
  37761. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  37762. reSortTable();
  37763. }
  37764. }
  37765. int TableHeaderComponent::getSortColumnId() const throw()
  37766. {
  37767. for (int i = columns.size(); --i >= 0;)
  37768. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37769. return columns.getUnchecked(i)->id;
  37770. return 0;
  37771. }
  37772. bool TableHeaderComponent::isSortedForwards() const throw()
  37773. {
  37774. for (int i = columns.size(); --i >= 0;)
  37775. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37776. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  37777. return true;
  37778. }
  37779. void TableHeaderComponent::reSortTable()
  37780. {
  37781. sortChanged = true;
  37782. repaint();
  37783. triggerAsyncUpdate();
  37784. }
  37785. const String TableHeaderComponent::toString() const
  37786. {
  37787. String s;
  37788. XmlElement doc (T("TABLELAYOUT"));
  37789. doc.setAttribute (T("sortedCol"), getSortColumnId());
  37790. doc.setAttribute (T("sortForwards"), isSortedForwards());
  37791. for (int i = 0; i < columns.size(); ++i)
  37792. {
  37793. const ColumnInfo* const ci = columns.getUnchecked (i);
  37794. XmlElement* const e = new XmlElement (T("COLUMN"));
  37795. doc.addChildElement (e);
  37796. e->setAttribute (T("id"), ci->id);
  37797. e->setAttribute (T("visible"), ci->isVisible());
  37798. e->setAttribute (T("width"), ci->width);
  37799. }
  37800. return doc.createDocument (String::empty, true, false);
  37801. }
  37802. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  37803. {
  37804. XmlDocument doc (storedVersion);
  37805. XmlElement* const storedXml = doc.getDocumentElement();
  37806. int index = 0;
  37807. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  37808. {
  37809. forEachXmlChildElement (*storedXml, col)
  37810. {
  37811. const int tabId = col->getIntAttribute (T("id"));
  37812. ColumnInfo* const ci = getInfoForId (tabId);
  37813. if (ci != 0)
  37814. {
  37815. columns.move (columns.indexOf (ci), index);
  37816. ci->width = col->getIntAttribute (T("width"));
  37817. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  37818. }
  37819. ++index;
  37820. }
  37821. columnsResized = true;
  37822. sendColumnsChanged();
  37823. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  37824. storedXml->getBoolAttribute (T("sortForwards"), true));
  37825. }
  37826. delete storedXml;
  37827. }
  37828. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  37829. {
  37830. listeners.addIfNotAlreadyThere (newListener);
  37831. }
  37832. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  37833. {
  37834. listeners.removeValue (listenerToRemove);
  37835. }
  37836. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  37837. {
  37838. const ColumnInfo* const ci = getInfoForId (columnId);
  37839. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  37840. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  37841. }
  37842. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  37843. {
  37844. for (int i = 0; i < columns.size(); ++i)
  37845. {
  37846. const ColumnInfo* const ci = columns.getUnchecked(i);
  37847. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  37848. menu.addItem (ci->id, ci->name,
  37849. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  37850. isColumnVisible (ci->id));
  37851. }
  37852. }
  37853. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  37854. {
  37855. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  37856. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  37857. }
  37858. void TableHeaderComponent::paint (Graphics& g)
  37859. {
  37860. LookAndFeel& lf = getLookAndFeel();
  37861. lf.drawTableHeaderBackground (g, *this);
  37862. const Rectangle clip (g.getClipBounds());
  37863. int x = 0;
  37864. for (int i = 0; i < columns.size(); ++i)
  37865. {
  37866. const ColumnInfo* const ci = columns.getUnchecked(i);
  37867. if (ci->isVisible())
  37868. {
  37869. if (x + ci->width > clip.getX()
  37870. && (ci->id != columnIdBeingDragged
  37871. || dragOverlayComp == 0
  37872. || ! dragOverlayComp->isVisible()))
  37873. {
  37874. g.saveState();
  37875. g.setOrigin (x, 0);
  37876. g.reduceClipRegion (0, 0, ci->width, getHeight());
  37877. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  37878. ci->id == columnIdUnderMouse,
  37879. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  37880. ci->propertyFlags);
  37881. g.restoreState();
  37882. }
  37883. x += ci->width;
  37884. if (x >= clip.getRight())
  37885. break;
  37886. }
  37887. }
  37888. }
  37889. void TableHeaderComponent::resized()
  37890. {
  37891. }
  37892. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  37893. {
  37894. updateColumnUnderMouse (e.x, e.y);
  37895. }
  37896. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  37897. {
  37898. updateColumnUnderMouse (e.x, e.y);
  37899. }
  37900. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  37901. {
  37902. updateColumnUnderMouse (e.x, e.y);
  37903. }
  37904. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  37905. {
  37906. repaint();
  37907. columnIdBeingResized = 0;
  37908. columnIdBeingDragged = 0;
  37909. if (columnIdUnderMouse != 0)
  37910. {
  37911. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  37912. if (e.mods.isPopupMenu())
  37913. columnClicked (columnIdUnderMouse, e.mods);
  37914. }
  37915. if (menuActive && e.mods.isPopupMenu())
  37916. showColumnChooserMenu (columnIdUnderMouse);
  37917. }
  37918. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  37919. {
  37920. if (columnIdBeingResized == 0
  37921. && columnIdBeingDragged == 0
  37922. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  37923. {
  37924. deleteAndZero (dragOverlayComp);
  37925. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  37926. if (columnIdBeingResized != 0)
  37927. {
  37928. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  37929. initialColumnWidth = ci->width;
  37930. }
  37931. else
  37932. {
  37933. beginDrag (e);
  37934. }
  37935. }
  37936. if (columnIdBeingResized != 0)
  37937. {
  37938. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  37939. if (ci != 0)
  37940. {
  37941. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  37942. initialColumnWidth + e.getDistanceFromDragStartX());
  37943. if (stretchToFit)
  37944. {
  37945. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  37946. int minWidthOnRight = 0;
  37947. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  37948. if (columns.getUnchecked (i)->isVisible())
  37949. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  37950. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  37951. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  37952. }
  37953. setColumnWidth (columnIdBeingResized, w);
  37954. }
  37955. }
  37956. else if (columnIdBeingDragged != 0)
  37957. {
  37958. if (e.y >= -50 && e.y < getHeight() + 50)
  37959. {
  37960. beginDrag (e);
  37961. if (dragOverlayComp != 0)
  37962. {
  37963. dragOverlayComp->setVisible (true);
  37964. dragOverlayComp->setBounds (jlimit (0,
  37965. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  37966. e.x - draggingColumnOffset),
  37967. 0,
  37968. dragOverlayComp->getWidth(),
  37969. getHeight());
  37970. for (int i = columns.size(); --i >= 0;)
  37971. {
  37972. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  37973. int newIndex = currentIndex;
  37974. if (newIndex > 0)
  37975. {
  37976. // if the previous column isn't draggable, we can't move our column
  37977. // past it, because that'd change the undraggable column's position..
  37978. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  37979. if ((previous->propertyFlags & draggable) != 0)
  37980. {
  37981. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  37982. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  37983. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  37984. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  37985. {
  37986. --newIndex;
  37987. }
  37988. }
  37989. }
  37990. if (newIndex < columns.size() - 1)
  37991. {
  37992. // if the next column isn't draggable, we can't move our column
  37993. // past it, because that'd change the undraggable column's position..
  37994. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  37995. if ((nextCol->propertyFlags & draggable) != 0)
  37996. {
  37997. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  37998. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  37999. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  38000. > abs (dragOverlayComp->getRight() - rightOfNext))
  38001. {
  38002. ++newIndex;
  38003. }
  38004. }
  38005. }
  38006. if (newIndex != currentIndex)
  38007. moveColumn (columnIdBeingDragged, newIndex);
  38008. else
  38009. break;
  38010. }
  38011. }
  38012. }
  38013. else
  38014. {
  38015. endDrag (draggingColumnOriginalIndex);
  38016. }
  38017. }
  38018. }
  38019. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  38020. {
  38021. if (columnIdBeingDragged == 0)
  38022. {
  38023. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  38024. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  38025. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  38026. {
  38027. columnIdBeingDragged = 0;
  38028. }
  38029. else
  38030. {
  38031. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  38032. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  38033. const int temp = columnIdBeingDragged;
  38034. columnIdBeingDragged = 0;
  38035. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  38036. columnIdBeingDragged = temp;
  38037. dragOverlayComp->setBounds (columnRect);
  38038. for (int i = listeners.size(); --i >= 0;)
  38039. {
  38040. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  38041. i = jmin (i, listeners.size() - 1);
  38042. }
  38043. }
  38044. }
  38045. }
  38046. void TableHeaderComponent::endDrag (const int finalIndex)
  38047. {
  38048. if (columnIdBeingDragged != 0)
  38049. {
  38050. moveColumn (columnIdBeingDragged, finalIndex);
  38051. columnIdBeingDragged = 0;
  38052. repaint();
  38053. for (int i = listeners.size(); --i >= 0;)
  38054. {
  38055. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  38056. i = jmin (i, listeners.size() - 1);
  38057. }
  38058. }
  38059. }
  38060. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  38061. {
  38062. mouseDrag (e);
  38063. for (int i = columns.size(); --i >= 0;)
  38064. if (columns.getUnchecked (i)->isVisible())
  38065. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  38066. columnIdBeingResized = 0;
  38067. repaint();
  38068. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  38069. updateColumnUnderMouse (e.x, e.y);
  38070. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  38071. columnClicked (columnIdUnderMouse, e.mods);
  38072. deleteAndZero (dragOverlayComp);
  38073. }
  38074. const MouseCursor TableHeaderComponent::getMouseCursor()
  38075. {
  38076. int x, y;
  38077. getMouseXYRelative (x, y);
  38078. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  38079. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  38080. return Component::getMouseCursor();
  38081. }
  38082. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  38083. {
  38084. return (propertyFlags & TableHeaderComponent::visible) != 0;
  38085. }
  38086. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  38087. {
  38088. for (int i = columns.size(); --i >= 0;)
  38089. if (columns.getUnchecked(i)->id == id)
  38090. return columns.getUnchecked(i);
  38091. return 0;
  38092. }
  38093. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  38094. {
  38095. int n = 0;
  38096. for (int i = 0; i < columns.size(); ++i)
  38097. {
  38098. if (columns.getUnchecked(i)->isVisible())
  38099. {
  38100. if (n == visibleIndex)
  38101. return i;
  38102. ++n;
  38103. }
  38104. }
  38105. return -1;
  38106. }
  38107. void TableHeaderComponent::sendColumnsChanged()
  38108. {
  38109. if (stretchToFit && lastDeliberateWidth > 0)
  38110. resizeAllColumnsToFit (lastDeliberateWidth);
  38111. repaint();
  38112. columnsChanged = true;
  38113. triggerAsyncUpdate();
  38114. }
  38115. void TableHeaderComponent::handleAsyncUpdate()
  38116. {
  38117. const bool changed = columnsChanged || sortChanged;
  38118. const bool sized = columnsResized || changed;
  38119. const bool sorted = sortChanged;
  38120. columnsChanged = false;
  38121. columnsResized = false;
  38122. sortChanged = false;
  38123. if (sorted)
  38124. {
  38125. for (int i = listeners.size(); --i >= 0;)
  38126. {
  38127. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  38128. i = jmin (i, listeners.size() - 1);
  38129. }
  38130. }
  38131. if (changed)
  38132. {
  38133. for (int i = listeners.size(); --i >= 0;)
  38134. {
  38135. listeners.getUnchecked(i)->tableColumnsChanged (this);
  38136. i = jmin (i, listeners.size() - 1);
  38137. }
  38138. }
  38139. if (sized)
  38140. {
  38141. for (int i = listeners.size(); --i >= 0;)
  38142. {
  38143. listeners.getUnchecked(i)->tableColumnsResized (this);
  38144. i = jmin (i, listeners.size() - 1);
  38145. }
  38146. }
  38147. }
  38148. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  38149. {
  38150. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  38151. {
  38152. const int draggableDistance = 3;
  38153. int x = 0;
  38154. for (int i = 0; i < columns.size(); ++i)
  38155. {
  38156. const ColumnInfo* const ci = columns.getUnchecked(i);
  38157. if (ci->isVisible())
  38158. {
  38159. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  38160. && (ci->propertyFlags & resizable) != 0)
  38161. return ci->id;
  38162. x += ci->width;
  38163. }
  38164. }
  38165. }
  38166. return 0;
  38167. }
  38168. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  38169. {
  38170. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  38171. ? getColumnIdAtX (x) : 0;
  38172. if (newCol != columnIdUnderMouse)
  38173. {
  38174. columnIdUnderMouse = newCol;
  38175. repaint();
  38176. }
  38177. }
  38178. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  38179. {
  38180. PopupMenu m;
  38181. addMenuItems (m, columnIdClicked);
  38182. if (m.getNumItems() > 0)
  38183. {
  38184. const int result = m.show();
  38185. if (result != 0)
  38186. reactToMenuItem (result, columnIdClicked);
  38187. }
  38188. }
  38189. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  38190. {
  38191. }
  38192. END_JUCE_NAMESPACE
  38193. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  38194. /********* Start of inlined file: juce_TableListBox.cpp *********/
  38195. BEGIN_JUCE_NAMESPACE
  38196. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  38197. class TableListRowComp : public Component
  38198. {
  38199. public:
  38200. TableListRowComp (TableListBox& owner_)
  38201. : owner (owner_),
  38202. row (-1),
  38203. isSelected (false)
  38204. {
  38205. }
  38206. ~TableListRowComp()
  38207. {
  38208. deleteAllChildren();
  38209. }
  38210. void paint (Graphics& g)
  38211. {
  38212. TableListBoxModel* const model = owner.getModel();
  38213. if (model != 0)
  38214. {
  38215. const TableHeaderComponent* const header = owner.getHeader();
  38216. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  38217. const int numColumns = header->getNumColumns (true);
  38218. for (int i = 0; i < numColumns; ++i)
  38219. {
  38220. if (! columnsWithComponents [i])
  38221. {
  38222. const int columnId = header->getColumnIdOfIndex (i, true);
  38223. Rectangle columnRect (header->getColumnPosition (i));
  38224. columnRect.setSize (columnRect.getWidth(), getHeight());
  38225. g.saveState();
  38226. g.reduceClipRegion (columnRect);
  38227. g.setOrigin (columnRect.getX(), 0);
  38228. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  38229. g.restoreState();
  38230. }
  38231. }
  38232. }
  38233. }
  38234. void update (const int newRow, const bool isNowSelected)
  38235. {
  38236. if (newRow != row || isNowSelected != isSelected)
  38237. {
  38238. row = newRow;
  38239. isSelected = isNowSelected;
  38240. repaint();
  38241. }
  38242. if (row < owner.getNumRows())
  38243. {
  38244. jassert (row >= 0);
  38245. const tchar* const tagPropertyName = T("_tableLastUseNum");
  38246. const int newTag = Random::getSystemRandom().nextInt();
  38247. const TableHeaderComponent* const header = owner.getHeader();
  38248. const int numColumns = header->getNumColumns (true);
  38249. int i;
  38250. columnsWithComponents.clear();
  38251. if (owner.getModel() != 0)
  38252. {
  38253. for (i = 0; i < numColumns; ++i)
  38254. {
  38255. const int columnId = header->getColumnIdOfIndex (i, true);
  38256. Component* const newComp
  38257. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  38258. findChildComponentForColumn (columnId));
  38259. if (newComp != 0)
  38260. {
  38261. addAndMakeVisible (newComp);
  38262. newComp->setComponentProperty (tagPropertyName, newTag);
  38263. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  38264. const Rectangle columnRect (header->getColumnPosition (i));
  38265. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38266. columnsWithComponents.setBit (i);
  38267. }
  38268. }
  38269. }
  38270. for (i = getNumChildComponents(); --i >= 0;)
  38271. {
  38272. Component* const c = getChildComponent (i);
  38273. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  38274. delete c;
  38275. }
  38276. }
  38277. else
  38278. {
  38279. columnsWithComponents.clear();
  38280. deleteAllChildren();
  38281. }
  38282. }
  38283. void resized()
  38284. {
  38285. for (int i = getNumChildComponents(); --i >= 0;)
  38286. {
  38287. Component* const c = getChildComponent (i);
  38288. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  38289. if (columnId != 0)
  38290. {
  38291. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  38292. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38293. }
  38294. }
  38295. }
  38296. void mouseDown (const MouseEvent& e)
  38297. {
  38298. isDragging = false;
  38299. selectRowOnMouseUp = false;
  38300. if (isEnabled())
  38301. {
  38302. if (! isSelected)
  38303. {
  38304. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38305. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38306. if (columnId != 0 && owner.getModel() != 0)
  38307. owner.getModel()->cellClicked (row, columnId, e);
  38308. }
  38309. else
  38310. {
  38311. selectRowOnMouseUp = true;
  38312. }
  38313. }
  38314. }
  38315. void mouseDrag (const MouseEvent& e)
  38316. {
  38317. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38318. {
  38319. const SparseSet <int> selectedRows (owner.getSelectedRows());
  38320. if (selectedRows.size() > 0)
  38321. {
  38322. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38323. if (dragDescription.isNotEmpty())
  38324. {
  38325. isDragging = true;
  38326. DragAndDropContainer* const dragContainer
  38327. = DragAndDropContainer::findParentDragContainerFor (this);
  38328. if (dragContainer != 0)
  38329. {
  38330. Image* dragImage = owner.createSnapshotOfSelectedRows();
  38331. dragImage->multiplyAllAlphas (0.6f);
  38332. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  38333. }
  38334. else
  38335. {
  38336. // to be able to do a drag-and-drop operation, the listbox needs to
  38337. // be inside a component which is also a DragAndDropContainer.
  38338. jassertfalse
  38339. }
  38340. }
  38341. }
  38342. }
  38343. }
  38344. void mouseUp (const MouseEvent& e)
  38345. {
  38346. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  38347. {
  38348. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38349. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38350. if (columnId != 0 && owner.getModel() != 0)
  38351. owner.getModel()->cellClicked (row, columnId, e);
  38352. }
  38353. }
  38354. void mouseDoubleClick (const MouseEvent& e)
  38355. {
  38356. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38357. if (columnId != 0 && owner.getModel() != 0)
  38358. owner.getModel()->cellDoubleClicked (row, columnId, e);
  38359. }
  38360. juce_UseDebuggingNewOperator
  38361. private:
  38362. TableListBox& owner;
  38363. int row;
  38364. bool isSelected, isDragging, selectRowOnMouseUp;
  38365. BitArray columnsWithComponents;
  38366. Component* findChildComponentForColumn (const int columnId) const
  38367. {
  38368. for (int i = getNumChildComponents(); --i >= 0;)
  38369. {
  38370. Component* const c = getChildComponent (i);
  38371. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  38372. return c;
  38373. }
  38374. return 0;
  38375. }
  38376. TableListRowComp (const TableListRowComp&);
  38377. const TableListRowComp& operator= (const TableListRowComp&);
  38378. };
  38379. class TableListBoxHeader : public TableHeaderComponent
  38380. {
  38381. public:
  38382. TableListBoxHeader (TableListBox& owner_)
  38383. : owner (owner_)
  38384. {
  38385. }
  38386. ~TableListBoxHeader()
  38387. {
  38388. }
  38389. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  38390. {
  38391. if (owner.isAutoSizeMenuOptionShown())
  38392. {
  38393. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  38394. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  38395. menu.addSeparator();
  38396. }
  38397. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  38398. }
  38399. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  38400. {
  38401. if (menuReturnId == 0xf836743)
  38402. {
  38403. owner.autoSizeColumn (columnIdClicked);
  38404. }
  38405. else if (menuReturnId == 0xf836744)
  38406. {
  38407. owner.autoSizeAllColumns();
  38408. }
  38409. else
  38410. {
  38411. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  38412. }
  38413. }
  38414. juce_UseDebuggingNewOperator
  38415. private:
  38416. TableListBox& owner;
  38417. TableListBoxHeader (const TableListBoxHeader&);
  38418. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  38419. };
  38420. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  38421. : ListBox (name, 0),
  38422. model (model_),
  38423. autoSizeOptionsShown (true)
  38424. {
  38425. ListBox::model = this;
  38426. header = new TableListBoxHeader (*this);
  38427. header->setSize (100, 28);
  38428. header->addListener (this);
  38429. setHeaderComponent (header);
  38430. }
  38431. TableListBox::~TableListBox()
  38432. {
  38433. deleteAllChildren();
  38434. }
  38435. void TableListBox::setModel (TableListBoxModel* const newModel)
  38436. {
  38437. if (model != newModel)
  38438. {
  38439. model = newModel;
  38440. updateContent();
  38441. }
  38442. }
  38443. int TableListBox::getHeaderHeight() const throw()
  38444. {
  38445. return header->getHeight();
  38446. }
  38447. void TableListBox::setHeaderHeight (const int newHeight)
  38448. {
  38449. header->setSize (header->getWidth(), newHeight);
  38450. resized();
  38451. }
  38452. void TableListBox::autoSizeColumn (const int columnId)
  38453. {
  38454. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  38455. if (width > 0)
  38456. header->setColumnWidth (columnId, width);
  38457. }
  38458. void TableListBox::autoSizeAllColumns()
  38459. {
  38460. for (int i = 0; i < header->getNumColumns (true); ++i)
  38461. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  38462. }
  38463. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  38464. {
  38465. autoSizeOptionsShown = shouldBeShown;
  38466. }
  38467. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  38468. {
  38469. return autoSizeOptionsShown;
  38470. }
  38471. const Rectangle TableListBox::getCellPosition (const int columnId,
  38472. const int rowNumber,
  38473. const bool relativeToComponentTopLeft) const
  38474. {
  38475. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38476. if (relativeToComponentTopLeft)
  38477. headerCell.translate (header->getX(), 0);
  38478. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  38479. return Rectangle (headerCell.getX(), row.getY(),
  38480. headerCell.getWidth(), row.getHeight());
  38481. }
  38482. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  38483. {
  38484. ScrollBar* const scrollbar = getHorizontalScrollBar();
  38485. if (scrollbar != 0)
  38486. {
  38487. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38488. double x = scrollbar->getCurrentRangeStart();
  38489. const double w = scrollbar->getCurrentRangeSize();
  38490. if (pos.getX() < x)
  38491. x = pos.getX();
  38492. else if (pos.getRight() > x + w)
  38493. x += jmax (0.0, pos.getRight() - (x + w));
  38494. scrollbar->setCurrentRangeStart (x);
  38495. }
  38496. }
  38497. int TableListBox::getNumRows()
  38498. {
  38499. return model != 0 ? model->getNumRows() : 0;
  38500. }
  38501. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  38502. {
  38503. }
  38504. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  38505. {
  38506. if (existingComponentToUpdate == 0)
  38507. existingComponentToUpdate = new TableListRowComp (*this);
  38508. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  38509. return existingComponentToUpdate;
  38510. }
  38511. void TableListBox::selectedRowsChanged (int row)
  38512. {
  38513. if (model != 0)
  38514. model->selectedRowsChanged (row);
  38515. }
  38516. void TableListBox::deleteKeyPressed (int row)
  38517. {
  38518. if (model != 0)
  38519. model->deleteKeyPressed (row);
  38520. }
  38521. void TableListBox::returnKeyPressed (int row)
  38522. {
  38523. if (model != 0)
  38524. model->returnKeyPressed (row);
  38525. }
  38526. void TableListBox::backgroundClicked()
  38527. {
  38528. if (model != 0)
  38529. model->backgroundClicked();
  38530. }
  38531. void TableListBox::listWasScrolled()
  38532. {
  38533. if (model != 0)
  38534. model->listWasScrolled();
  38535. }
  38536. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  38537. {
  38538. setMinimumContentWidth (header->getTotalWidth());
  38539. repaint();
  38540. updateColumnComponents();
  38541. }
  38542. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  38543. {
  38544. setMinimumContentWidth (header->getTotalWidth());
  38545. repaint();
  38546. updateColumnComponents();
  38547. }
  38548. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  38549. {
  38550. if (model != 0)
  38551. model->sortOrderChanged (header->getSortColumnId(),
  38552. header->isSortedForwards());
  38553. }
  38554. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  38555. {
  38556. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  38557. repaint();
  38558. }
  38559. void TableListBox::resized()
  38560. {
  38561. ListBox::resized();
  38562. header->resizeAllColumnsToFit (getVisibleContentWidth());
  38563. setMinimumContentWidth (header->getTotalWidth());
  38564. }
  38565. void TableListBox::updateColumnComponents() const
  38566. {
  38567. const int firstRow = getRowContainingPosition (0, 0);
  38568. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  38569. {
  38570. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  38571. if (rowComp != 0)
  38572. rowComp->resized();
  38573. }
  38574. }
  38575. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  38576. {
  38577. }
  38578. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  38579. {
  38580. }
  38581. void TableListBoxModel::backgroundClicked()
  38582. {
  38583. }
  38584. void TableListBoxModel::sortOrderChanged (int, const bool)
  38585. {
  38586. }
  38587. int TableListBoxModel::getColumnAutoSizeWidth (int)
  38588. {
  38589. return 0;
  38590. }
  38591. void TableListBoxModel::selectedRowsChanged (int)
  38592. {
  38593. }
  38594. void TableListBoxModel::deleteKeyPressed (int)
  38595. {
  38596. }
  38597. void TableListBoxModel::returnKeyPressed (int)
  38598. {
  38599. }
  38600. void TableListBoxModel::listWasScrolled()
  38601. {
  38602. }
  38603. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38604. {
  38605. return String::empty;
  38606. }
  38607. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  38608. {
  38609. (void) existingComponentToUpdate;
  38610. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38611. return 0;
  38612. }
  38613. END_JUCE_NAMESPACE
  38614. /********* End of inlined file: juce_TableListBox.cpp *********/
  38615. /********* Start of inlined file: juce_TextEditor.cpp *********/
  38616. BEGIN_JUCE_NAMESPACE
  38617. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  38618. // a word or space that can't be broken down any further
  38619. struct TextAtom
  38620. {
  38621. String atomText;
  38622. float width;
  38623. uint16 numChars;
  38624. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  38625. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  38626. const String getText (const tchar passwordCharacter) const throw()
  38627. {
  38628. if (passwordCharacter == 0)
  38629. return atomText;
  38630. else
  38631. return String::repeatedString (String::charToString (passwordCharacter),
  38632. atomText.length());
  38633. }
  38634. const String getTrimmedText (const tchar passwordCharacter) const throw()
  38635. {
  38636. if (passwordCharacter == 0)
  38637. return atomText.substring (0, numChars);
  38638. else if (isNewLine())
  38639. return String::empty;
  38640. else
  38641. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  38642. }
  38643. };
  38644. // a run of text with a single font and colour
  38645. class UniformTextSection
  38646. {
  38647. public:
  38648. UniformTextSection (const String& text,
  38649. const Font& font_,
  38650. const Colour& colour_,
  38651. const tchar passwordCharacter) throw()
  38652. : font (font_),
  38653. colour (colour_),
  38654. atoms (64)
  38655. {
  38656. initialiseAtoms (text, passwordCharacter);
  38657. }
  38658. UniformTextSection (const UniformTextSection& other) throw()
  38659. : font (other.font),
  38660. colour (other.colour),
  38661. atoms (64)
  38662. {
  38663. for (int i = 0; i < other.atoms.size(); ++i)
  38664. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  38665. }
  38666. ~UniformTextSection() throw()
  38667. {
  38668. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  38669. }
  38670. void clear() throw()
  38671. {
  38672. for (int i = atoms.size(); --i >= 0;)
  38673. {
  38674. TextAtom* const atom = getAtom(i);
  38675. delete atom;
  38676. }
  38677. atoms.clear();
  38678. }
  38679. int getNumAtoms() const throw()
  38680. {
  38681. return atoms.size();
  38682. }
  38683. TextAtom* getAtom (const int index) const throw()
  38684. {
  38685. return (TextAtom*) atoms.getUnchecked (index);
  38686. }
  38687. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  38688. {
  38689. if (other.atoms.size() > 0)
  38690. {
  38691. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  38692. int i = 0;
  38693. if (lastAtom != 0)
  38694. {
  38695. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  38696. {
  38697. TextAtom* const first = other.getAtom(0);
  38698. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  38699. {
  38700. lastAtom->atomText += first->atomText;
  38701. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  38702. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  38703. delete first;
  38704. ++i;
  38705. }
  38706. }
  38707. }
  38708. while (i < other.atoms.size())
  38709. {
  38710. atoms.add (other.getAtom(i));
  38711. ++i;
  38712. }
  38713. }
  38714. }
  38715. UniformTextSection* split (const int indexToBreakAt,
  38716. const tchar passwordCharacter) throw()
  38717. {
  38718. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  38719. font, colour,
  38720. passwordCharacter);
  38721. int index = 0;
  38722. for (int i = 0; i < atoms.size(); ++i)
  38723. {
  38724. TextAtom* const atom = getAtom(i);
  38725. const int nextIndex = index + atom->numChars;
  38726. if (index == indexToBreakAt)
  38727. {
  38728. int j;
  38729. for (j = i; j < atoms.size(); ++j)
  38730. section2->atoms.add (getAtom (j));
  38731. for (j = atoms.size(); --j >= i;)
  38732. atoms.remove (j);
  38733. break;
  38734. }
  38735. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  38736. {
  38737. TextAtom* const secondAtom = new TextAtom();
  38738. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  38739. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  38740. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  38741. section2->atoms.add (secondAtom);
  38742. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  38743. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38744. atom->numChars = (uint16) (indexToBreakAt - index);
  38745. int j;
  38746. for (j = i + 1; j < atoms.size(); ++j)
  38747. section2->atoms.add (getAtom (j));
  38748. for (j = atoms.size(); --j > i;)
  38749. atoms.remove (j);
  38750. break;
  38751. }
  38752. index = nextIndex;
  38753. }
  38754. return section2;
  38755. }
  38756. const String getAllText() const throw()
  38757. {
  38758. String s;
  38759. s.preallocateStorage (getTotalLength());
  38760. tchar* endOfString = (tchar*) &(s[0]);
  38761. for (int i = 0; i < atoms.size(); ++i)
  38762. {
  38763. const TextAtom* const atom = getAtom(i);
  38764. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  38765. endOfString += atom->numChars;
  38766. }
  38767. *endOfString = 0;
  38768. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  38769. return s;
  38770. }
  38771. const String getTextSubstring (const int startCharacter,
  38772. const int endCharacter) const throw()
  38773. {
  38774. int index = 0;
  38775. int totalLen = 0;
  38776. int i;
  38777. for (i = 0; i < atoms.size(); ++i)
  38778. {
  38779. const TextAtom* const atom = getAtom (i);
  38780. const int nextIndex = index + atom->numChars;
  38781. if (startCharacter < nextIndex)
  38782. {
  38783. if (endCharacter <= index)
  38784. break;
  38785. const int start = jmax (0, startCharacter - index);
  38786. const int end = jmin (endCharacter - index, atom->numChars);
  38787. jassert (end >= start);
  38788. totalLen += end - start;
  38789. }
  38790. index = nextIndex;
  38791. }
  38792. String s;
  38793. s.preallocateStorage (totalLen + 1);
  38794. tchar* psz = (tchar*) (const tchar*) s;
  38795. index = 0;
  38796. for (i = 0; i < atoms.size(); ++i)
  38797. {
  38798. const TextAtom* const atom = getAtom (i);
  38799. const int nextIndex = index + atom->numChars;
  38800. if (startCharacter < nextIndex)
  38801. {
  38802. if (endCharacter <= index)
  38803. break;
  38804. const int start = jmax (0, startCharacter - index);
  38805. const int len = jmin (endCharacter - index, atom->numChars) - start;
  38806. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  38807. psz += len;
  38808. *psz = 0;
  38809. }
  38810. index = nextIndex;
  38811. }
  38812. return s;
  38813. }
  38814. int getTotalLength() const throw()
  38815. {
  38816. int c = 0;
  38817. for (int i = atoms.size(); --i >= 0;)
  38818. c += getAtom(i)->numChars;
  38819. return c;
  38820. }
  38821. void setFont (const Font& newFont,
  38822. const tchar passwordCharacter) throw()
  38823. {
  38824. if (font != newFont)
  38825. {
  38826. font = newFont;
  38827. for (int i = atoms.size(); --i >= 0;)
  38828. {
  38829. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  38830. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  38831. }
  38832. }
  38833. }
  38834. juce_UseDebuggingNewOperator
  38835. Font font;
  38836. Colour colour;
  38837. private:
  38838. VoidArray atoms;
  38839. void initialiseAtoms (const String& textToParse,
  38840. const tchar passwordCharacter) throw()
  38841. {
  38842. int i = 0;
  38843. const int len = textToParse.length();
  38844. const tchar* const text = (const tchar*) textToParse;
  38845. while (i < len)
  38846. {
  38847. int start = i;
  38848. // create a whitespace atom unless it starts with non-ws
  38849. if (CharacterFunctions::isWhitespace (text[i])
  38850. && text[i] != T('\r')
  38851. && text[i] != T('\n'))
  38852. {
  38853. while (i < len
  38854. && CharacterFunctions::isWhitespace (text[i])
  38855. && text[i] != T('\r')
  38856. && text[i] != T('\n'))
  38857. {
  38858. ++i;
  38859. }
  38860. }
  38861. else
  38862. {
  38863. if (text[i] == T('\r'))
  38864. {
  38865. ++i;
  38866. if ((i < len) && (text[i] == T('\n')))
  38867. {
  38868. ++start;
  38869. ++i;
  38870. }
  38871. }
  38872. else if (text[i] == T('\n'))
  38873. {
  38874. ++i;
  38875. }
  38876. else
  38877. {
  38878. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  38879. ++i;
  38880. }
  38881. }
  38882. TextAtom* const atom = new TextAtom();
  38883. atom->atomText = String (text + start, i - start);
  38884. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38885. atom->numChars = (uint16) (i - start);
  38886. atoms.add (atom);
  38887. }
  38888. }
  38889. const UniformTextSection& operator= (const UniformTextSection& other);
  38890. };
  38891. class TextEditorIterator
  38892. {
  38893. public:
  38894. TextEditorIterator (const VoidArray& sections_,
  38895. const float wordWrapWidth_,
  38896. const tchar passwordCharacter_) throw()
  38897. : indexInText (0),
  38898. lineY (0),
  38899. lineHeight (0),
  38900. maxDescent (0),
  38901. atomX (0),
  38902. atomRight (0),
  38903. atom (0),
  38904. currentSection (0),
  38905. sections (sections_),
  38906. sectionIndex (0),
  38907. atomIndex (0),
  38908. wordWrapWidth (wordWrapWidth_),
  38909. passwordCharacter (passwordCharacter_)
  38910. {
  38911. jassert (wordWrapWidth_ > 0);
  38912. if (sections.size() > 0)
  38913. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  38914. if (currentSection != 0)
  38915. {
  38916. lineHeight = currentSection->font.getHeight();
  38917. maxDescent = currentSection->font.getDescent();
  38918. }
  38919. }
  38920. TextEditorIterator (const TextEditorIterator& other) throw()
  38921. : indexInText (other.indexInText),
  38922. lineY (other.lineY),
  38923. lineHeight (other.lineHeight),
  38924. maxDescent (other.maxDescent),
  38925. atomX (other.atomX),
  38926. atomRight (other.atomRight),
  38927. atom (other.atom),
  38928. currentSection (other.currentSection),
  38929. sections (other.sections),
  38930. sectionIndex (other.sectionIndex),
  38931. atomIndex (other.atomIndex),
  38932. wordWrapWidth (other.wordWrapWidth),
  38933. passwordCharacter (other.passwordCharacter),
  38934. tempAtom (other.tempAtom)
  38935. {
  38936. }
  38937. ~TextEditorIterator() throw()
  38938. {
  38939. }
  38940. bool next() throw()
  38941. {
  38942. if (atom == &tempAtom)
  38943. {
  38944. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  38945. if (numRemaining > 0)
  38946. {
  38947. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  38948. atomX = 0;
  38949. if (tempAtom.numChars > 0)
  38950. lineY += lineHeight;
  38951. indexInText += tempAtom.numChars;
  38952. GlyphArrangement g;
  38953. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  38954. int split;
  38955. for (split = 0; split < g.getNumGlyphs(); ++split)
  38956. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  38957. break;
  38958. if (split > 0 && split <= numRemaining)
  38959. {
  38960. tempAtom.numChars = (uint16) split;
  38961. tempAtom.width = g.getGlyph (split - 1).getRight();
  38962. atomRight = atomX + tempAtom.width;
  38963. return true;
  38964. }
  38965. }
  38966. }
  38967. bool forceNewLine = false;
  38968. if (sectionIndex >= sections.size())
  38969. {
  38970. moveToEndOfLastAtom();
  38971. return false;
  38972. }
  38973. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  38974. {
  38975. if (atomIndex >= currentSection->getNumAtoms())
  38976. {
  38977. if (++sectionIndex >= sections.size())
  38978. {
  38979. moveToEndOfLastAtom();
  38980. return false;
  38981. }
  38982. atomIndex = 0;
  38983. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  38984. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  38985. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  38986. }
  38987. else
  38988. {
  38989. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  38990. if (! lastAtom->isWhitespace())
  38991. {
  38992. // handle the case where the last atom in a section is actually part of the same
  38993. // word as the first atom of the next section...
  38994. float right = atomRight + lastAtom->width;
  38995. float lineHeight2 = lineHeight;
  38996. float maxDescent2 = maxDescent;
  38997. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  38998. {
  38999. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  39000. if (s->getNumAtoms() == 0)
  39001. break;
  39002. const TextAtom* const nextAtom = s->getAtom (0);
  39003. if (nextAtom->isWhitespace())
  39004. break;
  39005. right += nextAtom->width;
  39006. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  39007. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  39008. if (SHOULD_WRAP (right, wordWrapWidth))
  39009. {
  39010. lineHeight = lineHeight2;
  39011. maxDescent = maxDescent2;
  39012. forceNewLine = true;
  39013. break;
  39014. }
  39015. if (s->getNumAtoms() > 1)
  39016. break;
  39017. }
  39018. }
  39019. }
  39020. }
  39021. if (atom != 0)
  39022. {
  39023. atomX = atomRight;
  39024. indexInText += atom->numChars;
  39025. if (atom->isNewLine())
  39026. {
  39027. atomX = 0;
  39028. lineY += lineHeight;
  39029. }
  39030. }
  39031. atom = currentSection->getAtom (atomIndex);
  39032. atomRight = atomX + atom->width;
  39033. ++atomIndex;
  39034. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  39035. {
  39036. if (atom->isWhitespace())
  39037. {
  39038. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  39039. atomRight = jmin (atomRight, wordWrapWidth);
  39040. }
  39041. else
  39042. {
  39043. return wrapCurrentAtom();
  39044. }
  39045. }
  39046. return true;
  39047. }
  39048. bool wrapCurrentAtom() throw()
  39049. {
  39050. atomRight = atom->width;
  39051. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  39052. {
  39053. tempAtom = *atom;
  39054. tempAtom.width = 0;
  39055. tempAtom.numChars = 0;
  39056. atom = &tempAtom;
  39057. if (atomX > 0)
  39058. {
  39059. atomX = 0;
  39060. lineY += lineHeight;
  39061. }
  39062. return next();
  39063. }
  39064. atomX = 0;
  39065. lineY += lineHeight;
  39066. return true;
  39067. }
  39068. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  39069. {
  39070. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39071. {
  39072. if (lastSection != currentSection)
  39073. {
  39074. lastSection = currentSection;
  39075. g.setColour (currentSection->colour);
  39076. g.setFont (currentSection->font);
  39077. }
  39078. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  39079. GlyphArrangement ga;
  39080. ga.addLineOfText (currentSection->font,
  39081. atom->getTrimmedText (passwordCharacter),
  39082. atomX,
  39083. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39084. ga.draw (g);
  39085. }
  39086. }
  39087. void drawSelection (Graphics& g,
  39088. const int selectionStart,
  39089. const int selectionEnd) const throw()
  39090. {
  39091. const int startX = roundFloatToInt (indexToX (selectionStart));
  39092. const int endX = roundFloatToInt (indexToX (selectionEnd));
  39093. const int y = roundFloatToInt (lineY);
  39094. const int nextY = roundFloatToInt (lineY + lineHeight);
  39095. g.fillRect (startX, y, endX - startX, nextY - y);
  39096. }
  39097. void drawSelectedText (Graphics& g,
  39098. const int selectionStart,
  39099. const int selectionEnd,
  39100. const Colour& selectedTextColour) const throw()
  39101. {
  39102. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39103. {
  39104. GlyphArrangement ga;
  39105. ga.addLineOfText (currentSection->font,
  39106. atom->getTrimmedText (passwordCharacter),
  39107. atomX,
  39108. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39109. if (selectionEnd < indexInText + atom->numChars)
  39110. {
  39111. GlyphArrangement ga2 (ga);
  39112. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  39113. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  39114. g.setColour (currentSection->colour);
  39115. ga2.draw (g);
  39116. }
  39117. if (selectionStart > indexInText)
  39118. {
  39119. GlyphArrangement ga2 (ga);
  39120. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  39121. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  39122. g.setColour (currentSection->colour);
  39123. ga2.draw (g);
  39124. }
  39125. g.setColour (selectedTextColour);
  39126. ga.draw (g);
  39127. }
  39128. }
  39129. float indexToX (const int indexToFind) const throw()
  39130. {
  39131. if (indexToFind <= indexInText)
  39132. return atomX;
  39133. if (indexToFind >= indexInText + atom->numChars)
  39134. return atomRight;
  39135. GlyphArrangement g;
  39136. g.addLineOfText (currentSection->font,
  39137. atom->getText (passwordCharacter),
  39138. atomX, 0.0f);
  39139. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  39140. }
  39141. int xToIndex (const float xToFind) const throw()
  39142. {
  39143. if (xToFind <= atomX || atom->isNewLine())
  39144. return indexInText;
  39145. if (xToFind >= atomRight)
  39146. return indexInText + atom->numChars;
  39147. GlyphArrangement g;
  39148. g.addLineOfText (currentSection->font,
  39149. atom->getText (passwordCharacter),
  39150. atomX, 0.0f);
  39151. int j;
  39152. for (j = 0; j < atom->numChars; ++j)
  39153. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  39154. break;
  39155. return indexInText + j;
  39156. }
  39157. void updateLineHeight() throw()
  39158. {
  39159. float x = atomRight;
  39160. int tempSectionIndex = sectionIndex;
  39161. int tempAtomIndex = atomIndex;
  39162. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39163. while (! SHOULD_WRAP (x, wordWrapWidth))
  39164. {
  39165. if (tempSectionIndex >= sections.size())
  39166. break;
  39167. bool checkSize = false;
  39168. if (tempAtomIndex >= currentSection->getNumAtoms())
  39169. {
  39170. if (++tempSectionIndex >= sections.size())
  39171. break;
  39172. tempAtomIndex = 0;
  39173. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39174. checkSize = true;
  39175. }
  39176. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  39177. if (atom == 0)
  39178. break;
  39179. x += atom->width;
  39180. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  39181. break;
  39182. if (checkSize)
  39183. {
  39184. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39185. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39186. }
  39187. ++tempAtomIndex;
  39188. }
  39189. }
  39190. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  39191. {
  39192. while (next())
  39193. {
  39194. if (indexInText + atom->numChars >= index)
  39195. {
  39196. updateLineHeight();
  39197. if (indexInText + atom->numChars > index)
  39198. {
  39199. cx = indexToX (index);
  39200. cy = lineY;
  39201. lineHeight_ = lineHeight;
  39202. return true;
  39203. }
  39204. }
  39205. }
  39206. cx = atomX;
  39207. cy = lineY;
  39208. lineHeight_ = lineHeight;
  39209. return false;
  39210. }
  39211. juce_UseDebuggingNewOperator
  39212. int indexInText;
  39213. float lineY, lineHeight, maxDescent;
  39214. float atomX, atomRight;
  39215. const TextAtom* atom;
  39216. const UniformTextSection* currentSection;
  39217. private:
  39218. const VoidArray& sections;
  39219. int sectionIndex, atomIndex;
  39220. const float wordWrapWidth;
  39221. const tchar passwordCharacter;
  39222. TextAtom tempAtom;
  39223. const TextEditorIterator& operator= (const TextEditorIterator&);
  39224. void moveToEndOfLastAtom() throw()
  39225. {
  39226. if (atom != 0)
  39227. {
  39228. atomX = atomRight;
  39229. if (atom->isNewLine())
  39230. {
  39231. atomX = 0.0f;
  39232. lineY += lineHeight;
  39233. }
  39234. }
  39235. }
  39236. };
  39237. class TextEditorInsertAction : public UndoableAction
  39238. {
  39239. TextEditor& owner;
  39240. const String text;
  39241. const int insertIndex, oldCaretPos, newCaretPos;
  39242. const Font font;
  39243. const Colour colour;
  39244. TextEditorInsertAction (const TextEditorInsertAction&);
  39245. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  39246. public:
  39247. TextEditorInsertAction (TextEditor& owner_,
  39248. const String& text_,
  39249. const int insertIndex_,
  39250. const Font& font_,
  39251. const Colour& colour_,
  39252. const int oldCaretPos_,
  39253. const int newCaretPos_) throw()
  39254. : owner (owner_),
  39255. text (text_),
  39256. insertIndex (insertIndex_),
  39257. oldCaretPos (oldCaretPos_),
  39258. newCaretPos (newCaretPos_),
  39259. font (font_),
  39260. colour (colour_)
  39261. {
  39262. }
  39263. ~TextEditorInsertAction()
  39264. {
  39265. }
  39266. bool perform()
  39267. {
  39268. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  39269. return true;
  39270. }
  39271. bool undo()
  39272. {
  39273. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  39274. return true;
  39275. }
  39276. int getSizeInUnits()
  39277. {
  39278. return text.length() + 16;
  39279. }
  39280. };
  39281. class TextEditorRemoveAction : public UndoableAction
  39282. {
  39283. TextEditor& owner;
  39284. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  39285. VoidArray removedSections;
  39286. TextEditorRemoveAction (const TextEditorRemoveAction&);
  39287. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  39288. public:
  39289. TextEditorRemoveAction (TextEditor& owner_,
  39290. const int startIndex_,
  39291. const int endIndex_,
  39292. const int oldCaretPos_,
  39293. const int newCaretPos_,
  39294. const VoidArray& removedSections_) throw()
  39295. : owner (owner_),
  39296. startIndex (startIndex_),
  39297. endIndex (endIndex_),
  39298. oldCaretPos (oldCaretPos_),
  39299. newCaretPos (newCaretPos_),
  39300. removedSections (removedSections_)
  39301. {
  39302. }
  39303. ~TextEditorRemoveAction()
  39304. {
  39305. for (int i = removedSections.size(); --i >= 0;)
  39306. {
  39307. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39308. section->clear();
  39309. delete section;
  39310. }
  39311. }
  39312. bool perform()
  39313. {
  39314. owner.remove (startIndex, endIndex, 0, newCaretPos);
  39315. return true;
  39316. }
  39317. bool undo()
  39318. {
  39319. owner.reinsert (startIndex, removedSections);
  39320. owner.moveCursorTo (oldCaretPos, false);
  39321. return true;
  39322. }
  39323. int getSizeInUnits()
  39324. {
  39325. int n = 0;
  39326. for (int i = removedSections.size(); --i >= 0;)
  39327. {
  39328. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39329. n += section->getTotalLength();
  39330. }
  39331. return n + 16;
  39332. }
  39333. };
  39334. class TextHolderComponent : public Component,
  39335. public Timer
  39336. {
  39337. TextEditor* const owner;
  39338. TextHolderComponent (const TextHolderComponent&);
  39339. const TextHolderComponent& operator= (const TextHolderComponent&);
  39340. public:
  39341. TextHolderComponent (TextEditor* const owner_)
  39342. : owner (owner_)
  39343. {
  39344. setWantsKeyboardFocus (false);
  39345. setInterceptsMouseClicks (false, true);
  39346. }
  39347. ~TextHolderComponent()
  39348. {
  39349. }
  39350. void paint (Graphics& g)
  39351. {
  39352. owner->drawContent (g);
  39353. }
  39354. void timerCallback()
  39355. {
  39356. owner->timerCallbackInt();
  39357. }
  39358. const MouseCursor getMouseCursor()
  39359. {
  39360. return owner->getMouseCursor();
  39361. }
  39362. };
  39363. class TextEditorViewport : public Viewport
  39364. {
  39365. TextEditor* const owner;
  39366. float lastWordWrapWidth;
  39367. TextEditorViewport (const TextEditorViewport&);
  39368. const TextEditorViewport& operator= (const TextEditorViewport&);
  39369. public:
  39370. TextEditorViewport (TextEditor* const owner_)
  39371. : owner (owner_),
  39372. lastWordWrapWidth (0)
  39373. {
  39374. }
  39375. ~TextEditorViewport()
  39376. {
  39377. }
  39378. void visibleAreaChanged (int, int, int, int)
  39379. {
  39380. const float wordWrapWidth = owner->getWordWrapWidth();
  39381. if (wordWrapWidth != lastWordWrapWidth)
  39382. {
  39383. lastWordWrapWidth = wordWrapWidth;
  39384. owner->updateTextHolderSize();
  39385. }
  39386. }
  39387. };
  39388. const int flashSpeedIntervalMs = 380;
  39389. const int textChangeMessageId = 0x10003001;
  39390. const int returnKeyMessageId = 0x10003002;
  39391. const int escapeKeyMessageId = 0x10003003;
  39392. const int focusLossMessageId = 0x10003004;
  39393. TextEditor::TextEditor (const String& name,
  39394. const tchar passwordCharacter_)
  39395. : Component (name),
  39396. borderSize (1, 1, 1, 3),
  39397. readOnly (false),
  39398. multiline (false),
  39399. wordWrap (false),
  39400. returnKeyStartsNewLine (false),
  39401. caretVisible (true),
  39402. popupMenuEnabled (true),
  39403. selectAllTextWhenFocused (false),
  39404. scrollbarVisible (true),
  39405. wasFocused (false),
  39406. caretFlashState (true),
  39407. keepCursorOnScreen (true),
  39408. tabKeyUsed (false),
  39409. menuActive (false),
  39410. cursorX (0),
  39411. cursorY (0),
  39412. cursorHeight (0),
  39413. maxTextLength (0),
  39414. selectionStart (0),
  39415. selectionEnd (0),
  39416. leftIndent (4),
  39417. topIndent (4),
  39418. lastTransactionTime (0),
  39419. currentFont (14.0f),
  39420. totalNumChars (0),
  39421. caretPosition (0),
  39422. sections (8),
  39423. passwordCharacter (passwordCharacter_),
  39424. dragType (notDragging),
  39425. listeners (2)
  39426. {
  39427. setOpaque (true);
  39428. addAndMakeVisible (viewport = new TextEditorViewport (this));
  39429. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  39430. viewport->setWantsKeyboardFocus (false);
  39431. viewport->setScrollBarsShown (false, false);
  39432. setMouseCursor (MouseCursor::IBeamCursor);
  39433. setWantsKeyboardFocus (true);
  39434. }
  39435. TextEditor::~TextEditor()
  39436. {
  39437. clearInternal (0);
  39438. delete viewport;
  39439. }
  39440. void TextEditor::newTransaction() throw()
  39441. {
  39442. lastTransactionTime = Time::getApproximateMillisecondCounter();
  39443. undoManager.beginNewTransaction();
  39444. }
  39445. void TextEditor::doUndoRedo (const bool isRedo)
  39446. {
  39447. if (! isReadOnly())
  39448. {
  39449. if ((isRedo) ? undoManager.redo()
  39450. : undoManager.undo())
  39451. {
  39452. scrollToMakeSureCursorIsVisible();
  39453. repaint();
  39454. textChanged();
  39455. }
  39456. }
  39457. }
  39458. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  39459. const bool shouldWordWrap)
  39460. {
  39461. multiline = shouldBeMultiLine;
  39462. wordWrap = shouldWordWrap && shouldBeMultiLine;
  39463. setScrollbarsShown (scrollbarVisible);
  39464. viewport->setViewPosition (0, 0);
  39465. resized();
  39466. scrollToMakeSureCursorIsVisible();
  39467. }
  39468. bool TextEditor::isMultiLine() const throw()
  39469. {
  39470. return multiline;
  39471. }
  39472. void TextEditor::setScrollbarsShown (bool enabled) throw()
  39473. {
  39474. scrollbarVisible = enabled;
  39475. enabled = enabled && isMultiLine();
  39476. viewport->setScrollBarsShown (enabled, enabled);
  39477. }
  39478. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  39479. {
  39480. readOnly = shouldBeReadOnly;
  39481. enablementChanged();
  39482. }
  39483. bool TextEditor::isReadOnly() const throw()
  39484. {
  39485. return readOnly || ! isEnabled();
  39486. }
  39487. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  39488. {
  39489. returnKeyStartsNewLine = shouldStartNewLine;
  39490. }
  39491. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  39492. {
  39493. tabKeyUsed = shouldTabKeyBeUsed;
  39494. }
  39495. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  39496. {
  39497. popupMenuEnabled = b;
  39498. }
  39499. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  39500. {
  39501. selectAllTextWhenFocused = b;
  39502. }
  39503. const Font TextEditor::getFont() const throw()
  39504. {
  39505. return currentFont;
  39506. }
  39507. void TextEditor::setFont (const Font& newFont) throw()
  39508. {
  39509. currentFont = newFont;
  39510. scrollToMakeSureCursorIsVisible();
  39511. }
  39512. void TextEditor::applyFontToAllText (const Font& newFont)
  39513. {
  39514. currentFont = newFont;
  39515. const Colour overallColour (findColour (textColourId));
  39516. for (int i = sections.size(); --i >= 0;)
  39517. {
  39518. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  39519. uts->setFont (newFont, passwordCharacter);
  39520. uts->colour = overallColour;
  39521. }
  39522. coalesceSimilarSections();
  39523. updateTextHolderSize();
  39524. scrollToMakeSureCursorIsVisible();
  39525. repaint();
  39526. }
  39527. void TextEditor::colourChanged()
  39528. {
  39529. setOpaque (findColour (backgroundColourId).isOpaque());
  39530. repaint();
  39531. }
  39532. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  39533. {
  39534. caretVisible = shouldCaretBeVisible;
  39535. if (shouldCaretBeVisible)
  39536. textHolder->startTimer (flashSpeedIntervalMs);
  39537. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  39538. : MouseCursor::NormalCursor);
  39539. }
  39540. void TextEditor::setInputRestrictions (const int maxLen,
  39541. const String& chars) throw()
  39542. {
  39543. maxTextLength = jmax (0, maxLen);
  39544. allowedCharacters = chars;
  39545. }
  39546. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  39547. {
  39548. textToShowWhenEmpty = text;
  39549. colourForTextWhenEmpty = colourToUse;
  39550. }
  39551. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  39552. {
  39553. if (passwordCharacter != newPasswordCharacter)
  39554. {
  39555. passwordCharacter = newPasswordCharacter;
  39556. resized();
  39557. repaint();
  39558. }
  39559. }
  39560. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  39561. {
  39562. viewport->setScrollBarThickness (newThicknessPixels);
  39563. }
  39564. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  39565. {
  39566. viewport->setScrollBarButtonVisibility (buttonsVisible);
  39567. }
  39568. void TextEditor::clear()
  39569. {
  39570. clearInternal (0);
  39571. updateTextHolderSize();
  39572. undoManager.clearUndoHistory();
  39573. }
  39574. void TextEditor::setText (const String& newText,
  39575. const bool sendTextChangeMessage)
  39576. {
  39577. const int newLength = newText.length();
  39578. if (newLength != getTotalNumChars() || getText() != newText)
  39579. {
  39580. const int oldCursorPos = caretPosition;
  39581. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  39582. clearInternal (0);
  39583. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  39584. // if you're adding text with line-feeds to a single-line text editor, it
  39585. // ain't gonna look right!
  39586. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  39587. if (cursorWasAtEnd && ! isMultiLine())
  39588. moveCursorTo (getTotalNumChars(), false);
  39589. else
  39590. moveCursorTo (oldCursorPos, false);
  39591. if (sendTextChangeMessage)
  39592. textChanged();
  39593. repaint();
  39594. }
  39595. updateTextHolderSize();
  39596. scrollToMakeSureCursorIsVisible();
  39597. undoManager.clearUndoHistory();
  39598. }
  39599. void TextEditor::textChanged() throw()
  39600. {
  39601. updateTextHolderSize();
  39602. postCommandMessage (textChangeMessageId);
  39603. }
  39604. void TextEditor::returnPressed()
  39605. {
  39606. postCommandMessage (returnKeyMessageId);
  39607. }
  39608. void TextEditor::escapePressed()
  39609. {
  39610. postCommandMessage (escapeKeyMessageId);
  39611. }
  39612. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  39613. {
  39614. jassert (newListener != 0)
  39615. if (newListener != 0)
  39616. listeners.add (newListener);
  39617. }
  39618. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  39619. {
  39620. listeners.removeValue (listenerToRemove);
  39621. }
  39622. void TextEditor::timerCallbackInt()
  39623. {
  39624. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  39625. if (caretFlashState != newState)
  39626. {
  39627. caretFlashState = newState;
  39628. if (caretFlashState)
  39629. wasFocused = true;
  39630. if (caretVisible
  39631. && hasKeyboardFocus (false)
  39632. && ! isReadOnly())
  39633. {
  39634. repaintCaret();
  39635. }
  39636. }
  39637. const unsigned int now = Time::getApproximateMillisecondCounter();
  39638. if (now > lastTransactionTime + 200)
  39639. newTransaction();
  39640. }
  39641. void TextEditor::repaintCaret()
  39642. {
  39643. if (! findColour (caretColourId).isTransparent())
  39644. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  39645. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  39646. 4,
  39647. roundFloatToInt (cursorHeight) + 2);
  39648. }
  39649. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  39650. {
  39651. if (textStartIndex > textEndIndex && textEndIndex > 0)
  39652. swapVariables (textStartIndex, textEndIndex);
  39653. float x = 0, y = 0, lh = currentFont.getHeight();
  39654. const float wordWrapWidth = getWordWrapWidth();
  39655. if (wordWrapWidth > 0)
  39656. {
  39657. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39658. i.getCharPosition (textStartIndex, x, y, lh);
  39659. const int y1 = (int) y;
  39660. int y2;
  39661. if (textEndIndex >= 0)
  39662. {
  39663. i.getCharPosition (textEndIndex, x, y, lh);
  39664. y2 = (int) (y + lh * 2.0f);
  39665. }
  39666. else
  39667. {
  39668. y2 = textHolder->getHeight();
  39669. }
  39670. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  39671. }
  39672. }
  39673. void TextEditor::moveCaret (int newCaretPos) throw()
  39674. {
  39675. if (newCaretPos < 0)
  39676. newCaretPos = 0;
  39677. else if (newCaretPos > getTotalNumChars())
  39678. newCaretPos = getTotalNumChars();
  39679. if (newCaretPos != getCaretPosition())
  39680. {
  39681. repaintCaret();
  39682. caretFlashState = true;
  39683. caretPosition = newCaretPos;
  39684. textHolder->startTimer (flashSpeedIntervalMs);
  39685. scrollToMakeSureCursorIsVisible();
  39686. repaintCaret();
  39687. }
  39688. }
  39689. void TextEditor::setCaretPosition (const int newIndex) throw()
  39690. {
  39691. moveCursorTo (newIndex, false);
  39692. }
  39693. int TextEditor::getCaretPosition() const throw()
  39694. {
  39695. return caretPosition;
  39696. }
  39697. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  39698. const int desiredCaretY) throw()
  39699. {
  39700. updateCaretPosition();
  39701. int vx = roundFloatToInt (cursorX) - desiredCaretX;
  39702. int vy = roundFloatToInt (cursorY) - desiredCaretY;
  39703. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  39704. {
  39705. vx += desiredCaretX - proportionOfWidth (0.2f);
  39706. }
  39707. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39708. {
  39709. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39710. }
  39711. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  39712. if (! isMultiLine())
  39713. {
  39714. vy = viewport->getViewPositionY();
  39715. }
  39716. else
  39717. {
  39718. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  39719. const int curH = roundFloatToInt (cursorHeight);
  39720. if (desiredCaretY < 0)
  39721. {
  39722. vy = jmax (0, desiredCaretY + vy);
  39723. }
  39724. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39725. {
  39726. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39727. }
  39728. }
  39729. viewport->setViewPosition (vx, vy);
  39730. }
  39731. const Rectangle TextEditor::getCaretRectangle() throw()
  39732. {
  39733. updateCaretPosition();
  39734. return Rectangle (roundFloatToInt (cursorX) - viewport->getX(),
  39735. roundFloatToInt (cursorY) - viewport->getY(),
  39736. 1, roundFloatToInt (cursorHeight));
  39737. }
  39738. float TextEditor::getWordWrapWidth() const throw()
  39739. {
  39740. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  39741. : 1.0e10f;
  39742. }
  39743. void TextEditor::updateTextHolderSize() throw()
  39744. {
  39745. const float wordWrapWidth = getWordWrapWidth();
  39746. if (wordWrapWidth > 0)
  39747. {
  39748. float maxWidth = 0.0f;
  39749. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39750. while (i.next())
  39751. maxWidth = jmax (maxWidth, i.atomRight);
  39752. const int w = leftIndent + roundFloatToInt (maxWidth);
  39753. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  39754. currentFont.getHeight()));
  39755. textHolder->setSize (w + 1, h + 1);
  39756. }
  39757. }
  39758. int TextEditor::getTextWidth() const throw()
  39759. {
  39760. return textHolder->getWidth();
  39761. }
  39762. int TextEditor::getTextHeight() const throw()
  39763. {
  39764. return textHolder->getHeight();
  39765. }
  39766. void TextEditor::setIndents (const int newLeftIndent,
  39767. const int newTopIndent) throw()
  39768. {
  39769. leftIndent = newLeftIndent;
  39770. topIndent = newTopIndent;
  39771. }
  39772. void TextEditor::setBorder (const BorderSize& border) throw()
  39773. {
  39774. borderSize = border;
  39775. resized();
  39776. }
  39777. const BorderSize TextEditor::getBorder() const throw()
  39778. {
  39779. return borderSize;
  39780. }
  39781. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  39782. {
  39783. keepCursorOnScreen = shouldScrollToShowCursor;
  39784. }
  39785. void TextEditor::updateCaretPosition() throw()
  39786. {
  39787. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  39788. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  39789. }
  39790. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  39791. {
  39792. updateCaretPosition();
  39793. if (keepCursorOnScreen)
  39794. {
  39795. int x = viewport->getViewPositionX();
  39796. int y = viewport->getViewPositionY();
  39797. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  39798. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  39799. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  39800. {
  39801. x += relativeCursorX - proportionOfWidth (0.2f);
  39802. }
  39803. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39804. {
  39805. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39806. }
  39807. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  39808. if (! isMultiLine())
  39809. {
  39810. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  39811. }
  39812. else
  39813. {
  39814. const int curH = roundFloatToInt (cursorHeight);
  39815. if (relativeCursorY < 0)
  39816. {
  39817. y = jmax (0, relativeCursorY + y);
  39818. }
  39819. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39820. {
  39821. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39822. }
  39823. }
  39824. viewport->setViewPosition (x, y);
  39825. }
  39826. }
  39827. void TextEditor::moveCursorTo (const int newPosition,
  39828. const bool isSelecting) throw()
  39829. {
  39830. if (isSelecting)
  39831. {
  39832. moveCaret (newPosition);
  39833. const int oldSelStart = selectionStart;
  39834. const int oldSelEnd = selectionEnd;
  39835. if (dragType == notDragging)
  39836. {
  39837. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  39838. dragType = draggingSelectionStart;
  39839. else
  39840. dragType = draggingSelectionEnd;
  39841. }
  39842. if (dragType == draggingSelectionStart)
  39843. {
  39844. selectionStart = getCaretPosition();
  39845. if (selectionEnd < selectionStart)
  39846. {
  39847. swapVariables (selectionStart, selectionEnd);
  39848. dragType = draggingSelectionEnd;
  39849. }
  39850. }
  39851. else
  39852. {
  39853. selectionEnd = getCaretPosition();
  39854. if (selectionEnd < selectionStart)
  39855. {
  39856. swapVariables (selectionStart, selectionEnd);
  39857. dragType = draggingSelectionStart;
  39858. }
  39859. }
  39860. jassert (selectionStart <= selectionEnd);
  39861. jassert (oldSelStart <= oldSelEnd);
  39862. repaintText (jmin (oldSelStart, selectionStart),
  39863. jmax (oldSelEnd, selectionEnd));
  39864. }
  39865. else
  39866. {
  39867. dragType = notDragging;
  39868. if (selectionEnd > selectionStart)
  39869. repaintText (selectionStart, selectionEnd);
  39870. moveCaret (newPosition);
  39871. selectionStart = getCaretPosition();
  39872. selectionEnd = getCaretPosition();
  39873. }
  39874. }
  39875. int TextEditor::getTextIndexAt (const int x,
  39876. const int y) throw()
  39877. {
  39878. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  39879. (float) (y + viewport->getViewPositionY() - topIndent));
  39880. }
  39881. void TextEditor::insertTextAtCursor (String newText)
  39882. {
  39883. if (allowedCharacters.isNotEmpty())
  39884. newText = newText.retainCharacters (allowedCharacters);
  39885. if (! isMultiLine())
  39886. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  39887. else
  39888. newText = newText.replace (T("\r\n"), T("\n"));
  39889. const int newCaretPos = selectionStart + newText.length();
  39890. const int insertIndex = selectionStart;
  39891. remove (selectionStart, selectionEnd,
  39892. &undoManager,
  39893. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  39894. if (maxTextLength > 0)
  39895. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  39896. if (newText.isNotEmpty())
  39897. insert (newText,
  39898. insertIndex,
  39899. currentFont,
  39900. findColour (textColourId),
  39901. &undoManager,
  39902. newCaretPos);
  39903. textChanged();
  39904. }
  39905. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  39906. {
  39907. moveCursorTo (startPos, false);
  39908. moveCursorTo (startPos + numChars, true);
  39909. }
  39910. void TextEditor::copy()
  39911. {
  39912. if (passwordCharacter == 0)
  39913. {
  39914. const String selection (getTextSubstring (selectionStart, selectionEnd));
  39915. if (selection.isNotEmpty())
  39916. SystemClipboard::copyTextToClipboard (selection);
  39917. }
  39918. }
  39919. void TextEditor::paste()
  39920. {
  39921. if (! isReadOnly())
  39922. {
  39923. const String clip (SystemClipboard::getTextFromClipboard());
  39924. if (clip.isNotEmpty())
  39925. insertTextAtCursor (clip);
  39926. }
  39927. }
  39928. void TextEditor::cut()
  39929. {
  39930. if (! isReadOnly())
  39931. {
  39932. moveCaret (selectionEnd);
  39933. insertTextAtCursor (String::empty);
  39934. }
  39935. }
  39936. void TextEditor::drawContent (Graphics& g)
  39937. {
  39938. const float wordWrapWidth = getWordWrapWidth();
  39939. if (wordWrapWidth > 0)
  39940. {
  39941. g.setOrigin (leftIndent, topIndent);
  39942. const Rectangle clip (g.getClipBounds());
  39943. Colour selectedTextColour;
  39944. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39945. while (i.lineY + 200.0 < clip.getY() && i.next())
  39946. {}
  39947. if (selectionStart < selectionEnd)
  39948. {
  39949. g.setColour (findColour (highlightColourId)
  39950. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  39951. selectedTextColour = findColour (highlightedTextColourId);
  39952. TextEditorIterator i2 (i);
  39953. while (i2.next() && i2.lineY < clip.getBottom())
  39954. {
  39955. i2.updateLineHeight();
  39956. if (i2.lineY + i2.lineHeight >= clip.getY()
  39957. && selectionEnd >= i2.indexInText
  39958. && selectionStart <= i2.indexInText + i2.atom->numChars)
  39959. {
  39960. i2.drawSelection (g, selectionStart, selectionEnd);
  39961. }
  39962. }
  39963. }
  39964. const UniformTextSection* lastSection = 0;
  39965. while (i.next() && i.lineY < clip.getBottom())
  39966. {
  39967. i.updateLineHeight();
  39968. if (i.lineY + i.lineHeight >= clip.getY())
  39969. {
  39970. if (selectionEnd >= i.indexInText
  39971. && selectionStart <= i.indexInText + i.atom->numChars)
  39972. {
  39973. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  39974. lastSection = 0;
  39975. }
  39976. else
  39977. {
  39978. i.draw (g, lastSection);
  39979. }
  39980. }
  39981. }
  39982. }
  39983. }
  39984. void TextEditor::paint (Graphics& g)
  39985. {
  39986. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  39987. }
  39988. void TextEditor::paintOverChildren (Graphics& g)
  39989. {
  39990. if (caretFlashState
  39991. && hasKeyboardFocus (false)
  39992. && caretVisible
  39993. && ! isReadOnly())
  39994. {
  39995. g.setColour (findColour (caretColourId));
  39996. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  39997. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  39998. 2.0f, cursorHeight);
  39999. }
  40000. if (textToShowWhenEmpty.isNotEmpty()
  40001. && (! hasKeyboardFocus (false))
  40002. && getTotalNumChars() == 0)
  40003. {
  40004. g.setColour (colourForTextWhenEmpty);
  40005. g.setFont (getFont());
  40006. if (isMultiLine())
  40007. {
  40008. g.drawText (textToShowWhenEmpty,
  40009. 0, 0, getWidth(), getHeight(),
  40010. Justification::centred, true);
  40011. }
  40012. else
  40013. {
  40014. g.drawText (textToShowWhenEmpty,
  40015. leftIndent, topIndent,
  40016. viewport->getWidth() - leftIndent,
  40017. viewport->getHeight() - topIndent,
  40018. Justification::centredLeft, true);
  40019. }
  40020. }
  40021. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  40022. }
  40023. void TextEditor::mouseDown (const MouseEvent& e)
  40024. {
  40025. beginDragAutoRepeat (100);
  40026. newTransaction();
  40027. if (wasFocused || ! selectAllTextWhenFocused)
  40028. {
  40029. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40030. {
  40031. moveCursorTo (getTextIndexAt (e.x, e.y),
  40032. e.mods.isShiftDown());
  40033. }
  40034. else
  40035. {
  40036. PopupMenu m;
  40037. addPopupMenuItems (m, &e);
  40038. menuActive = true;
  40039. const int result = m.show();
  40040. menuActive = false;
  40041. if (result != 0)
  40042. performPopupMenuAction (result);
  40043. }
  40044. }
  40045. }
  40046. void TextEditor::mouseDrag (const MouseEvent& e)
  40047. {
  40048. if (wasFocused || ! selectAllTextWhenFocused)
  40049. {
  40050. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40051. {
  40052. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  40053. }
  40054. }
  40055. }
  40056. void TextEditor::mouseUp (const MouseEvent& e)
  40057. {
  40058. newTransaction();
  40059. textHolder->startTimer (flashSpeedIntervalMs);
  40060. if (wasFocused || ! selectAllTextWhenFocused)
  40061. {
  40062. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40063. {
  40064. moveCaret (getTextIndexAt (e.x, e.y));
  40065. }
  40066. }
  40067. wasFocused = true;
  40068. }
  40069. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  40070. {
  40071. int tokenEnd = getTextIndexAt (e.x, e.y);
  40072. int tokenStart = tokenEnd;
  40073. if (e.getNumberOfClicks() > 3)
  40074. {
  40075. tokenStart = 0;
  40076. tokenEnd = getTotalNumChars();
  40077. }
  40078. else
  40079. {
  40080. const String t (getText());
  40081. const int totalLength = getTotalNumChars();
  40082. while (tokenEnd < totalLength)
  40083. {
  40084. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  40085. ++tokenEnd;
  40086. else
  40087. break;
  40088. }
  40089. tokenStart = tokenEnd;
  40090. while (tokenStart > 0)
  40091. {
  40092. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  40093. --tokenStart;
  40094. else
  40095. break;
  40096. }
  40097. if (e.getNumberOfClicks() > 2)
  40098. {
  40099. while (tokenEnd < totalLength)
  40100. {
  40101. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  40102. ++tokenEnd;
  40103. else
  40104. break;
  40105. }
  40106. while (tokenStart > 0)
  40107. {
  40108. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  40109. --tokenStart;
  40110. else
  40111. break;
  40112. }
  40113. }
  40114. }
  40115. moveCursorTo (tokenEnd, false);
  40116. moveCursorTo (tokenStart, true);
  40117. }
  40118. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40119. {
  40120. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  40121. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40122. }
  40123. bool TextEditor::keyPressed (const KeyPress& key)
  40124. {
  40125. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  40126. return false;
  40127. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  40128. if (key.isKeyCode (KeyPress::leftKey)
  40129. || key.isKeyCode (KeyPress::upKey))
  40130. {
  40131. newTransaction();
  40132. int newPos;
  40133. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  40134. newPos = indexAtPosition (cursorX, cursorY - 1);
  40135. else if (moveInWholeWordSteps)
  40136. newPos = findWordBreakBefore (getCaretPosition());
  40137. else
  40138. newPos = getCaretPosition() - 1;
  40139. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40140. }
  40141. else if (key.isKeyCode (KeyPress::rightKey)
  40142. || key.isKeyCode (KeyPress::downKey))
  40143. {
  40144. newTransaction();
  40145. int newPos;
  40146. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  40147. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  40148. else if (moveInWholeWordSteps)
  40149. newPos = findWordBreakAfter (getCaretPosition());
  40150. else
  40151. newPos = getCaretPosition() + 1;
  40152. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40153. }
  40154. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  40155. {
  40156. newTransaction();
  40157. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  40158. key.getModifiers().isShiftDown());
  40159. }
  40160. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  40161. {
  40162. newTransaction();
  40163. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  40164. key.getModifiers().isShiftDown());
  40165. }
  40166. else if (key.isKeyCode (KeyPress::homeKey))
  40167. {
  40168. newTransaction();
  40169. if (isMultiLine() && ! moveInWholeWordSteps)
  40170. moveCursorTo (indexAtPosition (0.0f, cursorY),
  40171. key.getModifiers().isShiftDown());
  40172. else
  40173. moveCursorTo (0, key.getModifiers().isShiftDown());
  40174. }
  40175. else if (key.isKeyCode (KeyPress::endKey))
  40176. {
  40177. newTransaction();
  40178. if (isMultiLine() && ! moveInWholeWordSteps)
  40179. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  40180. key.getModifiers().isShiftDown());
  40181. else
  40182. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  40183. }
  40184. else if (key.isKeyCode (KeyPress::backspaceKey))
  40185. {
  40186. if (moveInWholeWordSteps)
  40187. {
  40188. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  40189. }
  40190. else
  40191. {
  40192. if (selectionStart == selectionEnd && selectionStart > 0)
  40193. --selectionStart;
  40194. }
  40195. cut();
  40196. }
  40197. else if (key.isKeyCode (KeyPress::deleteKey))
  40198. {
  40199. if (key.getModifiers().isShiftDown())
  40200. copy();
  40201. if (selectionStart == selectionEnd
  40202. && selectionEnd < getTotalNumChars())
  40203. {
  40204. ++selectionEnd;
  40205. }
  40206. cut();
  40207. }
  40208. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  40209. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  40210. {
  40211. newTransaction();
  40212. copy();
  40213. }
  40214. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  40215. {
  40216. newTransaction();
  40217. copy();
  40218. cut();
  40219. }
  40220. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  40221. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  40222. {
  40223. newTransaction();
  40224. paste();
  40225. }
  40226. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  40227. {
  40228. newTransaction();
  40229. doUndoRedo (false);
  40230. }
  40231. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  40232. {
  40233. newTransaction();
  40234. doUndoRedo (true);
  40235. }
  40236. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  40237. {
  40238. newTransaction();
  40239. moveCursorTo (getTotalNumChars(), false);
  40240. moveCursorTo (0, true);
  40241. }
  40242. else if (key == KeyPress::returnKey)
  40243. {
  40244. newTransaction();
  40245. if (returnKeyStartsNewLine)
  40246. insertTextAtCursor (T("\n"));
  40247. else
  40248. returnPressed();
  40249. }
  40250. else if (key.isKeyCode (KeyPress::escapeKey))
  40251. {
  40252. newTransaction();
  40253. moveCursorTo (getCaretPosition(), false);
  40254. escapePressed();
  40255. }
  40256. else if (key.getTextCharacter() >= ' '
  40257. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  40258. {
  40259. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  40260. lastTransactionTime = Time::getApproximateMillisecondCounter();
  40261. }
  40262. else
  40263. {
  40264. return false;
  40265. }
  40266. return true;
  40267. }
  40268. bool TextEditor::keyStateChanged (const bool isKeyDown)
  40269. {
  40270. if (! isKeyDown)
  40271. return false;
  40272. #if JUCE_WIN32
  40273. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  40274. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  40275. #endif
  40276. // (overridden to avoid forwarding key events to the parent)
  40277. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  40278. }
  40279. const int baseMenuItemID = 0x7fff0000;
  40280. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  40281. {
  40282. const bool writable = ! isReadOnly();
  40283. if (passwordCharacter == 0)
  40284. {
  40285. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  40286. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  40287. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  40288. }
  40289. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  40290. m.addSeparator();
  40291. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  40292. m.addSeparator();
  40293. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  40294. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  40295. }
  40296. void TextEditor::performPopupMenuAction (const int menuItemID)
  40297. {
  40298. switch (menuItemID)
  40299. {
  40300. case baseMenuItemID + 1:
  40301. copy();
  40302. cut();
  40303. break;
  40304. case baseMenuItemID + 2:
  40305. copy();
  40306. break;
  40307. case baseMenuItemID + 3:
  40308. paste();
  40309. break;
  40310. case baseMenuItemID + 4:
  40311. cut();
  40312. break;
  40313. case baseMenuItemID + 5:
  40314. moveCursorTo (getTotalNumChars(), false);
  40315. moveCursorTo (0, true);
  40316. break;
  40317. case baseMenuItemID + 6:
  40318. doUndoRedo (false);
  40319. break;
  40320. case baseMenuItemID + 7:
  40321. doUndoRedo (true);
  40322. break;
  40323. default:
  40324. break;
  40325. }
  40326. }
  40327. void TextEditor::focusGained (FocusChangeType)
  40328. {
  40329. newTransaction();
  40330. caretFlashState = true;
  40331. if (selectAllTextWhenFocused)
  40332. {
  40333. moveCursorTo (0, false);
  40334. moveCursorTo (getTotalNumChars(), true);
  40335. }
  40336. repaint();
  40337. if (caretVisible)
  40338. textHolder->startTimer (flashSpeedIntervalMs);
  40339. ComponentPeer* const peer = getPeer();
  40340. if (peer != 0)
  40341. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  40342. getScreenY() - peer->getScreenY());
  40343. }
  40344. void TextEditor::focusLost (FocusChangeType)
  40345. {
  40346. newTransaction();
  40347. wasFocused = false;
  40348. textHolder->stopTimer();
  40349. caretFlashState = false;
  40350. postCommandMessage (focusLossMessageId);
  40351. repaint();
  40352. }
  40353. void TextEditor::resized()
  40354. {
  40355. viewport->setBoundsInset (borderSize);
  40356. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  40357. updateTextHolderSize();
  40358. if (! isMultiLine())
  40359. {
  40360. scrollToMakeSureCursorIsVisible();
  40361. }
  40362. else
  40363. {
  40364. updateCaretPosition();
  40365. }
  40366. }
  40367. void TextEditor::handleCommandMessage (const int commandId)
  40368. {
  40369. const ComponentDeletionWatcher deletionChecker (this);
  40370. for (int i = listeners.size(); --i >= 0;)
  40371. {
  40372. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  40373. if (tl != 0)
  40374. {
  40375. switch (commandId)
  40376. {
  40377. case textChangeMessageId:
  40378. tl->textEditorTextChanged (*this);
  40379. break;
  40380. case returnKeyMessageId:
  40381. tl->textEditorReturnKeyPressed (*this);
  40382. break;
  40383. case escapeKeyMessageId:
  40384. tl->textEditorEscapeKeyPressed (*this);
  40385. break;
  40386. case focusLossMessageId:
  40387. tl->textEditorFocusLost (*this);
  40388. break;
  40389. default:
  40390. jassertfalse
  40391. break;
  40392. }
  40393. if (i > 0 && deletionChecker.hasBeenDeleted())
  40394. return;
  40395. }
  40396. }
  40397. }
  40398. void TextEditor::enablementChanged()
  40399. {
  40400. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  40401. : MouseCursor::IBeamCursor));
  40402. repaint();
  40403. }
  40404. void TextEditor::clearInternal (UndoManager* const um) throw()
  40405. {
  40406. remove (0, getTotalNumChars(), um, caretPosition);
  40407. }
  40408. void TextEditor::insert (const String& text,
  40409. const int insertIndex,
  40410. const Font& font,
  40411. const Colour& colour,
  40412. UndoManager* const um,
  40413. const int caretPositionToMoveTo) throw()
  40414. {
  40415. if (text.isNotEmpty())
  40416. {
  40417. if (um != 0)
  40418. {
  40419. um->perform (new TextEditorInsertAction (*this,
  40420. text,
  40421. insertIndex,
  40422. font,
  40423. colour,
  40424. caretPosition,
  40425. caretPositionToMoveTo));
  40426. }
  40427. else
  40428. {
  40429. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  40430. // a line gets moved due to word wrap
  40431. int index = 0;
  40432. int nextIndex = 0;
  40433. for (int i = 0; i < sections.size(); ++i)
  40434. {
  40435. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40436. if (insertIndex == index)
  40437. {
  40438. sections.insert (i, new UniformTextSection (text,
  40439. font, colour,
  40440. passwordCharacter));
  40441. break;
  40442. }
  40443. else if (insertIndex > index && insertIndex < nextIndex)
  40444. {
  40445. splitSection (i, insertIndex - index);
  40446. sections.insert (i + 1, new UniformTextSection (text,
  40447. font, colour,
  40448. passwordCharacter));
  40449. break;
  40450. }
  40451. index = nextIndex;
  40452. }
  40453. if (nextIndex == insertIndex)
  40454. sections.add (new UniformTextSection (text,
  40455. font, colour,
  40456. passwordCharacter));
  40457. coalesceSimilarSections();
  40458. totalNumChars = -1;
  40459. moveCursorTo (caretPositionToMoveTo, false);
  40460. repaintText (insertIndex, -1);
  40461. }
  40462. }
  40463. }
  40464. void TextEditor::reinsert (const int insertIndex,
  40465. const VoidArray& sectionsToInsert) throw()
  40466. {
  40467. int index = 0;
  40468. int nextIndex = 0;
  40469. for (int i = 0; i < sections.size(); ++i)
  40470. {
  40471. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40472. if (insertIndex == index)
  40473. {
  40474. for (int j = sectionsToInsert.size(); --j >= 0;)
  40475. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40476. break;
  40477. }
  40478. else if (insertIndex > index && insertIndex < nextIndex)
  40479. {
  40480. splitSection (i, insertIndex - index);
  40481. for (int j = sectionsToInsert.size(); --j >= 0;)
  40482. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40483. break;
  40484. }
  40485. index = nextIndex;
  40486. }
  40487. if (nextIndex == insertIndex)
  40488. {
  40489. for (int j = 0; j < sectionsToInsert.size(); ++j)
  40490. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40491. }
  40492. coalesceSimilarSections();
  40493. totalNumChars = -1;
  40494. }
  40495. void TextEditor::remove (const int startIndex,
  40496. int endIndex,
  40497. UndoManager* const um,
  40498. const int caretPositionToMoveTo) throw()
  40499. {
  40500. if (endIndex > startIndex)
  40501. {
  40502. int index = 0;
  40503. for (int i = 0; i < sections.size(); ++i)
  40504. {
  40505. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  40506. if (startIndex > index && startIndex < nextIndex)
  40507. {
  40508. splitSection (i, startIndex - index);
  40509. --i;
  40510. }
  40511. else if (endIndex > index && endIndex < nextIndex)
  40512. {
  40513. splitSection (i, endIndex - index);
  40514. --i;
  40515. }
  40516. else
  40517. {
  40518. index = nextIndex;
  40519. if (index > endIndex)
  40520. break;
  40521. }
  40522. }
  40523. index = 0;
  40524. if (um != 0)
  40525. {
  40526. VoidArray removedSections;
  40527. for (int i = 0; i < sections.size(); ++i)
  40528. {
  40529. if (endIndex <= startIndex)
  40530. break;
  40531. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40532. const int nextIndex = index + section->getTotalLength();
  40533. if (startIndex <= index && endIndex >= nextIndex)
  40534. removedSections.add (new UniformTextSection (*section));
  40535. index = nextIndex;
  40536. }
  40537. um->perform (new TextEditorRemoveAction (*this,
  40538. startIndex,
  40539. endIndex,
  40540. caretPosition,
  40541. caretPositionToMoveTo,
  40542. removedSections));
  40543. }
  40544. else
  40545. {
  40546. for (int i = 0; i < sections.size(); ++i)
  40547. {
  40548. if (endIndex <= startIndex)
  40549. break;
  40550. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40551. const int nextIndex = index + section->getTotalLength();
  40552. if (startIndex <= index && endIndex >= nextIndex)
  40553. {
  40554. sections.remove(i);
  40555. endIndex -= (nextIndex - index);
  40556. section->clear();
  40557. delete section;
  40558. --i;
  40559. }
  40560. else
  40561. {
  40562. index = nextIndex;
  40563. }
  40564. }
  40565. coalesceSimilarSections();
  40566. totalNumChars = -1;
  40567. moveCursorTo (caretPositionToMoveTo, false);
  40568. repaintText (startIndex, -1);
  40569. }
  40570. }
  40571. }
  40572. const String TextEditor::getText() const throw()
  40573. {
  40574. String t;
  40575. for (int i = 0; i < sections.size(); ++i)
  40576. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  40577. return t;
  40578. }
  40579. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  40580. {
  40581. String t;
  40582. int index = 0;
  40583. for (int i = 0; i < sections.size(); ++i)
  40584. {
  40585. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  40586. const int nextIndex = index + s->getTotalLength();
  40587. if (startCharacter < nextIndex)
  40588. {
  40589. if (endCharacter <= index)
  40590. break;
  40591. const int start = jmax (index, startCharacter);
  40592. t += s->getTextSubstring (start - index, endCharacter - index);
  40593. }
  40594. index = nextIndex;
  40595. }
  40596. return t;
  40597. }
  40598. const String TextEditor::getHighlightedText() const throw()
  40599. {
  40600. return getTextSubstring (getHighlightedRegionStart(),
  40601. getHighlightedRegionStart() + getHighlightedRegionLength());
  40602. }
  40603. int TextEditor::getTotalNumChars() throw()
  40604. {
  40605. if (totalNumChars < 0)
  40606. {
  40607. totalNumChars = 0;
  40608. for (int i = sections.size(); --i >= 0;)
  40609. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40610. }
  40611. return totalNumChars;
  40612. }
  40613. bool TextEditor::isEmpty() const throw()
  40614. {
  40615. if (totalNumChars != 0)
  40616. {
  40617. for (int i = sections.size(); --i >= 0;)
  40618. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  40619. return false;
  40620. }
  40621. return true;
  40622. }
  40623. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  40624. {
  40625. const float wordWrapWidth = getWordWrapWidth();
  40626. if (wordWrapWidth > 0 && sections.size() > 0)
  40627. {
  40628. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40629. i.getCharPosition (index, cx, cy, lineHeight);
  40630. }
  40631. else
  40632. {
  40633. cx = cy = 0;
  40634. lineHeight = currentFont.getHeight();
  40635. }
  40636. }
  40637. int TextEditor::indexAtPosition (const float x, const float y) throw()
  40638. {
  40639. const float wordWrapWidth = getWordWrapWidth();
  40640. if (wordWrapWidth > 0)
  40641. {
  40642. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40643. while (i.next())
  40644. {
  40645. if (i.lineY + getHeight() > y)
  40646. i.updateLineHeight();
  40647. if (i.lineY + i.lineHeight > y)
  40648. {
  40649. if (i.lineY > y)
  40650. return jmax (0, i.indexInText - 1);
  40651. if (i.atomX >= x)
  40652. return i.indexInText;
  40653. if (x < i.atomRight)
  40654. return i.xToIndex (x);
  40655. }
  40656. }
  40657. }
  40658. return getTotalNumChars();
  40659. }
  40660. static int getCharacterCategory (const tchar character) throw()
  40661. {
  40662. return CharacterFunctions::isLetterOrDigit (character)
  40663. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  40664. }
  40665. int TextEditor::findWordBreakAfter (const int position) const throw()
  40666. {
  40667. const String t (getTextSubstring (position, position + 512));
  40668. const int totalLength = t.length();
  40669. int i = 0;
  40670. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40671. ++i;
  40672. const int type = getCharacterCategory (t[i]);
  40673. while (i < totalLength && type == getCharacterCategory (t[i]))
  40674. ++i;
  40675. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40676. ++i;
  40677. return position + i;
  40678. }
  40679. int TextEditor::findWordBreakBefore (const int position) const throw()
  40680. {
  40681. if (position <= 0)
  40682. return 0;
  40683. const int startOfBuffer = jmax (0, position - 512);
  40684. const String t (getTextSubstring (startOfBuffer, position));
  40685. int i = position - startOfBuffer;
  40686. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  40687. --i;
  40688. if (i > 0)
  40689. {
  40690. const int type = getCharacterCategory (t [i - 1]);
  40691. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  40692. --i;
  40693. }
  40694. jassert (startOfBuffer + i >= 0);
  40695. return startOfBuffer + i;
  40696. }
  40697. void TextEditor::splitSection (const int sectionIndex,
  40698. const int charToSplitAt) throw()
  40699. {
  40700. jassert (sections[sectionIndex] != 0);
  40701. sections.insert (sectionIndex + 1,
  40702. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  40703. ->split (charToSplitAt, passwordCharacter));
  40704. }
  40705. void TextEditor::coalesceSimilarSections() throw()
  40706. {
  40707. for (int i = 0; i < sections.size() - 1; ++i)
  40708. {
  40709. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  40710. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  40711. if (s1->font == s2->font
  40712. && s1->colour == s2->colour)
  40713. {
  40714. s1->append (*s2, passwordCharacter);
  40715. sections.remove (i + 1);
  40716. delete s2;
  40717. --i;
  40718. }
  40719. }
  40720. }
  40721. END_JUCE_NAMESPACE
  40722. /********* End of inlined file: juce_TextEditor.cpp *********/
  40723. /********* Start of inlined file: juce_Toolbar.cpp *********/
  40724. BEGIN_JUCE_NAMESPACE
  40725. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  40726. class ToolbarSpacerComp : public ToolbarItemComponent
  40727. {
  40728. public:
  40729. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  40730. : ToolbarItemComponent (itemId, String::empty, false),
  40731. fixedSize (fixedSize_),
  40732. drawBar (drawBar_)
  40733. {
  40734. }
  40735. ~ToolbarSpacerComp()
  40736. {
  40737. }
  40738. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  40739. int& preferredSize, int& minSize, int& maxSize)
  40740. {
  40741. if (fixedSize <= 0)
  40742. {
  40743. preferredSize = toolbarThickness * 2;
  40744. minSize = 4;
  40745. maxSize = 32768;
  40746. }
  40747. else
  40748. {
  40749. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  40750. minSize = drawBar ? maxSize : jmin (4, maxSize);
  40751. preferredSize = maxSize;
  40752. if (getEditingMode() == editableOnPalette)
  40753. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  40754. }
  40755. return true;
  40756. }
  40757. void paintButtonArea (Graphics&, int, int, bool, bool)
  40758. {
  40759. }
  40760. void contentAreaChanged (const Rectangle&)
  40761. {
  40762. }
  40763. int getResizeOrder() const throw()
  40764. {
  40765. return fixedSize <= 0 ? 0 : 1;
  40766. }
  40767. void paint (Graphics& g)
  40768. {
  40769. const int w = getWidth();
  40770. const int h = getHeight();
  40771. if (drawBar)
  40772. {
  40773. g.setColour (findColour (Toolbar::separatorColourId, true));
  40774. const float thickness = 0.2f;
  40775. if (isToolbarVertical())
  40776. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  40777. else
  40778. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  40779. }
  40780. if (getEditingMode() != normalMode && ! drawBar)
  40781. {
  40782. g.setColour (findColour (Toolbar::separatorColourId, true));
  40783. const int indentX = jmin (2, (w - 3) / 2);
  40784. const int indentY = jmin (2, (h - 3) / 2);
  40785. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  40786. if (fixedSize <= 0)
  40787. {
  40788. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  40789. if (isToolbarVertical())
  40790. {
  40791. x1 = w * 0.5f;
  40792. y1 = h * 0.4f;
  40793. x2 = x1;
  40794. y2 = indentX * 2.0f;
  40795. x3 = x1;
  40796. y3 = h * 0.6f;
  40797. x4 = x1;
  40798. y4 = h - y2;
  40799. hw = w * 0.15f;
  40800. hl = w * 0.2f;
  40801. }
  40802. else
  40803. {
  40804. x1 = w * 0.4f;
  40805. y1 = h * 0.5f;
  40806. x2 = indentX * 2.0f;
  40807. y2 = y1;
  40808. x3 = w * 0.6f;
  40809. y3 = y1;
  40810. x4 = w - x2;
  40811. y4 = y1;
  40812. hw = h * 0.15f;
  40813. hl = h * 0.2f;
  40814. }
  40815. Path p;
  40816. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  40817. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  40818. g.fillPath (p);
  40819. }
  40820. }
  40821. }
  40822. juce_UseDebuggingNewOperator
  40823. private:
  40824. const float fixedSize;
  40825. const bool drawBar;
  40826. ToolbarSpacerComp (const ToolbarSpacerComp&);
  40827. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  40828. };
  40829. class MissingItemsComponent : public PopupMenuCustomComponent
  40830. {
  40831. public:
  40832. MissingItemsComponent (Toolbar& owner_, const int height_)
  40833. : PopupMenuCustomComponent (true),
  40834. owner (owner_),
  40835. height (height_)
  40836. {
  40837. for (int i = owner_.items.size(); --i >= 0;)
  40838. {
  40839. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  40840. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  40841. {
  40842. oldIndexes.insert (0, i);
  40843. addAndMakeVisible (tc, 0);
  40844. }
  40845. }
  40846. layout (400);
  40847. }
  40848. ~MissingItemsComponent()
  40849. {
  40850. // deleting the toolbar while its menu it open??
  40851. jassert (owner.isValidComponent());
  40852. for (int i = 0; i < getNumChildComponents(); ++i)
  40853. {
  40854. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  40855. if (tc != 0)
  40856. {
  40857. tc->setVisible (false);
  40858. const int index = oldIndexes.remove (i);
  40859. owner.addChildComponent (tc, index);
  40860. --i;
  40861. }
  40862. }
  40863. owner.resized();
  40864. }
  40865. void layout (const int preferredWidth)
  40866. {
  40867. const int indent = 8;
  40868. int x = indent;
  40869. int y = indent;
  40870. int maxX = 0;
  40871. for (int i = 0; i < getNumChildComponents(); ++i)
  40872. {
  40873. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  40874. if (tc != 0)
  40875. {
  40876. int preferredSize = 1, minSize = 1, maxSize = 1;
  40877. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  40878. {
  40879. if (x + preferredSize > preferredWidth && x > indent)
  40880. {
  40881. x = indent;
  40882. y += height;
  40883. }
  40884. tc->setBounds (x, y, preferredSize, height);
  40885. x += preferredSize;
  40886. maxX = jmax (maxX, x);
  40887. }
  40888. }
  40889. }
  40890. setSize (maxX + 8, y + height + 8);
  40891. }
  40892. void getIdealSize (int& idealWidth, int& idealHeight)
  40893. {
  40894. idealWidth = getWidth();
  40895. idealHeight = getHeight();
  40896. }
  40897. juce_UseDebuggingNewOperator
  40898. private:
  40899. Toolbar& owner;
  40900. const int height;
  40901. Array <int> oldIndexes;
  40902. MissingItemsComponent (const MissingItemsComponent&);
  40903. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  40904. };
  40905. Toolbar::Toolbar()
  40906. : vertical (false),
  40907. isEditingActive (false),
  40908. toolbarStyle (Toolbar::iconsOnly)
  40909. {
  40910. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  40911. missingItemsButton->setAlwaysOnTop (true);
  40912. missingItemsButton->addButtonListener (this);
  40913. }
  40914. Toolbar::~Toolbar()
  40915. {
  40916. animator.cancelAllAnimations (true);
  40917. deleteAllChildren();
  40918. }
  40919. void Toolbar::setVertical (const bool shouldBeVertical)
  40920. {
  40921. if (vertical != shouldBeVertical)
  40922. {
  40923. vertical = shouldBeVertical;
  40924. resized();
  40925. }
  40926. }
  40927. void Toolbar::clear()
  40928. {
  40929. for (int i = items.size(); --i >= 0;)
  40930. {
  40931. ToolbarItemComponent* const tc = items.getUnchecked(i);
  40932. items.remove (i);
  40933. delete tc;
  40934. }
  40935. resized();
  40936. }
  40937. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  40938. {
  40939. if (itemId == ToolbarItemFactory::separatorBarId)
  40940. return new ToolbarSpacerComp (itemId, 0.1f, true);
  40941. else if (itemId == ToolbarItemFactory::spacerId)
  40942. return new ToolbarSpacerComp (itemId, 0.5f, false);
  40943. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  40944. return new ToolbarSpacerComp (itemId, 0, false);
  40945. return factory.createItem (itemId);
  40946. }
  40947. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  40948. const int itemId,
  40949. const int insertIndex)
  40950. {
  40951. // An ID can't be zero - this might indicate a mistake somewhere?
  40952. jassert (itemId != 0);
  40953. ToolbarItemComponent* const tc = createItem (factory, itemId);
  40954. if (tc != 0)
  40955. {
  40956. #ifdef JUCE_DEBUG
  40957. Array <int> allowedIds;
  40958. factory.getAllToolbarItemIds (allowedIds);
  40959. // If your factory can create an item for a given ID, it must also return
  40960. // that ID from its getAllToolbarItemIds() method!
  40961. jassert (allowedIds.contains (itemId));
  40962. #endif
  40963. items.insert (insertIndex, tc);
  40964. addAndMakeVisible (tc, insertIndex);
  40965. }
  40966. }
  40967. void Toolbar::addItem (ToolbarItemFactory& factory,
  40968. const int itemId,
  40969. const int insertIndex)
  40970. {
  40971. addItemInternal (factory, itemId, insertIndex);
  40972. resized();
  40973. }
  40974. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  40975. {
  40976. Array <int> ids;
  40977. factoryToUse.getDefaultItemSet (ids);
  40978. clear();
  40979. for (int i = 0; i < ids.size(); ++i)
  40980. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  40981. resized();
  40982. }
  40983. void Toolbar::removeToolbarItem (const int itemIndex)
  40984. {
  40985. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  40986. if (tc != 0)
  40987. {
  40988. items.removeValue (tc);
  40989. delete tc;
  40990. resized();
  40991. }
  40992. }
  40993. int Toolbar::getNumItems() const throw()
  40994. {
  40995. return items.size();
  40996. }
  40997. int Toolbar::getItemId (const int itemIndex) const throw()
  40998. {
  40999. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  41000. return tc != 0 ? tc->getItemId() : 0;
  41001. }
  41002. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  41003. {
  41004. return items [itemIndex];
  41005. }
  41006. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  41007. {
  41008. for (;;)
  41009. {
  41010. index += delta;
  41011. ToolbarItemComponent* const tc = getItemComponent (index);
  41012. if (tc == 0)
  41013. break;
  41014. if (tc->isActive)
  41015. return tc;
  41016. }
  41017. return 0;
  41018. }
  41019. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  41020. {
  41021. if (toolbarStyle != newStyle)
  41022. {
  41023. toolbarStyle = newStyle;
  41024. updateAllItemPositions (false);
  41025. }
  41026. }
  41027. const String Toolbar::toString() const
  41028. {
  41029. String s (T("TB:"));
  41030. for (int i = 0; i < getNumItems(); ++i)
  41031. s << getItemId(i) << T(' ');
  41032. return s.trimEnd();
  41033. }
  41034. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  41035. const String& savedVersion)
  41036. {
  41037. if (! savedVersion.startsWith (T("TB:")))
  41038. return false;
  41039. StringArray tokens;
  41040. tokens.addTokens (savedVersion.substring (3), false);
  41041. clear();
  41042. for (int i = 0; i < tokens.size(); ++i)
  41043. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  41044. resized();
  41045. return true;
  41046. }
  41047. void Toolbar::paint (Graphics& g)
  41048. {
  41049. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  41050. }
  41051. int Toolbar::getThickness() const throw()
  41052. {
  41053. return vertical ? getWidth() : getHeight();
  41054. }
  41055. int Toolbar::getLength() const throw()
  41056. {
  41057. return vertical ? getHeight() : getWidth();
  41058. }
  41059. void Toolbar::setEditingActive (const bool active)
  41060. {
  41061. if (isEditingActive != active)
  41062. {
  41063. isEditingActive = active;
  41064. updateAllItemPositions (false);
  41065. }
  41066. }
  41067. void Toolbar::resized()
  41068. {
  41069. updateAllItemPositions (false);
  41070. }
  41071. void Toolbar::updateAllItemPositions (const bool animate)
  41072. {
  41073. if (getWidth() > 0 && getHeight() > 0)
  41074. {
  41075. StretchableObjectResizer resizer;
  41076. int i;
  41077. for (i = 0; i < items.size(); ++i)
  41078. {
  41079. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41080. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  41081. : ToolbarItemComponent::normalMode);
  41082. tc->setStyle (toolbarStyle);
  41083. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  41084. int preferredSize = 1, minSize = 1, maxSize = 1;
  41085. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  41086. preferredSize, minSize, maxSize))
  41087. {
  41088. tc->isActive = true;
  41089. resizer.addItem (preferredSize, minSize, maxSize,
  41090. spacer != 0 ? spacer->getResizeOrder() : 2);
  41091. }
  41092. else
  41093. {
  41094. tc->isActive = false;
  41095. tc->setVisible (false);
  41096. }
  41097. }
  41098. resizer.resizeToFit (getLength());
  41099. int totalLength = 0;
  41100. for (i = 0; i < resizer.getNumItems(); ++i)
  41101. totalLength += (int) resizer.getItemSize (i);
  41102. const bool itemsOffTheEnd = totalLength > getLength();
  41103. const int extrasButtonSize = getThickness() / 2;
  41104. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  41105. missingItemsButton->setVisible (itemsOffTheEnd);
  41106. missingItemsButton->setEnabled (! isEditingActive);
  41107. if (vertical)
  41108. missingItemsButton->setCentrePosition (getWidth() / 2,
  41109. getHeight() - 4 - extrasButtonSize / 2);
  41110. else
  41111. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  41112. getHeight() / 2);
  41113. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  41114. : missingItemsButton->getX()) - 4
  41115. : getLength();
  41116. int pos = 0, activeIndex = 0;
  41117. for (i = 0; i < items.size(); ++i)
  41118. {
  41119. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41120. if (tc->isActive)
  41121. {
  41122. const int size = (int) resizer.getItemSize (activeIndex++);
  41123. Rectangle newBounds;
  41124. if (vertical)
  41125. newBounds.setBounds (0, pos, getWidth(), size);
  41126. else
  41127. newBounds.setBounds (pos, 0, size, getHeight());
  41128. if (animate)
  41129. {
  41130. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  41131. }
  41132. else
  41133. {
  41134. animator.cancelAnimation (tc, false);
  41135. tc->setBounds (newBounds);
  41136. }
  41137. pos += size;
  41138. tc->setVisible (pos <= maxLength
  41139. && ((! tc->isBeingDragged)
  41140. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  41141. }
  41142. }
  41143. }
  41144. }
  41145. void Toolbar::buttonClicked (Button*)
  41146. {
  41147. jassert (missingItemsButton->isShowing());
  41148. if (missingItemsButton->isShowing())
  41149. {
  41150. PopupMenu m;
  41151. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  41152. m.showAt (missingItemsButton);
  41153. }
  41154. }
  41155. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  41156. Component* /*sourceComponent*/)
  41157. {
  41158. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  41159. }
  41160. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  41161. {
  41162. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41163. if (tc != 0)
  41164. {
  41165. if (getNumItems() == 0)
  41166. {
  41167. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41168. {
  41169. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41170. if (palette != 0)
  41171. palette->replaceComponent (tc);
  41172. }
  41173. else
  41174. {
  41175. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41176. }
  41177. items.add (tc);
  41178. addChildComponent (tc);
  41179. updateAllItemPositions (false);
  41180. }
  41181. else
  41182. {
  41183. for (int i = getNumItems(); --i >= 0;)
  41184. {
  41185. int currentIndex = getIndexOfChildComponent (tc);
  41186. if (currentIndex < 0)
  41187. {
  41188. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41189. {
  41190. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41191. if (palette != 0)
  41192. palette->replaceComponent (tc);
  41193. }
  41194. else
  41195. {
  41196. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41197. }
  41198. items.add (tc);
  41199. addChildComponent (tc);
  41200. currentIndex = getIndexOfChildComponent (tc);
  41201. updateAllItemPositions (true);
  41202. }
  41203. int newIndex = currentIndex;
  41204. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  41205. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  41206. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  41207. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  41208. if (prev != 0)
  41209. {
  41210. const Rectangle previousPos (animator.getComponentDestination (prev));
  41211. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  41212. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  41213. {
  41214. newIndex = getIndexOfChildComponent (prev);
  41215. }
  41216. }
  41217. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  41218. if (next != 0)
  41219. {
  41220. const Rectangle nextPos (animator.getComponentDestination (next));
  41221. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  41222. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  41223. {
  41224. newIndex = getIndexOfChildComponent (next) + 1;
  41225. }
  41226. }
  41227. if (newIndex != currentIndex)
  41228. {
  41229. items.removeValue (tc);
  41230. removeChildComponent (tc);
  41231. addChildComponent (tc, newIndex);
  41232. items.insert (newIndex, tc);
  41233. updateAllItemPositions (true);
  41234. }
  41235. else
  41236. {
  41237. break;
  41238. }
  41239. }
  41240. }
  41241. }
  41242. }
  41243. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  41244. {
  41245. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41246. if (tc != 0)
  41247. {
  41248. if (isParentOf (tc))
  41249. {
  41250. items.removeValue (tc);
  41251. removeChildComponent (tc);
  41252. updateAllItemPositions (true);
  41253. }
  41254. }
  41255. }
  41256. void Toolbar::itemDropped (const String&, Component*, int, int)
  41257. {
  41258. }
  41259. void Toolbar::mouseDown (const MouseEvent& e)
  41260. {
  41261. if (e.mods.isPopupMenu())
  41262. {
  41263. }
  41264. }
  41265. class ToolbarCustomisationDialog : public DialogWindow
  41266. {
  41267. public:
  41268. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  41269. Toolbar* const toolbar_,
  41270. const int optionFlags)
  41271. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  41272. toolbar (toolbar_)
  41273. {
  41274. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  41275. setResizable (true, true);
  41276. setResizeLimits (400, 300, 1500, 1000);
  41277. positionNearBar();
  41278. }
  41279. ~ToolbarCustomisationDialog()
  41280. {
  41281. setContentComponent (0, true);
  41282. }
  41283. void closeButtonPressed()
  41284. {
  41285. setVisible (false);
  41286. }
  41287. bool canModalEventBeSentToComponent (const Component* comp)
  41288. {
  41289. return toolbar->isParentOf (comp);
  41290. }
  41291. void positionNearBar()
  41292. {
  41293. const Rectangle screenSize (toolbar->getParentMonitorArea());
  41294. const int tbx = toolbar->getScreenX();
  41295. const int tby = toolbar->getScreenY();
  41296. const int gap = 8;
  41297. int x, y;
  41298. if (toolbar->isVertical())
  41299. {
  41300. y = tby;
  41301. if (tbx > screenSize.getCentreX())
  41302. x = tbx - getWidth() - gap;
  41303. else
  41304. x = tbx + toolbar->getWidth() + gap;
  41305. }
  41306. else
  41307. {
  41308. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  41309. if (tby > screenSize.getCentreY())
  41310. y = tby - getHeight() - gap;
  41311. else
  41312. y = tby + toolbar->getHeight() + gap;
  41313. }
  41314. setTopLeftPosition (x, y);
  41315. }
  41316. private:
  41317. Toolbar* const toolbar;
  41318. class CustomiserPanel : public Component,
  41319. private ComboBoxListener,
  41320. private ButtonListener
  41321. {
  41322. public:
  41323. CustomiserPanel (ToolbarItemFactory& factory_,
  41324. Toolbar* const toolbar_,
  41325. const int optionFlags)
  41326. : factory (factory_),
  41327. toolbar (toolbar_),
  41328. styleBox (0),
  41329. defaultButton (0)
  41330. {
  41331. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  41332. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  41333. | Toolbar::allowIconsWithTextChoice
  41334. | Toolbar::allowTextOnlyChoice)) != 0)
  41335. {
  41336. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  41337. styleBox->setEditableText (false);
  41338. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  41339. styleBox->addItem (TRANS("Show icons only"), 1);
  41340. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  41341. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  41342. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  41343. styleBox->addItem (TRANS("Show descriptions only"), 3);
  41344. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  41345. styleBox->setSelectedId (1);
  41346. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  41347. styleBox->setSelectedId (2);
  41348. else if (toolbar_->getStyle() == Toolbar::textOnly)
  41349. styleBox->setSelectedId (3);
  41350. styleBox->addListener (this);
  41351. }
  41352. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  41353. {
  41354. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  41355. defaultButton->addButtonListener (this);
  41356. }
  41357. addAndMakeVisible (instructions = new Label (String::empty,
  41358. 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.")));
  41359. instructions->setFont (Font (13.0f));
  41360. setSize (500, 300);
  41361. }
  41362. ~CustomiserPanel()
  41363. {
  41364. deleteAllChildren();
  41365. }
  41366. void comboBoxChanged (ComboBox*)
  41367. {
  41368. if (styleBox->getSelectedId() == 1)
  41369. toolbar->setStyle (Toolbar::iconsOnly);
  41370. else if (styleBox->getSelectedId() == 2)
  41371. toolbar->setStyle (Toolbar::iconsWithText);
  41372. else if (styleBox->getSelectedId() == 3)
  41373. toolbar->setStyle (Toolbar::textOnly);
  41374. palette->resized(); // to make it update the styles
  41375. }
  41376. void buttonClicked (Button*)
  41377. {
  41378. toolbar->addDefaultItems (factory);
  41379. }
  41380. void paint (Graphics& g)
  41381. {
  41382. Colour background;
  41383. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  41384. if (dw != 0)
  41385. background = dw->getBackgroundColour();
  41386. g.setColour (background.contrasting().withAlpha (0.3f));
  41387. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  41388. }
  41389. void resized()
  41390. {
  41391. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  41392. if (styleBox != 0)
  41393. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  41394. if (defaultButton != 0)
  41395. {
  41396. defaultButton->changeWidthToFitText (22);
  41397. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  41398. }
  41399. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  41400. }
  41401. private:
  41402. ToolbarItemFactory& factory;
  41403. Toolbar* const toolbar;
  41404. Label* instructions;
  41405. ToolbarItemPalette* palette;
  41406. ComboBox* styleBox;
  41407. TextButton* defaultButton;
  41408. };
  41409. };
  41410. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  41411. {
  41412. setEditingActive (true);
  41413. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  41414. dw.runModalLoop();
  41415. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  41416. setEditingActive (false);
  41417. }
  41418. END_JUCE_NAMESPACE
  41419. /********* End of inlined file: juce_Toolbar.cpp *********/
  41420. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  41421. BEGIN_JUCE_NAMESPACE
  41422. ToolbarItemFactory::ToolbarItemFactory()
  41423. {
  41424. }
  41425. ToolbarItemFactory::~ToolbarItemFactory()
  41426. {
  41427. }
  41428. class ItemDragAndDropOverlayComponent : public Component
  41429. {
  41430. public:
  41431. ItemDragAndDropOverlayComponent()
  41432. : isDragging (false)
  41433. {
  41434. setAlwaysOnTop (true);
  41435. setRepaintsOnMouseActivity (true);
  41436. setMouseCursor (MouseCursor::DraggingHandCursor);
  41437. }
  41438. ~ItemDragAndDropOverlayComponent()
  41439. {
  41440. }
  41441. void paint (Graphics& g)
  41442. {
  41443. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41444. if (isMouseOverOrDragging()
  41445. && tc != 0
  41446. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41447. {
  41448. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  41449. g.drawRect (0, 0, getWidth(), getHeight(),
  41450. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  41451. }
  41452. }
  41453. void mouseDown (const MouseEvent& e)
  41454. {
  41455. isDragging = false;
  41456. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41457. if (tc != 0)
  41458. {
  41459. tc->dragOffsetX = e.x;
  41460. tc->dragOffsetY = e.y;
  41461. }
  41462. }
  41463. void mouseDrag (const MouseEvent& e)
  41464. {
  41465. if (! (isDragging || e.mouseWasClicked()))
  41466. {
  41467. isDragging = true;
  41468. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  41469. if (dnd != 0)
  41470. {
  41471. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  41472. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41473. if (tc != 0)
  41474. {
  41475. tc->isBeingDragged = true;
  41476. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41477. tc->setVisible (false);
  41478. }
  41479. }
  41480. }
  41481. }
  41482. void mouseUp (const MouseEvent&)
  41483. {
  41484. isDragging = false;
  41485. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41486. if (tc != 0)
  41487. {
  41488. tc->isBeingDragged = false;
  41489. Toolbar* const tb = tc->getToolbar();
  41490. if (tb != 0)
  41491. tb->updateAllItemPositions (true);
  41492. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41493. delete tc;
  41494. }
  41495. }
  41496. void parentSizeChanged()
  41497. {
  41498. setBounds (0, 0, getParentWidth(), getParentHeight());
  41499. }
  41500. juce_UseDebuggingNewOperator
  41501. private:
  41502. bool isDragging;
  41503. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  41504. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  41505. };
  41506. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  41507. const String& labelText,
  41508. const bool isBeingUsedAsAButton_)
  41509. : Button (labelText),
  41510. itemId (itemId_),
  41511. mode (normalMode),
  41512. toolbarStyle (Toolbar::iconsOnly),
  41513. overlayComp (0),
  41514. dragOffsetX (0),
  41515. dragOffsetY (0),
  41516. isActive (true),
  41517. isBeingDragged (false),
  41518. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  41519. {
  41520. // Your item ID can't be 0!
  41521. jassert (itemId_ != 0);
  41522. }
  41523. ToolbarItemComponent::~ToolbarItemComponent()
  41524. {
  41525. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41526. delete overlayComp;
  41527. }
  41528. Toolbar* ToolbarItemComponent::getToolbar() const
  41529. {
  41530. return dynamic_cast <Toolbar*> (getParentComponent());
  41531. }
  41532. bool ToolbarItemComponent::isToolbarVertical() const
  41533. {
  41534. const Toolbar* const t = getToolbar();
  41535. return t != 0 && t->isVertical();
  41536. }
  41537. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  41538. {
  41539. if (toolbarStyle != newStyle)
  41540. {
  41541. toolbarStyle = newStyle;
  41542. repaint();
  41543. resized();
  41544. }
  41545. }
  41546. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  41547. {
  41548. if (isBeingUsedAsAButton)
  41549. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  41550. isMouseOver, isMouseDown, *this);
  41551. if (toolbarStyle != Toolbar::iconsOnly)
  41552. {
  41553. const int indent = contentArea.getX();
  41554. int y = indent;
  41555. int h = getHeight() - indent * 2;
  41556. if (toolbarStyle == Toolbar::iconsWithText)
  41557. {
  41558. y = contentArea.getBottom() + indent / 2;
  41559. h -= contentArea.getHeight();
  41560. }
  41561. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  41562. getButtonText(), *this);
  41563. }
  41564. if (! contentArea.isEmpty())
  41565. {
  41566. g.saveState();
  41567. g.setOrigin (contentArea.getX(), contentArea.getY());
  41568. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  41569. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  41570. g.restoreState();
  41571. }
  41572. }
  41573. void ToolbarItemComponent::resized()
  41574. {
  41575. if (toolbarStyle != Toolbar::textOnly)
  41576. {
  41577. const int indent = jmin (proportionOfWidth (0.08f),
  41578. proportionOfHeight (0.08f));
  41579. contentArea = Rectangle (indent, indent,
  41580. getWidth() - indent * 2,
  41581. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  41582. : (getHeight() - indent * 2));
  41583. }
  41584. else
  41585. {
  41586. contentArea = Rectangle();
  41587. }
  41588. contentAreaChanged (contentArea);
  41589. }
  41590. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  41591. {
  41592. if (mode != newMode)
  41593. {
  41594. mode = newMode;
  41595. repaint();
  41596. if (mode == normalMode)
  41597. {
  41598. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41599. delete overlayComp;
  41600. overlayComp = 0;
  41601. }
  41602. else if (overlayComp == 0)
  41603. {
  41604. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  41605. overlayComp->parentSizeChanged();
  41606. }
  41607. resized();
  41608. }
  41609. }
  41610. END_JUCE_NAMESPACE
  41611. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  41612. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  41613. BEGIN_JUCE_NAMESPACE
  41614. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  41615. Toolbar* const toolbar_)
  41616. : factory (factory_),
  41617. toolbar (toolbar_)
  41618. {
  41619. Component* const itemHolder = new Component();
  41620. Array <int> allIds;
  41621. factory_.getAllToolbarItemIds (allIds);
  41622. for (int i = 0; i < allIds.size(); ++i)
  41623. {
  41624. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  41625. jassert (tc != 0);
  41626. if (tc != 0)
  41627. {
  41628. itemHolder->addAndMakeVisible (tc);
  41629. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  41630. }
  41631. }
  41632. viewport = new Viewport();
  41633. viewport->setViewedComponent (itemHolder);
  41634. addAndMakeVisible (viewport);
  41635. }
  41636. ToolbarItemPalette::~ToolbarItemPalette()
  41637. {
  41638. viewport->getViewedComponent()->deleteAllChildren();
  41639. deleteAllChildren();
  41640. }
  41641. void ToolbarItemPalette::resized()
  41642. {
  41643. viewport->setBoundsInset (BorderSize (1));
  41644. Component* const itemHolder = viewport->getViewedComponent();
  41645. const int indent = 8;
  41646. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  41647. const int height = toolbar->getThickness();
  41648. int x = indent;
  41649. int y = indent;
  41650. int maxX = 0;
  41651. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  41652. {
  41653. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  41654. if (tc != 0)
  41655. {
  41656. tc->setStyle (toolbar->getStyle());
  41657. int preferredSize = 1, minSize = 1, maxSize = 1;
  41658. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  41659. {
  41660. if (x + preferredSize > preferredWidth && x > indent)
  41661. {
  41662. x = indent;
  41663. y += height;
  41664. }
  41665. tc->setBounds (x, y, preferredSize, height);
  41666. x += preferredSize + 8;
  41667. maxX = jmax (maxX, x);
  41668. }
  41669. }
  41670. }
  41671. itemHolder->setSize (maxX, y + height + 8);
  41672. }
  41673. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  41674. {
  41675. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  41676. jassert (tc != 0);
  41677. if (tc != 0)
  41678. {
  41679. tc->setBounds (comp->getBounds());
  41680. tc->setStyle (toolbar->getStyle());
  41681. tc->setEditingMode (comp->getEditingMode());
  41682. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  41683. }
  41684. }
  41685. END_JUCE_NAMESPACE
  41686. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  41687. /********* Start of inlined file: juce_TreeView.cpp *********/
  41688. BEGIN_JUCE_NAMESPACE
  41689. class TreeViewContentComponent : public Component,
  41690. public TooltipClient
  41691. {
  41692. public:
  41693. TreeViewContentComponent (TreeView* const owner_)
  41694. : owner (owner_),
  41695. buttonUnderMouse (0),
  41696. isDragging (false)
  41697. {
  41698. }
  41699. ~TreeViewContentComponent()
  41700. {
  41701. deleteAllChildren();
  41702. }
  41703. void mouseDown (const MouseEvent& e)
  41704. {
  41705. updateButtonUnderMouse (e);
  41706. isDragging = false;
  41707. needSelectionOnMouseUp = false;
  41708. Rectangle pos;
  41709. TreeViewItem* const item = findItemAt (e.y, pos);
  41710. if (item == 0)
  41711. return;
  41712. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  41713. // as selection clicks)
  41714. if (e.x < pos.getX() && owner->openCloseButtonsVisible)
  41715. {
  41716. if (e.x >= pos.getX() - owner->getIndentSize())
  41717. item->setOpen (! item->isOpen());
  41718. // (clicks to the left of an open/close button are ignored)
  41719. }
  41720. else
  41721. {
  41722. // mouse-down inside the body of the item..
  41723. if (! owner->isMultiSelectEnabled())
  41724. item->setSelected (true, true);
  41725. else if (item->isSelected())
  41726. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  41727. else
  41728. selectBasedOnModifiers (item, e.mods);
  41729. MouseEvent e2 (e);
  41730. e2.x -= pos.getX();
  41731. e2.y -= pos.getY();
  41732. if (e2.x >= 0)
  41733. item->itemClicked (e2);
  41734. }
  41735. }
  41736. void mouseUp (const MouseEvent& e)
  41737. {
  41738. updateButtonUnderMouse (e);
  41739. if (needSelectionOnMouseUp && e.mouseWasClicked())
  41740. {
  41741. Rectangle pos;
  41742. TreeViewItem* const item = findItemAt (e.y, pos);
  41743. if (item != 0)
  41744. selectBasedOnModifiers (item, e.mods);
  41745. }
  41746. }
  41747. void mouseDoubleClick (const MouseEvent& e)
  41748. {
  41749. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  41750. {
  41751. Rectangle pos;
  41752. TreeViewItem* const item = findItemAt (e.y, pos);
  41753. if (item != 0 && (e.x >= pos.getX() || ! owner->openCloseButtonsVisible))
  41754. {
  41755. MouseEvent e2 (e);
  41756. e2.x -= pos.getX();
  41757. e2.y -= pos.getY();
  41758. item->itemDoubleClicked (e2);
  41759. }
  41760. }
  41761. }
  41762. void mouseDrag (const MouseEvent& e)
  41763. {
  41764. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  41765. {
  41766. isDragging = true;
  41767. Rectangle pos;
  41768. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  41769. if (item != 0 && e.getMouseDownX() >= pos.getX())
  41770. {
  41771. const String dragDescription (item->getDragSourceDescription());
  41772. if (dragDescription.isNotEmpty())
  41773. {
  41774. DragAndDropContainer* const dragContainer
  41775. = DragAndDropContainer::findParentDragContainerFor (this);
  41776. if (dragContainer != 0)
  41777. {
  41778. pos.setSize (pos.getWidth(), item->itemHeight);
  41779. Image* dragImage = Component::createComponentSnapshot (pos, true);
  41780. dragImage->multiplyAllAlphas (0.6f);
  41781. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  41782. }
  41783. else
  41784. {
  41785. // to be able to do a drag-and-drop operation, the treeview needs to
  41786. // be inside a component which is also a DragAndDropContainer.
  41787. jassertfalse
  41788. }
  41789. }
  41790. }
  41791. }
  41792. }
  41793. void mouseMove (const MouseEvent& e)
  41794. {
  41795. updateButtonUnderMouse (e);
  41796. }
  41797. void mouseExit (const MouseEvent& e)
  41798. {
  41799. updateButtonUnderMouse (e);
  41800. }
  41801. void paint (Graphics& g);
  41802. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  41803. void updateComponents()
  41804. {
  41805. int xAdjust = 0, yAdjust = 0;
  41806. const int visibleTop = -getY();
  41807. const int visibleBottom = visibleTop + getParentHeight();
  41808. BitArray itemsToKeep;
  41809. TreeViewItem* item = owner->rootItem;
  41810. int y = -yAdjust;
  41811. while (item != 0 && y < visibleBottom)
  41812. {
  41813. y += item->itemHeight;
  41814. if (y >= visibleTop)
  41815. {
  41816. const int index = rowComponentIds.indexOf (item->uid);
  41817. if (index < 0)
  41818. {
  41819. Component* const comp = item->createItemComponent();
  41820. if (comp != 0)
  41821. {
  41822. addAndMakeVisible (comp);
  41823. itemsToKeep.setBit (rowComponentItems.size());
  41824. rowComponentItems.add (item);
  41825. rowComponentIds.add (item->uid);
  41826. rowComponents.add (comp);
  41827. }
  41828. }
  41829. else
  41830. {
  41831. itemsToKeep.setBit (index);
  41832. }
  41833. }
  41834. item = item->getNextVisibleItem (true);
  41835. }
  41836. for (int i = rowComponentItems.size(); --i >= 0;)
  41837. {
  41838. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  41839. bool keep = false;
  41840. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  41841. && isParentOf (comp))
  41842. {
  41843. if (itemsToKeep[i])
  41844. {
  41845. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  41846. Rectangle pos (item->getItemPosition (false));
  41847. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  41848. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  41849. {
  41850. keep = true;
  41851. comp->setBounds (pos);
  41852. }
  41853. }
  41854. else
  41855. {
  41856. comp->setSize (0, 0);
  41857. }
  41858. }
  41859. if (! keep)
  41860. {
  41861. delete comp;
  41862. rowComponents.remove (i);
  41863. rowComponentIds.remove (i);
  41864. rowComponentItems.remove (i);
  41865. }
  41866. }
  41867. }
  41868. void updateButtonUnderMouse (const MouseEvent& e)
  41869. {
  41870. TreeViewItem* newItem = 0;
  41871. if (owner->openCloseButtonsVisible)
  41872. {
  41873. Rectangle pos;
  41874. TreeViewItem* item = findItemAt (e.y, pos);
  41875. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner->getIndentSize())
  41876. {
  41877. newItem = item;
  41878. if (! newItem->mightContainSubItems())
  41879. newItem = 0;
  41880. }
  41881. }
  41882. if (buttonUnderMouse != newItem)
  41883. {
  41884. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  41885. {
  41886. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  41887. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  41888. }
  41889. buttonUnderMouse = newItem;
  41890. if (buttonUnderMouse != 0)
  41891. {
  41892. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  41893. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  41894. }
  41895. }
  41896. }
  41897. bool isMouseOverButton (TreeViewItem* item) const throw()
  41898. {
  41899. return item == buttonUnderMouse;
  41900. }
  41901. void resized()
  41902. {
  41903. owner->itemsChanged();
  41904. }
  41905. const String getTooltip()
  41906. {
  41907. int x, y;
  41908. getMouseXYRelative (x, y);
  41909. Rectangle pos;
  41910. TreeViewItem* const item = findItemAt (y, pos);
  41911. if (item != 0)
  41912. return item->getTooltip();
  41913. return owner->getTooltip();
  41914. }
  41915. juce_UseDebuggingNewOperator
  41916. private:
  41917. TreeView* const owner;
  41918. VoidArray rowComponentItems;
  41919. Array <int> rowComponentIds;
  41920. VoidArray rowComponents;
  41921. TreeViewItem* buttonUnderMouse;
  41922. bool isDragging, needSelectionOnMouseUp;
  41923. TreeViewContentComponent (const TreeViewContentComponent&);
  41924. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  41925. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  41926. {
  41927. TreeViewItem* firstSelected = 0;
  41928. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  41929. {
  41930. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  41931. jassert (lastSelected != 0);
  41932. int rowStart = firstSelected->getRowNumberInTree();
  41933. int rowEnd = lastSelected->getRowNumberInTree();
  41934. if (rowStart > rowEnd)
  41935. swapVariables (rowStart, rowEnd);
  41936. int ourRow = item->getRowNumberInTree();
  41937. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  41938. if (ourRow > otherEnd)
  41939. swapVariables (ourRow, otherEnd);
  41940. for (int i = ourRow; i <= otherEnd; ++i)
  41941. owner->getItemOnRow (i)->setSelected (true, false);
  41942. }
  41943. else
  41944. {
  41945. const bool cmd = modifiers.isCommandDown();
  41946. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  41947. }
  41948. }
  41949. bool containsItem (TreeViewItem* const item) const
  41950. {
  41951. for (int i = rowComponentItems.size(); --i >= 0;)
  41952. if ((TreeViewItem*) rowComponentItems.getUnchecked (i) == item)
  41953. return true;
  41954. return false;
  41955. }
  41956. };
  41957. class TreeViewport : public Viewport
  41958. {
  41959. public:
  41960. TreeViewport() throw() {}
  41961. ~TreeViewport() throw() {}
  41962. void updateComponents()
  41963. {
  41964. if (getViewedComponent() != 0)
  41965. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  41966. repaint();
  41967. }
  41968. void visibleAreaChanged (int, int, int, int)
  41969. {
  41970. updateComponents();
  41971. }
  41972. juce_UseDebuggingNewOperator
  41973. private:
  41974. TreeViewport (const TreeViewport&);
  41975. const TreeViewport& operator= (const TreeViewport&);
  41976. };
  41977. TreeView::TreeView (const String& componentName)
  41978. : Component (componentName),
  41979. rootItem (0),
  41980. indentSize (24),
  41981. defaultOpenness (false),
  41982. needsRecalculating (true),
  41983. rootItemVisible (true),
  41984. multiSelectEnabled (false),
  41985. openCloseButtonsVisible (true)
  41986. {
  41987. addAndMakeVisible (viewport = new TreeViewport());
  41988. viewport->setViewedComponent (new TreeViewContentComponent (this));
  41989. viewport->setWantsKeyboardFocus (false);
  41990. setWantsKeyboardFocus (true);
  41991. }
  41992. TreeView::~TreeView()
  41993. {
  41994. if (rootItem != 0)
  41995. rootItem->setOwnerView (0);
  41996. deleteAllChildren();
  41997. }
  41998. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  41999. {
  42000. if (rootItem != newRootItem)
  42001. {
  42002. if (newRootItem != 0)
  42003. {
  42004. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  42005. if (newRootItem->ownerView != 0)
  42006. newRootItem->ownerView->setRootItem (0);
  42007. }
  42008. if (rootItem != 0)
  42009. rootItem->setOwnerView (0);
  42010. rootItem = newRootItem;
  42011. if (newRootItem != 0)
  42012. newRootItem->setOwnerView (this);
  42013. needsRecalculating = true;
  42014. handleAsyncUpdate();
  42015. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42016. {
  42017. rootItem->setOpen (false); // force a re-open
  42018. rootItem->setOpen (true);
  42019. }
  42020. }
  42021. }
  42022. void TreeView::deleteRootItem()
  42023. {
  42024. TreeViewItem* const oldItem = rootItem;
  42025. setRootItem (0);
  42026. delete oldItem;
  42027. }
  42028. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  42029. {
  42030. rootItemVisible = shouldBeVisible;
  42031. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42032. {
  42033. rootItem->setOpen (false); // force a re-open
  42034. rootItem->setOpen (true);
  42035. }
  42036. itemsChanged();
  42037. }
  42038. void TreeView::colourChanged()
  42039. {
  42040. setOpaque (findColour (backgroundColourId).isOpaque());
  42041. repaint();
  42042. }
  42043. void TreeView::setIndentSize (const int newIndentSize)
  42044. {
  42045. if (indentSize != newIndentSize)
  42046. {
  42047. indentSize = newIndentSize;
  42048. resized();
  42049. }
  42050. }
  42051. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  42052. {
  42053. if (defaultOpenness != isOpenByDefault)
  42054. {
  42055. defaultOpenness = isOpenByDefault;
  42056. itemsChanged();
  42057. }
  42058. }
  42059. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  42060. {
  42061. multiSelectEnabled = canMultiSelect;
  42062. }
  42063. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  42064. {
  42065. if (openCloseButtonsVisible != shouldBeVisible)
  42066. {
  42067. openCloseButtonsVisible = shouldBeVisible;
  42068. itemsChanged();
  42069. }
  42070. }
  42071. void TreeView::clearSelectedItems()
  42072. {
  42073. if (rootItem != 0)
  42074. rootItem->deselectAllRecursively();
  42075. }
  42076. int TreeView::getNumSelectedItems() const throw()
  42077. {
  42078. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  42079. }
  42080. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  42081. {
  42082. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  42083. }
  42084. int TreeView::getNumRowsInTree() const
  42085. {
  42086. if (rootItem != 0)
  42087. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  42088. return 0;
  42089. }
  42090. TreeViewItem* TreeView::getItemOnRow (int index) const
  42091. {
  42092. if (! rootItemVisible)
  42093. ++index;
  42094. if (rootItem != 0 && index >= 0)
  42095. return rootItem->getItemOnRow (index);
  42096. return 0;
  42097. }
  42098. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  42099. {
  42100. XmlElement* e = 0;
  42101. if (rootItem != 0)
  42102. {
  42103. e = rootItem->createXmlOpenness();
  42104. if (e != 0 && alsoIncludeScrollPosition)
  42105. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  42106. }
  42107. return e;
  42108. }
  42109. void TreeView::restoreOpennessState (const XmlElement& newState)
  42110. {
  42111. if (rootItem != 0)
  42112. {
  42113. rootItem->restoreFromXml (newState);
  42114. if (newState.hasAttribute (T("scrollPos")))
  42115. viewport->setViewPosition (viewport->getViewPositionX(),
  42116. newState.getIntAttribute (T("scrollPos")));
  42117. }
  42118. }
  42119. void TreeView::paint (Graphics& g)
  42120. {
  42121. g.fillAll (findColour (backgroundColourId));
  42122. }
  42123. void TreeView::resized()
  42124. {
  42125. viewport->setBounds (0, 0, getWidth(), getHeight());
  42126. itemsChanged();
  42127. handleAsyncUpdate();
  42128. }
  42129. void TreeView::enablementChanged()
  42130. {
  42131. repaint();
  42132. }
  42133. void TreeView::moveSelectedRow (int delta)
  42134. {
  42135. if (delta == 0)
  42136. return;
  42137. int rowSelected = 0;
  42138. TreeViewItem* const firstSelected = getSelectedItem (0);
  42139. if (firstSelected != 0)
  42140. rowSelected = firstSelected->getRowNumberInTree();
  42141. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  42142. for (;;)
  42143. {
  42144. TreeViewItem* item = getItemOnRow (rowSelected);
  42145. if (item != 0)
  42146. {
  42147. if (! item->canBeSelected())
  42148. {
  42149. // if the row we want to highlight doesn't allow it, try skipping
  42150. // to the next item..
  42151. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  42152. rowSelected + (delta < 0 ? -1 : 1));
  42153. if (rowSelected != nextRowToTry)
  42154. {
  42155. rowSelected = nextRowToTry;
  42156. continue;
  42157. }
  42158. else
  42159. {
  42160. break;
  42161. }
  42162. }
  42163. item->setSelected (true, true);
  42164. scrollToKeepItemVisible (item);
  42165. }
  42166. break;
  42167. }
  42168. }
  42169. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  42170. {
  42171. if (item != 0 && item->ownerView == this)
  42172. {
  42173. handleAsyncUpdate();
  42174. item = item->getDeepestOpenParentItem();
  42175. int y = item->y;
  42176. int viewTop = viewport->getViewPositionY();
  42177. if (y < viewTop)
  42178. {
  42179. viewport->setViewPosition (viewport->getViewPositionX(), y);
  42180. }
  42181. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  42182. {
  42183. viewport->setViewPosition (viewport->getViewPositionX(),
  42184. (y + item->itemHeight) - viewport->getViewHeight());
  42185. }
  42186. }
  42187. }
  42188. bool TreeView::keyPressed (const KeyPress& key)
  42189. {
  42190. if (key.isKeyCode (KeyPress::upKey))
  42191. {
  42192. moveSelectedRow (-1);
  42193. }
  42194. else if (key.isKeyCode (KeyPress::downKey))
  42195. {
  42196. moveSelectedRow (1);
  42197. }
  42198. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  42199. {
  42200. if (rootItem != 0)
  42201. {
  42202. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  42203. if (key.isKeyCode (KeyPress::pageUpKey))
  42204. rowsOnScreen = -rowsOnScreen;
  42205. moveSelectedRow (rowsOnScreen);
  42206. }
  42207. }
  42208. else if (key.isKeyCode (KeyPress::homeKey))
  42209. {
  42210. moveSelectedRow (-0x3fffffff);
  42211. }
  42212. else if (key.isKeyCode (KeyPress::endKey))
  42213. {
  42214. moveSelectedRow (0x3fffffff);
  42215. }
  42216. else if (key.isKeyCode (KeyPress::returnKey))
  42217. {
  42218. TreeViewItem* const firstSelected = getSelectedItem (0);
  42219. if (firstSelected != 0)
  42220. firstSelected->setOpen (! firstSelected->isOpen());
  42221. }
  42222. else if (key.isKeyCode (KeyPress::leftKey))
  42223. {
  42224. TreeViewItem* const firstSelected = getSelectedItem (0);
  42225. if (firstSelected != 0)
  42226. {
  42227. if (firstSelected->isOpen())
  42228. {
  42229. firstSelected->setOpen (false);
  42230. }
  42231. else
  42232. {
  42233. TreeViewItem* parent = firstSelected->parentItem;
  42234. if ((! rootItemVisible) && parent == rootItem)
  42235. parent = 0;
  42236. if (parent != 0)
  42237. {
  42238. parent->setSelected (true, true);
  42239. scrollToKeepItemVisible (parent);
  42240. }
  42241. }
  42242. }
  42243. }
  42244. else if (key.isKeyCode (KeyPress::rightKey))
  42245. {
  42246. TreeViewItem* const firstSelected = getSelectedItem (0);
  42247. if (firstSelected != 0)
  42248. {
  42249. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  42250. moveSelectedRow (1);
  42251. else
  42252. firstSelected->setOpen (true);
  42253. }
  42254. }
  42255. else
  42256. {
  42257. return false;
  42258. }
  42259. return true;
  42260. }
  42261. void TreeView::itemsChanged() throw()
  42262. {
  42263. needsRecalculating = true;
  42264. repaint();
  42265. triggerAsyncUpdate();
  42266. }
  42267. void TreeView::handleAsyncUpdate()
  42268. {
  42269. if (needsRecalculating)
  42270. {
  42271. needsRecalculating = false;
  42272. const ScopedLock sl (nodeAlterationLock);
  42273. if (rootItem != 0)
  42274. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  42275. ((TreeViewport*) viewport)->updateComponents();
  42276. if (rootItem != 0)
  42277. {
  42278. viewport->getViewedComponent()
  42279. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  42280. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  42281. }
  42282. else
  42283. {
  42284. viewport->getViewedComponent()->setSize (0, 0);
  42285. }
  42286. }
  42287. }
  42288. void TreeViewContentComponent::paint (Graphics& g)
  42289. {
  42290. if (owner->rootItem != 0)
  42291. {
  42292. owner->handleAsyncUpdate();
  42293. if (! owner->rootItemVisible)
  42294. g.setOrigin (0, -owner->rootItem->itemHeight);
  42295. owner->rootItem->paintRecursively (g, getWidth());
  42296. }
  42297. }
  42298. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  42299. {
  42300. if (owner->rootItem != 0)
  42301. {
  42302. owner->handleAsyncUpdate();
  42303. if (! owner->rootItemVisible)
  42304. y += owner->rootItem->itemHeight;
  42305. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  42306. if (ti != 0)
  42307. itemPosition = ti->getItemPosition (false);
  42308. return ti;
  42309. }
  42310. return 0;
  42311. }
  42312. #define opennessDefault 0
  42313. #define opennessClosed 1
  42314. #define opennessOpen 2
  42315. TreeViewItem::TreeViewItem()
  42316. : ownerView (0),
  42317. parentItem (0),
  42318. subItems (8),
  42319. y (0),
  42320. itemHeight (0),
  42321. totalHeight (0),
  42322. selected (false),
  42323. redrawNeeded (true),
  42324. drawLinesInside (true),
  42325. drawsInLeftMargin (false),
  42326. openness (opennessDefault)
  42327. {
  42328. static int nextUID = 0;
  42329. uid = nextUID++;
  42330. }
  42331. TreeViewItem::~TreeViewItem()
  42332. {
  42333. }
  42334. const String TreeViewItem::getUniqueName() const
  42335. {
  42336. return String::empty;
  42337. }
  42338. void TreeViewItem::itemOpennessChanged (bool)
  42339. {
  42340. }
  42341. int TreeViewItem::getNumSubItems() const throw()
  42342. {
  42343. return subItems.size();
  42344. }
  42345. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  42346. {
  42347. return subItems [index];
  42348. }
  42349. void TreeViewItem::clearSubItems()
  42350. {
  42351. if (subItems.size() > 0)
  42352. {
  42353. if (ownerView != 0)
  42354. {
  42355. const ScopedLock sl (ownerView->nodeAlterationLock);
  42356. subItems.clear();
  42357. treeHasChanged();
  42358. }
  42359. else
  42360. {
  42361. subItems.clear();
  42362. }
  42363. }
  42364. }
  42365. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  42366. {
  42367. if (newItem != 0)
  42368. {
  42369. newItem->parentItem = this;
  42370. newItem->setOwnerView (ownerView);
  42371. newItem->y = 0;
  42372. newItem->itemHeight = newItem->getItemHeight();
  42373. newItem->totalHeight = 0;
  42374. newItem->itemWidth = newItem->getItemWidth();
  42375. newItem->totalWidth = 0;
  42376. if (ownerView != 0)
  42377. {
  42378. const ScopedLock sl (ownerView->nodeAlterationLock);
  42379. subItems.insert (insertPosition, newItem);
  42380. treeHasChanged();
  42381. if (newItem->isOpen())
  42382. newItem->itemOpennessChanged (true);
  42383. }
  42384. else
  42385. {
  42386. subItems.insert (insertPosition, newItem);
  42387. if (newItem->isOpen())
  42388. newItem->itemOpennessChanged (true);
  42389. }
  42390. }
  42391. }
  42392. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  42393. {
  42394. if (ownerView != 0)
  42395. ownerView->nodeAlterationLock.enter();
  42396. if (((unsigned int) index) < (unsigned int) subItems.size())
  42397. {
  42398. subItems.remove (index, deleteItem);
  42399. treeHasChanged();
  42400. }
  42401. if (ownerView != 0)
  42402. ownerView->nodeAlterationLock.exit();
  42403. }
  42404. bool TreeViewItem::isOpen() const throw()
  42405. {
  42406. if (openness == opennessDefault)
  42407. return ownerView != 0 && ownerView->defaultOpenness;
  42408. else
  42409. return openness == opennessOpen;
  42410. }
  42411. void TreeViewItem::setOpen (const bool shouldBeOpen)
  42412. {
  42413. if (isOpen() != shouldBeOpen)
  42414. {
  42415. openness = shouldBeOpen ? opennessOpen
  42416. : opennessClosed;
  42417. treeHasChanged();
  42418. itemOpennessChanged (isOpen());
  42419. }
  42420. }
  42421. bool TreeViewItem::isSelected() const throw()
  42422. {
  42423. return selected;
  42424. }
  42425. void TreeViewItem::deselectAllRecursively()
  42426. {
  42427. setSelected (false, false);
  42428. for (int i = 0; i < subItems.size(); ++i)
  42429. subItems.getUnchecked(i)->deselectAllRecursively();
  42430. }
  42431. void TreeViewItem::setSelected (const bool shouldBeSelected,
  42432. const bool deselectOtherItemsFirst)
  42433. {
  42434. if (shouldBeSelected && ! canBeSelected())
  42435. return;
  42436. if (deselectOtherItemsFirst)
  42437. getTopLevelItem()->deselectAllRecursively();
  42438. if (shouldBeSelected != selected)
  42439. {
  42440. selected = shouldBeSelected;
  42441. if (ownerView != 0)
  42442. ownerView->repaint();
  42443. itemSelectionChanged (shouldBeSelected);
  42444. }
  42445. }
  42446. void TreeViewItem::paintItem (Graphics&, int, int)
  42447. {
  42448. }
  42449. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  42450. {
  42451. ownerView->getLookAndFeel()
  42452. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  42453. }
  42454. void TreeViewItem::itemClicked (const MouseEvent&)
  42455. {
  42456. }
  42457. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  42458. {
  42459. if (mightContainSubItems())
  42460. setOpen (! isOpen());
  42461. }
  42462. void TreeViewItem::itemSelectionChanged (bool)
  42463. {
  42464. }
  42465. const String TreeViewItem::getTooltip()
  42466. {
  42467. return String::empty;
  42468. }
  42469. const String TreeViewItem::getDragSourceDescription()
  42470. {
  42471. return String::empty;
  42472. }
  42473. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  42474. {
  42475. const int indentX = getIndentX();
  42476. int width = itemWidth;
  42477. if (ownerView != 0 && width < 0)
  42478. width = ownerView->viewport->getViewWidth() - indentX;
  42479. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  42480. if (relativeToTreeViewTopLeft)
  42481. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  42482. r.getY() - ownerView->viewport->getViewPositionY());
  42483. return r;
  42484. }
  42485. void TreeViewItem::treeHasChanged() const throw()
  42486. {
  42487. if (ownerView != 0)
  42488. ownerView->itemsChanged();
  42489. }
  42490. void TreeViewItem::repaintItem() const
  42491. {
  42492. if (ownerView != 0 && areAllParentsOpen())
  42493. {
  42494. const Rectangle r (getItemPosition (true));
  42495. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  42496. }
  42497. }
  42498. bool TreeViewItem::areAllParentsOpen() const throw()
  42499. {
  42500. return parentItem == 0
  42501. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  42502. }
  42503. void TreeViewItem::updatePositions (int newY)
  42504. {
  42505. y = newY;
  42506. itemHeight = getItemHeight();
  42507. totalHeight = itemHeight;
  42508. itemWidth = getItemWidth();
  42509. totalWidth = jmax (itemWidth, 0) + getIndentX();
  42510. if (isOpen())
  42511. {
  42512. newY += totalHeight;
  42513. for (int i = 0; i < subItems.size(); ++i)
  42514. {
  42515. TreeViewItem* const ti = subItems.getUnchecked(i);
  42516. ti->updatePositions (newY);
  42517. newY += ti->totalHeight;
  42518. totalHeight += ti->totalHeight;
  42519. totalWidth = jmax (totalWidth, ti->totalWidth);
  42520. }
  42521. }
  42522. }
  42523. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  42524. {
  42525. TreeViewItem* result = this;
  42526. TreeViewItem* item = this;
  42527. while (item->parentItem != 0)
  42528. {
  42529. item = item->parentItem;
  42530. if (! item->isOpen())
  42531. result = item;
  42532. }
  42533. return result;
  42534. }
  42535. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  42536. {
  42537. ownerView = newOwner;
  42538. for (int i = subItems.size(); --i >= 0;)
  42539. subItems.getUnchecked(i)->setOwnerView (newOwner);
  42540. }
  42541. int TreeViewItem::getIndentX() const throw()
  42542. {
  42543. const int indentWidth = ownerView->getIndentSize();
  42544. int x = ownerView->rootItemVisible ? indentWidth : 0;
  42545. if (! ownerView->openCloseButtonsVisible)
  42546. x -= indentWidth;
  42547. TreeViewItem* p = parentItem;
  42548. while (p != 0)
  42549. {
  42550. x += indentWidth;
  42551. p = p->parentItem;
  42552. }
  42553. return x;
  42554. }
  42555. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  42556. {
  42557. drawsInLeftMargin = canDrawInLeftMargin;
  42558. }
  42559. void TreeViewItem::paintRecursively (Graphics& g, int width)
  42560. {
  42561. jassert (ownerView != 0);
  42562. if (ownerView == 0)
  42563. return;
  42564. const int indent = getIndentX();
  42565. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  42566. g.setColour (ownerView->findColour (TreeView::linesColourId));
  42567. const float halfH = itemHeight * 0.5f;
  42568. int depth = 0;
  42569. TreeViewItem* p = parentItem;
  42570. while (p != 0)
  42571. {
  42572. ++depth;
  42573. p = p->parentItem;
  42574. }
  42575. if (! ownerView->rootItemVisible)
  42576. --depth;
  42577. const int indentWidth = ownerView->getIndentSize();
  42578. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  42579. {
  42580. float x = (depth + 0.5f) * indentWidth;
  42581. if (depth >= 0)
  42582. {
  42583. if (parentItem != 0 && parentItem->drawLinesInside)
  42584. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  42585. if ((parentItem != 0 && parentItem->drawLinesInside)
  42586. || (parentItem == 0 && drawLinesInside))
  42587. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  42588. }
  42589. p = parentItem;
  42590. int d = depth;
  42591. while (p != 0 && --d >= 0)
  42592. {
  42593. x -= (float) indentWidth;
  42594. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  42595. && ! p->isLastOfSiblings())
  42596. {
  42597. g.drawLine (x, 0, x, (float) itemHeight);
  42598. }
  42599. p = p->parentItem;
  42600. }
  42601. if (mightContainSubItems())
  42602. {
  42603. g.saveState();
  42604. g.setOrigin (depth * indentWidth, 0);
  42605. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  42606. paintOpenCloseButton (g, indentWidth, itemHeight,
  42607. ((TreeViewContentComponent*) ownerView->viewport->getViewedComponent())
  42608. ->isMouseOverButton (this));
  42609. g.restoreState();
  42610. }
  42611. }
  42612. {
  42613. g.saveState();
  42614. g.setOrigin (indent, 0);
  42615. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  42616. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  42617. paintItem (g, itemW, itemHeight);
  42618. g.restoreState();
  42619. }
  42620. if (isOpen())
  42621. {
  42622. const Rectangle clip (g.getClipBounds());
  42623. for (int i = 0; i < subItems.size(); ++i)
  42624. {
  42625. TreeViewItem* const ti = subItems.getUnchecked(i);
  42626. const int relY = ti->y - y;
  42627. if (relY >= clip.getBottom())
  42628. break;
  42629. if (relY + ti->totalHeight >= clip.getY())
  42630. {
  42631. g.saveState();
  42632. g.setOrigin (0, relY);
  42633. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  42634. ti->paintRecursively (g, width);
  42635. g.restoreState();
  42636. }
  42637. }
  42638. }
  42639. }
  42640. bool TreeViewItem::isLastOfSiblings() const throw()
  42641. {
  42642. return parentItem == 0
  42643. || parentItem->subItems.getLast() == this;
  42644. }
  42645. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  42646. {
  42647. return (parentItem == 0) ? this
  42648. : parentItem->getTopLevelItem();
  42649. }
  42650. int TreeViewItem::getNumRows() const throw()
  42651. {
  42652. int num = 1;
  42653. if (isOpen())
  42654. {
  42655. for (int i = subItems.size(); --i >= 0;)
  42656. num += subItems.getUnchecked(i)->getNumRows();
  42657. }
  42658. return num;
  42659. }
  42660. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  42661. {
  42662. if (index == 0)
  42663. return this;
  42664. if (index > 0 && isOpen())
  42665. {
  42666. --index;
  42667. for (int i = 0; i < subItems.size(); ++i)
  42668. {
  42669. TreeViewItem* const item = subItems.getUnchecked(i);
  42670. if (index == 0)
  42671. return item;
  42672. const int numRows = item->getNumRows();
  42673. if (numRows > index)
  42674. return item->getItemOnRow (index);
  42675. index -= numRows;
  42676. }
  42677. }
  42678. return 0;
  42679. }
  42680. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  42681. {
  42682. if (((unsigned int) y) < (unsigned int) totalHeight)
  42683. {
  42684. const int h = itemHeight;
  42685. if (y < h)
  42686. return this;
  42687. if (isOpen())
  42688. {
  42689. y -= h;
  42690. for (int i = 0; i < subItems.size(); ++i)
  42691. {
  42692. TreeViewItem* const ti = subItems.getUnchecked(i);
  42693. if (ti->totalHeight >= y)
  42694. return ti->findItemRecursively (y);
  42695. y -= ti->totalHeight;
  42696. }
  42697. }
  42698. }
  42699. return 0;
  42700. }
  42701. int TreeViewItem::countSelectedItemsRecursively() const throw()
  42702. {
  42703. int total = 0;
  42704. if (isSelected())
  42705. ++total;
  42706. for (int i = subItems.size(); --i >= 0;)
  42707. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  42708. return total;
  42709. }
  42710. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  42711. {
  42712. if (isSelected())
  42713. {
  42714. if (index == 0)
  42715. return this;
  42716. --index;
  42717. }
  42718. if (index >= 0)
  42719. {
  42720. for (int i = 0; i < subItems.size(); ++i)
  42721. {
  42722. TreeViewItem* const item = subItems.getUnchecked(i);
  42723. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  42724. if (found != 0)
  42725. return found;
  42726. index -= item->countSelectedItemsRecursively();
  42727. }
  42728. }
  42729. return 0;
  42730. }
  42731. int TreeViewItem::getRowNumberInTree() const throw()
  42732. {
  42733. if (parentItem != 0 && ownerView != 0)
  42734. {
  42735. int n = 1 + parentItem->getRowNumberInTree();
  42736. int ourIndex = parentItem->subItems.indexOf (this);
  42737. jassert (ourIndex >= 0);
  42738. while (--ourIndex >= 0)
  42739. n += parentItem->subItems [ourIndex]->getNumRows();
  42740. if (parentItem->parentItem == 0
  42741. && ! ownerView->rootItemVisible)
  42742. --n;
  42743. return n;
  42744. }
  42745. else
  42746. {
  42747. return 0;
  42748. }
  42749. }
  42750. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  42751. {
  42752. drawLinesInside = drawLines;
  42753. }
  42754. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  42755. {
  42756. if (recurse && isOpen() && subItems.size() > 0)
  42757. return subItems [0];
  42758. if (parentItem != 0)
  42759. {
  42760. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  42761. if (nextIndex >= parentItem->subItems.size())
  42762. return parentItem->getNextVisibleItem (false);
  42763. return parentItem->subItems [nextIndex];
  42764. }
  42765. return 0;
  42766. }
  42767. void TreeViewItem::restoreFromXml (const XmlElement& e)
  42768. {
  42769. if (e.hasTagName (T("CLOSED")))
  42770. {
  42771. setOpen (false);
  42772. }
  42773. else if (e.hasTagName (T("OPEN")))
  42774. {
  42775. setOpen (true);
  42776. forEachXmlChildElement (e, n)
  42777. {
  42778. const String id (n->getStringAttribute (T("id")));
  42779. for (int i = 0; i < subItems.size(); ++i)
  42780. {
  42781. TreeViewItem* const ti = subItems.getUnchecked(i);
  42782. if (ti->getUniqueName() == id)
  42783. {
  42784. ti->restoreFromXml (*n);
  42785. break;
  42786. }
  42787. }
  42788. }
  42789. }
  42790. }
  42791. XmlElement* TreeViewItem::createXmlOpenness() const
  42792. {
  42793. if (openness != opennessDefault)
  42794. {
  42795. const String name (getUniqueName());
  42796. if (name.isNotEmpty())
  42797. {
  42798. XmlElement* e;
  42799. if (isOpen())
  42800. {
  42801. e = new XmlElement (T("OPEN"));
  42802. for (int i = 0; i < subItems.size(); ++i)
  42803. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  42804. }
  42805. else
  42806. {
  42807. e = new XmlElement (T("CLOSED"));
  42808. }
  42809. e->setAttribute (T("id"), name);
  42810. return e;
  42811. }
  42812. else
  42813. {
  42814. // trying to save the openness for an element that has no name - this won't
  42815. // work because it needs the names to identify what to open.
  42816. jassertfalse
  42817. }
  42818. }
  42819. return 0;
  42820. }
  42821. END_JUCE_NAMESPACE
  42822. /********* End of inlined file: juce_TreeView.cpp *********/
  42823. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42824. BEGIN_JUCE_NAMESPACE
  42825. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  42826. : fileList (listToShow),
  42827. listeners (2)
  42828. {
  42829. }
  42830. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  42831. {
  42832. }
  42833. FileBrowserListener::~FileBrowserListener()
  42834. {
  42835. }
  42836. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  42837. {
  42838. jassert (listener != 0);
  42839. if (listener != 0)
  42840. listeners.add (listener);
  42841. }
  42842. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  42843. {
  42844. listeners.removeValue (listener);
  42845. }
  42846. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  42847. {
  42848. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42849. for (int i = listeners.size(); --i >= 0;)
  42850. {
  42851. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  42852. if (deletionWatcher.hasBeenDeleted())
  42853. return;
  42854. i = jmin (i, listeners.size() - 1);
  42855. }
  42856. }
  42857. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  42858. {
  42859. if (fileList.getDirectory().exists())
  42860. {
  42861. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42862. for (int i = listeners.size(); --i >= 0;)
  42863. {
  42864. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  42865. if (deletionWatcher.hasBeenDeleted())
  42866. return;
  42867. i = jmin (i, listeners.size() - 1);
  42868. }
  42869. }
  42870. }
  42871. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  42872. {
  42873. if (fileList.getDirectory().exists())
  42874. {
  42875. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42876. for (int i = listeners.size(); --i >= 0;)
  42877. {
  42878. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  42879. if (deletionWatcher.hasBeenDeleted())
  42880. return;
  42881. i = jmin (i, listeners.size() - 1);
  42882. }
  42883. }
  42884. }
  42885. END_JUCE_NAMESPACE
  42886. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42887. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  42888. BEGIN_JUCE_NAMESPACE
  42889. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  42890. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  42891. Time* creationTime, bool* isReadOnly) throw();
  42892. bool juce_findFileNext (void* handle, String& resultFile,
  42893. bool* isDirectory, bool* isHidden, int64* fileSize,
  42894. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  42895. void juce_findFileClose (void* handle) throw();
  42896. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  42897. TimeSliceThread& thread_)
  42898. : fileFilter (fileFilter_),
  42899. thread (thread_),
  42900. includeDirectories (false),
  42901. includeFiles (false),
  42902. ignoreHiddenFiles (true),
  42903. fileFindHandle (0),
  42904. shouldStop (true)
  42905. {
  42906. }
  42907. DirectoryContentsList::~DirectoryContentsList()
  42908. {
  42909. clear();
  42910. }
  42911. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  42912. {
  42913. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  42914. }
  42915. const File& DirectoryContentsList::getDirectory() const throw()
  42916. {
  42917. return root;
  42918. }
  42919. void DirectoryContentsList::setDirectory (const File& directory,
  42920. const bool includeDirectories_,
  42921. const bool includeFiles_)
  42922. {
  42923. if (directory != root
  42924. || includeDirectories != includeDirectories_
  42925. || includeFiles != includeFiles_)
  42926. {
  42927. clear();
  42928. root = directory;
  42929. includeDirectories = includeDirectories_;
  42930. includeFiles = includeFiles_;
  42931. refresh();
  42932. }
  42933. }
  42934. void DirectoryContentsList::clear()
  42935. {
  42936. shouldStop = true;
  42937. thread.removeTimeSliceClient (this);
  42938. if (fileFindHandle != 0)
  42939. {
  42940. juce_findFileClose (fileFindHandle);
  42941. fileFindHandle = 0;
  42942. }
  42943. if (files.size() > 0)
  42944. {
  42945. files.clear();
  42946. changed();
  42947. }
  42948. }
  42949. void DirectoryContentsList::refresh()
  42950. {
  42951. clear();
  42952. if (root.isDirectory())
  42953. {
  42954. String fileFound;
  42955. bool fileFoundIsDir, isHidden, isReadOnly;
  42956. int64 fileSize;
  42957. Time modTime, creationTime;
  42958. String path (root.getFullPathName());
  42959. if (! path.endsWithChar (File::separator))
  42960. path += File::separator;
  42961. jassert (fileFindHandle == 0);
  42962. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  42963. &fileFoundIsDir,
  42964. &isHidden,
  42965. &fileSize,
  42966. &modTime,
  42967. &creationTime,
  42968. &isReadOnly);
  42969. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  42970. {
  42971. if (addFile (fileFound, fileFoundIsDir, isHidden,
  42972. fileSize, modTime, creationTime, isReadOnly))
  42973. {
  42974. changed();
  42975. }
  42976. }
  42977. shouldStop = false;
  42978. thread.addTimeSliceClient (this);
  42979. }
  42980. }
  42981. int DirectoryContentsList::getNumFiles() const
  42982. {
  42983. return files.size();
  42984. }
  42985. bool DirectoryContentsList::getFileInfo (const int index,
  42986. FileInfo& result) const
  42987. {
  42988. const ScopedLock sl (fileListLock);
  42989. const FileInfo* const info = files [index];
  42990. if (info != 0)
  42991. {
  42992. result = *info;
  42993. return true;
  42994. }
  42995. return false;
  42996. }
  42997. const File DirectoryContentsList::getFile (const int index) const
  42998. {
  42999. const ScopedLock sl (fileListLock);
  43000. const FileInfo* const info = files [index];
  43001. if (info != 0)
  43002. return root.getChildFile (info->filename);
  43003. return File::nonexistent;
  43004. }
  43005. bool DirectoryContentsList::isStillLoading() const
  43006. {
  43007. return fileFindHandle != 0;
  43008. }
  43009. void DirectoryContentsList::changed()
  43010. {
  43011. sendChangeMessage (this);
  43012. }
  43013. bool DirectoryContentsList::useTimeSlice()
  43014. {
  43015. const uint32 startTime = Time::getApproximateMillisecondCounter();
  43016. bool hasChanged = false;
  43017. for (int i = 100; --i >= 0;)
  43018. {
  43019. if (! checkNextFile (hasChanged))
  43020. {
  43021. if (hasChanged)
  43022. changed();
  43023. return false;
  43024. }
  43025. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  43026. break;
  43027. }
  43028. if (hasChanged)
  43029. changed();
  43030. return true;
  43031. }
  43032. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  43033. {
  43034. if (fileFindHandle != 0)
  43035. {
  43036. String fileFound;
  43037. bool fileFoundIsDir, isHidden, isReadOnly;
  43038. int64 fileSize;
  43039. Time modTime, creationTime;
  43040. if (juce_findFileNext (fileFindHandle, fileFound,
  43041. &fileFoundIsDir, &isHidden,
  43042. &fileSize,
  43043. &modTime,
  43044. &creationTime,
  43045. &isReadOnly))
  43046. {
  43047. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  43048. modTime, creationTime, isReadOnly))
  43049. {
  43050. hasChanged = true;
  43051. }
  43052. return true;
  43053. }
  43054. else
  43055. {
  43056. juce_findFileClose (fileFindHandle);
  43057. fileFindHandle = 0;
  43058. }
  43059. }
  43060. return false;
  43061. }
  43062. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  43063. const DirectoryContentsList::FileInfo* const second) throw()
  43064. {
  43065. #if JUCE_WIN32
  43066. if (first->isDirectory != second->isDirectory)
  43067. return first->isDirectory ? -1 : 1;
  43068. #endif
  43069. return first->filename.compareIgnoreCase (second->filename);
  43070. }
  43071. bool DirectoryContentsList::addFile (const String& filename,
  43072. const bool isDir,
  43073. const bool isHidden,
  43074. const int64 fileSize,
  43075. const Time& modTime,
  43076. const Time& creationTime,
  43077. const bool isReadOnly)
  43078. {
  43079. if (filename == T("..")
  43080. || filename == T(".")
  43081. || (ignoreHiddenFiles && isHidden))
  43082. return false;
  43083. const File file (root.getChildFile (filename));
  43084. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  43085. && (fileFilter == 0
  43086. || ((! isDir) && fileFilter->isFileSuitable (file))
  43087. || (isDir && fileFilter->isDirectorySuitable (file))))
  43088. {
  43089. FileInfo* const info = new FileInfo();
  43090. info->filename = filename;
  43091. info->fileSize = fileSize;
  43092. info->modificationTime = modTime;
  43093. info->creationTime = creationTime;
  43094. info->isDirectory = isDir;
  43095. info->isReadOnly = isReadOnly;
  43096. const ScopedLock sl (fileListLock);
  43097. for (int i = files.size(); --i >= 0;)
  43098. {
  43099. if (files.getUnchecked(i)->filename == info->filename)
  43100. {
  43101. delete info;
  43102. return false;
  43103. }
  43104. }
  43105. files.addSorted (*this, info);
  43106. return true;
  43107. }
  43108. return false;
  43109. }
  43110. END_JUCE_NAMESPACE
  43111. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  43112. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  43113. BEGIN_JUCE_NAMESPACE
  43114. class DirectoriesOnlyFilter : public FileFilter
  43115. {
  43116. public:
  43117. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  43118. bool isFileSuitable (const File&) const { return false; }
  43119. bool isDirectorySuitable (const File&) const { return true; }
  43120. };
  43121. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  43122. const File& initialFileOrDirectory,
  43123. const FileFilter* fileFilter,
  43124. FilePreviewComponent* previewComp_,
  43125. const bool useTreeView,
  43126. const bool filenameTextBoxIsReadOnly)
  43127. : directoriesOnlyFilter (0),
  43128. mode (mode_),
  43129. listeners (2),
  43130. previewComp (previewComp_),
  43131. thread ("Juce FileBrowser")
  43132. {
  43133. String filename;
  43134. if (initialFileOrDirectory == File::nonexistent)
  43135. {
  43136. currentRoot = File::getCurrentWorkingDirectory();
  43137. }
  43138. else if (initialFileOrDirectory.isDirectory())
  43139. {
  43140. currentRoot = initialFileOrDirectory;
  43141. }
  43142. else
  43143. {
  43144. currentRoot = initialFileOrDirectory.getParentDirectory();
  43145. filename = initialFileOrDirectory.getFileName();
  43146. }
  43147. if (mode_ == chooseDirectoryMode)
  43148. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  43149. fileList = new DirectoryContentsList (fileFilter, thread);
  43150. if (useTreeView)
  43151. {
  43152. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  43153. addAndMakeVisible (tree);
  43154. fileListComponent = tree;
  43155. }
  43156. else
  43157. {
  43158. FileListComponent* const list = new FileListComponent (*fileList);
  43159. list->setOutlineThickness (1);
  43160. addAndMakeVisible (list);
  43161. fileListComponent = list;
  43162. }
  43163. fileListComponent->addListener (this);
  43164. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  43165. currentPathBox->setEditableText (true);
  43166. StringArray rootNames, rootPaths;
  43167. const BitArray separators (getRoots (rootNames, rootPaths));
  43168. for (int i = 0; i < rootNames.size(); ++i)
  43169. {
  43170. if (separators [i])
  43171. currentPathBox->addSeparator();
  43172. currentPathBox->addItem (rootNames[i], i + 1);
  43173. }
  43174. currentPathBox->addSeparator();
  43175. currentPathBox->addListener (this);
  43176. addAndMakeVisible (filenameBox = new TextEditor());
  43177. filenameBox->setMultiLine (false);
  43178. filenameBox->setSelectAllWhenFocused (true);
  43179. filenameBox->setText (filename, false);
  43180. filenameBox->addListener (this);
  43181. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  43182. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  43183. : TRANS("file:"));
  43184. addAndMakeVisible (label);
  43185. label->attachToComponent (filenameBox, true);
  43186. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  43187. goUpButton->addButtonListener (this);
  43188. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  43189. if (previewComp != 0)
  43190. addAndMakeVisible (previewComp);
  43191. setRoot (currentRoot);
  43192. thread.startThread (4);
  43193. }
  43194. FileBrowserComponent::~FileBrowserComponent()
  43195. {
  43196. if (previewComp != 0)
  43197. removeChildComponent (previewComp);
  43198. deleteAllChildren();
  43199. deleteAndZero (fileList);
  43200. delete directoriesOnlyFilter;
  43201. thread.stopThread (10000);
  43202. }
  43203. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  43204. {
  43205. jassert (newListener != 0)
  43206. if (newListener != 0)
  43207. listeners.add (newListener);
  43208. }
  43209. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  43210. {
  43211. listeners.removeValue (listener);
  43212. }
  43213. const File FileBrowserComponent::getCurrentFile() const throw()
  43214. {
  43215. return currentRoot.getChildFile (filenameBox->getText());
  43216. }
  43217. bool FileBrowserComponent::currentFileIsValid() const
  43218. {
  43219. if (mode == saveFileMode)
  43220. return ! getCurrentFile().isDirectory();
  43221. else if (mode == loadFileMode)
  43222. return getCurrentFile().existsAsFile();
  43223. else if (mode == chooseDirectoryMode)
  43224. return getCurrentFile().isDirectory();
  43225. jassertfalse
  43226. return false;
  43227. }
  43228. const File FileBrowserComponent::getRoot() const
  43229. {
  43230. return currentRoot;
  43231. }
  43232. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  43233. {
  43234. if (currentRoot != newRootDirectory)
  43235. {
  43236. fileListComponent->scrollToTop();
  43237. if (mode == chooseDirectoryMode)
  43238. filenameBox->setText (String::empty, false);
  43239. String path (newRootDirectory.getFullPathName());
  43240. if (path.isEmpty())
  43241. path += File::separator;
  43242. StringArray rootNames, rootPaths;
  43243. getRoots (rootNames, rootPaths);
  43244. if (! rootPaths.contains (path, true))
  43245. {
  43246. bool alreadyListed = false;
  43247. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  43248. {
  43249. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  43250. {
  43251. alreadyListed = true;
  43252. break;
  43253. }
  43254. }
  43255. if (! alreadyListed)
  43256. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  43257. }
  43258. }
  43259. currentRoot = newRootDirectory;
  43260. fileList->setDirectory (currentRoot, true, true);
  43261. String currentRootName (currentRoot.getFullPathName());
  43262. if (currentRootName.isEmpty())
  43263. currentRootName += File::separator;
  43264. currentPathBox->setText (currentRootName, true);
  43265. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  43266. && currentRoot.getParentDirectory() != currentRoot);
  43267. }
  43268. void FileBrowserComponent::goUp()
  43269. {
  43270. setRoot (getRoot().getParentDirectory());
  43271. }
  43272. void FileBrowserComponent::refresh()
  43273. {
  43274. fileList->refresh();
  43275. }
  43276. const String FileBrowserComponent::getActionVerb() const
  43277. {
  43278. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  43279. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  43280. }
  43281. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  43282. {
  43283. return previewComp;
  43284. }
  43285. void FileBrowserComponent::resized()
  43286. {
  43287. getLookAndFeel()
  43288. .layoutFileBrowserComponent (*this, fileListComponent,
  43289. previewComp, currentPathBox,
  43290. filenameBox, goUpButton);
  43291. }
  43292. void FileBrowserComponent::sendListenerChangeMessage()
  43293. {
  43294. ComponentDeletionWatcher deletionWatcher (this);
  43295. if (previewComp != 0)
  43296. previewComp->selectedFileChanged (getCurrentFile());
  43297. jassert (! deletionWatcher.hasBeenDeleted());
  43298. for (int i = listeners.size(); --i >= 0;)
  43299. {
  43300. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  43301. if (deletionWatcher.hasBeenDeleted())
  43302. return;
  43303. i = jmin (i, listeners.size() - 1);
  43304. }
  43305. }
  43306. void FileBrowserComponent::selectionChanged()
  43307. {
  43308. const File selected (fileListComponent->getSelectedFile());
  43309. if ((mode == chooseDirectoryMode && selected.isDirectory())
  43310. || selected.existsAsFile())
  43311. {
  43312. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  43313. }
  43314. sendListenerChangeMessage();
  43315. }
  43316. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  43317. {
  43318. ComponentDeletionWatcher deletionWatcher (this);
  43319. for (int i = listeners.size(); --i >= 0;)
  43320. {
  43321. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  43322. if (deletionWatcher.hasBeenDeleted())
  43323. return;
  43324. i = jmin (i, listeners.size() - 1);
  43325. }
  43326. }
  43327. void FileBrowserComponent::fileDoubleClicked (const File& f)
  43328. {
  43329. if (f.isDirectory())
  43330. {
  43331. setRoot (f);
  43332. }
  43333. else
  43334. {
  43335. ComponentDeletionWatcher deletionWatcher (this);
  43336. for (int i = listeners.size(); --i >= 0;)
  43337. {
  43338. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  43339. if (deletionWatcher.hasBeenDeleted())
  43340. return;
  43341. i = jmin (i, listeners.size() - 1);
  43342. }
  43343. }
  43344. }
  43345. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  43346. {
  43347. #if JUCE_LINUX || JUCE_WIN32
  43348. if (key.getModifiers().isCommandDown()
  43349. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  43350. {
  43351. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  43352. fileList->refresh();
  43353. return true;
  43354. }
  43355. #endif
  43356. return false;
  43357. }
  43358. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  43359. {
  43360. sendListenerChangeMessage();
  43361. }
  43362. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  43363. {
  43364. if (filenameBox->getText().containsChar (File::separator))
  43365. {
  43366. const File f (currentRoot.getChildFile (filenameBox->getText()));
  43367. if (f.isDirectory())
  43368. {
  43369. setRoot (f);
  43370. filenameBox->setText (String::empty);
  43371. }
  43372. else
  43373. {
  43374. setRoot (f.getParentDirectory());
  43375. filenameBox->setText (f.getFileName());
  43376. }
  43377. }
  43378. else
  43379. {
  43380. fileDoubleClicked (getCurrentFile());
  43381. }
  43382. }
  43383. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  43384. {
  43385. }
  43386. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  43387. {
  43388. if (mode != saveFileMode)
  43389. selectionChanged();
  43390. }
  43391. void FileBrowserComponent::buttonClicked (Button*)
  43392. {
  43393. goUp();
  43394. }
  43395. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  43396. {
  43397. const String newText (currentPathBox->getText().trim().unquoted());
  43398. if (newText.isNotEmpty())
  43399. {
  43400. const int index = currentPathBox->getSelectedId() - 1;
  43401. StringArray rootNames, rootPaths;
  43402. getRoots (rootNames, rootPaths);
  43403. if (rootPaths [index].isNotEmpty())
  43404. {
  43405. setRoot (File (rootPaths [index]));
  43406. }
  43407. else
  43408. {
  43409. File f (newText);
  43410. for (;;)
  43411. {
  43412. if (f.isDirectory())
  43413. {
  43414. setRoot (f);
  43415. break;
  43416. }
  43417. if (f.getParentDirectory() == f)
  43418. break;
  43419. f = f.getParentDirectory();
  43420. }
  43421. }
  43422. }
  43423. }
  43424. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  43425. {
  43426. BitArray separators;
  43427. #if JUCE_WIN32
  43428. OwnedArray<File> roots;
  43429. File::findFileSystemRoots (roots);
  43430. rootPaths.clear();
  43431. for (int i = 0; i < roots.size(); ++i)
  43432. {
  43433. const File* const drive = roots.getUnchecked(i);
  43434. String name (drive->getFullPathName());
  43435. rootPaths.add (name);
  43436. if (drive->isOnHardDisk())
  43437. {
  43438. String volume (drive->getVolumeLabel());
  43439. if (volume.isEmpty())
  43440. volume = TRANS("Hard Drive");
  43441. name << " [" << drive->getVolumeLabel() << ']';
  43442. }
  43443. else if (drive->isOnCDRomDrive())
  43444. {
  43445. name << TRANS(" [CD/DVD drive]");
  43446. }
  43447. rootNames.add (name);
  43448. }
  43449. separators.setBit (rootPaths.size());
  43450. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43451. rootNames.add ("Documents");
  43452. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43453. rootNames.add ("Desktop");
  43454. #endif
  43455. #if JUCE_MAC
  43456. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43457. rootNames.add ("Home folder");
  43458. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43459. rootNames.add ("Documents");
  43460. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43461. rootNames.add ("Desktop");
  43462. separators.setBit (rootPaths.size());
  43463. OwnedArray <File> volumes;
  43464. File vol ("/Volumes");
  43465. vol.findChildFiles (volumes, File::findDirectories, false);
  43466. for (int i = 0; i < volumes.size(); ++i)
  43467. {
  43468. const File* const volume = volumes.getUnchecked(i);
  43469. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  43470. {
  43471. rootPaths.add (volume->getFullPathName());
  43472. rootNames.add (volume->getFileName());
  43473. }
  43474. }
  43475. #endif
  43476. #if JUCE_LINUX
  43477. rootPaths.add ("/");
  43478. rootNames.add ("/");
  43479. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43480. rootNames.add ("Home folder");
  43481. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43482. rootNames.add ("Desktop");
  43483. #endif
  43484. return separators;
  43485. }
  43486. END_JUCE_NAMESPACE
  43487. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  43488. /********* Start of inlined file: juce_FileChooser.cpp *********/
  43489. BEGIN_JUCE_NAMESPACE
  43490. FileChooser::FileChooser (const String& chooserBoxTitle,
  43491. const File& currentFileOrDirectory,
  43492. const String& fileFilters,
  43493. const bool useNativeDialogBox_)
  43494. : title (chooserBoxTitle),
  43495. filters (fileFilters),
  43496. startingFile (currentFileOrDirectory),
  43497. useNativeDialogBox (useNativeDialogBox_)
  43498. {
  43499. #if JUCE_LINUX
  43500. useNativeDialogBox = false;
  43501. #endif
  43502. if (! fileFilters.containsNonWhitespaceChars())
  43503. filters = T("*");
  43504. }
  43505. FileChooser::~FileChooser()
  43506. {
  43507. }
  43508. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  43509. {
  43510. return showDialog (false, false, false, false, previewComponent);
  43511. }
  43512. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  43513. {
  43514. return showDialog (false, false, false, true, previewComponent);
  43515. }
  43516. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  43517. {
  43518. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  43519. }
  43520. bool FileChooser::browseForDirectory()
  43521. {
  43522. return showDialog (true, false, false, false, 0);
  43523. }
  43524. const File FileChooser::getResult() const
  43525. {
  43526. // if you've used a multiple-file select, you should use the getResults() method
  43527. // to retrieve all the files that were chosen.
  43528. jassert (results.size() <= 1);
  43529. const File* const f = results.getFirst();
  43530. if (f != 0)
  43531. return *f;
  43532. return File::nonexistent;
  43533. }
  43534. const OwnedArray <File>& FileChooser::getResults() const
  43535. {
  43536. return results;
  43537. }
  43538. bool FileChooser::showDialog (const bool isDirectory,
  43539. const bool isSave,
  43540. const bool warnAboutOverwritingExistingFiles,
  43541. const bool selectMultipleFiles,
  43542. FilePreviewComponent* const previewComponent)
  43543. {
  43544. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  43545. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  43546. if (currentlyFocused != 0)
  43547. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  43548. results.clear();
  43549. // the preview component needs to be the right size before you pass it in here..
  43550. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  43551. && previewComponent->getHeight() > 10));
  43552. #if JUCE_WIN32
  43553. if (useNativeDialogBox)
  43554. #else
  43555. if (useNativeDialogBox && (previewComponent == 0))
  43556. #endif
  43557. {
  43558. showPlatformDialog (results, title, startingFile, filters,
  43559. isDirectory, isSave,
  43560. warnAboutOverwritingExistingFiles,
  43561. selectMultipleFiles,
  43562. previewComponent);
  43563. }
  43564. else
  43565. {
  43566. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  43567. WildcardFileFilter wildcard (filters, String::empty);
  43568. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  43569. : (isSave ? FileBrowserComponent::saveFileMode
  43570. : FileBrowserComponent::loadFileMode),
  43571. startingFile, &wildcard, previewComponent);
  43572. FileChooserDialogBox box (title, String::empty,
  43573. browserComponent,
  43574. warnAboutOverwritingExistingFiles,
  43575. browserComponent.findColour (AlertWindow::backgroundColourId));
  43576. if (box.show())
  43577. results.add (new File (browserComponent.getCurrentFile()));
  43578. }
  43579. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  43580. currentlyFocused->grabKeyboardFocus();
  43581. delete currentlyFocusedChecker;
  43582. return results.size() > 0;
  43583. }
  43584. FilePreviewComponent::FilePreviewComponent()
  43585. {
  43586. }
  43587. FilePreviewComponent::~FilePreviewComponent()
  43588. {
  43589. }
  43590. END_JUCE_NAMESPACE
  43591. /********* End of inlined file: juce_FileChooser.cpp *********/
  43592. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  43593. BEGIN_JUCE_NAMESPACE
  43594. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  43595. const String& instructions,
  43596. FileBrowserComponent& chooserComponent,
  43597. const bool warnAboutOverwritingExistingFiles_,
  43598. const Colour& backgroundColour)
  43599. : ResizableWindow (name, backgroundColour, true),
  43600. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  43601. {
  43602. content = new ContentComponent();
  43603. content->setName (name);
  43604. content->instructions = instructions;
  43605. content->chooserComponent = &chooserComponent;
  43606. content->addAndMakeVisible (&chooserComponent);
  43607. content->okButton = new TextButton (chooserComponent.getActionVerb());
  43608. content->addAndMakeVisible (content->okButton);
  43609. content->okButton->addButtonListener (this);
  43610. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  43611. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  43612. content->cancelButton = new TextButton (TRANS("Cancel"));
  43613. content->addAndMakeVisible (content->cancelButton);
  43614. content->cancelButton->addButtonListener (this);
  43615. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  43616. setContentComponent (content);
  43617. setResizable (true, true);
  43618. setResizeLimits (300, 300, 1200, 1000);
  43619. content->chooserComponent->addListener (this);
  43620. }
  43621. FileChooserDialogBox::~FileChooserDialogBox()
  43622. {
  43623. content->chooserComponent->removeListener (this);
  43624. }
  43625. bool FileChooserDialogBox::show (int w, int h)
  43626. {
  43627. if (w <= 0)
  43628. {
  43629. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  43630. if (previewComp != 0)
  43631. w = 400 + previewComp->getWidth();
  43632. else
  43633. w = 600;
  43634. }
  43635. if (h <= 0)
  43636. h = 500;
  43637. centreWithSize (w, h);
  43638. const bool ok = (runModalLoop() != 0);
  43639. setVisible (false);
  43640. return ok;
  43641. }
  43642. void FileChooserDialogBox::buttonClicked (Button* button)
  43643. {
  43644. if (button == content->okButton)
  43645. {
  43646. if (warnAboutOverwritingExistingFiles
  43647. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  43648. && content->chooserComponent->getCurrentFile().exists())
  43649. {
  43650. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  43651. TRANS("File already exists"),
  43652. TRANS("There's already a file called:\n\n")
  43653. + content->chooserComponent->getCurrentFile().getFullPathName()
  43654. + T("\n\nAre you sure you want to overwrite it?"),
  43655. TRANS("overwrite"),
  43656. TRANS("cancel")))
  43657. {
  43658. return;
  43659. }
  43660. }
  43661. exitModalState (1);
  43662. }
  43663. else if (button == content->cancelButton)
  43664. closeButtonPressed();
  43665. }
  43666. void FileChooserDialogBox::closeButtonPressed()
  43667. {
  43668. setVisible (false);
  43669. }
  43670. void FileChooserDialogBox::selectionChanged()
  43671. {
  43672. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  43673. }
  43674. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  43675. {
  43676. }
  43677. void FileChooserDialogBox::fileDoubleClicked (const File&)
  43678. {
  43679. selectionChanged();
  43680. content->okButton->triggerClick();
  43681. }
  43682. FileChooserDialogBox::ContentComponent::ContentComponent()
  43683. {
  43684. setInterceptsMouseClicks (false, true);
  43685. }
  43686. FileChooserDialogBox::ContentComponent::~ContentComponent()
  43687. {
  43688. delete okButton;
  43689. delete cancelButton;
  43690. }
  43691. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  43692. {
  43693. g.setColour (Colours::black);
  43694. text.draw (g);
  43695. }
  43696. void FileChooserDialogBox::ContentComponent::resized()
  43697. {
  43698. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  43699. float left, top, right, bottom;
  43700. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  43701. const int y = roundFloatToInt (bottom) + 10;
  43702. const int buttonHeight = 26;
  43703. const int buttonY = getHeight() - buttonHeight - 8;
  43704. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  43705. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  43706. proportionOfWidth (0.2f), buttonHeight);
  43707. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  43708. proportionOfWidth (0.2f), buttonHeight);
  43709. }
  43710. END_JUCE_NAMESPACE
  43711. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  43712. /********* Start of inlined file: juce_FileFilter.cpp *********/
  43713. BEGIN_JUCE_NAMESPACE
  43714. FileFilter::FileFilter (const String& filterDescription)
  43715. : description (filterDescription)
  43716. {
  43717. }
  43718. FileFilter::~FileFilter()
  43719. {
  43720. }
  43721. const String& FileFilter::getDescription() const throw()
  43722. {
  43723. return description;
  43724. }
  43725. END_JUCE_NAMESPACE
  43726. /********* End of inlined file: juce_FileFilter.cpp *********/
  43727. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  43728. BEGIN_JUCE_NAMESPACE
  43729. Image* juce_createIconForFile (const File& file);
  43730. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  43731. : ListBox (String::empty, 0),
  43732. DirectoryContentsDisplayComponent (listToShow)
  43733. {
  43734. setModel (this);
  43735. fileList.addChangeListener (this);
  43736. }
  43737. FileListComponent::~FileListComponent()
  43738. {
  43739. fileList.removeChangeListener (this);
  43740. deleteAllChildren();
  43741. }
  43742. const File FileListComponent::getSelectedFile() const
  43743. {
  43744. return fileList.getFile (getSelectedRow());
  43745. }
  43746. void FileListComponent::scrollToTop()
  43747. {
  43748. getVerticalScrollBar()->setCurrentRangeStart (0);
  43749. }
  43750. void FileListComponent::changeListenerCallback (void*)
  43751. {
  43752. updateContent();
  43753. if (lastDirectory != fileList.getDirectory())
  43754. {
  43755. lastDirectory = fileList.getDirectory();
  43756. deselectAllRows();
  43757. }
  43758. }
  43759. class FileListItemComponent : public Component,
  43760. public TimeSliceClient,
  43761. public AsyncUpdater
  43762. {
  43763. public:
  43764. FileListItemComponent (FileListComponent& owner_,
  43765. TimeSliceThread& thread_) throw()
  43766. : owner (owner_),
  43767. thread (thread_),
  43768. icon (0)
  43769. {
  43770. }
  43771. ~FileListItemComponent() throw()
  43772. {
  43773. thread.removeTimeSliceClient (this);
  43774. clearIcon();
  43775. }
  43776. void paint (Graphics& g)
  43777. {
  43778. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  43779. file.getFileName(),
  43780. icon,
  43781. fileSize, modTime,
  43782. isDirectory, highlighted,
  43783. index);
  43784. }
  43785. void mouseDown (const MouseEvent& e)
  43786. {
  43787. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  43788. owner.sendMouseClickMessage (file, e);
  43789. }
  43790. void mouseDoubleClick (const MouseEvent&)
  43791. {
  43792. owner.sendDoubleClickMessage (file);
  43793. }
  43794. void update (const File& root,
  43795. const DirectoryContentsList::FileInfo* const fileInfo,
  43796. const int index_,
  43797. const bool highlighted_) throw()
  43798. {
  43799. thread.removeTimeSliceClient (this);
  43800. if (highlighted_ != highlighted
  43801. || index_ != index)
  43802. {
  43803. index = index_;
  43804. highlighted = highlighted_;
  43805. repaint();
  43806. }
  43807. File newFile;
  43808. String newFileSize;
  43809. String newModTime;
  43810. if (fileInfo != 0)
  43811. {
  43812. newFile = root.getChildFile (fileInfo->filename);
  43813. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  43814. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  43815. }
  43816. if (newFile != file
  43817. || fileSize != newFileSize
  43818. || modTime != newModTime)
  43819. {
  43820. file = newFile;
  43821. fileSize = newFileSize;
  43822. modTime = newModTime;
  43823. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  43824. repaint();
  43825. clearIcon();
  43826. }
  43827. if (file != File::nonexistent
  43828. && icon == 0 && ! isDirectory)
  43829. {
  43830. updateIcon (true);
  43831. if (icon == 0)
  43832. thread.addTimeSliceClient (this);
  43833. }
  43834. }
  43835. bool useTimeSlice()
  43836. {
  43837. updateIcon (false);
  43838. return false;
  43839. }
  43840. void handleAsyncUpdate()
  43841. {
  43842. repaint();
  43843. }
  43844. juce_UseDebuggingNewOperator
  43845. private:
  43846. FileListComponent& owner;
  43847. TimeSliceThread& thread;
  43848. bool highlighted;
  43849. int index;
  43850. File file;
  43851. String fileSize;
  43852. String modTime;
  43853. Image* icon;
  43854. bool isDirectory;
  43855. void clearIcon() throw()
  43856. {
  43857. ImageCache::release (icon);
  43858. icon = 0;
  43859. }
  43860. void updateIcon (const bool onlyUpdateIfCached) throw()
  43861. {
  43862. if (icon == 0)
  43863. {
  43864. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  43865. Image* im = ImageCache::getFromHashCode (hashCode);
  43866. if (im == 0 && ! onlyUpdateIfCached)
  43867. {
  43868. im = juce_createIconForFile (file);
  43869. if (im != 0)
  43870. ImageCache::addImageToCache (im, hashCode);
  43871. }
  43872. if (im != 0)
  43873. {
  43874. icon = im;
  43875. triggerAsyncUpdate();
  43876. }
  43877. }
  43878. }
  43879. };
  43880. int FileListComponent::getNumRows()
  43881. {
  43882. return fileList.getNumFiles();
  43883. }
  43884. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  43885. {
  43886. }
  43887. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  43888. {
  43889. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  43890. if (comp == 0)
  43891. {
  43892. delete existingComponentToUpdate;
  43893. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  43894. }
  43895. DirectoryContentsList::FileInfo fileInfo;
  43896. if (fileList.getFileInfo (row, fileInfo))
  43897. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  43898. else
  43899. comp->update (fileList.getDirectory(), 0, row, isSelected);
  43900. return comp;
  43901. }
  43902. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  43903. {
  43904. sendSelectionChangeMessage();
  43905. }
  43906. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  43907. {
  43908. }
  43909. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  43910. {
  43911. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  43912. }
  43913. END_JUCE_NAMESPACE
  43914. /********* End of inlined file: juce_FileListComponent.cpp *********/
  43915. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  43916. BEGIN_JUCE_NAMESPACE
  43917. FilenameComponent::FilenameComponent (const String& name,
  43918. const File& currentFile,
  43919. const bool canEditFilename,
  43920. const bool isDirectory,
  43921. const bool isForSaving,
  43922. const String& fileBrowserWildcard,
  43923. const String& enforcedSuffix_,
  43924. const String& textWhenNothingSelected)
  43925. : Component (name),
  43926. maxRecentFiles (30),
  43927. isDir (isDirectory),
  43928. isSaving (isForSaving),
  43929. isFileDragOver (false),
  43930. wildcard (fileBrowserWildcard),
  43931. enforcedSuffix (enforcedSuffix_)
  43932. {
  43933. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  43934. filenameBox->setEditableText (canEditFilename);
  43935. filenameBox->addListener (this);
  43936. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  43937. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  43938. browseButton = 0;
  43939. setBrowseButtonText (T("..."));
  43940. setCurrentFile (currentFile, true);
  43941. }
  43942. FilenameComponent::~FilenameComponent()
  43943. {
  43944. deleteAllChildren();
  43945. }
  43946. void FilenameComponent::paintOverChildren (Graphics& g)
  43947. {
  43948. if (isFileDragOver)
  43949. {
  43950. g.setColour (Colours::red.withAlpha (0.2f));
  43951. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  43952. }
  43953. }
  43954. void FilenameComponent::resized()
  43955. {
  43956. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  43957. }
  43958. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  43959. {
  43960. browseButtonText = newBrowseButtonText;
  43961. lookAndFeelChanged();
  43962. }
  43963. void FilenameComponent::lookAndFeelChanged()
  43964. {
  43965. deleteAndZero (browseButton);
  43966. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  43967. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  43968. resized();
  43969. browseButton->addButtonListener (this);
  43970. }
  43971. void FilenameComponent::setTooltip (const String& newTooltip)
  43972. {
  43973. SettableTooltipClient::setTooltip (newTooltip);
  43974. filenameBox->setTooltip (newTooltip);
  43975. }
  43976. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  43977. {
  43978. defaultBrowseFile = newDefaultDirectory;
  43979. }
  43980. void FilenameComponent::buttonClicked (Button*)
  43981. {
  43982. FileChooser fc (TRANS("Choose a new file"),
  43983. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  43984. : getCurrentFile(),
  43985. wildcard);
  43986. if (isDir ? fc.browseForDirectory()
  43987. : (isSaving ? fc.browseForFileToSave (false)
  43988. : fc.browseForFileToOpen()))
  43989. {
  43990. setCurrentFile (fc.getResult(), true);
  43991. }
  43992. }
  43993. void FilenameComponent::comboBoxChanged (ComboBox*)
  43994. {
  43995. setCurrentFile (getCurrentFile(), true);
  43996. }
  43997. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  43998. {
  43999. return true;
  44000. }
  44001. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  44002. {
  44003. isFileDragOver = false;
  44004. repaint();
  44005. const File f (filenames[0]);
  44006. if (f.exists() && (f.isDirectory() == isDir))
  44007. setCurrentFile (f, true);
  44008. }
  44009. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  44010. {
  44011. isFileDragOver = true;
  44012. repaint();
  44013. }
  44014. void FilenameComponent::fileDragExit (const StringArray&)
  44015. {
  44016. isFileDragOver = false;
  44017. repaint();
  44018. }
  44019. const File FilenameComponent::getCurrentFile() const
  44020. {
  44021. File f (filenameBox->getText());
  44022. if (enforcedSuffix.isNotEmpty())
  44023. f = f.withFileExtension (enforcedSuffix);
  44024. return f;
  44025. }
  44026. void FilenameComponent::setCurrentFile (File newFile,
  44027. const bool addToRecentlyUsedList,
  44028. const bool sendChangeNotification)
  44029. {
  44030. if (enforcedSuffix.isNotEmpty())
  44031. newFile = newFile.withFileExtension (enforcedSuffix);
  44032. if (newFile.getFullPathName() != lastFilename)
  44033. {
  44034. lastFilename = newFile.getFullPathName();
  44035. if (addToRecentlyUsedList)
  44036. addRecentlyUsedFile (newFile);
  44037. filenameBox->setText (lastFilename, true);
  44038. if (sendChangeNotification)
  44039. triggerAsyncUpdate();
  44040. }
  44041. }
  44042. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  44043. {
  44044. filenameBox->setEditableText (shouldBeEditable);
  44045. }
  44046. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  44047. {
  44048. StringArray names;
  44049. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  44050. names.add (filenameBox->getItemText (i));
  44051. return names;
  44052. }
  44053. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  44054. {
  44055. if (filenames != getRecentlyUsedFilenames())
  44056. {
  44057. filenameBox->clear();
  44058. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  44059. filenameBox->addItem (filenames[i], i + 1);
  44060. }
  44061. }
  44062. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  44063. {
  44064. maxRecentFiles = jmax (1, newMaximum);
  44065. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  44066. }
  44067. void FilenameComponent::addRecentlyUsedFile (const File& file)
  44068. {
  44069. StringArray files (getRecentlyUsedFilenames());
  44070. if (file.getFullPathName().isNotEmpty())
  44071. {
  44072. files.removeString (file.getFullPathName(), true);
  44073. files.insert (0, file.getFullPathName());
  44074. setRecentlyUsedFilenames (files);
  44075. }
  44076. }
  44077. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  44078. {
  44079. jassert (listener != 0);
  44080. if (listener != 0)
  44081. listeners.add (listener);
  44082. }
  44083. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  44084. {
  44085. listeners.removeValue (listener);
  44086. }
  44087. void FilenameComponent::handleAsyncUpdate()
  44088. {
  44089. for (int i = listeners.size(); --i >= 0;)
  44090. {
  44091. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  44092. i = jmin (i, listeners.size());
  44093. }
  44094. }
  44095. END_JUCE_NAMESPACE
  44096. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  44097. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44098. BEGIN_JUCE_NAMESPACE
  44099. FileSearchPathListComponent::FileSearchPathListComponent()
  44100. {
  44101. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  44102. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  44103. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  44104. listBox->setOutlineThickness (1);
  44105. addAndMakeVisible (addButton = new TextButton ("+"));
  44106. addButton->addButtonListener (this);
  44107. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44108. addAndMakeVisible (removeButton = new TextButton ("-"));
  44109. removeButton->addButtonListener (this);
  44110. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44111. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  44112. changeButton->addButtonListener (this);
  44113. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44114. upButton->addButtonListener (this);
  44115. {
  44116. Path arrowPath;
  44117. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  44118. DrawablePath arrowImage;
  44119. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44120. arrowImage.setPath (arrowPath);
  44121. ((DrawableButton*) upButton)->setImages (&arrowImage);
  44122. }
  44123. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44124. downButton->addButtonListener (this);
  44125. {
  44126. Path arrowPath;
  44127. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  44128. DrawablePath arrowImage;
  44129. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44130. arrowImage.setPath (arrowPath);
  44131. ((DrawableButton*) downButton)->setImages (&arrowImage);
  44132. }
  44133. updateButtons();
  44134. }
  44135. FileSearchPathListComponent::~FileSearchPathListComponent()
  44136. {
  44137. deleteAllChildren();
  44138. }
  44139. void FileSearchPathListComponent::updateButtons() throw()
  44140. {
  44141. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  44142. removeButton->setEnabled (anythingSelected);
  44143. changeButton->setEnabled (anythingSelected);
  44144. upButton->setEnabled (anythingSelected);
  44145. downButton->setEnabled (anythingSelected);
  44146. }
  44147. void FileSearchPathListComponent::changed() throw()
  44148. {
  44149. listBox->updateContent();
  44150. listBox->repaint();
  44151. updateButtons();
  44152. }
  44153. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  44154. {
  44155. if (newPath.toString() != path.toString())
  44156. {
  44157. path = newPath;
  44158. changed();
  44159. }
  44160. }
  44161. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  44162. {
  44163. defaultBrowseTarget = newDefaultDirectory;
  44164. }
  44165. int FileSearchPathListComponent::getNumRows()
  44166. {
  44167. return path.getNumPaths();
  44168. }
  44169. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  44170. {
  44171. if (rowIsSelected)
  44172. g.fillAll (findColour (TextEditor::highlightColourId));
  44173. g.setColour (findColour (ListBox::textColourId));
  44174. Font f (height * 0.7f);
  44175. f.setHorizontalScale (0.9f);
  44176. g.setFont (f);
  44177. g.drawText (path [rowNumber].getFullPathName(),
  44178. 4, 0, width - 6, height,
  44179. Justification::centredLeft, true);
  44180. }
  44181. void FileSearchPathListComponent::deleteKeyPressed (int row)
  44182. {
  44183. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  44184. {
  44185. path.remove (row);
  44186. changed();
  44187. }
  44188. }
  44189. void FileSearchPathListComponent::returnKeyPressed (int row)
  44190. {
  44191. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  44192. if (chooser.browseForDirectory())
  44193. {
  44194. path.remove (row);
  44195. path.add (chooser.getResult(), row);
  44196. changed();
  44197. }
  44198. }
  44199. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  44200. {
  44201. returnKeyPressed (row);
  44202. }
  44203. void FileSearchPathListComponent::selectedRowsChanged (int)
  44204. {
  44205. updateButtons();
  44206. }
  44207. void FileSearchPathListComponent::paint (Graphics& g)
  44208. {
  44209. g.fillAll (findColour (backgroundColourId));
  44210. }
  44211. void FileSearchPathListComponent::resized()
  44212. {
  44213. const int buttonH = 22;
  44214. const int buttonY = getHeight() - buttonH - 4;
  44215. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  44216. addButton->setBounds (2, buttonY, buttonH, buttonH);
  44217. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  44218. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  44219. downButton->setSize (buttonH * 2, buttonH);
  44220. upButton->setSize (buttonH * 2, buttonH);
  44221. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  44222. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  44223. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  44224. }
  44225. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  44226. {
  44227. return true;
  44228. }
  44229. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  44230. {
  44231. for (int i = filenames.size(); --i >= 0;)
  44232. {
  44233. const File f (filenames[i]);
  44234. if (f.isDirectory())
  44235. {
  44236. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  44237. path.add (f, row);
  44238. changed();
  44239. }
  44240. }
  44241. }
  44242. void FileSearchPathListComponent::buttonClicked (Button* button)
  44243. {
  44244. const int currentRow = listBox->getSelectedRow();
  44245. if (button == removeButton)
  44246. {
  44247. deleteKeyPressed (currentRow);
  44248. }
  44249. else if (button == addButton)
  44250. {
  44251. File start (defaultBrowseTarget);
  44252. if (start == File::nonexistent)
  44253. start = path [0];
  44254. if (start == File::nonexistent)
  44255. start = File::getCurrentWorkingDirectory();
  44256. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  44257. if (chooser.browseForDirectory())
  44258. {
  44259. path.add (chooser.getResult(), currentRow);
  44260. }
  44261. }
  44262. else if (button == changeButton)
  44263. {
  44264. returnKeyPressed (currentRow);
  44265. }
  44266. else if (button == upButton)
  44267. {
  44268. if (currentRow > 0 && currentRow < path.getNumPaths())
  44269. {
  44270. const File f (path[currentRow]);
  44271. path.remove (currentRow);
  44272. path.add (f, currentRow - 1);
  44273. listBox->selectRow (currentRow - 1);
  44274. }
  44275. }
  44276. else if (button == downButton)
  44277. {
  44278. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  44279. {
  44280. const File f (path[currentRow]);
  44281. path.remove (currentRow);
  44282. path.add (f, currentRow + 1);
  44283. listBox->selectRow (currentRow + 1);
  44284. }
  44285. }
  44286. changed();
  44287. }
  44288. END_JUCE_NAMESPACE
  44289. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44290. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  44291. BEGIN_JUCE_NAMESPACE
  44292. Image* juce_createIconForFile (const File& file);
  44293. class FileListTreeItem : public TreeViewItem,
  44294. public TimeSliceClient,
  44295. public AsyncUpdater,
  44296. public ChangeListener
  44297. {
  44298. public:
  44299. FileListTreeItem (FileTreeComponent& owner_,
  44300. DirectoryContentsList* const parentContentsList_,
  44301. const int indexInContentsList_,
  44302. const File& file_,
  44303. TimeSliceThread& thread_) throw()
  44304. : file (file_),
  44305. owner (owner_),
  44306. parentContentsList (parentContentsList_),
  44307. indexInContentsList (indexInContentsList_),
  44308. subContentsList (0),
  44309. canDeleteSubContentsList (false),
  44310. thread (thread_),
  44311. icon (0)
  44312. {
  44313. DirectoryContentsList::FileInfo fileInfo;
  44314. if (parentContentsList_ != 0
  44315. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  44316. {
  44317. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  44318. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  44319. isDirectory = fileInfo.isDirectory;
  44320. }
  44321. else
  44322. {
  44323. isDirectory = true;
  44324. }
  44325. }
  44326. ~FileListTreeItem() throw()
  44327. {
  44328. thread.removeTimeSliceClient (this);
  44329. clearSubItems();
  44330. ImageCache::release (icon);
  44331. if (canDeleteSubContentsList)
  44332. delete subContentsList;
  44333. }
  44334. bool mightContainSubItems() { return isDirectory; }
  44335. const String getUniqueName() const { return file.getFullPathName(); }
  44336. int getItemHeight() const { return 22; }
  44337. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  44338. void itemOpennessChanged (bool isNowOpen)
  44339. {
  44340. if (isNowOpen)
  44341. {
  44342. clearSubItems();
  44343. isDirectory = file.isDirectory();
  44344. if (isDirectory)
  44345. {
  44346. if (subContentsList == 0)
  44347. {
  44348. jassert (parentContentsList != 0);
  44349. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  44350. l->setDirectory (file, true, true);
  44351. setSubContentsList (l);
  44352. canDeleteSubContentsList = true;
  44353. }
  44354. changeListenerCallback (0);
  44355. }
  44356. }
  44357. }
  44358. void setSubContentsList (DirectoryContentsList* newList) throw()
  44359. {
  44360. jassert (subContentsList == 0);
  44361. subContentsList = newList;
  44362. newList->addChangeListener (this);
  44363. }
  44364. void changeListenerCallback (void*)
  44365. {
  44366. clearSubItems();
  44367. if (isOpen() && subContentsList != 0)
  44368. {
  44369. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  44370. {
  44371. FileListTreeItem* const item
  44372. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  44373. addSubItem (item);
  44374. }
  44375. }
  44376. }
  44377. void paintItem (Graphics& g, int width, int height)
  44378. {
  44379. if (file != File::nonexistent && ! isDirectory)
  44380. {
  44381. updateIcon (true);
  44382. if (icon == 0)
  44383. thread.addTimeSliceClient (this);
  44384. }
  44385. owner.getLookAndFeel()
  44386. .drawFileBrowserRow (g, width, height,
  44387. file.getFileName(),
  44388. icon,
  44389. fileSize, modTime,
  44390. isDirectory, isSelected(),
  44391. indexInContentsList);
  44392. }
  44393. void itemClicked (const MouseEvent& e)
  44394. {
  44395. owner.sendMouseClickMessage (file, e);
  44396. }
  44397. void itemDoubleClicked (const MouseEvent& e)
  44398. {
  44399. TreeViewItem::itemDoubleClicked (e);
  44400. owner.sendDoubleClickMessage (file);
  44401. }
  44402. void itemSelectionChanged (bool)
  44403. {
  44404. owner.sendSelectionChangeMessage();
  44405. }
  44406. bool useTimeSlice()
  44407. {
  44408. updateIcon (false);
  44409. thread.removeTimeSliceClient (this);
  44410. return false;
  44411. }
  44412. void handleAsyncUpdate()
  44413. {
  44414. owner.repaint();
  44415. }
  44416. const File file;
  44417. juce_UseDebuggingNewOperator
  44418. private:
  44419. FileTreeComponent& owner;
  44420. DirectoryContentsList* parentContentsList;
  44421. int indexInContentsList;
  44422. DirectoryContentsList* subContentsList;
  44423. bool isDirectory, canDeleteSubContentsList;
  44424. TimeSliceThread& thread;
  44425. Image* icon;
  44426. String fileSize;
  44427. String modTime;
  44428. void updateIcon (const bool onlyUpdateIfCached) throw()
  44429. {
  44430. if (icon == 0)
  44431. {
  44432. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  44433. Image* im = ImageCache::getFromHashCode (hashCode);
  44434. if (im == 0 && ! onlyUpdateIfCached)
  44435. {
  44436. im = juce_createIconForFile (file);
  44437. if (im != 0)
  44438. ImageCache::addImageToCache (im, hashCode);
  44439. }
  44440. if (im != 0)
  44441. {
  44442. icon = im;
  44443. triggerAsyncUpdate();
  44444. }
  44445. }
  44446. }
  44447. };
  44448. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  44449. : DirectoryContentsDisplayComponent (listToShow)
  44450. {
  44451. FileListTreeItem* const root
  44452. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  44453. listToShow.getTimeSliceThread());
  44454. root->setSubContentsList (&listToShow);
  44455. setRootItemVisible (false);
  44456. setRootItem (root);
  44457. }
  44458. FileTreeComponent::~FileTreeComponent()
  44459. {
  44460. TreeViewItem* const root = getRootItem();
  44461. setRootItem (0);
  44462. delete root;
  44463. }
  44464. const File FileTreeComponent::getSelectedFile() const
  44465. {
  44466. return getSelectedFile (0);
  44467. }
  44468. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  44469. {
  44470. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  44471. if (item != 0)
  44472. return item->file;
  44473. return File::nonexistent;
  44474. }
  44475. void FileTreeComponent::scrollToTop()
  44476. {
  44477. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  44478. }
  44479. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  44480. {
  44481. dragAndDropDescription = description;
  44482. }
  44483. END_JUCE_NAMESPACE
  44484. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  44485. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  44486. BEGIN_JUCE_NAMESPACE
  44487. ImagePreviewComponent::ImagePreviewComponent()
  44488. : currentThumbnail (0)
  44489. {
  44490. }
  44491. ImagePreviewComponent::~ImagePreviewComponent()
  44492. {
  44493. delete currentThumbnail;
  44494. }
  44495. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  44496. {
  44497. const int availableW = proportionOfWidth (0.97f);
  44498. const int availableH = getHeight() - 13 * 4;
  44499. const double scale = jmin (1.0,
  44500. availableW / (double) w,
  44501. availableH / (double) h);
  44502. w = roundDoubleToInt (scale * w);
  44503. h = roundDoubleToInt (scale * h);
  44504. }
  44505. void ImagePreviewComponent::selectedFileChanged (const File& file)
  44506. {
  44507. if (fileToLoad != file)
  44508. {
  44509. fileToLoad = file;
  44510. startTimer (100);
  44511. }
  44512. }
  44513. void ImagePreviewComponent::timerCallback()
  44514. {
  44515. stopTimer();
  44516. deleteAndZero (currentThumbnail);
  44517. currentDetails = String::empty;
  44518. repaint();
  44519. FileInputStream* const in = fileToLoad.createInputStream();
  44520. if (in != 0)
  44521. {
  44522. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  44523. if (format != 0)
  44524. {
  44525. currentThumbnail = format->decodeImage (*in);
  44526. if (currentThumbnail != 0)
  44527. {
  44528. int w = currentThumbnail->getWidth();
  44529. int h = currentThumbnail->getHeight();
  44530. currentDetails
  44531. << fileToLoad.getFileName() << "\n"
  44532. << format->getFormatName() << "\n"
  44533. << w << " x " << h << " pixels\n"
  44534. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  44535. getThumbSize (w, h);
  44536. Image* const reduced = currentThumbnail->createCopy (w, h);
  44537. delete currentThumbnail;
  44538. currentThumbnail = reduced;
  44539. }
  44540. }
  44541. delete in;
  44542. }
  44543. }
  44544. void ImagePreviewComponent::paint (Graphics& g)
  44545. {
  44546. if (currentThumbnail != 0)
  44547. {
  44548. g.setFont (13.0f);
  44549. int w = currentThumbnail->getWidth();
  44550. int h = currentThumbnail->getHeight();
  44551. getThumbSize (w, h);
  44552. const int numLines = 4;
  44553. const int totalH = 13 * numLines + h + 4;
  44554. const int y = (getHeight() - totalH) / 2;
  44555. g.drawImageWithin (currentThumbnail,
  44556. (getWidth() - w) / 2, y, w, h,
  44557. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  44558. false);
  44559. g.drawFittedText (currentDetails,
  44560. 0, y + h + 4, getWidth(), 100,
  44561. Justification::centredTop, numLines);
  44562. }
  44563. }
  44564. END_JUCE_NAMESPACE
  44565. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  44566. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  44567. BEGIN_JUCE_NAMESPACE
  44568. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  44569. const String& description)
  44570. : FileFilter (description.isEmpty() ? wildcardPatterns
  44571. : (description + T(" (") + wildcardPatterns + T(")")))
  44572. {
  44573. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  44574. wildcards.trim();
  44575. wildcards.removeEmptyStrings();
  44576. // special case for *.*, because people use it to mean "any file", but it
  44577. // would actually ignore files with no extension.
  44578. for (int i = wildcards.size(); --i >= 0;)
  44579. if (wildcards[i] == T("*.*"))
  44580. wildcards.set (i, T("*"));
  44581. }
  44582. WildcardFileFilter::~WildcardFileFilter()
  44583. {
  44584. }
  44585. bool WildcardFileFilter::isFileSuitable (const File& file) const
  44586. {
  44587. const String filename (file.getFileName());
  44588. for (int i = wildcards.size(); --i >= 0;)
  44589. if (filename.matchesWildcard (wildcards[i], true))
  44590. return true;
  44591. return false;
  44592. }
  44593. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  44594. {
  44595. return true;
  44596. }
  44597. END_JUCE_NAMESPACE
  44598. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  44599. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44600. BEGIN_JUCE_NAMESPACE
  44601. KeyboardFocusTraverser::KeyboardFocusTraverser()
  44602. {
  44603. }
  44604. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  44605. {
  44606. }
  44607. // This will sort a set of components, so that they are ordered in terms of
  44608. // left-to-right and then top-to-bottom.
  44609. class ScreenPositionComparator
  44610. {
  44611. public:
  44612. ScreenPositionComparator() {}
  44613. static int compareElements (const Component* const first, const Component* const second) throw()
  44614. {
  44615. int explicitOrder1 = first->getExplicitFocusOrder();
  44616. if (explicitOrder1 <= 0)
  44617. explicitOrder1 = INT_MAX / 2;
  44618. int explicitOrder2 = second->getExplicitFocusOrder();
  44619. if (explicitOrder2 <= 0)
  44620. explicitOrder2 = INT_MAX / 2;
  44621. if (explicitOrder1 != explicitOrder2)
  44622. return explicitOrder1 - explicitOrder2;
  44623. const int diff = first->getY() - second->getY();
  44624. return (diff == 0) ? first->getX() - second->getX()
  44625. : diff;
  44626. }
  44627. };
  44628. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  44629. {
  44630. if (parent->getNumChildComponents() > 0)
  44631. {
  44632. Array <Component*> localComps;
  44633. ScreenPositionComparator comparator;
  44634. int i;
  44635. for (i = parent->getNumChildComponents(); --i >= 0;)
  44636. {
  44637. Component* const c = parent->getChildComponent (i);
  44638. if (c->isVisible() && c->isEnabled())
  44639. localComps.addSorted (comparator, c);
  44640. }
  44641. for (i = 0; i < localComps.size(); ++i)
  44642. {
  44643. Component* const c = localComps.getUnchecked (i);
  44644. if (c->getWantsKeyboardFocus())
  44645. comps.add (c);
  44646. if (! c->isFocusContainer())
  44647. findAllFocusableComponents (c, comps);
  44648. }
  44649. }
  44650. }
  44651. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  44652. {
  44653. Component* focusContainer = current->getParentComponent();
  44654. if (focusContainer != 0)
  44655. {
  44656. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  44657. focusContainer = focusContainer->getParentComponent();
  44658. if (focusContainer != 0)
  44659. {
  44660. Array <Component*> comps;
  44661. findAllFocusableComponents (focusContainer, comps);
  44662. if (comps.size() > 0)
  44663. {
  44664. const int index = comps.indexOf (current);
  44665. return comps [(index + comps.size() + delta) % comps.size()];
  44666. }
  44667. }
  44668. }
  44669. return 0;
  44670. }
  44671. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  44672. {
  44673. return getIncrementedComponent (current, 1);
  44674. }
  44675. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  44676. {
  44677. return getIncrementedComponent (current, -1);
  44678. }
  44679. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  44680. {
  44681. Array <Component*> comps;
  44682. if (parentComponent != 0)
  44683. findAllFocusableComponents (parentComponent, comps);
  44684. return comps.getFirst();
  44685. }
  44686. END_JUCE_NAMESPACE
  44687. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44688. /********* Start of inlined file: juce_KeyListener.cpp *********/
  44689. BEGIN_JUCE_NAMESPACE
  44690. bool KeyListener::keyStateChanged (const bool, Component*)
  44691. {
  44692. return false;
  44693. }
  44694. END_JUCE_NAMESPACE
  44695. /********* End of inlined file: juce_KeyListener.cpp *********/
  44696. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  44697. BEGIN_JUCE_NAMESPACE
  44698. // N.B. these two includes are put here deliberately to avoid problems with
  44699. // old GCCs failing on long include paths
  44700. const int maxKeys = 3;
  44701. class KeyMappingChangeButton : public Button
  44702. {
  44703. public:
  44704. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  44705. const CommandID commandID_,
  44706. const String& keyName,
  44707. const int keyNum_)
  44708. : Button (keyName),
  44709. owner (owner_),
  44710. commandID (commandID_),
  44711. keyNum (keyNum_)
  44712. {
  44713. setWantsKeyboardFocus (false);
  44714. setTriggeredOnMouseDown (keyNum >= 0);
  44715. if (keyNum_ < 0)
  44716. setTooltip (TRANS("adds a new key-mapping"));
  44717. else
  44718. setTooltip (TRANS("click to change this key-mapping"));
  44719. }
  44720. ~KeyMappingChangeButton()
  44721. {
  44722. }
  44723. void paintButton (Graphics& g, bool isOver, bool isDown)
  44724. {
  44725. if (keyNum >= 0)
  44726. {
  44727. if (isEnabled())
  44728. {
  44729. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  44730. g.fillAll (owner->textColour.withAlpha (alpha));
  44731. g.setOpacity (0.3f);
  44732. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  44733. }
  44734. g.setColour (owner->textColour);
  44735. g.setFont (getHeight() * 0.6f);
  44736. g.drawFittedText (getName(),
  44737. 3, 0, getWidth() - 6, getHeight(),
  44738. Justification::centred, 1);
  44739. }
  44740. else
  44741. {
  44742. const float thickness = 7.0f;
  44743. const float indent = 22.0f;
  44744. Path p;
  44745. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  44746. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  44747. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  44748. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  44749. p.setUsingNonZeroWinding (false);
  44750. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  44751. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  44752. }
  44753. if (hasKeyboardFocus (false))
  44754. {
  44755. g.setColour (owner->textColour.withAlpha (0.4f));
  44756. g.drawRect (0, 0, getWidth(), getHeight());
  44757. }
  44758. }
  44759. void clicked()
  44760. {
  44761. if (keyNum >= 0)
  44762. {
  44763. // existing key clicked..
  44764. PopupMenu m;
  44765. m.addItem (1, TRANS("change this key-mapping"));
  44766. m.addSeparator();
  44767. m.addItem (2, TRANS("remove this key-mapping"));
  44768. const int res = m.show();
  44769. if (res == 1)
  44770. {
  44771. owner->assignNewKey (commandID, keyNum);
  44772. }
  44773. else if (res == 2)
  44774. {
  44775. owner->getMappings()->removeKeyPress (commandID, keyNum);
  44776. }
  44777. }
  44778. else
  44779. {
  44780. // + button pressed..
  44781. owner->assignNewKey (commandID, -1);
  44782. }
  44783. }
  44784. void fitToContent (const int h) throw()
  44785. {
  44786. if (keyNum < 0)
  44787. {
  44788. setSize (h, h);
  44789. }
  44790. else
  44791. {
  44792. Font f (h * 0.6f);
  44793. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  44794. }
  44795. }
  44796. juce_UseDebuggingNewOperator
  44797. private:
  44798. KeyMappingEditorComponent* const owner;
  44799. const CommandID commandID;
  44800. const int keyNum;
  44801. KeyMappingChangeButton (const KeyMappingChangeButton&);
  44802. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  44803. };
  44804. class KeyMappingItemComponent : public Component
  44805. {
  44806. public:
  44807. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  44808. const CommandID commandID_)
  44809. : owner (owner_),
  44810. commandID (commandID_)
  44811. {
  44812. setInterceptsMouseClicks (false, true);
  44813. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  44814. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  44815. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  44816. {
  44817. KeyMappingChangeButton* const kb
  44818. = new KeyMappingChangeButton (owner_, commandID,
  44819. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  44820. kb->setEnabled (! isReadOnly);
  44821. addAndMakeVisible (kb);
  44822. }
  44823. KeyMappingChangeButton* const kb
  44824. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  44825. addChildComponent (kb);
  44826. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  44827. }
  44828. ~KeyMappingItemComponent()
  44829. {
  44830. deleteAllChildren();
  44831. }
  44832. void paint (Graphics& g)
  44833. {
  44834. g.setFont (getHeight() * 0.7f);
  44835. g.setColour (owner->textColour);
  44836. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  44837. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  44838. Justification::centredLeft, true);
  44839. }
  44840. void resized()
  44841. {
  44842. int x = getWidth() - 4;
  44843. for (int i = getNumChildComponents(); --i >= 0;)
  44844. {
  44845. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  44846. kb->fitToContent (getHeight() - 2);
  44847. kb->setTopRightPosition (x, 1);
  44848. x -= kb->getWidth() + 5;
  44849. }
  44850. }
  44851. juce_UseDebuggingNewOperator
  44852. private:
  44853. KeyMappingEditorComponent* const owner;
  44854. const CommandID commandID;
  44855. KeyMappingItemComponent (const KeyMappingItemComponent&);
  44856. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  44857. };
  44858. class KeyMappingTreeViewItem : public TreeViewItem
  44859. {
  44860. public:
  44861. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  44862. const CommandID commandID_)
  44863. : owner (owner_),
  44864. commandID (commandID_)
  44865. {
  44866. }
  44867. ~KeyMappingTreeViewItem()
  44868. {
  44869. }
  44870. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  44871. bool mightContainSubItems() { return false; }
  44872. int getItemHeight() const { return 20; }
  44873. Component* createItemComponent()
  44874. {
  44875. return new KeyMappingItemComponent (owner, commandID);
  44876. }
  44877. juce_UseDebuggingNewOperator
  44878. private:
  44879. KeyMappingEditorComponent* const owner;
  44880. const CommandID commandID;
  44881. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  44882. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  44883. };
  44884. class KeyCategoryTreeViewItem : public TreeViewItem
  44885. {
  44886. public:
  44887. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  44888. const String& name)
  44889. : owner (owner_),
  44890. categoryName (name)
  44891. {
  44892. }
  44893. ~KeyCategoryTreeViewItem()
  44894. {
  44895. }
  44896. const String getUniqueName() const { return categoryName + "_cat"; }
  44897. bool mightContainSubItems() { return true; }
  44898. int getItemHeight() const { return 28; }
  44899. void paintItem (Graphics& g, int width, int height)
  44900. {
  44901. g.setFont (height * 0.6f, Font::bold);
  44902. g.setColour (owner->textColour);
  44903. g.drawText (categoryName,
  44904. 2, 0, width - 2, height,
  44905. Justification::centredLeft, true);
  44906. }
  44907. void itemOpennessChanged (bool isNowOpen)
  44908. {
  44909. if (isNowOpen)
  44910. {
  44911. if (getNumSubItems() == 0)
  44912. {
  44913. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  44914. for (int i = 0; i < commands.size(); ++i)
  44915. {
  44916. if (owner->shouldCommandBeIncluded (commands[i]))
  44917. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  44918. }
  44919. }
  44920. }
  44921. else
  44922. {
  44923. clearSubItems();
  44924. }
  44925. }
  44926. juce_UseDebuggingNewOperator
  44927. private:
  44928. KeyMappingEditorComponent* owner;
  44929. String categoryName;
  44930. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  44931. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  44932. };
  44933. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  44934. const bool showResetToDefaultButton)
  44935. : mappings (mappingManager),
  44936. textColour (Colours::black)
  44937. {
  44938. jassert (mappingManager != 0); // can't be null!
  44939. mappingManager->addChangeListener (this);
  44940. setLinesDrawnForSubItems (false);
  44941. resetButton = 0;
  44942. if (showResetToDefaultButton)
  44943. {
  44944. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  44945. resetButton->addButtonListener (this);
  44946. }
  44947. addAndMakeVisible (tree = new TreeView());
  44948. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  44949. tree->setRootItemVisible (false);
  44950. tree->setDefaultOpenness (true);
  44951. tree->setRootItem (this);
  44952. }
  44953. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  44954. {
  44955. mappings->removeChangeListener (this);
  44956. deleteAllChildren();
  44957. }
  44958. bool KeyMappingEditorComponent::mightContainSubItems()
  44959. {
  44960. return true;
  44961. }
  44962. const String KeyMappingEditorComponent::getUniqueName() const
  44963. {
  44964. return T("keys");
  44965. }
  44966. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  44967. const Colour& textColour_)
  44968. {
  44969. backgroundColour = mainBackground;
  44970. textColour = textColour_;
  44971. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  44972. }
  44973. void KeyMappingEditorComponent::parentHierarchyChanged()
  44974. {
  44975. changeListenerCallback (0);
  44976. }
  44977. void KeyMappingEditorComponent::resized()
  44978. {
  44979. int h = getHeight();
  44980. if (resetButton != 0)
  44981. {
  44982. const int buttonHeight = 20;
  44983. h -= buttonHeight + 8;
  44984. int x = getWidth() - 8;
  44985. const int y = h + 6;
  44986. resetButton->changeWidthToFitText (buttonHeight);
  44987. resetButton->setTopRightPosition (x, y);
  44988. }
  44989. tree->setBounds (0, 0, getWidth(), h);
  44990. }
  44991. void KeyMappingEditorComponent::buttonClicked (Button* button)
  44992. {
  44993. if (button == resetButton)
  44994. {
  44995. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  44996. TRANS("Reset to defaults"),
  44997. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  44998. TRANS("Reset")))
  44999. {
  45000. mappings->resetToDefaultMappings();
  45001. }
  45002. }
  45003. }
  45004. void KeyMappingEditorComponent::changeListenerCallback (void*)
  45005. {
  45006. XmlElement* openness = tree->getOpennessState (true);
  45007. clearSubItems();
  45008. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  45009. for (int i = 0; i < categories.size(); ++i)
  45010. {
  45011. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  45012. int count = 0;
  45013. for (int j = 0; j < commands.size(); ++j)
  45014. if (shouldCommandBeIncluded (commands[j]))
  45015. ++count;
  45016. if (count > 0)
  45017. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  45018. }
  45019. if (openness != 0)
  45020. {
  45021. tree->restoreOpennessState (*openness);
  45022. delete openness;
  45023. }
  45024. }
  45025. class KeyEntryWindow : public AlertWindow
  45026. {
  45027. public:
  45028. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  45029. : AlertWindow (TRANS("New key-mapping"),
  45030. TRANS("Please press a key combination now..."),
  45031. AlertWindow::NoIcon),
  45032. owner (owner_)
  45033. {
  45034. addButton (TRANS("ok"), 1);
  45035. addButton (TRANS("cancel"), 0);
  45036. // (avoid return + escape keys getting processed by the buttons..)
  45037. for (int i = getNumChildComponents(); --i >= 0;)
  45038. getChildComponent (i)->setWantsKeyboardFocus (false);
  45039. setWantsKeyboardFocus (true);
  45040. grabKeyboardFocus();
  45041. }
  45042. ~KeyEntryWindow()
  45043. {
  45044. }
  45045. bool keyPressed (const KeyPress& key)
  45046. {
  45047. lastPress = key;
  45048. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  45049. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  45050. if (previousCommand != 0)
  45051. {
  45052. message << "\n\n"
  45053. << TRANS("(Currently assigned to \"")
  45054. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  45055. << "\")";
  45056. }
  45057. setMessage (message);
  45058. return true;
  45059. }
  45060. bool keyStateChanged (const bool)
  45061. {
  45062. return true;
  45063. }
  45064. KeyPress lastPress;
  45065. juce_UseDebuggingNewOperator
  45066. private:
  45067. KeyMappingEditorComponent* owner;
  45068. KeyEntryWindow (const KeyEntryWindow&);
  45069. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  45070. };
  45071. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  45072. {
  45073. KeyEntryWindow entryWindow (this);
  45074. if (entryWindow.runModalLoop() != 0)
  45075. {
  45076. entryWindow.setVisible (false);
  45077. if (entryWindow.lastPress.isValid())
  45078. {
  45079. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  45080. if (previousCommand != 0)
  45081. {
  45082. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  45083. TRANS("Change key-mapping"),
  45084. TRANS("This key is already assigned to the command \"")
  45085. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  45086. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  45087. TRANS("re-assign"),
  45088. TRANS("cancel")))
  45089. {
  45090. return;
  45091. }
  45092. }
  45093. mappings->removeKeyPress (entryWindow.lastPress);
  45094. if (index >= 0)
  45095. mappings->removeKeyPress (commandID, index);
  45096. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  45097. }
  45098. }
  45099. }
  45100. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  45101. {
  45102. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45103. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  45104. }
  45105. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  45106. {
  45107. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45108. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  45109. }
  45110. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  45111. {
  45112. return key.getTextDescription();
  45113. }
  45114. END_JUCE_NAMESPACE
  45115. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  45116. /********* Start of inlined file: juce_KeyPress.cpp *********/
  45117. BEGIN_JUCE_NAMESPACE
  45118. KeyPress::KeyPress() throw()
  45119. : keyCode (0),
  45120. mods (0),
  45121. textCharacter (0)
  45122. {
  45123. }
  45124. KeyPress::KeyPress (const int keyCode_,
  45125. const ModifierKeys& mods_,
  45126. const juce_wchar textCharacter_) throw()
  45127. : keyCode (keyCode_),
  45128. mods (mods_),
  45129. textCharacter (textCharacter_)
  45130. {
  45131. }
  45132. KeyPress::KeyPress (const int keyCode_) throw()
  45133. : keyCode (keyCode_),
  45134. textCharacter (0)
  45135. {
  45136. }
  45137. KeyPress::KeyPress (const KeyPress& other) throw()
  45138. : keyCode (other.keyCode),
  45139. mods (other.mods),
  45140. textCharacter (other.textCharacter)
  45141. {
  45142. }
  45143. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  45144. {
  45145. keyCode = other.keyCode;
  45146. mods = other.mods;
  45147. textCharacter = other.textCharacter;
  45148. return *this;
  45149. }
  45150. bool KeyPress::operator== (const KeyPress& other) const throw()
  45151. {
  45152. return mods.getRawFlags() == other.mods.getRawFlags()
  45153. && (textCharacter == other.textCharacter
  45154. || textCharacter == 0
  45155. || other.textCharacter == 0)
  45156. && (keyCode == other.keyCode
  45157. || (keyCode < 256
  45158. && other.keyCode < 256
  45159. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  45160. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  45161. }
  45162. bool KeyPress::operator!= (const KeyPress& other) const throw()
  45163. {
  45164. return ! operator== (other);
  45165. }
  45166. bool KeyPress::isCurrentlyDown() const throw()
  45167. {
  45168. return isKeyCurrentlyDown (keyCode)
  45169. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  45170. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  45171. }
  45172. struct KeyNameAndCode
  45173. {
  45174. const char* name;
  45175. int code;
  45176. };
  45177. static const KeyNameAndCode keyNameTranslations[] =
  45178. {
  45179. { "spacebar", KeyPress::spaceKey },
  45180. { "return", KeyPress::returnKey },
  45181. { "escape", KeyPress::escapeKey },
  45182. { "backspace", KeyPress::backspaceKey },
  45183. { "cursor left", KeyPress::leftKey },
  45184. { "cursor right", KeyPress::rightKey },
  45185. { "cursor up", KeyPress::upKey },
  45186. { "cursor down", KeyPress::downKey },
  45187. { "page up", KeyPress::pageUpKey },
  45188. { "page down", KeyPress::pageDownKey },
  45189. { "home", KeyPress::homeKey },
  45190. { "end", KeyPress::endKey },
  45191. { "delete", KeyPress::deleteKey },
  45192. { "insert", KeyPress::insertKey },
  45193. { "tab", KeyPress::tabKey },
  45194. { "play", KeyPress::playKey },
  45195. { "stop", KeyPress::stopKey },
  45196. { "fast forward", KeyPress::fastForwardKey },
  45197. { "rewind", KeyPress::rewindKey }
  45198. };
  45199. static const tchar* const numberPadPrefix = T("numpad ");
  45200. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  45201. {
  45202. int modifiers = 0;
  45203. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  45204. || desc.containsWholeWordIgnoreCase (T("control"))
  45205. || desc.containsWholeWordIgnoreCase (T("ctl")))
  45206. modifiers |= ModifierKeys::ctrlModifier;
  45207. if (desc.containsWholeWordIgnoreCase (T("shift"))
  45208. || desc.containsWholeWordIgnoreCase (T("shft")))
  45209. modifiers |= ModifierKeys::shiftModifier;
  45210. if (desc.containsWholeWordIgnoreCase (T("alt"))
  45211. || desc.containsWholeWordIgnoreCase (T("option")))
  45212. modifiers |= ModifierKeys::altModifier;
  45213. if (desc.containsWholeWordIgnoreCase (T("command"))
  45214. || desc.containsWholeWordIgnoreCase (T("cmd")))
  45215. modifiers |= ModifierKeys::commandModifier;
  45216. int key = 0;
  45217. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45218. {
  45219. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  45220. {
  45221. key = keyNameTranslations[i].code;
  45222. break;
  45223. }
  45224. }
  45225. if (key == 0)
  45226. {
  45227. // see if it's a numpad key..
  45228. if (desc.containsIgnoreCase (numberPadPrefix))
  45229. {
  45230. const tchar lastChar = desc.trimEnd().getLastCharacter();
  45231. if (lastChar >= T('0') && lastChar <= T('9'))
  45232. key = numberPad0 + lastChar - T('0');
  45233. else if (lastChar == T('+'))
  45234. key = numberPadAdd;
  45235. else if (lastChar == T('-'))
  45236. key = numberPadSubtract;
  45237. else if (lastChar == T('*'))
  45238. key = numberPadMultiply;
  45239. else if (lastChar == T('/'))
  45240. key = numberPadDivide;
  45241. else if (lastChar == T('.'))
  45242. key = numberPadDecimalPoint;
  45243. else if (lastChar == T('='))
  45244. key = numberPadEquals;
  45245. else if (desc.endsWith (T("separator")))
  45246. key = numberPadSeparator;
  45247. else if (desc.endsWith (T("delete")))
  45248. key = numberPadDelete;
  45249. }
  45250. if (key == 0)
  45251. {
  45252. // see if it's a function key..
  45253. for (int i = 1; i <= 12; ++i)
  45254. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  45255. key = F1Key + i - 1;
  45256. if (key == 0)
  45257. {
  45258. // give up and use the hex code..
  45259. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  45260. .toLowerCase()
  45261. .retainCharacters (T("0123456789abcdef"))
  45262. .getHexValue32();
  45263. if (hexCode > 0)
  45264. key = hexCode;
  45265. else
  45266. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  45267. }
  45268. }
  45269. }
  45270. return KeyPress (key, ModifierKeys (modifiers), 0);
  45271. }
  45272. const String KeyPress::getTextDescription() const throw()
  45273. {
  45274. String desc;
  45275. if (keyCode > 0)
  45276. {
  45277. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  45278. // want to store it as being a slash, not shift+whatever.
  45279. if (textCharacter == T('/'))
  45280. return "/";
  45281. if (mods.isCtrlDown())
  45282. desc << "ctrl + ";
  45283. if (mods.isShiftDown())
  45284. desc << "shift + ";
  45285. #if JUCE_MAC
  45286. // only do this on the mac, because on Windows ctrl and command are the same,
  45287. // and this would get confusing
  45288. if (mods.isCommandDown())
  45289. desc << "command + ";
  45290. if (mods.isAltDown())
  45291. desc << "option + ";
  45292. #else
  45293. if (mods.isAltDown())
  45294. desc << "alt + ";
  45295. #endif
  45296. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45297. if (keyCode == keyNameTranslations[i].code)
  45298. return desc + keyNameTranslations[i].name;
  45299. if (keyCode >= F1Key && keyCode <= F16Key)
  45300. desc << 'F' << (1 + keyCode - F1Key);
  45301. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  45302. desc << numberPadPrefix << (keyCode - numberPad0);
  45303. else if (keyCode >= 33 && keyCode < 176)
  45304. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  45305. else if (keyCode == numberPadAdd)
  45306. desc << numberPadPrefix << '+';
  45307. else if (keyCode == numberPadSubtract)
  45308. desc << numberPadPrefix << '-';
  45309. else if (keyCode == numberPadMultiply)
  45310. desc << numberPadPrefix << '*';
  45311. else if (keyCode == numberPadDivide)
  45312. desc << numberPadPrefix << '/';
  45313. else if (keyCode == numberPadSeparator)
  45314. desc << numberPadPrefix << "separator";
  45315. else if (keyCode == numberPadDecimalPoint)
  45316. desc << numberPadPrefix << '.';
  45317. else if (keyCode == numberPadDelete)
  45318. desc << numberPadPrefix << "delete";
  45319. else
  45320. desc << '#' << String::toHexString (keyCode);
  45321. }
  45322. return desc;
  45323. }
  45324. END_JUCE_NAMESPACE
  45325. /********* End of inlined file: juce_KeyPress.cpp *********/
  45326. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  45327. BEGIN_JUCE_NAMESPACE
  45328. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  45329. : commandManager (commandManager_)
  45330. {
  45331. // A manager is needed to get the descriptions of commands, and will be called when
  45332. // a command is invoked. So you can't leave this null..
  45333. jassert (commandManager_ != 0);
  45334. Desktop::getInstance().addFocusChangeListener (this);
  45335. }
  45336. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  45337. : commandManager (other.commandManager)
  45338. {
  45339. Desktop::getInstance().addFocusChangeListener (this);
  45340. }
  45341. KeyPressMappingSet::~KeyPressMappingSet()
  45342. {
  45343. Desktop::getInstance().removeFocusChangeListener (this);
  45344. }
  45345. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  45346. {
  45347. for (int i = 0; i < mappings.size(); ++i)
  45348. if (mappings.getUnchecked(i)->commandID == commandID)
  45349. return mappings.getUnchecked (i)->keypresses;
  45350. return Array <KeyPress> ();
  45351. }
  45352. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  45353. const KeyPress& newKeyPress,
  45354. int insertIndex) throw()
  45355. {
  45356. if (findCommandForKeyPress (newKeyPress) != commandID)
  45357. {
  45358. removeKeyPress (newKeyPress);
  45359. if (newKeyPress.isValid())
  45360. {
  45361. for (int i = mappings.size(); --i >= 0;)
  45362. {
  45363. if (mappings.getUnchecked(i)->commandID == commandID)
  45364. {
  45365. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  45366. sendChangeMessage (this);
  45367. return;
  45368. }
  45369. }
  45370. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45371. if (ci != 0)
  45372. {
  45373. CommandMapping* const cm = new CommandMapping();
  45374. cm->commandID = commandID;
  45375. cm->keypresses.add (newKeyPress);
  45376. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  45377. mappings.add (cm);
  45378. sendChangeMessage (this);
  45379. }
  45380. }
  45381. }
  45382. }
  45383. void KeyPressMappingSet::resetToDefaultMappings() throw()
  45384. {
  45385. mappings.clear();
  45386. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  45387. {
  45388. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  45389. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45390. {
  45391. addKeyPress (ci->commandID,
  45392. ci->defaultKeypresses.getReference (j));
  45393. }
  45394. }
  45395. sendChangeMessage (this);
  45396. }
  45397. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  45398. {
  45399. clearAllKeyPresses (commandID);
  45400. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45401. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45402. {
  45403. addKeyPress (ci->commandID,
  45404. ci->defaultKeypresses.getReference (j));
  45405. }
  45406. }
  45407. void KeyPressMappingSet::clearAllKeyPresses() throw()
  45408. {
  45409. if (mappings.size() > 0)
  45410. {
  45411. sendChangeMessage (this);
  45412. mappings.clear();
  45413. }
  45414. }
  45415. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  45416. {
  45417. for (int i = mappings.size(); --i >= 0;)
  45418. {
  45419. if (mappings.getUnchecked(i)->commandID == commandID)
  45420. {
  45421. mappings.remove (i);
  45422. sendChangeMessage (this);
  45423. }
  45424. }
  45425. }
  45426. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  45427. {
  45428. if (keypress.isValid())
  45429. {
  45430. for (int i = mappings.size(); --i >= 0;)
  45431. {
  45432. CommandMapping* const cm = mappings.getUnchecked(i);
  45433. for (int j = cm->keypresses.size(); --j >= 0;)
  45434. {
  45435. if (keypress == cm->keypresses [j])
  45436. {
  45437. cm->keypresses.remove (j);
  45438. sendChangeMessage (this);
  45439. }
  45440. }
  45441. }
  45442. }
  45443. }
  45444. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  45445. const int keyPressIndex) throw()
  45446. {
  45447. for (int i = mappings.size(); --i >= 0;)
  45448. {
  45449. if (mappings.getUnchecked(i)->commandID == commandID)
  45450. {
  45451. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  45452. sendChangeMessage (this);
  45453. break;
  45454. }
  45455. }
  45456. }
  45457. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  45458. {
  45459. for (int i = 0; i < mappings.size(); ++i)
  45460. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  45461. return mappings.getUnchecked(i)->commandID;
  45462. return 0;
  45463. }
  45464. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  45465. const KeyPress& keyPress) const throw()
  45466. {
  45467. for (int i = mappings.size(); --i >= 0;)
  45468. if (mappings.getUnchecked(i)->commandID == commandID)
  45469. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  45470. return false;
  45471. }
  45472. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  45473. const KeyPress& key,
  45474. const bool isKeyDown,
  45475. const int millisecsSinceKeyPressed,
  45476. Component* const originatingComponent) const
  45477. {
  45478. ApplicationCommandTarget::InvocationInfo info (commandID);
  45479. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  45480. info.isKeyDown = isKeyDown;
  45481. info.keyPress = key;
  45482. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  45483. info.originatingComponent = originatingComponent;
  45484. commandManager->invoke (info, false);
  45485. }
  45486. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  45487. {
  45488. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  45489. {
  45490. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  45491. {
  45492. // if the XML was created as a set of differences from the default mappings,
  45493. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  45494. resetToDefaultMappings();
  45495. }
  45496. else
  45497. {
  45498. // if the XML was created calling createXml (false), then we need to clear all
  45499. // the keys and treat the xml as describing the entire set of mappings.
  45500. clearAllKeyPresses();
  45501. }
  45502. forEachXmlChildElement (xmlVersion, map)
  45503. {
  45504. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  45505. if (commandId != 0)
  45506. {
  45507. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  45508. if (map->hasTagName (T("MAPPING")))
  45509. {
  45510. addKeyPress (commandId, key);
  45511. }
  45512. else if (map->hasTagName (T("UNMAPPING")))
  45513. {
  45514. if (containsMapping (commandId, key))
  45515. removeKeyPress (key);
  45516. }
  45517. }
  45518. }
  45519. return true;
  45520. }
  45521. return false;
  45522. }
  45523. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  45524. {
  45525. KeyPressMappingSet* defaultSet = 0;
  45526. if (saveDifferencesFromDefaultSet)
  45527. {
  45528. defaultSet = new KeyPressMappingSet (commandManager);
  45529. defaultSet->resetToDefaultMappings();
  45530. }
  45531. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  45532. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  45533. int i;
  45534. for (i = 0; i < mappings.size(); ++i)
  45535. {
  45536. const CommandMapping* const cm = mappings.getUnchecked(i);
  45537. for (int j = 0; j < cm->keypresses.size(); ++j)
  45538. {
  45539. if (defaultSet == 0
  45540. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45541. {
  45542. XmlElement* const map = new XmlElement (T("MAPPING"));
  45543. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45544. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45545. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45546. doc->addChildElement (map);
  45547. }
  45548. }
  45549. }
  45550. if (defaultSet != 0)
  45551. {
  45552. for (i = 0; i < defaultSet->mappings.size(); ++i)
  45553. {
  45554. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  45555. for (int j = 0; j < cm->keypresses.size(); ++j)
  45556. {
  45557. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45558. {
  45559. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  45560. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45561. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45562. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45563. doc->addChildElement (map);
  45564. }
  45565. }
  45566. }
  45567. delete defaultSet;
  45568. }
  45569. return doc;
  45570. }
  45571. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  45572. Component* originatingComponent)
  45573. {
  45574. bool used = false;
  45575. const CommandID commandID = findCommandForKeyPress (key);
  45576. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45577. if (ci != 0
  45578. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  45579. {
  45580. ApplicationCommandInfo info (0);
  45581. if (commandManager->getTargetForCommand (commandID, info) != 0
  45582. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  45583. {
  45584. invokeCommand (commandID, key, true, 0, originatingComponent);
  45585. used = true;
  45586. }
  45587. else
  45588. {
  45589. if (originatingComponent != 0)
  45590. originatingComponent->getLookAndFeel().playAlertSound();
  45591. }
  45592. }
  45593. return used;
  45594. }
  45595. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  45596. {
  45597. bool used = false;
  45598. const uint32 now = Time::getMillisecondCounter();
  45599. for (int i = mappings.size(); --i >= 0;)
  45600. {
  45601. CommandMapping* const cm = mappings.getUnchecked(i);
  45602. if (cm->wantsKeyUpDownCallbacks)
  45603. {
  45604. for (int j = cm->keypresses.size(); --j >= 0;)
  45605. {
  45606. const KeyPress key (cm->keypresses.getReference (j));
  45607. const bool isDown = key.isCurrentlyDown();
  45608. int keyPressEntryIndex = 0;
  45609. bool wasDown = false;
  45610. for (int k = keysDown.size(); --k >= 0;)
  45611. {
  45612. if (key == keysDown.getUnchecked(k)->key)
  45613. {
  45614. keyPressEntryIndex = k;
  45615. wasDown = true;
  45616. used = true;
  45617. break;
  45618. }
  45619. }
  45620. if (isDown != wasDown)
  45621. {
  45622. int millisecs = 0;
  45623. if (isDown)
  45624. {
  45625. KeyPressTime* const k = new KeyPressTime();
  45626. k->key = key;
  45627. k->timeWhenPressed = now;
  45628. keysDown.add (k);
  45629. }
  45630. else
  45631. {
  45632. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  45633. if (now > pressTime)
  45634. millisecs = now - pressTime;
  45635. keysDown.remove (keyPressEntryIndex);
  45636. }
  45637. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  45638. used = true;
  45639. }
  45640. }
  45641. }
  45642. }
  45643. return used;
  45644. }
  45645. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  45646. {
  45647. if (focusedComponent != 0)
  45648. focusedComponent->keyStateChanged (false);
  45649. }
  45650. END_JUCE_NAMESPACE
  45651. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  45652. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  45653. BEGIN_JUCE_NAMESPACE
  45654. ModifierKeys::ModifierKeys (const int flags_) throw()
  45655. : flags (flags_)
  45656. {
  45657. }
  45658. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  45659. : flags (other.flags)
  45660. {
  45661. }
  45662. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  45663. {
  45664. flags = other.flags;
  45665. return *this;
  45666. }
  45667. int ModifierKeys::currentModifierFlags = 0;
  45668. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  45669. {
  45670. return ModifierKeys (currentModifierFlags);
  45671. }
  45672. END_JUCE_NAMESPACE
  45673. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  45674. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  45675. BEGIN_JUCE_NAMESPACE
  45676. struct AnimationTask
  45677. {
  45678. AnimationTask (Component* const comp)
  45679. : component (comp),
  45680. watcher (comp)
  45681. {
  45682. }
  45683. Component* component;
  45684. ComponentDeletionWatcher watcher;
  45685. Rectangle destination;
  45686. int msElapsed, msTotal;
  45687. double startSpeed, midSpeed, endSpeed, lastProgress;
  45688. double left, top, right, bottom;
  45689. bool useTimeslice (const int elapsed)
  45690. {
  45691. if (watcher.hasBeenDeleted())
  45692. return false;
  45693. msElapsed += elapsed;
  45694. double newProgress = msElapsed / (double) msTotal;
  45695. if (newProgress >= 0 && newProgress < 1.0)
  45696. {
  45697. newProgress = timeToDistance (newProgress);
  45698. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  45699. jassert (newProgress >= lastProgress);
  45700. lastProgress = newProgress;
  45701. left += (destination.getX() - left) * delta;
  45702. top += (destination.getY() - top) * delta;
  45703. right += (destination.getRight() - right) * delta;
  45704. bottom += (destination.getBottom() - bottom) * delta;
  45705. if (delta < 1.0)
  45706. {
  45707. const Rectangle newBounds (roundDoubleToInt (left),
  45708. roundDoubleToInt (top),
  45709. roundDoubleToInt (right - left),
  45710. roundDoubleToInt (bottom - top));
  45711. if (newBounds != destination)
  45712. {
  45713. component->setBounds (newBounds);
  45714. return true;
  45715. }
  45716. }
  45717. }
  45718. component->setBounds (destination);
  45719. return false;
  45720. }
  45721. void moveToFinalDestination()
  45722. {
  45723. if (! watcher.hasBeenDeleted())
  45724. component->setBounds (destination);
  45725. }
  45726. private:
  45727. inline double timeToDistance (const double time) const
  45728. {
  45729. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  45730. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  45731. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  45732. }
  45733. };
  45734. ComponentAnimator::ComponentAnimator()
  45735. : lastTime (0)
  45736. {
  45737. }
  45738. ComponentAnimator::~ComponentAnimator()
  45739. {
  45740. cancelAllAnimations (false);
  45741. jassert (tasks.size() == 0);
  45742. }
  45743. void* ComponentAnimator::findTaskFor (Component* const component) const
  45744. {
  45745. for (int i = tasks.size(); --i >= 0;)
  45746. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  45747. return tasks.getUnchecked(i);
  45748. return 0;
  45749. }
  45750. void ComponentAnimator::animateComponent (Component* const component,
  45751. const Rectangle& finalPosition,
  45752. const int millisecondsToSpendMoving,
  45753. const double startSpeed,
  45754. const double endSpeed)
  45755. {
  45756. if (component != 0)
  45757. {
  45758. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  45759. if (at == 0)
  45760. {
  45761. at = new AnimationTask (component);
  45762. tasks.add (at);
  45763. sendChangeMessage (this);
  45764. }
  45765. at->msElapsed = 0;
  45766. at->lastProgress = 0;
  45767. at->msTotal = jmax (1, millisecondsToSpendMoving);
  45768. at->destination = finalPosition;
  45769. // the speeds must be 0 or greater!
  45770. jassert (startSpeed >= 0 && endSpeed >= 0)
  45771. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  45772. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  45773. at->midSpeed = invTotalDistance;
  45774. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  45775. at->left = component->getX();
  45776. at->top = component->getY();
  45777. at->right = component->getRight();
  45778. at->bottom = component->getBottom();
  45779. if (! isTimerRunning())
  45780. {
  45781. lastTime = Time::getMillisecondCounter();
  45782. startTimer (1000 / 50);
  45783. }
  45784. }
  45785. }
  45786. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  45787. {
  45788. for (int i = tasks.size(); --i >= 0;)
  45789. {
  45790. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45791. if (moveComponentsToTheirFinalPositions)
  45792. at->moveToFinalDestination();
  45793. delete at;
  45794. tasks.remove (i);
  45795. sendChangeMessage (this);
  45796. }
  45797. }
  45798. void ComponentAnimator::cancelAnimation (Component* const component,
  45799. const bool moveComponentToItsFinalPosition)
  45800. {
  45801. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45802. if (at != 0)
  45803. {
  45804. if (moveComponentToItsFinalPosition)
  45805. at->moveToFinalDestination();
  45806. tasks.removeValue (at);
  45807. delete at;
  45808. sendChangeMessage (this);
  45809. }
  45810. }
  45811. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  45812. {
  45813. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45814. if (at != 0)
  45815. return at->destination;
  45816. else if (component != 0)
  45817. return component->getBounds();
  45818. return Rectangle();
  45819. }
  45820. bool ComponentAnimator::isAnimating (Component* component) const
  45821. {
  45822. return findTaskFor (component) != 0;
  45823. }
  45824. void ComponentAnimator::timerCallback()
  45825. {
  45826. const uint32 timeNow = Time::getMillisecondCounter();
  45827. if (lastTime == 0 || lastTime == timeNow)
  45828. lastTime = timeNow;
  45829. const int elapsed = timeNow - lastTime;
  45830. for (int i = tasks.size(); --i >= 0;)
  45831. {
  45832. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45833. if (! at->useTimeslice (elapsed))
  45834. {
  45835. tasks.remove (i);
  45836. delete at;
  45837. sendChangeMessage (this);
  45838. }
  45839. }
  45840. lastTime = timeNow;
  45841. if (tasks.size() == 0)
  45842. stopTimer();
  45843. }
  45844. END_JUCE_NAMESPACE
  45845. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  45846. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  45847. BEGIN_JUCE_NAMESPACE
  45848. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  45849. : minW (0),
  45850. maxW (0x3fffffff),
  45851. minH (0),
  45852. maxH (0x3fffffff),
  45853. minOffTop (0),
  45854. minOffLeft (0),
  45855. minOffBottom (0),
  45856. minOffRight (0),
  45857. aspectRatio (0.0)
  45858. {
  45859. }
  45860. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  45861. {
  45862. }
  45863. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  45864. {
  45865. minW = minimumWidth;
  45866. }
  45867. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  45868. {
  45869. maxW = maximumWidth;
  45870. }
  45871. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  45872. {
  45873. minH = minimumHeight;
  45874. }
  45875. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  45876. {
  45877. maxH = maximumHeight;
  45878. }
  45879. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  45880. {
  45881. jassert (maxW >= minimumWidth);
  45882. jassert (maxH >= minimumHeight);
  45883. jassert (minimumWidth > 0 && minimumHeight > 0);
  45884. minW = minimumWidth;
  45885. minH = minimumHeight;
  45886. if (minW > maxW)
  45887. maxW = minW;
  45888. if (minH > maxH)
  45889. maxH = minH;
  45890. }
  45891. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  45892. {
  45893. jassert (maximumWidth >= minW);
  45894. jassert (maximumHeight >= minH);
  45895. jassert (maximumWidth > 0 && maximumHeight > 0);
  45896. maxW = jmax (minW, maximumWidth);
  45897. maxH = jmax (minH, maximumHeight);
  45898. }
  45899. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  45900. const int minimumHeight,
  45901. const int maximumWidth,
  45902. const int maximumHeight) throw()
  45903. {
  45904. jassert (maximumWidth >= minimumWidth);
  45905. jassert (maximumHeight >= minimumHeight);
  45906. jassert (maximumWidth > 0 && maximumHeight > 0);
  45907. jassert (minimumWidth > 0 && minimumHeight > 0);
  45908. minW = jmax (0, minimumWidth);
  45909. minH = jmax (0, minimumHeight);
  45910. maxW = jmax (minW, maximumWidth);
  45911. maxH = jmax (minH, maximumHeight);
  45912. }
  45913. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  45914. const int minimumWhenOffTheLeft,
  45915. const int minimumWhenOffTheBottom,
  45916. const int minimumWhenOffTheRight) throw()
  45917. {
  45918. minOffTop = minimumWhenOffTheTop;
  45919. minOffLeft = minimumWhenOffTheLeft;
  45920. minOffBottom = minimumWhenOffTheBottom;
  45921. minOffRight = minimumWhenOffTheRight;
  45922. }
  45923. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  45924. {
  45925. aspectRatio = jmax (0.0, widthOverHeight);
  45926. }
  45927. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  45928. {
  45929. return aspectRatio;
  45930. }
  45931. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  45932. int x, int y, int w, int h,
  45933. const bool isStretchingTop,
  45934. const bool isStretchingLeft,
  45935. const bool isStretchingBottom,
  45936. const bool isStretchingRight)
  45937. {
  45938. jassert (component != 0);
  45939. Rectangle limits;
  45940. Component* const p = component->getParentComponent();
  45941. if (p == 0)
  45942. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  45943. else
  45944. limits.setSize (p->getWidth(), p->getHeight());
  45945. if (component->isOnDesktop())
  45946. {
  45947. ComponentPeer* const peer = component->getPeer();
  45948. const BorderSize border (peer->getFrameSize());
  45949. x -= border.getLeft();
  45950. y -= border.getTop();
  45951. w += border.getLeftAndRight();
  45952. h += border.getTopAndBottom();
  45953. checkBounds (x, y, w, h,
  45954. border.addedTo (component->getBounds()), limits,
  45955. isStretchingTop, isStretchingLeft,
  45956. isStretchingBottom, isStretchingRight);
  45957. x += border.getLeft();
  45958. y += border.getTop();
  45959. w -= border.getLeftAndRight();
  45960. h -= border.getTopAndBottom();
  45961. }
  45962. else
  45963. {
  45964. checkBounds (x, y, w, h,
  45965. component->getBounds(), limits,
  45966. isStretchingTop, isStretchingLeft,
  45967. isStretchingBottom, isStretchingRight);
  45968. }
  45969. applyBoundsToComponent (component, x, y, w, h);
  45970. }
  45971. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  45972. {
  45973. setBoundsForComponent (component,
  45974. component->getX(), component->getY(),
  45975. component->getWidth(), component->getHeight(),
  45976. false, false, false, false);
  45977. }
  45978. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  45979. int x, int y, int w, int h)
  45980. {
  45981. component->setBounds (x, y, w, h);
  45982. }
  45983. void ComponentBoundsConstrainer::resizeStart()
  45984. {
  45985. }
  45986. void ComponentBoundsConstrainer::resizeEnd()
  45987. {
  45988. }
  45989. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  45990. const Rectangle& old,
  45991. const Rectangle& limits,
  45992. const bool isStretchingTop,
  45993. const bool isStretchingLeft,
  45994. const bool isStretchingBottom,
  45995. const bool isStretchingRight)
  45996. {
  45997. // constrain the size if it's being stretched..
  45998. if (isStretchingLeft)
  45999. {
  46000. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  46001. w = old.getRight() - x;
  46002. }
  46003. if (isStretchingRight)
  46004. {
  46005. w = jlimit (minW, maxW, w);
  46006. }
  46007. if (isStretchingTop)
  46008. {
  46009. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  46010. h = old.getBottom() - y;
  46011. }
  46012. if (isStretchingBottom)
  46013. {
  46014. h = jlimit (minH, maxH, h);
  46015. }
  46016. // constrain the aspect ratio if one has been specified..
  46017. if (aspectRatio > 0.0 && w > 0 && h > 0)
  46018. {
  46019. bool adjustWidth;
  46020. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46021. {
  46022. adjustWidth = true;
  46023. }
  46024. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46025. {
  46026. adjustWidth = false;
  46027. }
  46028. else
  46029. {
  46030. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  46031. const double newRatio = fabs (w / (double) h);
  46032. adjustWidth = (oldRatio > newRatio);
  46033. }
  46034. if (adjustWidth)
  46035. {
  46036. w = roundDoubleToInt (h * aspectRatio);
  46037. if (w > maxW || w < minW)
  46038. {
  46039. w = jlimit (minW, maxW, w);
  46040. h = roundDoubleToInt (w / aspectRatio);
  46041. }
  46042. }
  46043. else
  46044. {
  46045. h = roundDoubleToInt (w / aspectRatio);
  46046. if (h > maxH || h < minH)
  46047. {
  46048. h = jlimit (minH, maxH, h);
  46049. w = roundDoubleToInt (h * aspectRatio);
  46050. }
  46051. }
  46052. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46053. {
  46054. x = old.getX() + (old.getWidth() - w) / 2;
  46055. }
  46056. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46057. {
  46058. y = old.getY() + (old.getHeight() - h) / 2;
  46059. }
  46060. else
  46061. {
  46062. if (isStretchingLeft)
  46063. x = old.getRight() - w;
  46064. if (isStretchingTop)
  46065. y = old.getBottom() - h;
  46066. }
  46067. }
  46068. // ...and constrain the position if limits have been set for that.
  46069. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  46070. {
  46071. if (minOffTop > 0)
  46072. {
  46073. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  46074. if (y < limit)
  46075. {
  46076. if (isStretchingTop)
  46077. h -= (limit - y);
  46078. y = limit;
  46079. }
  46080. }
  46081. if (minOffLeft > 0)
  46082. {
  46083. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  46084. if (x < limit)
  46085. {
  46086. if (isStretchingLeft)
  46087. w -= (limit - x);
  46088. x = limit;
  46089. }
  46090. }
  46091. if (minOffBottom > 0)
  46092. {
  46093. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  46094. if (y > limit)
  46095. {
  46096. if (isStretchingBottom)
  46097. h += (limit - y);
  46098. else
  46099. y = limit;
  46100. }
  46101. }
  46102. if (minOffRight > 0)
  46103. {
  46104. const int limit = limits.getRight() - jmin (minOffRight, w);
  46105. if (x > limit)
  46106. {
  46107. if (isStretchingRight)
  46108. w += (limit - x);
  46109. else
  46110. x = limit;
  46111. }
  46112. }
  46113. }
  46114. jassert (w >= 0 && h >= 0);
  46115. }
  46116. END_JUCE_NAMESPACE
  46117. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  46118. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46119. BEGIN_JUCE_NAMESPACE
  46120. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  46121. : component (component_),
  46122. lastPeer (0),
  46123. registeredParentComps (4),
  46124. reentrant (false)
  46125. {
  46126. jassert (component != 0); // can't use this with a null pointer..
  46127. #ifdef JUCE_DEBUG
  46128. deletionWatcher = new ComponentDeletionWatcher (component_);
  46129. #endif
  46130. component->addComponentListener (this);
  46131. registerWithParentComps();
  46132. }
  46133. ComponentMovementWatcher::~ComponentMovementWatcher()
  46134. {
  46135. component->removeComponentListener (this);
  46136. unregister();
  46137. #ifdef JUCE_DEBUG
  46138. delete deletionWatcher;
  46139. #endif
  46140. }
  46141. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  46142. {
  46143. #ifdef JUCE_DEBUG
  46144. // agh! don't delete the target component without deleting this object first!
  46145. jassert (! deletionWatcher->hasBeenDeleted());
  46146. #endif
  46147. if (! reentrant)
  46148. {
  46149. reentrant = true;
  46150. ComponentPeer* const peer = component->getPeer();
  46151. if (peer != lastPeer)
  46152. {
  46153. ComponentDeletionWatcher watcher (component);
  46154. componentPeerChanged();
  46155. if (watcher.hasBeenDeleted())
  46156. return;
  46157. lastPeer = peer;
  46158. }
  46159. unregister();
  46160. registerWithParentComps();
  46161. reentrant = false;
  46162. componentMovedOrResized (*component, true, true);
  46163. }
  46164. }
  46165. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  46166. {
  46167. #ifdef JUCE_DEBUG
  46168. // agh! don't delete the target component without deleting this object first!
  46169. jassert (! deletionWatcher->hasBeenDeleted());
  46170. #endif
  46171. if (wasMoved)
  46172. {
  46173. int x = 0, y = 0;
  46174. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  46175. wasMoved = (lastX != x || lastY != y);
  46176. lastX = x;
  46177. lastY = y;
  46178. }
  46179. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  46180. lastWidth = component->getWidth();
  46181. lastHeight = component->getHeight();
  46182. if (wasMoved || wasResized)
  46183. componentMovedOrResized (wasMoved, wasResized);
  46184. }
  46185. void ComponentMovementWatcher::registerWithParentComps() throw()
  46186. {
  46187. Component* p = component->getParentComponent();
  46188. while (p != 0)
  46189. {
  46190. p->addComponentListener (this);
  46191. registeredParentComps.add (p);
  46192. p = p->getParentComponent();
  46193. }
  46194. }
  46195. void ComponentMovementWatcher::unregister() throw()
  46196. {
  46197. for (int i = registeredParentComps.size(); --i >= 0;)
  46198. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  46199. registeredParentComps.clear();
  46200. }
  46201. END_JUCE_NAMESPACE
  46202. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46203. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  46204. BEGIN_JUCE_NAMESPACE
  46205. GroupComponent::GroupComponent (const String& componentName,
  46206. const String& labelText)
  46207. : Component (componentName),
  46208. text (labelText),
  46209. justification (Justification::left)
  46210. {
  46211. setInterceptsMouseClicks (false, true);
  46212. }
  46213. GroupComponent::~GroupComponent()
  46214. {
  46215. }
  46216. void GroupComponent::setText (const String& newText) throw()
  46217. {
  46218. if (text != newText)
  46219. {
  46220. text = newText;
  46221. repaint();
  46222. }
  46223. }
  46224. const String GroupComponent::getText() const throw()
  46225. {
  46226. return text;
  46227. }
  46228. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  46229. {
  46230. if (justification.getFlags() != newJustification.getFlags())
  46231. {
  46232. justification = newJustification;
  46233. repaint();
  46234. }
  46235. }
  46236. void GroupComponent::paint (Graphics& g)
  46237. {
  46238. getLookAndFeel()
  46239. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  46240. text, justification,
  46241. *this);
  46242. }
  46243. void GroupComponent::enablementChanged()
  46244. {
  46245. repaint();
  46246. }
  46247. void GroupComponent::colourChanged()
  46248. {
  46249. repaint();
  46250. }
  46251. END_JUCE_NAMESPACE
  46252. /********* End of inlined file: juce_GroupComponent.cpp *********/
  46253. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  46254. BEGIN_JUCE_NAMESPACE
  46255. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  46256. : DocumentWindow (String::empty, backgroundColour,
  46257. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  46258. {
  46259. }
  46260. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  46261. {
  46262. }
  46263. void MultiDocumentPanelWindow::maximiseButtonPressed()
  46264. {
  46265. MultiDocumentPanel* const owner = getOwner();
  46266. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46267. if (owner != 0)
  46268. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  46269. }
  46270. void MultiDocumentPanelWindow::closeButtonPressed()
  46271. {
  46272. MultiDocumentPanel* const owner = getOwner();
  46273. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46274. if (owner != 0)
  46275. owner->closeDocument (getContentComponent(), true);
  46276. }
  46277. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  46278. {
  46279. DocumentWindow::activeWindowStatusChanged();
  46280. updateOrder();
  46281. }
  46282. void MultiDocumentPanelWindow::broughtToFront()
  46283. {
  46284. DocumentWindow::broughtToFront();
  46285. updateOrder();
  46286. }
  46287. void MultiDocumentPanelWindow::updateOrder()
  46288. {
  46289. MultiDocumentPanel* const owner = getOwner();
  46290. if (owner != 0)
  46291. owner->updateOrder();
  46292. }
  46293. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  46294. {
  46295. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46296. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46297. }
  46298. class MDITabbedComponentInternal : public TabbedComponent
  46299. {
  46300. public:
  46301. MDITabbedComponentInternal()
  46302. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  46303. {
  46304. }
  46305. ~MDITabbedComponentInternal()
  46306. {
  46307. }
  46308. void currentTabChanged (const int, const String&)
  46309. {
  46310. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46311. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46312. if (owner != 0)
  46313. owner->updateOrder();
  46314. }
  46315. };
  46316. MultiDocumentPanel::MultiDocumentPanel()
  46317. : mode (MaximisedWindowsWithTabs),
  46318. tabComponent (0),
  46319. backgroundColour (Colours::lightblue),
  46320. maximumNumDocuments (0),
  46321. numDocsBeforeTabsUsed (0)
  46322. {
  46323. setOpaque (true);
  46324. }
  46325. MultiDocumentPanel::~MultiDocumentPanel()
  46326. {
  46327. closeAllDocuments (false);
  46328. }
  46329. static bool shouldDeleteComp (Component* const c)
  46330. {
  46331. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  46332. }
  46333. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  46334. {
  46335. while (components.size() > 0)
  46336. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  46337. return false;
  46338. return true;
  46339. }
  46340. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  46341. {
  46342. return new MultiDocumentPanelWindow (backgroundColour);
  46343. }
  46344. void MultiDocumentPanel::addWindow (Component* component)
  46345. {
  46346. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  46347. dw->setResizable (true, false);
  46348. dw->setContentComponent (component, false, true);
  46349. dw->setName (component->getName());
  46350. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  46351. int x = 4;
  46352. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  46353. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  46354. x += 16;
  46355. dw->setTopLeftPosition (x, x);
  46356. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  46357. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  46358. addAndMakeVisible (dw);
  46359. dw->toFront (true);
  46360. }
  46361. bool MultiDocumentPanel::addDocument (Component* const component,
  46362. const Colour& docColour,
  46363. const bool deleteWhenRemoved)
  46364. {
  46365. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  46366. // with a frame-within-a-frame! Just pass in the bare content component.
  46367. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  46368. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  46369. return false;
  46370. components.add (component);
  46371. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  46372. component->setComponentProperty (T("mdiDocumentBkg_"), docColour);
  46373. component->addComponentListener (this);
  46374. if (mode == FloatingWindows)
  46375. {
  46376. if (isFullscreenWhenOneDocument())
  46377. {
  46378. if (components.size() == 1)
  46379. {
  46380. addAndMakeVisible (component);
  46381. }
  46382. else
  46383. {
  46384. if (components.size() == 2)
  46385. addWindow (components.getFirst());
  46386. addWindow (component);
  46387. }
  46388. }
  46389. else
  46390. {
  46391. addWindow (component);
  46392. }
  46393. }
  46394. else
  46395. {
  46396. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  46397. {
  46398. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  46399. Array <Component*> temp (components);
  46400. for (int i = 0; i < temp.size(); ++i)
  46401. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  46402. resized();
  46403. }
  46404. else
  46405. {
  46406. if (tabComponent != 0)
  46407. tabComponent->addTab (component->getName(), docColour, component, false);
  46408. else
  46409. addAndMakeVisible (component);
  46410. }
  46411. setActiveDocument (component);
  46412. }
  46413. resized();
  46414. activeDocumentChanged();
  46415. return true;
  46416. }
  46417. bool MultiDocumentPanel::closeDocument (Component* component,
  46418. const bool checkItsOkToCloseFirst)
  46419. {
  46420. if (components.contains (component))
  46421. {
  46422. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  46423. return false;
  46424. component->removeComponentListener (this);
  46425. const bool shouldDelete = shouldDeleteComp (component);
  46426. component->removeComponentProperty (T("mdiDocumentDelete_"));
  46427. component->removeComponentProperty (T("mdiDocumentBkg_"));
  46428. if (mode == FloatingWindows)
  46429. {
  46430. for (int i = getNumChildComponents(); --i >= 0;)
  46431. {
  46432. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46433. if (dw != 0 && dw->getContentComponent() == component)
  46434. {
  46435. dw->setContentComponent (0, false);
  46436. delete dw;
  46437. break;
  46438. }
  46439. }
  46440. if (shouldDelete)
  46441. delete component;
  46442. components.removeValue (component);
  46443. if (isFullscreenWhenOneDocument() && components.size() == 1)
  46444. {
  46445. for (int i = getNumChildComponents(); --i >= 0;)
  46446. {
  46447. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46448. if (dw != 0)
  46449. {
  46450. dw->setContentComponent (0, false);
  46451. delete dw;
  46452. }
  46453. }
  46454. addAndMakeVisible (components.getFirst());
  46455. }
  46456. }
  46457. else
  46458. {
  46459. jassert (components.indexOf (component) >= 0);
  46460. if (tabComponent != 0)
  46461. {
  46462. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46463. if (tabComponent->getTabContentComponent (i) == component)
  46464. tabComponent->removeTab (i);
  46465. }
  46466. else
  46467. {
  46468. removeChildComponent (component);
  46469. }
  46470. if (shouldDelete)
  46471. delete component;
  46472. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  46473. deleteAndZero (tabComponent);
  46474. components.removeValue (component);
  46475. if (components.size() > 0 && tabComponent == 0)
  46476. addAndMakeVisible (components.getFirst());
  46477. }
  46478. resized();
  46479. activeDocumentChanged();
  46480. }
  46481. else
  46482. {
  46483. jassertfalse
  46484. }
  46485. return true;
  46486. }
  46487. int MultiDocumentPanel::getNumDocuments() const throw()
  46488. {
  46489. return components.size();
  46490. }
  46491. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  46492. {
  46493. return components [index];
  46494. }
  46495. Component* MultiDocumentPanel::getActiveDocument() const throw()
  46496. {
  46497. if (mode == FloatingWindows)
  46498. {
  46499. for (int i = getNumChildComponents(); --i >= 0;)
  46500. {
  46501. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46502. if (dw != 0 && dw->isActiveWindow())
  46503. return dw->getContentComponent();
  46504. }
  46505. }
  46506. return components.getLast();
  46507. }
  46508. void MultiDocumentPanel::setActiveDocument (Component* component)
  46509. {
  46510. if (mode == FloatingWindows)
  46511. {
  46512. component = getContainerComp (component);
  46513. if (component != 0)
  46514. component->toFront (true);
  46515. }
  46516. else if (tabComponent != 0)
  46517. {
  46518. jassert (components.indexOf (component) >= 0);
  46519. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46520. {
  46521. if (tabComponent->getTabContentComponent (i) == component)
  46522. {
  46523. tabComponent->setCurrentTabIndex (i);
  46524. break;
  46525. }
  46526. }
  46527. }
  46528. else
  46529. {
  46530. component->grabKeyboardFocus();
  46531. }
  46532. }
  46533. void MultiDocumentPanel::activeDocumentChanged()
  46534. {
  46535. }
  46536. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  46537. {
  46538. maximumNumDocuments = newNumber;
  46539. }
  46540. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  46541. {
  46542. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  46543. }
  46544. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  46545. {
  46546. return numDocsBeforeTabsUsed != 0;
  46547. }
  46548. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  46549. {
  46550. if (mode != newLayoutMode)
  46551. {
  46552. mode = newLayoutMode;
  46553. if (mode == FloatingWindows)
  46554. {
  46555. deleteAndZero (tabComponent);
  46556. }
  46557. else
  46558. {
  46559. for (int i = getNumChildComponents(); --i >= 0;)
  46560. {
  46561. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46562. if (dw != 0)
  46563. {
  46564. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  46565. dw->setContentComponent (0, false);
  46566. delete dw;
  46567. }
  46568. }
  46569. }
  46570. resized();
  46571. const Array <Component*> tempComps (components);
  46572. components.clear();
  46573. for (int i = 0; i < tempComps.size(); ++i)
  46574. {
  46575. Component* const c = tempComps.getUnchecked(i);
  46576. addDocument (c,
  46577. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  46578. shouldDeleteComp (c));
  46579. }
  46580. }
  46581. }
  46582. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  46583. {
  46584. if (backgroundColour != newBackgroundColour)
  46585. {
  46586. backgroundColour = newBackgroundColour;
  46587. setOpaque (newBackgroundColour.isOpaque());
  46588. repaint();
  46589. }
  46590. }
  46591. void MultiDocumentPanel::paint (Graphics& g)
  46592. {
  46593. g.fillAll (backgroundColour);
  46594. }
  46595. void MultiDocumentPanel::resized()
  46596. {
  46597. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  46598. {
  46599. for (int i = getNumChildComponents(); --i >= 0;)
  46600. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  46601. }
  46602. setWantsKeyboardFocus (components.size() == 0);
  46603. }
  46604. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  46605. {
  46606. if (mode == FloatingWindows)
  46607. {
  46608. for (int i = 0; i < getNumChildComponents(); ++i)
  46609. {
  46610. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46611. if (dw != 0 && dw->getContentComponent() == c)
  46612. {
  46613. c = dw;
  46614. break;
  46615. }
  46616. }
  46617. }
  46618. return c;
  46619. }
  46620. void MultiDocumentPanel::componentNameChanged (Component&)
  46621. {
  46622. if (mode == FloatingWindows)
  46623. {
  46624. for (int i = 0; i < getNumChildComponents(); ++i)
  46625. {
  46626. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46627. if (dw != 0)
  46628. dw->setName (dw->getContentComponent()->getName());
  46629. }
  46630. }
  46631. else if (tabComponent != 0)
  46632. {
  46633. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46634. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  46635. }
  46636. }
  46637. void MultiDocumentPanel::updateOrder()
  46638. {
  46639. const Array <Component*> oldList (components);
  46640. if (mode == FloatingWindows)
  46641. {
  46642. components.clear();
  46643. for (int i = 0; i < getNumChildComponents(); ++i)
  46644. {
  46645. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46646. if (dw != 0)
  46647. components.add (dw->getContentComponent());
  46648. }
  46649. }
  46650. else
  46651. {
  46652. if (tabComponent != 0)
  46653. {
  46654. Component* const current = tabComponent->getCurrentContentComponent();
  46655. if (current != 0)
  46656. {
  46657. components.removeValue (current);
  46658. components.add (current);
  46659. }
  46660. }
  46661. }
  46662. if (components != oldList)
  46663. activeDocumentChanged();
  46664. }
  46665. END_JUCE_NAMESPACE
  46666. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  46667. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  46668. BEGIN_JUCE_NAMESPACE
  46669. const int zoneL = 1;
  46670. const int zoneR = 2;
  46671. const int zoneT = 4;
  46672. const int zoneB = 8;
  46673. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  46674. ComponentBoundsConstrainer* const constrainer_)
  46675. : component (componentToResize),
  46676. constrainer (constrainer_),
  46677. borderSize (5),
  46678. mouseZone (0)
  46679. {
  46680. }
  46681. ResizableBorderComponent::~ResizableBorderComponent()
  46682. {
  46683. }
  46684. void ResizableBorderComponent::paint (Graphics& g)
  46685. {
  46686. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  46687. }
  46688. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  46689. {
  46690. updateMouseZone (e);
  46691. }
  46692. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  46693. {
  46694. updateMouseZone (e);
  46695. }
  46696. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  46697. {
  46698. if (component->isValidComponent())
  46699. {
  46700. updateMouseZone (e);
  46701. originalX = component->getX();
  46702. originalY = component->getY();
  46703. originalW = component->getWidth();
  46704. originalH = component->getHeight();
  46705. if (constrainer != 0)
  46706. constrainer->resizeStart();
  46707. }
  46708. else
  46709. {
  46710. jassertfalse
  46711. }
  46712. }
  46713. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  46714. {
  46715. if (! component->isValidComponent())
  46716. {
  46717. jassertfalse
  46718. return;
  46719. }
  46720. int x = originalX;
  46721. int y = originalY;
  46722. int w = originalW;
  46723. int h = originalH;
  46724. const int dx = e.getDistanceFromDragStartX();
  46725. const int dy = e.getDistanceFromDragStartY();
  46726. if ((mouseZone & zoneL) != 0)
  46727. {
  46728. x += dx;
  46729. w -= dx;
  46730. }
  46731. if ((mouseZone & zoneT) != 0)
  46732. {
  46733. y += dy;
  46734. h -= dy;
  46735. }
  46736. if ((mouseZone & zoneR) != 0)
  46737. w += dx;
  46738. if ((mouseZone & zoneB) != 0)
  46739. h += dy;
  46740. if (constrainer != 0)
  46741. constrainer->setBoundsForComponent (component,
  46742. x, y, w, h,
  46743. (mouseZone & zoneT) != 0,
  46744. (mouseZone & zoneL) != 0,
  46745. (mouseZone & zoneB) != 0,
  46746. (mouseZone & zoneR) != 0);
  46747. else
  46748. component->setBounds (x, y, w, h);
  46749. }
  46750. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  46751. {
  46752. if (constrainer != 0)
  46753. constrainer->resizeEnd();
  46754. }
  46755. bool ResizableBorderComponent::hitTest (int x, int y)
  46756. {
  46757. return x < borderSize.getLeft()
  46758. || x >= getWidth() - borderSize.getRight()
  46759. || y < borderSize.getTop()
  46760. || y >= getHeight() - borderSize.getBottom();
  46761. }
  46762. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  46763. {
  46764. if (borderSize != newBorderSize)
  46765. {
  46766. borderSize = newBorderSize;
  46767. repaint();
  46768. }
  46769. }
  46770. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  46771. {
  46772. return borderSize;
  46773. }
  46774. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  46775. {
  46776. int newZone = 0;
  46777. if (ResizableBorderComponent::hitTest (e.x, e.y))
  46778. {
  46779. if (e.x < jmax (borderSize.getLeft(),
  46780. proportionOfWidth (0.1f),
  46781. jmin (10, proportionOfWidth (0.33f))))
  46782. newZone |= zoneL;
  46783. else if (e.x >= jmin (getWidth() - borderSize.getRight(),
  46784. proportionOfWidth (0.9f),
  46785. getWidth() - jmin (10, proportionOfWidth (0.33f))))
  46786. newZone |= zoneR;
  46787. if (e.y < jmax (borderSize.getTop(),
  46788. proportionOfHeight (0.1f),
  46789. jmin (10, proportionOfHeight (0.33f))))
  46790. newZone |= zoneT;
  46791. else if (e.y >= jmin (getHeight() - borderSize.getBottom(),
  46792. proportionOfHeight (0.9f),
  46793. getHeight() - jmin (10, proportionOfHeight (0.33f))))
  46794. newZone |= zoneB;
  46795. }
  46796. if (mouseZone != newZone)
  46797. {
  46798. mouseZone = newZone;
  46799. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  46800. switch (newZone)
  46801. {
  46802. case (zoneL | zoneT):
  46803. mc = MouseCursor::TopLeftCornerResizeCursor;
  46804. break;
  46805. case zoneT:
  46806. mc = MouseCursor::TopEdgeResizeCursor;
  46807. break;
  46808. case (zoneR | zoneT):
  46809. mc = MouseCursor::TopRightCornerResizeCursor;
  46810. break;
  46811. case zoneL:
  46812. mc = MouseCursor::LeftEdgeResizeCursor;
  46813. break;
  46814. case zoneR:
  46815. mc = MouseCursor::RightEdgeResizeCursor;
  46816. break;
  46817. case (zoneL | zoneB):
  46818. mc = MouseCursor::BottomLeftCornerResizeCursor;
  46819. break;
  46820. case zoneB:
  46821. mc = MouseCursor::BottomEdgeResizeCursor;
  46822. break;
  46823. case (zoneR | zoneB):
  46824. mc = MouseCursor::BottomRightCornerResizeCursor;
  46825. break;
  46826. default:
  46827. break;
  46828. }
  46829. setMouseCursor (mc);
  46830. }
  46831. }
  46832. END_JUCE_NAMESPACE
  46833. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  46834. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  46835. BEGIN_JUCE_NAMESPACE
  46836. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  46837. ComponentBoundsConstrainer* const constrainer_)
  46838. : component (componentToResize),
  46839. constrainer (constrainer_)
  46840. {
  46841. setRepaintsOnMouseActivity (true);
  46842. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  46843. }
  46844. ResizableCornerComponent::~ResizableCornerComponent()
  46845. {
  46846. }
  46847. void ResizableCornerComponent::paint (Graphics& g)
  46848. {
  46849. getLookAndFeel()
  46850. .drawCornerResizer (g, getWidth(), getHeight(),
  46851. isMouseOverOrDragging(),
  46852. isMouseButtonDown());
  46853. }
  46854. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  46855. {
  46856. if (component->isValidComponent())
  46857. {
  46858. originalX = component->getX();
  46859. originalY = component->getY();
  46860. originalW = component->getWidth();
  46861. originalH = component->getHeight();
  46862. if (constrainer != 0)
  46863. constrainer->resizeStart();
  46864. }
  46865. else
  46866. {
  46867. jassertfalse
  46868. }
  46869. }
  46870. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  46871. {
  46872. if (! component->isValidComponent())
  46873. {
  46874. jassertfalse
  46875. return;
  46876. }
  46877. int x = originalX;
  46878. int y = originalY;
  46879. int w = originalW + e.getDistanceFromDragStartX();
  46880. int h = originalH + e.getDistanceFromDragStartY();
  46881. if (constrainer != 0)
  46882. constrainer->setBoundsForComponent (component, x, y, w, h,
  46883. false, false, true, true);
  46884. else
  46885. component->setBounds (x, y, w, h);
  46886. }
  46887. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  46888. {
  46889. if (constrainer != 0)
  46890. constrainer->resizeStart();
  46891. }
  46892. bool ResizableCornerComponent::hitTest (int x, int y)
  46893. {
  46894. if (getWidth() <= 0)
  46895. return false;
  46896. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  46897. return y >= yAtX - getHeight() / 4;
  46898. }
  46899. END_JUCE_NAMESPACE
  46900. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  46901. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  46902. BEGIN_JUCE_NAMESPACE
  46903. class ScrollbarButton : public Button
  46904. {
  46905. public:
  46906. int direction;
  46907. ScrollbarButton (const int direction_,
  46908. ScrollBar& owner_) throw()
  46909. : Button (String::empty),
  46910. direction (direction_),
  46911. owner (owner_)
  46912. {
  46913. setWantsKeyboardFocus (false);
  46914. }
  46915. ~ScrollbarButton()
  46916. {
  46917. }
  46918. void paintButton (Graphics& g,
  46919. bool isMouseOver,
  46920. bool isMouseDown)
  46921. {
  46922. getLookAndFeel()
  46923. .drawScrollbarButton (g, owner,
  46924. getWidth(), getHeight(),
  46925. direction,
  46926. owner.isVertical(),
  46927. isMouseOver, isMouseDown);
  46928. }
  46929. void clicked()
  46930. {
  46931. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  46932. }
  46933. juce_UseDebuggingNewOperator
  46934. private:
  46935. ScrollBar& owner;
  46936. ScrollbarButton (const ScrollbarButton&);
  46937. const ScrollbarButton& operator= (const ScrollbarButton&);
  46938. };
  46939. ScrollBar::ScrollBar (const bool vertical_,
  46940. const bool buttonsAreVisible)
  46941. : minimum (0.0),
  46942. maximum (1.0),
  46943. rangeStart (0.0),
  46944. rangeSize (0.1),
  46945. singleStepSize (0.1),
  46946. thumbAreaStart (0),
  46947. thumbAreaSize (0),
  46948. thumbStart (0),
  46949. thumbSize (0),
  46950. initialDelayInMillisecs (100),
  46951. repeatDelayInMillisecs (50),
  46952. minimumDelayInMillisecs (10),
  46953. vertical (vertical_),
  46954. isDraggingThumb (false),
  46955. alwaysVisible (false),
  46956. upButton (0),
  46957. downButton (0),
  46958. listeners (2)
  46959. {
  46960. setButtonVisibility (buttonsAreVisible);
  46961. setRepaintsOnMouseActivity (true);
  46962. setFocusContainer (true);
  46963. }
  46964. ScrollBar::~ScrollBar()
  46965. {
  46966. deleteAllChildren();
  46967. }
  46968. void ScrollBar::setRangeLimits (const double newMinimum,
  46969. const double newMaximum) throw()
  46970. {
  46971. minimum = newMinimum;
  46972. maximum = newMaximum;
  46973. jassert (maximum >= minimum); // these can't be the wrong way round!
  46974. setCurrentRangeStart (rangeStart);
  46975. updateThumbPosition();
  46976. }
  46977. void ScrollBar::setCurrentRange (double newStart,
  46978. double newSize) throw()
  46979. {
  46980. newSize = jlimit (0.0, maximum - minimum, newSize);
  46981. newStart = jlimit (minimum, maximum - newSize, newStart);
  46982. if (rangeStart != newStart
  46983. || rangeSize != newSize)
  46984. {
  46985. rangeStart = newStart;
  46986. rangeSize = newSize;
  46987. updateThumbPosition();
  46988. triggerAsyncUpdate();
  46989. }
  46990. }
  46991. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  46992. {
  46993. setCurrentRange (newStart, rangeSize);
  46994. }
  46995. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  46996. {
  46997. singleStepSize = newSingleStepSize;
  46998. }
  46999. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  47000. {
  47001. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  47002. }
  47003. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  47004. {
  47005. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  47006. }
  47007. void ScrollBar::scrollToTop() throw()
  47008. {
  47009. setCurrentRangeStart (minimum);
  47010. }
  47011. void ScrollBar::scrollToBottom() throw()
  47012. {
  47013. setCurrentRangeStart (maximum - rangeSize);
  47014. }
  47015. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  47016. const int repeatDelayInMillisecs_,
  47017. const int minimumDelayInMillisecs_) throw()
  47018. {
  47019. initialDelayInMillisecs = initialDelayInMillisecs_;
  47020. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  47021. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  47022. if (upButton != 0)
  47023. {
  47024. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47025. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47026. }
  47027. }
  47028. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  47029. {
  47030. jassert (listener != 0);
  47031. if (listener != 0)
  47032. listeners.add (listener);
  47033. }
  47034. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  47035. {
  47036. listeners.removeValue (listener);
  47037. }
  47038. void ScrollBar::handleAsyncUpdate()
  47039. {
  47040. const double value = getCurrentRangeStart();
  47041. for (int i = listeners.size(); --i >= 0;)
  47042. {
  47043. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  47044. i = jmin (i, listeners.size());
  47045. }
  47046. }
  47047. void ScrollBar::updateThumbPosition() throw()
  47048. {
  47049. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  47050. : thumbAreaSize);
  47051. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47052. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  47053. if (newThumbSize > thumbAreaSize)
  47054. newThumbSize = thumbAreaSize;
  47055. int newThumbStart = thumbAreaStart;
  47056. if (maximum - minimum > rangeSize)
  47057. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  47058. / ((maximum - minimum) - rangeSize));
  47059. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  47060. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  47061. {
  47062. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  47063. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  47064. if (vertical)
  47065. repaint (0, repaintStart, getWidth(), repaintSize);
  47066. else
  47067. repaint (repaintStart, 0, repaintSize, getHeight());
  47068. thumbStart = newThumbStart;
  47069. thumbSize = newThumbSize;
  47070. }
  47071. }
  47072. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  47073. {
  47074. if (vertical != shouldBeVertical)
  47075. {
  47076. vertical = shouldBeVertical;
  47077. if (upButton != 0)
  47078. {
  47079. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  47080. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  47081. }
  47082. updateThumbPosition();
  47083. }
  47084. }
  47085. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  47086. {
  47087. deleteAndZero (upButton);
  47088. deleteAndZero (downButton);
  47089. if (buttonsAreVisible)
  47090. {
  47091. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  47092. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  47093. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47094. }
  47095. updateThumbPosition();
  47096. }
  47097. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  47098. {
  47099. alwaysVisible = ! shouldHideWhenFullRange;
  47100. updateThumbPosition();
  47101. }
  47102. void ScrollBar::paint (Graphics& g)
  47103. {
  47104. if (thumbAreaSize > 0)
  47105. {
  47106. LookAndFeel& lf = getLookAndFeel();
  47107. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  47108. ? thumbSize : 0;
  47109. if (vertical)
  47110. {
  47111. lf.drawScrollbar (g, *this,
  47112. 0, thumbAreaStart,
  47113. getWidth(), thumbAreaSize,
  47114. vertical,
  47115. thumbStart, thumb,
  47116. isMouseOver(), isMouseButtonDown());
  47117. }
  47118. else
  47119. {
  47120. lf.drawScrollbar (g, *this,
  47121. thumbAreaStart, 0,
  47122. thumbAreaSize, getHeight(),
  47123. vertical,
  47124. thumbStart, thumb,
  47125. isMouseOver(), isMouseButtonDown());
  47126. }
  47127. }
  47128. }
  47129. void ScrollBar::lookAndFeelChanged()
  47130. {
  47131. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  47132. }
  47133. void ScrollBar::resized()
  47134. {
  47135. const int length = ((vertical) ? getHeight() : getWidth());
  47136. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  47137. : 0;
  47138. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47139. {
  47140. thumbAreaStart = length >> 1;
  47141. thumbAreaSize = 0;
  47142. }
  47143. else
  47144. {
  47145. thumbAreaStart = buttonSize;
  47146. thumbAreaSize = length - (buttonSize << 1);
  47147. }
  47148. if (upButton != 0)
  47149. {
  47150. if (vertical)
  47151. {
  47152. upButton->setBounds (0, 0, getWidth(), buttonSize);
  47153. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  47154. }
  47155. else
  47156. {
  47157. upButton->setBounds (0, 0, buttonSize, getHeight());
  47158. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  47159. }
  47160. }
  47161. updateThumbPosition();
  47162. }
  47163. void ScrollBar::mouseDown (const MouseEvent& e)
  47164. {
  47165. isDraggingThumb = false;
  47166. lastMousePos = vertical ? e.y : e.x;
  47167. dragStartMousePos = lastMousePos;
  47168. dragStartRange = rangeStart;
  47169. if (dragStartMousePos < thumbStart)
  47170. {
  47171. moveScrollbarInPages (-1);
  47172. startTimer (400);
  47173. }
  47174. else if (dragStartMousePos >= thumbStart + thumbSize)
  47175. {
  47176. moveScrollbarInPages (1);
  47177. startTimer (400);
  47178. }
  47179. else
  47180. {
  47181. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47182. && (thumbAreaSize > thumbSize);
  47183. }
  47184. }
  47185. void ScrollBar::mouseDrag (const MouseEvent& e)
  47186. {
  47187. if (isDraggingThumb)
  47188. {
  47189. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  47190. setCurrentRangeStart (dragStartRange
  47191. + deltaPixels * ((maximum - minimum) - rangeSize)
  47192. / (thumbAreaSize - thumbSize));
  47193. }
  47194. else
  47195. {
  47196. lastMousePos = (vertical) ? e.y : e.x;
  47197. }
  47198. }
  47199. void ScrollBar::mouseUp (const MouseEvent&)
  47200. {
  47201. isDraggingThumb = false;
  47202. stopTimer();
  47203. repaint();
  47204. }
  47205. void ScrollBar::mouseWheelMove (const MouseEvent&,
  47206. float wheelIncrementX,
  47207. float wheelIncrementY)
  47208. {
  47209. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  47210. if (increment < 0)
  47211. increment = jmin (increment * 10.0f, -1.0f);
  47212. else if (increment > 0)
  47213. increment = jmax (increment * 10.0f, 1.0f);
  47214. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  47215. }
  47216. void ScrollBar::timerCallback()
  47217. {
  47218. if (isMouseButtonDown())
  47219. {
  47220. startTimer (40);
  47221. if (lastMousePos < thumbStart)
  47222. setCurrentRangeStart (rangeStart - rangeSize);
  47223. else if (lastMousePos > thumbStart + thumbSize)
  47224. setCurrentRangeStart (rangeStart + rangeSize);
  47225. }
  47226. else
  47227. {
  47228. stopTimer();
  47229. }
  47230. }
  47231. bool ScrollBar::keyPressed (const KeyPress& key)
  47232. {
  47233. if (! isVisible())
  47234. return false;
  47235. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  47236. moveScrollbarInSteps (-1);
  47237. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  47238. moveScrollbarInSteps (1);
  47239. else if (key.isKeyCode (KeyPress::pageUpKey))
  47240. moveScrollbarInPages (-1);
  47241. else if (key.isKeyCode (KeyPress::pageDownKey))
  47242. moveScrollbarInPages (1);
  47243. else if (key.isKeyCode (KeyPress::homeKey))
  47244. scrollToTop();
  47245. else if (key.isKeyCode (KeyPress::endKey))
  47246. scrollToBottom();
  47247. else
  47248. return false;
  47249. return true;
  47250. }
  47251. END_JUCE_NAMESPACE
  47252. /********* End of inlined file: juce_ScrollBar.cpp *********/
  47253. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  47254. BEGIN_JUCE_NAMESPACE
  47255. StretchableLayoutManager::StretchableLayoutManager()
  47256. : totalSize (0)
  47257. {
  47258. }
  47259. StretchableLayoutManager::~StretchableLayoutManager()
  47260. {
  47261. }
  47262. void StretchableLayoutManager::clearAllItems()
  47263. {
  47264. items.clear();
  47265. totalSize = 0;
  47266. }
  47267. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  47268. const double minimumSize,
  47269. const double maximumSize,
  47270. const double preferredSize)
  47271. {
  47272. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  47273. if (layout == 0)
  47274. {
  47275. layout = new ItemLayoutProperties();
  47276. layout->itemIndex = itemIndex;
  47277. int i;
  47278. for (i = 0; i < items.size(); ++i)
  47279. if (items.getUnchecked (i)->itemIndex > itemIndex)
  47280. break;
  47281. items.insert (i, layout);
  47282. }
  47283. layout->minSize = minimumSize;
  47284. layout->maxSize = maximumSize;
  47285. layout->preferredSize = preferredSize;
  47286. layout->currentSize = 0;
  47287. }
  47288. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  47289. double& minimumSize,
  47290. double& maximumSize,
  47291. double& preferredSize) const
  47292. {
  47293. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47294. if (layout != 0)
  47295. {
  47296. minimumSize = layout->minSize;
  47297. maximumSize = layout->maxSize;
  47298. preferredSize = layout->preferredSize;
  47299. return true;
  47300. }
  47301. return false;
  47302. }
  47303. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  47304. {
  47305. totalSize = newTotalSize;
  47306. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  47307. }
  47308. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  47309. {
  47310. int pos = 0;
  47311. for (int i = 0; i < itemIndex; ++i)
  47312. {
  47313. const ItemLayoutProperties* const layout = getInfoFor (i);
  47314. if (layout != 0)
  47315. pos += layout->currentSize;
  47316. }
  47317. return pos;
  47318. }
  47319. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  47320. {
  47321. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47322. if (layout != 0)
  47323. return layout->currentSize;
  47324. return 0;
  47325. }
  47326. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  47327. {
  47328. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47329. if (layout != 0)
  47330. return -layout->currentSize / (double) totalSize;
  47331. return 0;
  47332. }
  47333. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  47334. int newPosition)
  47335. {
  47336. for (int i = items.size(); --i >= 0;)
  47337. {
  47338. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  47339. if (layout->itemIndex == itemIndex)
  47340. {
  47341. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  47342. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  47343. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  47344. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  47345. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  47346. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  47347. endPos += layout->currentSize;
  47348. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  47349. updatePrefSizesToMatchCurrentPositions();
  47350. break;
  47351. }
  47352. }
  47353. }
  47354. void StretchableLayoutManager::layOutComponents (Component** const components,
  47355. int numComponents,
  47356. int x, int y, int w, int h,
  47357. const bool vertically,
  47358. const bool resizeOtherDimension)
  47359. {
  47360. setTotalSize (vertically ? h : w);
  47361. int pos = vertically ? y : x;
  47362. for (int i = 0; i < numComponents; ++i)
  47363. {
  47364. const ItemLayoutProperties* const layout = getInfoFor (i);
  47365. if (layout != 0)
  47366. {
  47367. Component* const c = components[i];
  47368. if (c != 0)
  47369. {
  47370. if (i == numComponents - 1)
  47371. {
  47372. // if it's the last item, crop it to exactly fit the available space..
  47373. if (resizeOtherDimension)
  47374. {
  47375. if (vertically)
  47376. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  47377. else
  47378. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  47379. }
  47380. else
  47381. {
  47382. if (vertically)
  47383. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  47384. else
  47385. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  47386. }
  47387. }
  47388. else
  47389. {
  47390. if (resizeOtherDimension)
  47391. {
  47392. if (vertically)
  47393. c->setBounds (x, pos, w, layout->currentSize);
  47394. else
  47395. c->setBounds (pos, y, layout->currentSize, h);
  47396. }
  47397. else
  47398. {
  47399. if (vertically)
  47400. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  47401. else
  47402. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  47403. }
  47404. }
  47405. }
  47406. pos += layout->currentSize;
  47407. }
  47408. }
  47409. }
  47410. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  47411. {
  47412. for (int i = items.size(); --i >= 0;)
  47413. if (items.getUnchecked(i)->itemIndex == itemIndex)
  47414. return items.getUnchecked(i);
  47415. return 0;
  47416. }
  47417. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  47418. const int endIndex,
  47419. const int availableSpace,
  47420. int startPos)
  47421. {
  47422. // calculate the total sizes
  47423. int i;
  47424. double totalIdealSize = 0.0;
  47425. int totalMinimums = 0;
  47426. for (i = startIndex; i < endIndex; ++i)
  47427. {
  47428. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47429. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  47430. totalMinimums += layout->currentSize;
  47431. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  47432. }
  47433. if (totalIdealSize <= 0)
  47434. totalIdealSize = 1.0;
  47435. // now calc the best sizes..
  47436. int extraSpace = availableSpace - totalMinimums;
  47437. while (extraSpace > 0)
  47438. {
  47439. int numWantingMoreSpace = 0;
  47440. int numHavingTakenExtraSpace = 0;
  47441. // first figure out how many comps want a slice of the extra space..
  47442. for (i = startIndex; i < endIndex; ++i)
  47443. {
  47444. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47445. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47446. const int bestSize = jlimit (layout->currentSize,
  47447. jmax (layout->currentSize,
  47448. sizeToRealSize (layout->maxSize, totalSize)),
  47449. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47450. if (bestSize > layout->currentSize)
  47451. ++numWantingMoreSpace;
  47452. }
  47453. // ..share out the extra space..
  47454. for (i = startIndex; i < endIndex; ++i)
  47455. {
  47456. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47457. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47458. int bestSize = jlimit (layout->currentSize,
  47459. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  47460. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47461. const int extraWanted = bestSize - layout->currentSize;
  47462. if (extraWanted > 0)
  47463. {
  47464. const int extraAllowed = jmin (extraWanted,
  47465. extraSpace / jmax (1, numWantingMoreSpace));
  47466. if (extraAllowed > 0)
  47467. {
  47468. ++numHavingTakenExtraSpace;
  47469. --numWantingMoreSpace;
  47470. layout->currentSize += extraAllowed;
  47471. extraSpace -= extraAllowed;
  47472. }
  47473. }
  47474. }
  47475. if (numHavingTakenExtraSpace <= 0)
  47476. break;
  47477. }
  47478. // ..and calculate the end position
  47479. for (i = startIndex; i < endIndex; ++i)
  47480. {
  47481. ItemLayoutProperties* const layout = items.getUnchecked(i);
  47482. startPos += layout->currentSize;
  47483. }
  47484. return startPos;
  47485. }
  47486. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  47487. const int endIndex) const
  47488. {
  47489. int totalMinimums = 0;
  47490. for (int i = startIndex; i < endIndex; ++i)
  47491. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  47492. return totalMinimums;
  47493. }
  47494. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  47495. {
  47496. int totalMaximums = 0;
  47497. for (int i = startIndex; i < endIndex; ++i)
  47498. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  47499. return totalMaximums;
  47500. }
  47501. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  47502. {
  47503. for (int i = 0; i < items.size(); ++i)
  47504. {
  47505. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47506. layout->preferredSize
  47507. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  47508. : getItemCurrentAbsoluteSize (i);
  47509. }
  47510. }
  47511. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  47512. {
  47513. if (size < 0)
  47514. size *= -totalSpace;
  47515. return roundDoubleToInt (size);
  47516. }
  47517. END_JUCE_NAMESPACE
  47518. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  47519. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47520. BEGIN_JUCE_NAMESPACE
  47521. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  47522. const int itemIndex_,
  47523. const bool isVertical_)
  47524. : layout (layout_),
  47525. itemIndex (itemIndex_),
  47526. isVertical (isVertical_)
  47527. {
  47528. setRepaintsOnMouseActivity (true);
  47529. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  47530. : MouseCursor::UpDownResizeCursor));
  47531. }
  47532. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  47533. {
  47534. }
  47535. void StretchableLayoutResizerBar::paint (Graphics& g)
  47536. {
  47537. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  47538. getWidth(), getHeight(),
  47539. isVertical,
  47540. isMouseOver(),
  47541. isMouseButtonDown());
  47542. }
  47543. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  47544. {
  47545. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  47546. }
  47547. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  47548. {
  47549. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  47550. : e.getDistanceFromDragStartY());
  47551. layout->setItemPosition (itemIndex, desiredPos);
  47552. hasBeenMoved();
  47553. }
  47554. void StretchableLayoutResizerBar::hasBeenMoved()
  47555. {
  47556. if (getParentComponent() != 0)
  47557. getParentComponent()->resized();
  47558. }
  47559. END_JUCE_NAMESPACE
  47560. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47561. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  47562. BEGIN_JUCE_NAMESPACE
  47563. StretchableObjectResizer::StretchableObjectResizer()
  47564. {
  47565. }
  47566. StretchableObjectResizer::~StretchableObjectResizer()
  47567. {
  47568. }
  47569. void StretchableObjectResizer::addItem (const double size,
  47570. const double minSize, const double maxSize,
  47571. const int order)
  47572. {
  47573. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  47574. Item* const item = new Item();
  47575. item->size = size;
  47576. item->minSize = minSize;
  47577. item->maxSize = maxSize;
  47578. item->order = order;
  47579. items.add (item);
  47580. }
  47581. double StretchableObjectResizer::getItemSize (const int index) const throw()
  47582. {
  47583. const Item* const it = items [index];
  47584. return it != 0 ? it->size : 0;
  47585. }
  47586. void StretchableObjectResizer::resizeToFit (const double targetSize)
  47587. {
  47588. int order = 0;
  47589. for (;;)
  47590. {
  47591. double currentSize = 0;
  47592. double minSize = 0;
  47593. double maxSize = 0;
  47594. int nextHighestOrder = INT_MAX;
  47595. for (int i = 0; i < items.size(); ++i)
  47596. {
  47597. const Item* const it = items.getUnchecked(i);
  47598. currentSize += it->size;
  47599. if (it->order <= order)
  47600. {
  47601. minSize += it->minSize;
  47602. maxSize += it->maxSize;
  47603. }
  47604. else
  47605. {
  47606. minSize += it->size;
  47607. maxSize += it->size;
  47608. nextHighestOrder = jmin (nextHighestOrder, it->order);
  47609. }
  47610. }
  47611. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  47612. if (thisIterationTarget >= currentSize)
  47613. {
  47614. const double availableExtraSpace = maxSize - currentSize;
  47615. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  47616. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  47617. for (int i = 0; i < items.size(); ++i)
  47618. {
  47619. Item* const it = items.getUnchecked(i);
  47620. if (it->order <= order)
  47621. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  47622. }
  47623. }
  47624. else
  47625. {
  47626. const double amountOfSlack = currentSize - minSize;
  47627. const double targetAmountOfSlack = thisIterationTarget - minSize;
  47628. const double scale = targetAmountOfSlack / amountOfSlack;
  47629. for (int i = 0; i < items.size(); ++i)
  47630. {
  47631. Item* const it = items.getUnchecked(i);
  47632. if (it->order <= order)
  47633. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  47634. }
  47635. }
  47636. if (nextHighestOrder < INT_MAX)
  47637. order = nextHighestOrder;
  47638. else
  47639. break;
  47640. }
  47641. }
  47642. END_JUCE_NAMESPACE
  47643. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  47644. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  47645. BEGIN_JUCE_NAMESPACE
  47646. TabBarButton::TabBarButton (const String& name,
  47647. TabbedButtonBar* const owner_,
  47648. const int index)
  47649. : Button (name),
  47650. owner (owner_),
  47651. tabIndex (index),
  47652. overlapPixels (0)
  47653. {
  47654. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  47655. setComponentEffect (&shadow);
  47656. setWantsKeyboardFocus (false);
  47657. }
  47658. TabBarButton::~TabBarButton()
  47659. {
  47660. }
  47661. void TabBarButton::paintButton (Graphics& g,
  47662. bool isMouseOverButton,
  47663. bool isButtonDown)
  47664. {
  47665. int x, y, w, h;
  47666. getActiveArea (x, y, w, h);
  47667. g.setOrigin (x, y);
  47668. getLookAndFeel()
  47669. .drawTabButton (g, w, h,
  47670. owner->getTabBackgroundColour (tabIndex),
  47671. tabIndex, getButtonText(), *this,
  47672. owner->getOrientation(),
  47673. isMouseOverButton, isButtonDown,
  47674. getToggleState());
  47675. }
  47676. void TabBarButton::clicked (const ModifierKeys& mods)
  47677. {
  47678. if (mods.isPopupMenu())
  47679. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  47680. else
  47681. owner->setCurrentTabIndex (tabIndex);
  47682. }
  47683. bool TabBarButton::hitTest (int mx, int my)
  47684. {
  47685. int x, y, w, h;
  47686. getActiveArea (x, y, w, h);
  47687. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  47688. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  47689. {
  47690. if (((unsigned int) mx) < (unsigned int) getWidth()
  47691. && my >= y + overlapPixels
  47692. && my < y + h - overlapPixels)
  47693. return true;
  47694. }
  47695. else
  47696. {
  47697. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  47698. && ((unsigned int) my) < (unsigned int) getHeight())
  47699. return true;
  47700. }
  47701. Path p;
  47702. getLookAndFeel()
  47703. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  47704. owner->getOrientation(),
  47705. false, false, getToggleState());
  47706. return p.contains ((float) (mx - x),
  47707. (float) (my - y));
  47708. }
  47709. int TabBarButton::getBestTabLength (const int depth)
  47710. {
  47711. return jlimit (depth * 2,
  47712. depth * 7,
  47713. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  47714. }
  47715. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  47716. {
  47717. x = 0;
  47718. y = 0;
  47719. int r = getWidth();
  47720. int b = getHeight();
  47721. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  47722. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  47723. r -= spaceAroundImage;
  47724. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  47725. x += spaceAroundImage;
  47726. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  47727. y += spaceAroundImage;
  47728. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  47729. b -= spaceAroundImage;
  47730. w = r - x;
  47731. h = b - y;
  47732. }
  47733. class TabAreaBehindFrontButtonComponent : public Component
  47734. {
  47735. public:
  47736. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  47737. : owner (owner_)
  47738. {
  47739. setInterceptsMouseClicks (false, false);
  47740. }
  47741. ~TabAreaBehindFrontButtonComponent()
  47742. {
  47743. }
  47744. void paint (Graphics& g)
  47745. {
  47746. getLookAndFeel()
  47747. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  47748. *owner, owner->getOrientation());
  47749. }
  47750. void enablementChanged()
  47751. {
  47752. repaint();
  47753. }
  47754. private:
  47755. TabbedButtonBar* const owner;
  47756. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  47757. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  47758. };
  47759. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  47760. : orientation (orientation_),
  47761. currentTabIndex (-1),
  47762. extraTabsButton (0)
  47763. {
  47764. setInterceptsMouseClicks (false, true);
  47765. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  47766. setFocusContainer (true);
  47767. }
  47768. TabbedButtonBar::~TabbedButtonBar()
  47769. {
  47770. deleteAllChildren();
  47771. }
  47772. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  47773. {
  47774. orientation = newOrientation;
  47775. for (int i = getNumChildComponents(); --i >= 0;)
  47776. getChildComponent (i)->resized();
  47777. resized();
  47778. }
  47779. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  47780. {
  47781. return new TabBarButton (name, this, index);
  47782. }
  47783. void TabbedButtonBar::clearTabs()
  47784. {
  47785. tabs.clear();
  47786. tabColours.clear();
  47787. currentTabIndex = -1;
  47788. deleteAndZero (extraTabsButton);
  47789. removeChildComponent (behindFrontTab);
  47790. deleteAllChildren();
  47791. addChildComponent (behindFrontTab);
  47792. setCurrentTabIndex (-1);
  47793. }
  47794. void TabbedButtonBar::addTab (const String& tabName,
  47795. const Colour& tabBackgroundColour,
  47796. int insertIndex)
  47797. {
  47798. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  47799. if (tabName.isNotEmpty())
  47800. {
  47801. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  47802. insertIndex = tabs.size();
  47803. for (int i = tabs.size(); --i >= insertIndex;)
  47804. {
  47805. TabBarButton* const tb = getTabButton (i);
  47806. if (tb != 0)
  47807. tb->tabIndex++;
  47808. }
  47809. tabs.insert (insertIndex, tabName);
  47810. tabColours.insert (insertIndex, tabBackgroundColour);
  47811. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  47812. jassert (tb != 0); // your createTabButton() mustn't return zero!
  47813. addAndMakeVisible (tb, insertIndex);
  47814. resized();
  47815. if (currentTabIndex < 0)
  47816. setCurrentTabIndex (0);
  47817. }
  47818. }
  47819. void TabbedButtonBar::setTabName (const int tabIndex,
  47820. const String& newName)
  47821. {
  47822. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  47823. && tabs[tabIndex] != newName)
  47824. {
  47825. tabs.set (tabIndex, newName);
  47826. TabBarButton* const tb = getTabButton (tabIndex);
  47827. if (tb != 0)
  47828. tb->setButtonText (newName);
  47829. resized();
  47830. }
  47831. }
  47832. void TabbedButtonBar::removeTab (const int tabIndex)
  47833. {
  47834. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  47835. {
  47836. const int oldTabIndex = currentTabIndex;
  47837. if (currentTabIndex == tabIndex)
  47838. currentTabIndex = -1;
  47839. tabs.remove (tabIndex);
  47840. tabColours.remove (tabIndex);
  47841. TabBarButton* const tb = getTabButton (tabIndex);
  47842. if (tb != 0)
  47843. delete tb;
  47844. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  47845. {
  47846. TabBarButton* const tb = getTabButton (i);
  47847. if (tb != 0)
  47848. tb->tabIndex--;
  47849. }
  47850. resized();
  47851. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  47852. }
  47853. }
  47854. void TabbedButtonBar::moveTab (const int currentIndex,
  47855. const int newIndex)
  47856. {
  47857. tabs.move (currentIndex, newIndex);
  47858. tabColours.move (currentIndex, newIndex);
  47859. resized();
  47860. }
  47861. int TabbedButtonBar::getNumTabs() const
  47862. {
  47863. return tabs.size();
  47864. }
  47865. const StringArray TabbedButtonBar::getTabNames() const
  47866. {
  47867. return tabs;
  47868. }
  47869. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  47870. {
  47871. if (currentTabIndex != newIndex)
  47872. {
  47873. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  47874. newIndex = -1;
  47875. currentTabIndex = newIndex;
  47876. for (int i = 0; i < getNumChildComponents(); ++i)
  47877. {
  47878. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47879. if (tb != 0)
  47880. tb->setToggleState (tb->tabIndex == newIndex, false);
  47881. }
  47882. resized();
  47883. if (sendChangeMessage_)
  47884. sendChangeMessage (this);
  47885. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  47886. }
  47887. }
  47888. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  47889. {
  47890. for (int i = getNumChildComponents(); --i >= 0;)
  47891. {
  47892. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47893. if (tb != 0 && tb->tabIndex == index)
  47894. return tb;
  47895. }
  47896. return 0;
  47897. }
  47898. void TabbedButtonBar::lookAndFeelChanged()
  47899. {
  47900. deleteAndZero (extraTabsButton);
  47901. resized();
  47902. }
  47903. void TabbedButtonBar::resized()
  47904. {
  47905. const double minimumScale = 0.7;
  47906. int depth = getWidth();
  47907. int length = getHeight();
  47908. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47909. swapVariables (depth, length);
  47910. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  47911. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  47912. int i, totalLength = overlap;
  47913. int numVisibleButtons = tabs.size();
  47914. for (i = 0; i < getNumChildComponents(); ++i)
  47915. {
  47916. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47917. if (tb != 0)
  47918. {
  47919. totalLength += tb->getBestTabLength (depth) - overlap;
  47920. tb->overlapPixels = overlap / 2;
  47921. }
  47922. }
  47923. double scale = 1.0;
  47924. if (totalLength > length)
  47925. scale = jmax (minimumScale, length / (double) totalLength);
  47926. const bool isTooBig = totalLength * scale > length;
  47927. int tabsButtonPos = 0;
  47928. if (isTooBig)
  47929. {
  47930. if (extraTabsButton == 0)
  47931. {
  47932. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  47933. extraTabsButton->addButtonListener (this);
  47934. extraTabsButton->setAlwaysOnTop (true);
  47935. extraTabsButton->setTriggeredOnMouseDown (true);
  47936. }
  47937. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  47938. extraTabsButton->setSize (buttonSize, buttonSize);
  47939. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47940. {
  47941. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  47942. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  47943. }
  47944. else
  47945. {
  47946. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  47947. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  47948. }
  47949. totalLength = 0;
  47950. for (i = 0; i < tabs.size(); ++i)
  47951. {
  47952. TabBarButton* const tb = getTabButton (i);
  47953. if (tb != 0)
  47954. {
  47955. const int newLength = totalLength + tb->getBestTabLength (depth);
  47956. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  47957. {
  47958. totalLength += overlap;
  47959. break;
  47960. }
  47961. numVisibleButtons = i + 1;
  47962. totalLength = newLength - overlap;
  47963. }
  47964. }
  47965. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  47966. }
  47967. else
  47968. {
  47969. deleteAndZero (extraTabsButton);
  47970. }
  47971. int pos = 0;
  47972. TabBarButton* frontTab = 0;
  47973. for (i = 0; i < tabs.size(); ++i)
  47974. {
  47975. TabBarButton* const tb = getTabButton (i);
  47976. if (tb != 0)
  47977. {
  47978. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  47979. if (i < numVisibleButtons)
  47980. {
  47981. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47982. tb->setBounds (pos, 0, bestLength, getHeight());
  47983. else
  47984. tb->setBounds (0, pos, getWidth(), bestLength);
  47985. tb->toBack();
  47986. if (tb->tabIndex == currentTabIndex)
  47987. frontTab = tb;
  47988. tb->setVisible (true);
  47989. }
  47990. else
  47991. {
  47992. tb->setVisible (false);
  47993. }
  47994. pos += bestLength - overlap;
  47995. }
  47996. }
  47997. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  47998. if (frontTab != 0)
  47999. {
  48000. frontTab->toFront (false);
  48001. behindFrontTab->toBehind (frontTab);
  48002. }
  48003. }
  48004. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  48005. {
  48006. return tabColours [tabIndex];
  48007. }
  48008. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48009. {
  48010. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  48011. && tabColours [tabIndex] != newColour)
  48012. {
  48013. tabColours.set (tabIndex, newColour);
  48014. repaint();
  48015. }
  48016. }
  48017. void TabbedButtonBar::buttonClicked (Button* button)
  48018. {
  48019. if (extraTabsButton == button)
  48020. {
  48021. PopupMenu m;
  48022. for (int i = 0; i < tabs.size(); ++i)
  48023. {
  48024. TabBarButton* const tb = getTabButton (i);
  48025. if (tb != 0 && ! tb->isVisible())
  48026. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  48027. }
  48028. const int res = m.showAt (extraTabsButton);
  48029. if (res != 0)
  48030. setCurrentTabIndex (res - 1);
  48031. }
  48032. }
  48033. void TabbedButtonBar::currentTabChanged (const int, const String&)
  48034. {
  48035. }
  48036. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  48037. {
  48038. }
  48039. END_JUCE_NAMESPACE
  48040. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  48041. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  48042. BEGIN_JUCE_NAMESPACE
  48043. class TabCompButtonBar : public TabbedButtonBar
  48044. {
  48045. public:
  48046. TabCompButtonBar (TabbedComponent* const owner_,
  48047. const TabbedButtonBar::Orientation orientation)
  48048. : TabbedButtonBar (orientation),
  48049. owner (owner_)
  48050. {
  48051. }
  48052. ~TabCompButtonBar()
  48053. {
  48054. }
  48055. void currentTabChanged (const int newCurrentTabIndex,
  48056. const String& newTabName)
  48057. {
  48058. owner->changeCallback (newCurrentTabIndex, newTabName);
  48059. }
  48060. void popupMenuClickOnTab (const int tabIndex,
  48061. const String& tabName)
  48062. {
  48063. owner->popupMenuClickOnTab (tabIndex, tabName);
  48064. }
  48065. const Colour getTabBackgroundColour (const int tabIndex)
  48066. {
  48067. return owner->tabs->getTabBackgroundColour (tabIndex);
  48068. }
  48069. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  48070. {
  48071. return owner->createTabButton (tabName, tabIndex);
  48072. }
  48073. juce_UseDebuggingNewOperator
  48074. private:
  48075. TabbedComponent* const owner;
  48076. TabCompButtonBar (const TabCompButtonBar&);
  48077. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  48078. };
  48079. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  48080. : panelComponent (0),
  48081. tabDepth (30),
  48082. outlineThickness (1),
  48083. edgeIndent (0)
  48084. {
  48085. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  48086. }
  48087. TabbedComponent::~TabbedComponent()
  48088. {
  48089. clearTabs();
  48090. delete tabs;
  48091. }
  48092. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  48093. {
  48094. tabs->setOrientation (orientation);
  48095. resized();
  48096. }
  48097. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  48098. {
  48099. return tabs->getOrientation();
  48100. }
  48101. void TabbedComponent::setTabBarDepth (const int newDepth)
  48102. {
  48103. if (tabDepth != newDepth)
  48104. {
  48105. tabDepth = newDepth;
  48106. resized();
  48107. }
  48108. }
  48109. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  48110. {
  48111. return new TabBarButton (tabName, tabs, tabIndex);
  48112. }
  48113. void TabbedComponent::clearTabs()
  48114. {
  48115. if (panelComponent != 0)
  48116. {
  48117. panelComponent->setVisible (false);
  48118. removeChildComponent (panelComponent);
  48119. panelComponent = 0;
  48120. }
  48121. tabs->clearTabs();
  48122. for (int i = contentComponents.size(); --i >= 0;)
  48123. {
  48124. Component* const c = contentComponents.getUnchecked(i);
  48125. // be careful not to delete these components until they've been removed from the tab component
  48126. jassert (c == 0 || c->isValidComponent());
  48127. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48128. delete c;
  48129. }
  48130. contentComponents.clear();
  48131. }
  48132. void TabbedComponent::addTab (const String& tabName,
  48133. const Colour& tabBackgroundColour,
  48134. Component* const contentComponent,
  48135. const bool deleteComponentWhenNotNeeded,
  48136. const int insertIndex)
  48137. {
  48138. contentComponents.insert (insertIndex, contentComponent);
  48139. if (contentComponent != 0)
  48140. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  48141. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  48142. }
  48143. void TabbedComponent::setTabName (const int tabIndex,
  48144. const String& newName)
  48145. {
  48146. tabs->setTabName (tabIndex, newName);
  48147. }
  48148. void TabbedComponent::removeTab (const int tabIndex)
  48149. {
  48150. Component* const c = contentComponents [tabIndex];
  48151. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48152. {
  48153. if (c == panelComponent)
  48154. panelComponent = 0;
  48155. delete c;
  48156. }
  48157. contentComponents.remove (tabIndex);
  48158. tabs->removeTab (tabIndex);
  48159. }
  48160. int TabbedComponent::getNumTabs() const
  48161. {
  48162. return tabs->getNumTabs();
  48163. }
  48164. const StringArray TabbedComponent::getTabNames() const
  48165. {
  48166. return tabs->getTabNames();
  48167. }
  48168. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  48169. {
  48170. return contentComponents [tabIndex];
  48171. }
  48172. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  48173. {
  48174. return tabs->getTabBackgroundColour (tabIndex);
  48175. }
  48176. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48177. {
  48178. tabs->setTabBackgroundColour (tabIndex, newColour);
  48179. if (getCurrentTabIndex() == tabIndex)
  48180. repaint();
  48181. }
  48182. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  48183. {
  48184. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  48185. }
  48186. int TabbedComponent::getCurrentTabIndex() const
  48187. {
  48188. return tabs->getCurrentTabIndex();
  48189. }
  48190. const String& TabbedComponent::getCurrentTabName() const
  48191. {
  48192. return tabs->getCurrentTabName();
  48193. }
  48194. void TabbedComponent::setOutline (int thickness)
  48195. {
  48196. outlineThickness = thickness;
  48197. repaint();
  48198. }
  48199. void TabbedComponent::setIndent (const int indentThickness)
  48200. {
  48201. edgeIndent = indentThickness;
  48202. }
  48203. void TabbedComponent::paint (Graphics& g)
  48204. {
  48205. g.fillAll (findColour (backgroundColourId));
  48206. const TabbedButtonBar::Orientation o = getOrientation();
  48207. int x = 0;
  48208. int y = 0;
  48209. int r = getWidth();
  48210. int b = getHeight();
  48211. if (o == TabbedButtonBar::TabsAtTop)
  48212. y += tabDepth;
  48213. else if (o == TabbedButtonBar::TabsAtBottom)
  48214. b -= tabDepth;
  48215. else if (o == TabbedButtonBar::TabsAtLeft)
  48216. x += tabDepth;
  48217. else if (o == TabbedButtonBar::TabsAtRight)
  48218. r -= tabDepth;
  48219. g.reduceClipRegion (x, y, r - x, b - y);
  48220. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  48221. if (outlineThickness > 0)
  48222. {
  48223. if (o == TabbedButtonBar::TabsAtTop)
  48224. --y;
  48225. else if (o == TabbedButtonBar::TabsAtBottom)
  48226. ++b;
  48227. else if (o == TabbedButtonBar::TabsAtLeft)
  48228. --x;
  48229. else if (o == TabbedButtonBar::TabsAtRight)
  48230. ++r;
  48231. g.setColour (findColour (outlineColourId));
  48232. g.drawRect (x, y, r - x, b - y, outlineThickness);
  48233. }
  48234. }
  48235. void TabbedComponent::resized()
  48236. {
  48237. const TabbedButtonBar::Orientation o = getOrientation();
  48238. const int indent = edgeIndent + outlineThickness;
  48239. BorderSize indents (indent);
  48240. if (o == TabbedButtonBar::TabsAtTop)
  48241. {
  48242. tabs->setBounds (0, 0, getWidth(), tabDepth);
  48243. indents.setTop (tabDepth + edgeIndent);
  48244. }
  48245. else if (o == TabbedButtonBar::TabsAtBottom)
  48246. {
  48247. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  48248. indents.setBottom (tabDepth + edgeIndent);
  48249. }
  48250. else if (o == TabbedButtonBar::TabsAtLeft)
  48251. {
  48252. tabs->setBounds (0, 0, tabDepth, getHeight());
  48253. indents.setLeft (tabDepth + edgeIndent);
  48254. }
  48255. else if (o == TabbedButtonBar::TabsAtRight)
  48256. {
  48257. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  48258. indents.setRight (tabDepth + edgeIndent);
  48259. }
  48260. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  48261. for (int i = contentComponents.size(); --i >= 0;)
  48262. if (contentComponents.getUnchecked (i) != 0)
  48263. contentComponents.getUnchecked (i)->setBounds (bounds);
  48264. }
  48265. void TabbedComponent::lookAndFeelChanged()
  48266. {
  48267. for (int i = contentComponents.size(); --i >= 0;)
  48268. if (contentComponents.getUnchecked (i) != 0)
  48269. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  48270. }
  48271. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  48272. const String& newTabName)
  48273. {
  48274. if (panelComponent != 0)
  48275. {
  48276. panelComponent->setVisible (false);
  48277. removeChildComponent (panelComponent);
  48278. panelComponent = 0;
  48279. }
  48280. if (getCurrentTabIndex() >= 0)
  48281. {
  48282. panelComponent = contentComponents [getCurrentTabIndex()];
  48283. if (panelComponent != 0)
  48284. {
  48285. // do these ops as two stages instead of addAndMakeVisible() so that the
  48286. // component has always got a parent when it gets the visibilityChanged() callback
  48287. addChildComponent (panelComponent);
  48288. panelComponent->setVisible (true);
  48289. panelComponent->toFront (true);
  48290. }
  48291. repaint();
  48292. }
  48293. resized();
  48294. currentTabChanged (newCurrentTabIndex, newTabName);
  48295. }
  48296. void TabbedComponent::currentTabChanged (const int, const String&)
  48297. {
  48298. }
  48299. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  48300. {
  48301. }
  48302. END_JUCE_NAMESPACE
  48303. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  48304. /********* Start of inlined file: juce_Viewport.cpp *********/
  48305. BEGIN_JUCE_NAMESPACE
  48306. Viewport::Viewport (const String& componentName)
  48307. : Component (componentName),
  48308. contentComp (0),
  48309. lastVX (0),
  48310. lastVY (0),
  48311. lastVW (0),
  48312. lastVH (0),
  48313. scrollBarThickness (0),
  48314. singleStepX (16),
  48315. singleStepY (16),
  48316. showHScrollbar (true),
  48317. showVScrollbar (true)
  48318. {
  48319. // content holder is used to clip the contents so they don't overlap the scrollbars
  48320. addAndMakeVisible (contentHolder = new Component());
  48321. contentHolder->setInterceptsMouseClicks (false, true);
  48322. verticalScrollBar = new ScrollBar (true);
  48323. horizontalScrollBar = new ScrollBar (false);
  48324. addChildComponent (verticalScrollBar);
  48325. addChildComponent (horizontalScrollBar);
  48326. verticalScrollBar->addListener (this);
  48327. horizontalScrollBar->addListener (this);
  48328. setInterceptsMouseClicks (false, true);
  48329. setWantsKeyboardFocus (true);
  48330. }
  48331. Viewport::~Viewport()
  48332. {
  48333. contentHolder->deleteAllChildren();
  48334. deleteAllChildren();
  48335. }
  48336. void Viewport::visibleAreaChanged (int, int, int, int)
  48337. {
  48338. }
  48339. void Viewport::setViewedComponent (Component* const newViewedComponent)
  48340. {
  48341. if (contentComp != newViewedComponent)
  48342. {
  48343. if (contentComp->isValidComponent())
  48344. {
  48345. Component* const oldComp = contentComp;
  48346. contentComp = 0;
  48347. delete oldComp;
  48348. }
  48349. contentComp = newViewedComponent;
  48350. if (contentComp != 0)
  48351. {
  48352. contentComp->setTopLeftPosition (0, 0);
  48353. contentHolder->addAndMakeVisible (contentComp);
  48354. contentComp->addComponentListener (this);
  48355. }
  48356. updateVisibleRegion();
  48357. }
  48358. }
  48359. int Viewport::getMaximumVisibleWidth() const throw()
  48360. {
  48361. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48362. }
  48363. int Viewport::getMaximumVisibleHeight() const throw()
  48364. {
  48365. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48366. }
  48367. void Viewport::setViewPosition (const int xPixelsOffset,
  48368. const int yPixelsOffset)
  48369. {
  48370. if (contentComp != 0)
  48371. contentComp->setTopLeftPosition (-xPixelsOffset,
  48372. -yPixelsOffset);
  48373. }
  48374. void Viewport::setViewPositionProportionately (const double x,
  48375. const double y)
  48376. {
  48377. if (contentComp != 0)
  48378. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  48379. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  48380. }
  48381. void Viewport::componentMovedOrResized (Component&, bool, bool)
  48382. {
  48383. updateVisibleRegion();
  48384. }
  48385. void Viewport::resized()
  48386. {
  48387. updateVisibleRegion();
  48388. }
  48389. void Viewport::updateVisibleRegion()
  48390. {
  48391. if (contentComp != 0)
  48392. {
  48393. const int newVX = -contentComp->getX();
  48394. const int newVY = -contentComp->getY();
  48395. if (newVX == 0 && newVY == 0
  48396. && contentComp->getWidth() <= getWidth()
  48397. && contentComp->getHeight() <= getHeight())
  48398. {
  48399. horizontalScrollBar->setVisible (false);
  48400. verticalScrollBar->setVisible (false);
  48401. }
  48402. if ((contentComp->getWidth() > 0) && showHScrollbar
  48403. && getHeight() > getScrollBarThickness())
  48404. {
  48405. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  48406. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48407. horizontalScrollBar->setSingleStepSize (singleStepX);
  48408. }
  48409. else
  48410. {
  48411. horizontalScrollBar->setVisible (false);
  48412. }
  48413. if ((contentComp->getHeight() > 0) && showVScrollbar
  48414. && getWidth() > getScrollBarThickness())
  48415. {
  48416. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  48417. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48418. verticalScrollBar->setSingleStepSize (singleStepY);
  48419. }
  48420. else
  48421. {
  48422. verticalScrollBar->setVisible (false);
  48423. }
  48424. if (verticalScrollBar->isVisible())
  48425. {
  48426. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48427. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48428. verticalScrollBar
  48429. ->setBounds (getMaximumVisibleWidth(), 0,
  48430. getScrollBarThickness(), getMaximumVisibleHeight());
  48431. }
  48432. if (horizontalScrollBar->isVisible())
  48433. {
  48434. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48435. horizontalScrollBar
  48436. ->setBounds (0, getMaximumVisibleHeight(),
  48437. getMaximumVisibleWidth(), getScrollBarThickness());
  48438. }
  48439. contentHolder->setSize (getMaximumVisibleWidth(),
  48440. getMaximumVisibleHeight());
  48441. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  48442. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  48443. if (newVX != lastVX
  48444. || newVY != lastVY
  48445. || newVW != lastVW
  48446. || newVH != lastVH)
  48447. {
  48448. lastVX = newVX;
  48449. lastVY = newVY;
  48450. lastVW = newVW;
  48451. lastVH = newVH;
  48452. visibleAreaChanged (newVX, newVY, newVW, newVH);
  48453. }
  48454. horizontalScrollBar->handleUpdateNowIfNeeded();
  48455. verticalScrollBar->handleUpdateNowIfNeeded();
  48456. }
  48457. else
  48458. {
  48459. horizontalScrollBar->setVisible (false);
  48460. verticalScrollBar->setVisible (false);
  48461. }
  48462. }
  48463. void Viewport::setSingleStepSizes (const int stepX,
  48464. const int stepY)
  48465. {
  48466. singleStepX = stepX;
  48467. singleStepY = stepY;
  48468. updateVisibleRegion();
  48469. }
  48470. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  48471. const bool showHorizontalScrollbarIfNeeded)
  48472. {
  48473. showVScrollbar = showVerticalScrollbarIfNeeded;
  48474. showHScrollbar = showHorizontalScrollbarIfNeeded;
  48475. updateVisibleRegion();
  48476. }
  48477. void Viewport::setScrollBarThickness (const int thickness)
  48478. {
  48479. scrollBarThickness = thickness;
  48480. updateVisibleRegion();
  48481. }
  48482. int Viewport::getScrollBarThickness() const throw()
  48483. {
  48484. return (scrollBarThickness > 0) ? scrollBarThickness
  48485. : getLookAndFeel().getDefaultScrollbarWidth();
  48486. }
  48487. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  48488. {
  48489. verticalScrollBar->setButtonVisibility (buttonsVisible);
  48490. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  48491. }
  48492. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  48493. {
  48494. if (scrollBarThatHasMoved == horizontalScrollBar)
  48495. {
  48496. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  48497. }
  48498. else if (scrollBarThatHasMoved == verticalScrollBar)
  48499. {
  48500. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  48501. }
  48502. }
  48503. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48504. {
  48505. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  48506. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  48507. }
  48508. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48509. {
  48510. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  48511. {
  48512. const bool hasVertBar = verticalScrollBar->isVisible();
  48513. const bool hasHorzBar = horizontalScrollBar->isVisible();
  48514. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  48515. {
  48516. if (wheelIncrementX == 0 && ! hasVertBar)
  48517. wheelIncrementX = wheelIncrementY;
  48518. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  48519. wheelIncrementX, wheelIncrementY);
  48520. return true;
  48521. }
  48522. else if (hasVertBar && wheelIncrementY != 0)
  48523. {
  48524. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  48525. wheelIncrementX, wheelIncrementY);
  48526. return true;
  48527. }
  48528. }
  48529. return false;
  48530. }
  48531. bool Viewport::keyPressed (const KeyPress& key)
  48532. {
  48533. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  48534. || key.isKeyCode (KeyPress::downKey)
  48535. || key.isKeyCode (KeyPress::pageUpKey)
  48536. || key.isKeyCode (KeyPress::pageDownKey)
  48537. || key.isKeyCode (KeyPress::homeKey)
  48538. || key.isKeyCode (KeyPress::endKey);
  48539. if (verticalScrollBar->isVisible() && isUpDownKey)
  48540. return verticalScrollBar->keyPressed (key);
  48541. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  48542. || key.isKeyCode (KeyPress::rightKey);
  48543. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  48544. return horizontalScrollBar->keyPressed (key);
  48545. return false;
  48546. }
  48547. END_JUCE_NAMESPACE
  48548. /********* End of inlined file: juce_Viewport.cpp *********/
  48549. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  48550. BEGIN_JUCE_NAMESPACE
  48551. static const Colour createBaseColour (const Colour& buttonColour,
  48552. const bool hasKeyboardFocus,
  48553. const bool isMouseOverButton,
  48554. const bool isButtonDown) throw()
  48555. {
  48556. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  48557. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  48558. if (isButtonDown)
  48559. return baseColour.contrasting (0.2f);
  48560. else if (isMouseOverButton)
  48561. return baseColour.contrasting (0.1f);
  48562. return baseColour;
  48563. }
  48564. static String defaultSansName, defaultSerifName, defaultFixedName;
  48565. void clearUpDefaultFontNames() throw()
  48566. {
  48567. defaultSansName = String::empty;
  48568. defaultSerifName = String::empty;
  48569. defaultFixedName = String::empty;
  48570. }
  48571. LookAndFeel::LookAndFeel()
  48572. {
  48573. /* if this fails it means you're trying to create a LookAndFeel object before
  48574. the static Colours have been initialised. That ain't gonna work. It probably
  48575. means that you're using a static LookAndFeel object and that your compiler has
  48576. decided to intialise it before the Colours class.
  48577. */
  48578. jassert (Colours::white == Colour (0xffffffff));
  48579. // set up the standard set of colours..
  48580. #define textButtonColour 0xffbbbbff
  48581. #define textHighlightColour 0x401111ee
  48582. #define standardOutlineColour 0xb2808080
  48583. static const int standardColours[] =
  48584. {
  48585. TextButton::buttonColourId, textButtonColour,
  48586. TextButton::buttonOnColourId, 0xff4444ff,
  48587. TextButton::textColourId, 0xff000000,
  48588. ComboBox::buttonColourId, 0xffbbbbff,
  48589. ComboBox::outlineColourId, standardOutlineColour,
  48590. ToggleButton::textColourId, 0xff000000,
  48591. TextEditor::backgroundColourId, 0xffffffff,
  48592. TextEditor::textColourId, 0xff000000,
  48593. TextEditor::highlightColourId, textHighlightColour,
  48594. TextEditor::highlightedTextColourId, 0xff000000,
  48595. TextEditor::caretColourId, 0xff000000,
  48596. TextEditor::outlineColourId, 0x00000000,
  48597. TextEditor::focusedOutlineColourId, textButtonColour,
  48598. TextEditor::shadowColourId, 0x38000000,
  48599. Label::backgroundColourId, 0x00000000,
  48600. Label::textColourId, 0xff000000,
  48601. Label::outlineColourId, 0x00000000,
  48602. ScrollBar::backgroundColourId, 0x00000000,
  48603. ScrollBar::thumbColourId, 0xffffffff,
  48604. ScrollBar::trackColourId, 0xffffffff,
  48605. TreeView::linesColourId, 0x4c000000,
  48606. TreeView::backgroundColourId, 0x00000000,
  48607. PopupMenu::backgroundColourId, 0xffffffff,
  48608. PopupMenu::textColourId, 0xff000000,
  48609. PopupMenu::headerTextColourId, 0xff000000,
  48610. PopupMenu::highlightedTextColourId, 0xffffffff,
  48611. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  48612. ComboBox::textColourId, 0xff000000,
  48613. ComboBox::backgroundColourId, 0xffffffff,
  48614. ComboBox::arrowColourId, 0x99000000,
  48615. ListBox::backgroundColourId, 0xffffffff,
  48616. ListBox::outlineColourId, standardOutlineColour,
  48617. ListBox::textColourId, 0xff000000,
  48618. Slider::backgroundColourId, 0x00000000,
  48619. Slider::thumbColourId, textButtonColour,
  48620. Slider::trackColourId, 0x7fffffff,
  48621. Slider::rotarySliderFillColourId, 0x7f0000ff,
  48622. Slider::rotarySliderOutlineColourId, 0x66000000,
  48623. Slider::textBoxTextColourId, 0xff000000,
  48624. Slider::textBoxBackgroundColourId, 0xffffffff,
  48625. Slider::textBoxHighlightColourId, textHighlightColour,
  48626. Slider::textBoxOutlineColourId, standardOutlineColour,
  48627. ResizableWindow::backgroundColourId, 0xff777777,
  48628. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  48629. AlertWindow::backgroundColourId, 0xffededed,
  48630. AlertWindow::textColourId, 0xff000000,
  48631. AlertWindow::outlineColourId, 0xff666666,
  48632. ProgressBar::backgroundColourId, 0xffeeeeee,
  48633. ProgressBar::foregroundColourId, 0xffaaaaee,
  48634. TooltipWindow::backgroundColourId, 0xffeeeebb,
  48635. TooltipWindow::textColourId, 0xff000000,
  48636. TooltipWindow::outlineColourId, 0x4c000000,
  48637. TabbedComponent::backgroundColourId, 0x00000000,
  48638. TabbedComponent::outlineColourId, 0xff777777,
  48639. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  48640. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  48641. Toolbar::backgroundColourId, 0xfff6f8f9,
  48642. Toolbar::separatorColourId, 0x4c000000,
  48643. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  48644. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  48645. Toolbar::labelTextColourId, 0xff000000,
  48646. Toolbar::editingModeOutlineColourId, 0xffff0000,
  48647. HyperlinkButton::textColourId, 0xcc1111ee,
  48648. GroupComponent::outlineColourId, 0x66000000,
  48649. GroupComponent::textColourId, 0xff000000,
  48650. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  48651. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  48652. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  48653. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  48654. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  48655. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  48656. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  48657. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  48658. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  48659. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  48660. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  48661. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  48662. ColourSelector::backgroundColourId, 0xffe5e5e5,
  48663. ColourSelector::labelTextColourId, 0xff000000,
  48664. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  48665. };
  48666. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  48667. setColour (standardColours [i], Colour (standardColours [i + 1]));
  48668. if (defaultSansName.isEmpty())
  48669. Typeface::getDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  48670. defaultSans = defaultSansName;
  48671. defaultSerif = defaultSerifName;
  48672. defaultFixed = defaultFixedName;
  48673. }
  48674. LookAndFeel::~LookAndFeel()
  48675. {
  48676. }
  48677. const Colour LookAndFeel::findColour (const int colourId) const throw()
  48678. {
  48679. const int index = colourIds.indexOf (colourId);
  48680. if (index >= 0)
  48681. return colours [index];
  48682. jassertfalse
  48683. return Colours::black;
  48684. }
  48685. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  48686. {
  48687. const int index = colourIds.indexOf (colourId);
  48688. if (index >= 0)
  48689. colours.set (index, colour);
  48690. colourIds.add (colourId);
  48691. colours.add (colour);
  48692. }
  48693. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  48694. {
  48695. return colourIds.contains (colourId);
  48696. }
  48697. static LookAndFeel* defaultLF = 0;
  48698. static LookAndFeel* currentDefaultLF = 0;
  48699. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  48700. {
  48701. // if this happens, your app hasn't initialised itself properly.. if you're
  48702. // trying to hack your own main() function, have a look at
  48703. // JUCEApplication::initialiseForGUI()
  48704. jassert (currentDefaultLF != 0);
  48705. return *currentDefaultLF;
  48706. }
  48707. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  48708. {
  48709. if (newDefaultLookAndFeel == 0)
  48710. {
  48711. if (defaultLF == 0)
  48712. defaultLF = new LookAndFeel();
  48713. newDefaultLookAndFeel = defaultLF;
  48714. }
  48715. currentDefaultLF = newDefaultLookAndFeel;
  48716. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  48717. {
  48718. Component* const c = Desktop::getInstance().getComponent (i);
  48719. if (c != 0)
  48720. c->sendLookAndFeelChange();
  48721. }
  48722. }
  48723. void LookAndFeel::clearDefaultLookAndFeel() throw()
  48724. {
  48725. if (currentDefaultLF == defaultLF)
  48726. currentDefaultLF = 0;
  48727. deleteAndZero (defaultLF);
  48728. }
  48729. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  48730. {
  48731. String faceName (font.getTypefaceName());
  48732. if (faceName == Typeface::defaultTypefaceNameSans)
  48733. faceName = defaultSans;
  48734. else if (faceName == Typeface::defaultTypefaceNameSerif)
  48735. faceName = defaultSerif;
  48736. else if (faceName == Typeface::defaultTypefaceNameMono)
  48737. faceName = defaultFixed;
  48738. return new Typeface (faceName, font.isBold(), font.isItalic());
  48739. }
  48740. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  48741. {
  48742. defaultSans = newName;
  48743. }
  48744. void LookAndFeel::drawButtonBackground (Graphics& g,
  48745. Button& button,
  48746. const Colour& backgroundColour,
  48747. bool isMouseOverButton,
  48748. bool isButtonDown)
  48749. {
  48750. const int width = button.getWidth();
  48751. const int height = button.getHeight();
  48752. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  48753. const float halfThickness = outlineThickness * 0.5f;
  48754. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  48755. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  48756. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  48757. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  48758. const Colour baseColour (createBaseColour (backgroundColour,
  48759. button.hasKeyboardFocus (true),
  48760. isMouseOverButton, isButtonDown)
  48761. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48762. drawGlassLozenge (g,
  48763. indentL,
  48764. indentT,
  48765. width - indentL - indentR,
  48766. height - indentT - indentB,
  48767. baseColour, outlineThickness, -1.0f,
  48768. button.isConnectedOnLeft(),
  48769. button.isConnectedOnRight(),
  48770. button.isConnectedOnTop(),
  48771. button.isConnectedOnBottom());
  48772. }
  48773. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  48774. {
  48775. return button.getFont();
  48776. }
  48777. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  48778. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  48779. {
  48780. g.setFont (getFontForTextButton (button));
  48781. g.setColour (button.findColour (TextButton::textColourId)
  48782. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48783. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  48784. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  48785. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  48786. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  48787. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  48788. g.drawFittedText (button.getButtonText(),
  48789. leftIndent,
  48790. yIndent,
  48791. button.getWidth() - leftIndent - rightIndent,
  48792. button.getHeight() - yIndent * 2,
  48793. Justification::centred, 2);
  48794. }
  48795. void LookAndFeel::drawTickBox (Graphics& g,
  48796. Component& component,
  48797. int x, int y, int w, int h,
  48798. const bool ticked,
  48799. const bool isEnabled,
  48800. const bool isMouseOverButton,
  48801. const bool isButtonDown)
  48802. {
  48803. const float boxSize = w * 0.7f;
  48804. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  48805. createBaseColour (component.findColour (TextButton::buttonColourId)
  48806. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  48807. true,
  48808. isMouseOverButton,
  48809. isButtonDown),
  48810. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  48811. if (ticked)
  48812. {
  48813. Path tick;
  48814. tick.startNewSubPath (1.5f, 3.0f);
  48815. tick.lineTo (3.0f, 6.0f);
  48816. tick.lineTo (6.0f, 0.0f);
  48817. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48818. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48819. .translated ((float) x, (float) y));
  48820. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48821. }
  48822. }
  48823. void LookAndFeel::drawToggleButton (Graphics& g,
  48824. ToggleButton& button,
  48825. bool isMouseOverButton,
  48826. bool isButtonDown)
  48827. {
  48828. if (button.hasKeyboardFocus (true))
  48829. {
  48830. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48831. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48832. }
  48833. const int tickWidth = jmin (20, button.getHeight() - 4);
  48834. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48835. tickWidth, tickWidth,
  48836. button.getToggleState(),
  48837. button.isEnabled(),
  48838. isMouseOverButton,
  48839. isButtonDown);
  48840. g.setColour (button.findColour (ToggleButton::textColourId));
  48841. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48842. if (! button.isEnabled())
  48843. g.setOpacity (0.5f);
  48844. const int textX = tickWidth + 5;
  48845. g.drawFittedText (button.getButtonText(),
  48846. textX, 4,
  48847. button.getWidth() - textX - 2, button.getHeight() - 8,
  48848. Justification::centredLeft, 10);
  48849. }
  48850. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  48851. {
  48852. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  48853. const int tickWidth = jmin (24, button.getHeight());
  48854. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  48855. button.getHeight());
  48856. }
  48857. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  48858. const String& message,
  48859. const String& button1,
  48860. const String& button2,
  48861. const String& button3,
  48862. AlertWindow::AlertIconType iconType,
  48863. int numButtons,
  48864. Component* associatedComponent)
  48865. {
  48866. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  48867. if (numButtons == 1)
  48868. {
  48869. aw->addButton (button1, 0,
  48870. KeyPress (KeyPress::escapeKey, 0, 0),
  48871. KeyPress (KeyPress::returnKey, 0, 0));
  48872. }
  48873. else
  48874. {
  48875. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  48876. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  48877. if (button1ShortCut == button2ShortCut)
  48878. button2ShortCut = KeyPress();
  48879. if (numButtons == 2)
  48880. {
  48881. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  48882. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  48883. }
  48884. else if (numButtons == 3)
  48885. {
  48886. aw->addButton (button1, 1, button1ShortCut);
  48887. aw->addButton (button2, 2, button2ShortCut);
  48888. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  48889. }
  48890. }
  48891. return aw;
  48892. }
  48893. void LookAndFeel::drawAlertBox (Graphics& g,
  48894. AlertWindow& alert,
  48895. const Rectangle& textArea,
  48896. TextLayout& textLayout)
  48897. {
  48898. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  48899. int iconSpaceUsed = 0;
  48900. Justification alignment (Justification::horizontallyCentred);
  48901. const int iconWidth = 80;
  48902. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  48903. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  48904. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  48905. const Rectangle iconRect (iconSize / -10, iconSize / -10,
  48906. iconSize, iconSize);
  48907. if (alert.getAlertType() != AlertWindow::NoIcon)
  48908. {
  48909. Path icon;
  48910. uint32 colour;
  48911. char character;
  48912. if (alert.getAlertType() == AlertWindow::WarningIcon)
  48913. {
  48914. colour = 0x55ff5555;
  48915. character = '!';
  48916. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  48917. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  48918. (float) iconRect.getX(), (float) iconRect.getBottom());
  48919. icon = icon.createPathWithRoundedCorners (5.0f);
  48920. }
  48921. else
  48922. {
  48923. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  48924. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  48925. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  48926. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  48927. }
  48928. GlyphArrangement ga;
  48929. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  48930. String::charToString (character),
  48931. (float) iconRect.getX(), (float) iconRect.getY(),
  48932. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  48933. Justification::centred, false);
  48934. ga.createPath (icon);
  48935. icon.setUsingNonZeroWinding (false);
  48936. g.setColour (Colour (colour));
  48937. g.fillPath (icon);
  48938. iconSpaceUsed = iconWidth;
  48939. alignment = Justification::left;
  48940. }
  48941. g.setColour (alert.findColour (AlertWindow::textColourId));
  48942. textLayout.drawWithin (g,
  48943. textArea.getX() + iconSpaceUsed, textArea.getY(),
  48944. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  48945. alignment.getFlags() | Justification::top);
  48946. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  48947. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  48948. }
  48949. int LookAndFeel::getAlertBoxWindowFlags()
  48950. {
  48951. return ComponentPeer::windowAppearsOnTaskbar
  48952. | ComponentPeer::windowHasDropShadow;
  48953. }
  48954. int LookAndFeel::getAlertWindowButtonHeight()
  48955. {
  48956. return 28;
  48957. }
  48958. const Font LookAndFeel::getAlertWindowFont()
  48959. {
  48960. return Font (12.0f);
  48961. }
  48962. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48963. int width, int height,
  48964. double progress, const String& textToShow)
  48965. {
  48966. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48967. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48968. g.fillAll (background);
  48969. if (progress >= 0.0f && progress < 1.0f)
  48970. {
  48971. drawGlassLozenge (g, 1.0f, 1.0f,
  48972. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  48973. (float) (height - 2),
  48974. foreground,
  48975. 0.5f, 0.0f,
  48976. true, true, true, true);
  48977. }
  48978. else
  48979. {
  48980. // spinning bar..
  48981. g.setColour (foreground);
  48982. const int stripeWidth = height * 2;
  48983. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  48984. Path p;
  48985. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  48986. p.addQuadrilateral (x, 0.0f,
  48987. x + stripeWidth * 0.5f, 0.0f,
  48988. x, (float) height,
  48989. x - stripeWidth * 0.5f, (float) height);
  48990. Image im (Image::ARGB, width, height, true);
  48991. {
  48992. Graphics g (im);
  48993. drawGlassLozenge (g, 1.0f, 1.0f,
  48994. (float) (width - 2),
  48995. (float) (height - 2),
  48996. foreground,
  48997. 0.5f, 0.0f,
  48998. true, true, true, true);
  48999. }
  49000. ImageBrush ib (&im, 0, 0, 0.85f);
  49001. g.setBrush (&ib);
  49002. g.fillPath (p);
  49003. }
  49004. if (textToShow.isNotEmpty())
  49005. {
  49006. g.setColour (Colour::contrasting (background, foreground));
  49007. g.setFont (height * 0.6f);
  49008. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  49009. }
  49010. }
  49011. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, int x, int y, int w, int h)
  49012. {
  49013. const float radius = jmin (w, h) * 0.4f;
  49014. const float thickness = radius * 0.15f;
  49015. Path p;
  49016. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  49017. radius * 0.6f, thickness,
  49018. thickness * 0.5f);
  49019. const float cx = x + w * 0.5f;
  49020. const float cy = y + h * 0.5f;
  49021. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  49022. const Colour col (g.getCurrentColour());
  49023. for (int i = 0; i < 12; ++i)
  49024. {
  49025. const int n = (i + 12 - animationIndex) % 12;
  49026. g.setColour (col.withMultipliedAlpha ((n + 1) / 12.0f));
  49027. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  49028. .translated (cx, cy));
  49029. }
  49030. }
  49031. void LookAndFeel::drawScrollbarButton (Graphics& g,
  49032. ScrollBar& scrollbar,
  49033. int width, int height,
  49034. int buttonDirection,
  49035. bool /*isScrollbarVertical*/,
  49036. bool /*isMouseOverButton*/,
  49037. bool isButtonDown)
  49038. {
  49039. Path p;
  49040. if (buttonDirection == 0)
  49041. p.addTriangle (width * 0.5f, height * 0.2f,
  49042. width * 0.1f, height * 0.7f,
  49043. width * 0.9f, height * 0.7f);
  49044. else if (buttonDirection == 1)
  49045. p.addTriangle (width * 0.8f, height * 0.5f,
  49046. width * 0.3f, height * 0.1f,
  49047. width * 0.3f, height * 0.9f);
  49048. else if (buttonDirection == 2)
  49049. p.addTriangle (width * 0.5f, height * 0.8f,
  49050. width * 0.1f, height * 0.3f,
  49051. width * 0.9f, height * 0.3f);
  49052. else if (buttonDirection == 3)
  49053. p.addTriangle (width * 0.2f, height * 0.5f,
  49054. width * 0.7f, height * 0.1f,
  49055. width * 0.7f, height * 0.9f);
  49056. if (isButtonDown)
  49057. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  49058. else
  49059. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  49060. g.fillPath (p);
  49061. g.setColour (Colour (0x80000000));
  49062. g.strokePath (p, PathStrokeType (0.5f));
  49063. }
  49064. void LookAndFeel::drawScrollbar (Graphics& g,
  49065. ScrollBar& scrollbar,
  49066. int x, int y,
  49067. int width, int height,
  49068. bool isScrollbarVertical,
  49069. int thumbStartPosition,
  49070. int thumbSize,
  49071. bool /*isMouseOver*/,
  49072. bool /*isMouseDown*/)
  49073. {
  49074. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  49075. Path slotPath, thumbPath;
  49076. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  49077. const float slotIndentx2 = slotIndent * 2.0f;
  49078. const float thumbIndent = slotIndent + 1.0f;
  49079. const float thumbIndentx2 = thumbIndent * 2.0f;
  49080. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  49081. if (isScrollbarVertical)
  49082. {
  49083. slotPath.addRoundedRectangle (x + slotIndent,
  49084. y + slotIndent,
  49085. width - slotIndentx2,
  49086. height - slotIndentx2,
  49087. (width - slotIndentx2) * 0.5f);
  49088. if (thumbSize > 0)
  49089. thumbPath.addRoundedRectangle (x + thumbIndent,
  49090. thumbStartPosition + thumbIndent,
  49091. width - thumbIndentx2,
  49092. thumbSize - thumbIndentx2,
  49093. (width - thumbIndentx2) * 0.5f);
  49094. gx1 = (float) x;
  49095. gx2 = x + width * 0.7f;
  49096. }
  49097. else
  49098. {
  49099. slotPath.addRoundedRectangle (x + slotIndent,
  49100. y + slotIndent,
  49101. width - slotIndentx2,
  49102. height - slotIndentx2,
  49103. (height - slotIndentx2) * 0.5f);
  49104. if (thumbSize > 0)
  49105. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  49106. y + thumbIndent,
  49107. thumbSize - thumbIndentx2,
  49108. height - thumbIndentx2,
  49109. (height - thumbIndentx2) * 0.5f);
  49110. gy1 = (float) y;
  49111. gy2 = y + height * 0.7f;
  49112. }
  49113. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  49114. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  49115. gx1, gy1,
  49116. thumbColour.overlaidWith (Colour (0x19000000)),
  49117. gx2, gy2, false);
  49118. g.setBrush (&gb);
  49119. g.fillPath (slotPath);
  49120. if (isScrollbarVertical)
  49121. {
  49122. gx1 = x + width * 0.6f;
  49123. gx2 = (float) x + width;
  49124. }
  49125. else
  49126. {
  49127. gy1 = y + height * 0.6f;
  49128. gy2 = (float) y + height;
  49129. }
  49130. GradientBrush gb2 (Colours::transparentBlack,
  49131. gx1, gy1,
  49132. Colour (0x19000000),
  49133. gx2, gy2, false);
  49134. g.setBrush (&gb2);
  49135. g.fillPath (slotPath);
  49136. g.setColour (thumbColour);
  49137. g.fillPath (thumbPath);
  49138. GradientBrush gb3 (Colour (0x10000000),
  49139. gx1, gy1,
  49140. Colours::transparentBlack,
  49141. gx2, gy2, false);
  49142. g.saveState();
  49143. g.setBrush (&gb3);
  49144. if (isScrollbarVertical)
  49145. g.reduceClipRegion (x + width / 2, y, width, height);
  49146. else
  49147. g.reduceClipRegion (x, y + height / 2, width, height);
  49148. g.fillPath (thumbPath);
  49149. g.restoreState();
  49150. g.setColour (Colour (0x4c000000));
  49151. g.strokePath (thumbPath, PathStrokeType (0.4f));
  49152. }
  49153. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  49154. {
  49155. return 0;
  49156. }
  49157. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  49158. {
  49159. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  49160. }
  49161. int LookAndFeel::getDefaultScrollbarWidth()
  49162. {
  49163. return 18;
  49164. }
  49165. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  49166. {
  49167. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  49168. : scrollbar.getHeight());
  49169. }
  49170. const Path LookAndFeel::getTickShape (const float height)
  49171. {
  49172. static const unsigned char tickShapeData[] =
  49173. {
  49174. 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,
  49175. 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,
  49176. 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,
  49177. 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,
  49178. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  49179. };
  49180. Path p;
  49181. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  49182. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49183. return p;
  49184. }
  49185. const Path LookAndFeel::getCrossShape (const float height)
  49186. {
  49187. static const unsigned char crossShapeData[] =
  49188. {
  49189. 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,
  49190. 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,
  49191. 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,
  49192. 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,
  49193. 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,
  49194. 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,
  49195. 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
  49196. };
  49197. Path p;
  49198. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  49199. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49200. return p;
  49201. }
  49202. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  49203. {
  49204. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  49205. x += (w - boxSize) >> 1;
  49206. y += (h - boxSize) >> 1;
  49207. w = boxSize;
  49208. h = boxSize;
  49209. g.setColour (Colour (0xe5ffffff));
  49210. g.fillRect (x, y, w, h);
  49211. g.setColour (Colour (0x80000000));
  49212. g.drawRect (x, y, w, h);
  49213. const float size = boxSize / 2 + 1.0f;
  49214. const float centre = (float) (boxSize / 2);
  49215. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  49216. if (isPlus)
  49217. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  49218. }
  49219. void LookAndFeel::drawBubble (Graphics& g,
  49220. float tipX, float tipY,
  49221. float boxX, float boxY,
  49222. float boxW, float boxH)
  49223. {
  49224. int side = 0;
  49225. if (tipX < boxX)
  49226. side = 1;
  49227. else if (tipX > boxX + boxW)
  49228. side = 3;
  49229. else if (tipY > boxY + boxH)
  49230. side = 2;
  49231. const float indent = 2.0f;
  49232. Path p;
  49233. p.addBubble (boxX + indent,
  49234. boxY + indent,
  49235. boxW - indent * 2.0f,
  49236. boxH - indent * 2.0f,
  49237. 5.0f,
  49238. tipX, tipY,
  49239. side,
  49240. 0.5f,
  49241. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  49242. //xxx need to take comp as param for colour
  49243. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  49244. g.fillPath (p);
  49245. //xxx as above
  49246. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  49247. g.strokePath (p, PathStrokeType (1.33f));
  49248. }
  49249. const Font LookAndFeel::getPopupMenuFont()
  49250. {
  49251. return Font (17.0f);
  49252. }
  49253. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  49254. const bool isSeparator,
  49255. int standardMenuItemHeight,
  49256. int& idealWidth,
  49257. int& idealHeight)
  49258. {
  49259. if (isSeparator)
  49260. {
  49261. idealWidth = 50;
  49262. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  49263. }
  49264. else
  49265. {
  49266. Font font (getPopupMenuFont());
  49267. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  49268. font.setHeight (standardMenuItemHeight / 1.3f);
  49269. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  49270. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  49271. }
  49272. }
  49273. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  49274. {
  49275. const Colour background (findColour (PopupMenu::backgroundColourId));
  49276. g.fillAll (background);
  49277. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  49278. for (int i = 0; i < height; i += 3)
  49279. g.fillRect (0, i, width, 1);
  49280. #if ! JUCE_MAC
  49281. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  49282. g.drawRect (0, 0, width, height);
  49283. #endif
  49284. }
  49285. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  49286. int width, int height,
  49287. bool isScrollUpArrow)
  49288. {
  49289. const Colour background (findColour (PopupMenu::backgroundColourId));
  49290. GradientBrush gb (background,
  49291. 0.0f, height * 0.5f,
  49292. background.withAlpha (0.0f),
  49293. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  49294. false);
  49295. g.setBrush (&gb);
  49296. g.fillRect (1, 1, width - 2, height - 2);
  49297. const float hw = width * 0.5f;
  49298. const float arrowW = height * 0.3f;
  49299. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  49300. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  49301. Path p;
  49302. p.addTriangle (hw - arrowW, y1,
  49303. hw + arrowW, y1,
  49304. hw, y2);
  49305. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  49306. g.fillPath (p);
  49307. }
  49308. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  49309. int width, int height,
  49310. const bool isSeparator,
  49311. const bool isActive,
  49312. const bool isHighlighted,
  49313. const bool isTicked,
  49314. const bool hasSubMenu,
  49315. const String& text,
  49316. const String& shortcutKeyText,
  49317. Image* image,
  49318. const Colour* const textColourToUse)
  49319. {
  49320. const float halfH = height * 0.5f;
  49321. if (isSeparator)
  49322. {
  49323. const float separatorIndent = 5.5f;
  49324. g.setColour (Colour (0x33000000));
  49325. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  49326. g.setColour (Colour (0x66ffffff));
  49327. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  49328. }
  49329. else
  49330. {
  49331. Colour textColour (findColour (PopupMenu::textColourId));
  49332. if (textColourToUse != 0)
  49333. textColour = *textColourToUse;
  49334. if (isHighlighted)
  49335. {
  49336. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  49337. g.fillRect (1, 1, width - 2, height - 2);
  49338. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  49339. }
  49340. else
  49341. {
  49342. g.setColour (textColour);
  49343. }
  49344. if (! isActive)
  49345. g.setOpacity (0.3f);
  49346. Font font (getPopupMenuFont());
  49347. if (font.getHeight() > height / 1.3f)
  49348. font.setHeight (height / 1.3f);
  49349. g.setFont (font);
  49350. const int leftBorder = (height * 5) / 4;
  49351. const int rightBorder = 4;
  49352. if (image != 0)
  49353. {
  49354. g.drawImageWithin (image,
  49355. 2, 1, leftBorder - 4, height - 2,
  49356. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  49357. }
  49358. else if (isTicked)
  49359. {
  49360. const Path tick (getTickShape (1.0f));
  49361. const float th = font.getAscent();
  49362. const float ty = halfH - th * 0.5f;
  49363. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  49364. th, true));
  49365. }
  49366. g.drawFittedText (text,
  49367. leftBorder, 0,
  49368. width - (leftBorder + rightBorder), height,
  49369. Justification::centredLeft, 1);
  49370. if (shortcutKeyText.isNotEmpty())
  49371. {
  49372. Font f2 (g.getCurrentFont());
  49373. f2.setHeight (f2.getHeight() * 0.75f);
  49374. f2.setHorizontalScale (0.95f);
  49375. g.setFont (f2);
  49376. g.drawText (shortcutKeyText,
  49377. leftBorder,
  49378. 0,
  49379. width - (leftBorder + rightBorder + 4),
  49380. height,
  49381. Justification::centredRight,
  49382. true);
  49383. }
  49384. if (hasSubMenu)
  49385. {
  49386. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  49387. const float x = width - height * 0.6f;
  49388. Path p;
  49389. p.addTriangle (x, halfH - arrowH * 0.5f,
  49390. x, halfH + arrowH * 0.5f,
  49391. x + arrowH * 0.6f, halfH);
  49392. g.fillPath (p);
  49393. }
  49394. }
  49395. }
  49396. int LookAndFeel::getMenuWindowFlags()
  49397. {
  49398. return ComponentPeer::windowHasDropShadow;
  49399. }
  49400. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  49401. bool, MenuBarComponent& menuBar)
  49402. {
  49403. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  49404. if (menuBar.isEnabled())
  49405. {
  49406. drawShinyButtonShape (g,
  49407. -4.0f, 0.0f,
  49408. width + 8.0f, (float) height,
  49409. 0.0f,
  49410. baseColour,
  49411. 0.4f,
  49412. true, true, true, true);
  49413. }
  49414. else
  49415. {
  49416. g.fillAll (baseColour);
  49417. }
  49418. }
  49419. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  49420. {
  49421. return Font (menuBar.getHeight() * 0.7f);
  49422. }
  49423. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  49424. {
  49425. return getMenuBarFont (menuBar, itemIndex, itemText)
  49426. .getStringWidth (itemText) + menuBar.getHeight();
  49427. }
  49428. void LookAndFeel::drawMenuBarItem (Graphics& g,
  49429. int width, int height,
  49430. int itemIndex,
  49431. const String& itemText,
  49432. bool isMouseOverItem,
  49433. bool isMenuOpen,
  49434. bool /*isMouseOverBar*/,
  49435. MenuBarComponent& menuBar)
  49436. {
  49437. if (! menuBar.isEnabled())
  49438. {
  49439. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  49440. .withMultipliedAlpha (0.5f));
  49441. }
  49442. else if (isMenuOpen || isMouseOverItem)
  49443. {
  49444. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  49445. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  49446. }
  49447. else
  49448. {
  49449. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  49450. }
  49451. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  49452. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  49453. }
  49454. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  49455. TextEditor& textEditor)
  49456. {
  49457. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  49458. }
  49459. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  49460. {
  49461. if (textEditor.isEnabled())
  49462. {
  49463. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  49464. {
  49465. const int border = 2;
  49466. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  49467. g.drawRect (0, 0, width, height, border);
  49468. g.setOpacity (1.0f);
  49469. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  49470. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  49471. }
  49472. else
  49473. {
  49474. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  49475. g.drawRect (0, 0, width, height);
  49476. g.setOpacity (1.0f);
  49477. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  49478. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  49479. }
  49480. }
  49481. }
  49482. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  49483. const bool isButtonDown,
  49484. int buttonX, int buttonY,
  49485. int buttonW, int buttonH,
  49486. ComboBox& box)
  49487. {
  49488. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  49489. if (box.isEnabled() && box.hasKeyboardFocus (false))
  49490. {
  49491. g.setColour (box.findColour (TextButton::buttonColourId));
  49492. g.drawRect (0, 0, width, height, 2);
  49493. }
  49494. else
  49495. {
  49496. g.setColour (box.findColour (ComboBox::outlineColourId));
  49497. g.drawRect (0, 0, width, height);
  49498. }
  49499. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  49500. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  49501. box.hasKeyboardFocus (true),
  49502. false, isButtonDown)
  49503. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  49504. drawGlassLozenge (g,
  49505. buttonX + outlineThickness, buttonY + outlineThickness,
  49506. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  49507. baseColour, outlineThickness, -1.0f,
  49508. true, true, true, true);
  49509. if (box.isEnabled())
  49510. {
  49511. const float arrowX = 0.3f;
  49512. const float arrowH = 0.2f;
  49513. Path p;
  49514. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  49515. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  49516. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  49517. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  49518. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  49519. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  49520. g.setColour (box.findColour (ComboBox::arrowColourId));
  49521. g.fillPath (p);
  49522. }
  49523. }
  49524. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  49525. {
  49526. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  49527. }
  49528. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  49529. {
  49530. return new Label (String::empty, String::empty);
  49531. }
  49532. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  49533. {
  49534. label.setBounds (1, 1,
  49535. box.getWidth() + 3 - box.getHeight(),
  49536. box.getHeight() - 2);
  49537. label.setFont (getComboBoxFont (box));
  49538. }
  49539. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  49540. {
  49541. g.fillAll (label.findColour (Label::backgroundColourId));
  49542. if (! label.isBeingEdited())
  49543. {
  49544. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  49545. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  49546. g.setFont (label.getFont());
  49547. g.drawFittedText (label.getText(),
  49548. label.getHorizontalBorderSize(),
  49549. label.getVerticalBorderSize(),
  49550. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  49551. label.getHeight() - 2 * label.getVerticalBorderSize(),
  49552. label.getJustificationType(),
  49553. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  49554. label.getMinimumHorizontalScale());
  49555. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  49556. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49557. }
  49558. else if (label.isEnabled())
  49559. {
  49560. g.setColour (label.findColour (Label::outlineColourId));
  49561. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49562. }
  49563. }
  49564. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  49565. int x, int y,
  49566. int width, int height,
  49567. float /*sliderPos*/,
  49568. float /*minSliderPos*/,
  49569. float /*maxSliderPos*/,
  49570. const Slider::SliderStyle /*style*/,
  49571. Slider& slider)
  49572. {
  49573. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49574. const Colour trackColour (slider.findColour (Slider::trackColourId));
  49575. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  49576. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  49577. Path indent;
  49578. if (slider.isHorizontal())
  49579. {
  49580. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  49581. const float ih = sliderRadius;
  49582. GradientBrush gb (gradCol1, 0.0f, iy,
  49583. gradCol2, 0.0f, iy + ih, false);
  49584. g.setBrush (&gb);
  49585. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  49586. width + sliderRadius, ih,
  49587. 5.0f);
  49588. g.fillPath (indent);
  49589. }
  49590. else
  49591. {
  49592. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  49593. const float iw = sliderRadius;
  49594. GradientBrush gb (gradCol1, ix, 0.0f,
  49595. gradCol2, ix + iw, 0.0f, false);
  49596. g.setBrush (&gb);
  49597. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  49598. iw, height + sliderRadius,
  49599. 5.0f);
  49600. g.fillPath (indent);
  49601. }
  49602. g.setColour (Colour (0x4c000000));
  49603. g.strokePath (indent, PathStrokeType (0.5f));
  49604. }
  49605. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  49606. int x, int y,
  49607. int width, int height,
  49608. float sliderPos,
  49609. float minSliderPos,
  49610. float maxSliderPos,
  49611. const Slider::SliderStyle style,
  49612. Slider& slider)
  49613. {
  49614. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49615. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  49616. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  49617. slider.isMouseOverOrDragging() && slider.isEnabled(),
  49618. slider.isMouseButtonDown() && slider.isEnabled()));
  49619. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  49620. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  49621. {
  49622. float kx, ky;
  49623. if (style == Slider::LinearVertical)
  49624. {
  49625. kx = x + width * 0.5f;
  49626. ky = sliderPos;
  49627. }
  49628. else
  49629. {
  49630. kx = sliderPos;
  49631. ky = y + height * 0.5f;
  49632. }
  49633. drawGlassSphere (g,
  49634. kx - sliderRadius,
  49635. ky - sliderRadius,
  49636. sliderRadius * 2.0f,
  49637. knobColour, outlineThickness);
  49638. }
  49639. else
  49640. {
  49641. if (style == Slider::ThreeValueVertical)
  49642. {
  49643. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  49644. sliderPos - sliderRadius,
  49645. sliderRadius * 2.0f,
  49646. knobColour, outlineThickness);
  49647. }
  49648. else if (style == Slider::ThreeValueHorizontal)
  49649. {
  49650. drawGlassSphere (g,sliderPos - sliderRadius,
  49651. y + height * 0.5f - sliderRadius,
  49652. sliderRadius * 2.0f,
  49653. knobColour, outlineThickness);
  49654. }
  49655. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  49656. {
  49657. const float sr = jmin (sliderRadius, width * 0.4f);
  49658. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  49659. minSliderPos - sliderRadius,
  49660. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  49661. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  49662. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  49663. }
  49664. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  49665. {
  49666. const float sr = jmin (sliderRadius, height * 0.4f);
  49667. drawGlassPointer (g, minSliderPos - sr,
  49668. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  49669. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  49670. drawGlassPointer (g, maxSliderPos - sliderRadius,
  49671. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  49672. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  49673. }
  49674. }
  49675. }
  49676. void LookAndFeel::drawLinearSlider (Graphics& g,
  49677. int x, int y,
  49678. int width, int height,
  49679. float sliderPos,
  49680. float minSliderPos,
  49681. float maxSliderPos,
  49682. const Slider::SliderStyle style,
  49683. Slider& slider)
  49684. {
  49685. g.fillAll (slider.findColour (Slider::backgroundColourId));
  49686. if (style == Slider::LinearBar)
  49687. {
  49688. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49689. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  49690. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  49691. false,
  49692. isMouseOver,
  49693. isMouseOver || slider.isMouseButtonDown()));
  49694. drawShinyButtonShape (g,
  49695. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  49696. baseColour,
  49697. slider.isEnabled() ? 0.9f : 0.3f,
  49698. true, true, true, true);
  49699. }
  49700. else
  49701. {
  49702. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49703. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49704. }
  49705. }
  49706. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  49707. {
  49708. return jmin (7,
  49709. slider.getHeight() / 2,
  49710. slider.getWidth() / 2) + 2;
  49711. }
  49712. void LookAndFeel::drawRotarySlider (Graphics& g,
  49713. int x, int y,
  49714. int width, int height,
  49715. float sliderPos,
  49716. const float rotaryStartAngle,
  49717. const float rotaryEndAngle,
  49718. Slider& slider)
  49719. {
  49720. const float radius = jmin (width / 2, height / 2) - 2.0f;
  49721. const float centreX = x + width * 0.5f;
  49722. const float centreY = y + height * 0.5f;
  49723. const float rx = centreX - radius;
  49724. const float ry = centreY - radius;
  49725. const float rw = radius * 2.0f;
  49726. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  49727. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49728. if (radius > 12.0f)
  49729. {
  49730. if (slider.isEnabled())
  49731. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49732. else
  49733. g.setColour (Colour (0x80808080));
  49734. const float thickness = 0.7f;
  49735. {
  49736. Path filledArc;
  49737. filledArc.addPieSegment (rx, ry, rw, rw,
  49738. rotaryStartAngle,
  49739. angle,
  49740. thickness);
  49741. g.fillPath (filledArc);
  49742. }
  49743. if (thickness > 0)
  49744. {
  49745. const float innerRadius = radius * 0.2f;
  49746. Path p;
  49747. p.addTriangle (-innerRadius, 0.0f,
  49748. 0.0f, -radius * thickness * 1.1f,
  49749. innerRadius, 0.0f);
  49750. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  49751. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49752. }
  49753. if (slider.isEnabled())
  49754. {
  49755. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  49756. Path outlineArc;
  49757. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  49758. outlineArc.closeSubPath();
  49759. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  49760. }
  49761. }
  49762. else
  49763. {
  49764. if (slider.isEnabled())
  49765. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49766. else
  49767. g.setColour (Colour (0x80808080));
  49768. Path p;
  49769. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  49770. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  49771. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  49772. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49773. }
  49774. }
  49775. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  49776. {
  49777. return new TextButton (isIncrement ? "+" : "-", String::empty);
  49778. }
  49779. class SliderLabelComp : public Label
  49780. {
  49781. public:
  49782. SliderLabelComp() : Label (String::empty, String::empty) {}
  49783. ~SliderLabelComp() {}
  49784. void mouseWheelMove (const MouseEvent&, float, float) {}
  49785. };
  49786. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  49787. {
  49788. Label* const l = new SliderLabelComp();
  49789. l->setJustificationType (Justification::centred);
  49790. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49791. l->setColour (Label::backgroundColourId,
  49792. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  49793. : slider.findColour (Slider::textBoxBackgroundColourId));
  49794. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49795. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49796. l->setColour (TextEditor::backgroundColourId,
  49797. slider.findColour (Slider::textBoxBackgroundColourId)
  49798. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  49799. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49800. return l;
  49801. }
  49802. ImageEffectFilter* LookAndFeel::getSliderEffect()
  49803. {
  49804. return 0;
  49805. }
  49806. static const TextLayout layoutTooltipText (const String& text) throw()
  49807. {
  49808. const float tooltipFontSize = 12.0f;
  49809. const int maxToolTipWidth = 400;
  49810. const Font f (tooltipFontSize, Font::bold);
  49811. TextLayout tl (text, f);
  49812. tl.layout (maxToolTipWidth, Justification::left, true);
  49813. return tl;
  49814. }
  49815. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  49816. {
  49817. const TextLayout tl (layoutTooltipText (tipText));
  49818. width = tl.getWidth() + 14;
  49819. height = tl.getHeight() + 6;
  49820. }
  49821. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  49822. {
  49823. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  49824. const Colour textCol (findColour (TooltipWindow::textColourId));
  49825. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  49826. g.setColour (findColour (TooltipWindow::outlineColourId));
  49827. g.drawRect (0, 0, width, height, 1);
  49828. #endif
  49829. const TextLayout tl (layoutTooltipText (text));
  49830. g.setColour (findColour (TooltipWindow::textColourId));
  49831. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  49832. }
  49833. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  49834. {
  49835. return new TextButton (text, TRANS("click to browse for a different file"));
  49836. }
  49837. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  49838. ComboBox* filenameBox,
  49839. Button* browseButton)
  49840. {
  49841. browseButton->setSize (80, filenameComp.getHeight());
  49842. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  49843. if (tb != 0)
  49844. tb->changeWidthToFitText();
  49845. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  49846. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  49847. }
  49848. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  49849. int imageX, int imageY, int imageW, int imageH,
  49850. const Colour& overlayColour,
  49851. float imageOpacity,
  49852. ImageButton& button)
  49853. {
  49854. if (! button.isEnabled())
  49855. imageOpacity *= 0.3f;
  49856. if (! overlayColour.isOpaque())
  49857. {
  49858. g.setOpacity (imageOpacity);
  49859. g.drawImage (image, imageX, imageY, imageW, imageH,
  49860. 0, 0, image->getWidth(), image->getHeight(), false);
  49861. }
  49862. if (! overlayColour.isTransparent())
  49863. {
  49864. g.setColour (overlayColour);
  49865. g.drawImage (image, imageX, imageY, imageW, imageH,
  49866. 0, 0, image->getWidth(), image->getHeight(), true);
  49867. }
  49868. }
  49869. void LookAndFeel::drawCornerResizer (Graphics& g,
  49870. int w, int h,
  49871. bool /*isMouseOver*/,
  49872. bool /*isMouseDragging*/)
  49873. {
  49874. const float lineThickness = jmin (w, h) * 0.075f;
  49875. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  49876. {
  49877. g.setColour (Colours::lightgrey);
  49878. g.drawLine (w * i,
  49879. h + 1.0f,
  49880. w + 1.0f,
  49881. h * i,
  49882. lineThickness);
  49883. g.setColour (Colours::darkgrey);
  49884. g.drawLine (w * i + lineThickness,
  49885. h + 1.0f,
  49886. w + 1.0f,
  49887. h * i + lineThickness,
  49888. lineThickness);
  49889. }
  49890. }
  49891. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  49892. const BorderSize& /*borders*/)
  49893. {
  49894. }
  49895. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  49896. const BorderSize& /*border*/, ResizableWindow& window)
  49897. {
  49898. g.fillAll (window.getBackgroundColour());
  49899. }
  49900. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  49901. const BorderSize& border, ResizableWindow&)
  49902. {
  49903. g.setColour (Colour (0x80000000));
  49904. g.drawRect (0, 0, w, h);
  49905. g.setColour (Colour (0x19000000));
  49906. g.drawRect (border.getLeft() - 1,
  49907. border.getTop() - 1,
  49908. w + 2 - border.getLeftAndRight(),
  49909. h + 2 - border.getTopAndBottom());
  49910. }
  49911. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  49912. Graphics& g, int w, int h,
  49913. int titleSpaceX, int titleSpaceW,
  49914. const Image* icon,
  49915. bool drawTitleTextOnLeft)
  49916. {
  49917. const bool isActive = window.isActiveWindow();
  49918. GradientBrush gb (window.getBackgroundColour(),
  49919. 0.0f, 0.0f,
  49920. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  49921. 0.0f, (float) h, false);
  49922. g.setBrush (&gb);
  49923. g.fillAll();
  49924. g.setFont (h * 0.65f, Font::bold);
  49925. int textW = g.getCurrentFont().getStringWidth (window.getName());
  49926. int iconW = 0;
  49927. int iconH = 0;
  49928. if (icon != 0)
  49929. {
  49930. iconH = (int) g.getCurrentFont().getHeight();
  49931. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  49932. }
  49933. textW = jmin (titleSpaceW, textW + iconW);
  49934. int textX = drawTitleTextOnLeft ? titleSpaceX
  49935. : jmax (titleSpaceX, (w - textW) / 2);
  49936. if (textX + textW > titleSpaceX + titleSpaceW)
  49937. textX = titleSpaceX + titleSpaceW - textW;
  49938. if (icon != 0)
  49939. {
  49940. g.setOpacity (isActive ? 1.0f : 0.6f);
  49941. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  49942. RectanglePlacement::centred, false);
  49943. textX += iconW;
  49944. textW -= iconW;
  49945. }
  49946. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  49947. g.setColour (findColour (DocumentWindow::textColourId));
  49948. else
  49949. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  49950. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  49951. }
  49952. class GlassWindowButton : public Button
  49953. {
  49954. public:
  49955. GlassWindowButton (const String& name, const Colour& col,
  49956. const Path& normalShape_,
  49957. const Path& toggledShape_) throw()
  49958. : Button (name),
  49959. colour (col),
  49960. normalShape (normalShape_),
  49961. toggledShape (toggledShape_)
  49962. {
  49963. }
  49964. ~GlassWindowButton()
  49965. {
  49966. }
  49967. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  49968. {
  49969. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  49970. if (! isEnabled())
  49971. alpha *= 0.5f;
  49972. float x = 0, y = 0, diam;
  49973. if (getWidth() < getHeight())
  49974. {
  49975. diam = (float) getWidth();
  49976. y = (getHeight() - getWidth()) * 0.5f;
  49977. }
  49978. else
  49979. {
  49980. diam = (float) getHeight();
  49981. y = (getWidth() - getHeight()) * 0.5f;
  49982. }
  49983. x += diam * 0.05f;
  49984. y += diam * 0.05f;
  49985. diam *= 0.9f;
  49986. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  49987. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  49988. g.setBrush (&gb1);
  49989. g.fillEllipse (x, y, diam, diam);
  49990. x += 2.0f;
  49991. y += 2.0f;
  49992. diam -= 4.0f;
  49993. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  49994. Path& p = getToggleState() ? toggledShape : normalShape;
  49995. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  49996. diam * 0.4f, diam * 0.4f, true));
  49997. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  49998. g.fillPath (p, t);
  49999. }
  50000. juce_UseDebuggingNewOperator
  50001. private:
  50002. Colour colour;
  50003. Path normalShape, toggledShape;
  50004. GlassWindowButton (const GlassWindowButton&);
  50005. const GlassWindowButton& operator= (const GlassWindowButton&);
  50006. };
  50007. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  50008. {
  50009. Path shape;
  50010. const float crossThickness = 0.25f;
  50011. if (buttonType == DocumentWindow::closeButton)
  50012. {
  50013. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  50014. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  50015. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  50016. }
  50017. else if (buttonType == DocumentWindow::minimiseButton)
  50018. {
  50019. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50020. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  50021. }
  50022. else if (buttonType == DocumentWindow::maximiseButton)
  50023. {
  50024. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  50025. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50026. Path fullscreenShape;
  50027. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  50028. fullscreenShape.lineTo (0.0f, 100.0f);
  50029. fullscreenShape.lineTo (0.0f, 0.0f);
  50030. fullscreenShape.lineTo (100.0f, 0.0f);
  50031. fullscreenShape.lineTo (100.0f, 45.0f);
  50032. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  50033. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  50034. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  50035. }
  50036. jassertfalse
  50037. return 0;
  50038. }
  50039. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  50040. int titleBarX,
  50041. int titleBarY,
  50042. int titleBarW,
  50043. int titleBarH,
  50044. Button* minimiseButton,
  50045. Button* maximiseButton,
  50046. Button* closeButton,
  50047. bool positionTitleBarButtonsOnLeft)
  50048. {
  50049. const int buttonW = titleBarH - titleBarH / 8;
  50050. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  50051. : titleBarX + titleBarW - buttonW - buttonW / 4;
  50052. if (closeButton != 0)
  50053. {
  50054. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50055. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  50056. }
  50057. if (positionTitleBarButtonsOnLeft)
  50058. swapVariables (minimiseButton, maximiseButton);
  50059. if (maximiseButton != 0)
  50060. {
  50061. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50062. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  50063. }
  50064. if (minimiseButton != 0)
  50065. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50066. }
  50067. int LookAndFeel::getDefaultMenuBarHeight()
  50068. {
  50069. return 24;
  50070. }
  50071. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  50072. {
  50073. return new DropShadower (0.4f, 1, 5, 10);
  50074. }
  50075. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  50076. int w, int h,
  50077. bool /*isVerticalBar*/,
  50078. bool isMouseOver,
  50079. bool isMouseDragging)
  50080. {
  50081. float alpha = 0.5f;
  50082. if (isMouseOver || isMouseDragging)
  50083. {
  50084. g.fillAll (Colour (0x190000ff));
  50085. alpha = 1.0f;
  50086. }
  50087. const float cx = w * 0.5f;
  50088. const float cy = h * 0.5f;
  50089. const float cr = jmin (w, h) * 0.4f;
  50090. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  50091. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  50092. true);
  50093. g.setBrush (&gb);
  50094. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  50095. }
  50096. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  50097. const String& text,
  50098. const Justification& position,
  50099. GroupComponent& group)
  50100. {
  50101. const float textH = 15.0f;
  50102. const float indent = 3.0f;
  50103. const float textEdgeGap = 4.0f;
  50104. float cs = 5.0f;
  50105. Font f (textH);
  50106. Path p;
  50107. float x = indent;
  50108. float y = f.getAscent() - 3.0f;
  50109. float w = jmax (0.0f, width - x * 2.0f);
  50110. float h = jmax (0.0f, height - y - indent);
  50111. cs = jmin (cs, w * 0.5f, h * 0.5f);
  50112. const float cs2 = 2.0f * cs;
  50113. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  50114. float textX = cs + textEdgeGap;
  50115. if (position.testFlags (Justification::horizontallyCentred))
  50116. textX = cs + (w - cs2 - textW) * 0.5f;
  50117. else if (position.testFlags (Justification::right))
  50118. textX = w - cs - textW - textEdgeGap;
  50119. p.startNewSubPath (x + textX + textW, y);
  50120. p.lineTo (x + w - cs, y);
  50121. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  50122. p.lineTo (x + w, y + h - cs);
  50123. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50124. p.lineTo (x + cs, y + h);
  50125. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50126. p.lineTo (x, y + cs);
  50127. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50128. p.lineTo (x + textX, y);
  50129. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  50130. g.setColour (group.findColour (GroupComponent::outlineColourId)
  50131. .withMultipliedAlpha (alpha));
  50132. g.strokePath (p, PathStrokeType (2.0f));
  50133. g.setColour (group.findColour (GroupComponent::textColourId)
  50134. .withMultipliedAlpha (alpha));
  50135. g.setFont (f);
  50136. g.drawText (text,
  50137. roundFloatToInt (x + textX), 0,
  50138. roundFloatToInt (textW),
  50139. roundFloatToInt (textH),
  50140. Justification::centred, true);
  50141. }
  50142. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  50143. {
  50144. return 1 + tabDepth / 3;
  50145. }
  50146. int LookAndFeel::getTabButtonSpaceAroundImage()
  50147. {
  50148. return 4;
  50149. }
  50150. void LookAndFeel::createTabButtonShape (Path& p,
  50151. int width, int height,
  50152. int /*tabIndex*/,
  50153. const String& /*text*/,
  50154. Button& /*button*/,
  50155. TabbedButtonBar::Orientation orientation,
  50156. const bool /*isMouseOver*/,
  50157. const bool /*isMouseDown*/,
  50158. const bool /*isFrontTab*/)
  50159. {
  50160. const float w = (float) width;
  50161. const float h = (float) height;
  50162. float length = w;
  50163. float depth = h;
  50164. if (orientation == TabbedButtonBar::TabsAtLeft
  50165. || orientation == TabbedButtonBar::TabsAtRight)
  50166. {
  50167. swapVariables (length, depth);
  50168. }
  50169. const float indent = (float) getTabButtonOverlap ((int) depth);
  50170. const float overhang = 4.0f;
  50171. if (orientation == TabbedButtonBar::TabsAtLeft)
  50172. {
  50173. p.startNewSubPath (w, 0.0f);
  50174. p.lineTo (0.0f, indent);
  50175. p.lineTo (0.0f, h - indent);
  50176. p.lineTo (w, h);
  50177. p.lineTo (w + overhang, h + overhang);
  50178. p.lineTo (w + overhang, -overhang);
  50179. }
  50180. else if (orientation == TabbedButtonBar::TabsAtRight)
  50181. {
  50182. p.startNewSubPath (0.0f, 0.0f);
  50183. p.lineTo (w, indent);
  50184. p.lineTo (w, h - indent);
  50185. p.lineTo (0.0f, h);
  50186. p.lineTo (-overhang, h + overhang);
  50187. p.lineTo (-overhang, -overhang);
  50188. }
  50189. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50190. {
  50191. p.startNewSubPath (0.0f, 0.0f);
  50192. p.lineTo (indent, h);
  50193. p.lineTo (w - indent, h);
  50194. p.lineTo (w, 0.0f);
  50195. p.lineTo (w + overhang, -overhang);
  50196. p.lineTo (-overhang, -overhang);
  50197. }
  50198. else
  50199. {
  50200. p.startNewSubPath (0.0f, h);
  50201. p.lineTo (indent, 0.0f);
  50202. p.lineTo (w - indent, 0.0f);
  50203. p.lineTo (w, h);
  50204. p.lineTo (w + overhang, h + overhang);
  50205. p.lineTo (-overhang, h + overhang);
  50206. }
  50207. p.closeSubPath();
  50208. p = p.createPathWithRoundedCorners (3.0f);
  50209. }
  50210. void LookAndFeel::fillTabButtonShape (Graphics& g,
  50211. const Path& path,
  50212. const Colour& preferredColour,
  50213. int /*tabIndex*/,
  50214. const String& /*text*/,
  50215. Button& button,
  50216. TabbedButtonBar::Orientation /*orientation*/,
  50217. const bool /*isMouseOver*/,
  50218. const bool /*isMouseDown*/,
  50219. const bool isFrontTab)
  50220. {
  50221. g.setColour (isFrontTab ? preferredColour
  50222. : preferredColour.withMultipliedAlpha (0.9f));
  50223. g.fillPath (path);
  50224. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  50225. : TabbedButtonBar::tabOutlineColourId, false)
  50226. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  50227. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  50228. }
  50229. void LookAndFeel::drawTabButtonText (Graphics& g,
  50230. int x, int y, int w, int h,
  50231. const Colour& preferredBackgroundColour,
  50232. int /*tabIndex*/,
  50233. const String& text,
  50234. Button& button,
  50235. TabbedButtonBar::Orientation orientation,
  50236. const bool isMouseOver,
  50237. const bool isMouseDown,
  50238. const bool isFrontTab)
  50239. {
  50240. int length = w;
  50241. int depth = h;
  50242. if (orientation == TabbedButtonBar::TabsAtLeft
  50243. || orientation == TabbedButtonBar::TabsAtRight)
  50244. {
  50245. swapVariables (length, depth);
  50246. }
  50247. Font font (depth * 0.6f);
  50248. font.setUnderline (button.hasKeyboardFocus (false));
  50249. GlyphArrangement textLayout;
  50250. textLayout.addFittedText (font, text.trim(),
  50251. 0.0f, 0.0f, (float) length, (float) depth,
  50252. Justification::centred,
  50253. jmax (1, depth / 12));
  50254. AffineTransform transform;
  50255. if (orientation == TabbedButtonBar::TabsAtLeft)
  50256. {
  50257. transform = transform.rotated (float_Pi * -0.5f)
  50258. .translated ((float) x, (float) (y + h));
  50259. }
  50260. else if (orientation == TabbedButtonBar::TabsAtRight)
  50261. {
  50262. transform = transform.rotated (float_Pi * 0.5f)
  50263. .translated ((float) (x + w), (float) y);
  50264. }
  50265. else
  50266. {
  50267. transform = transform.translated ((float) x, (float) y);
  50268. }
  50269. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  50270. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  50271. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  50272. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  50273. else
  50274. g.setColour (preferredBackgroundColour.contrasting());
  50275. if (! (isMouseOver || isMouseDown))
  50276. g.setOpacity (0.8f);
  50277. if (! button.isEnabled())
  50278. g.setOpacity (0.3f);
  50279. textLayout.draw (g, transform);
  50280. }
  50281. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  50282. const String& text,
  50283. int tabDepth,
  50284. Button&)
  50285. {
  50286. Font f (tabDepth * 0.6f);
  50287. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  50288. }
  50289. void LookAndFeel::drawTabButton (Graphics& g,
  50290. int w, int h,
  50291. const Colour& preferredColour,
  50292. int tabIndex,
  50293. const String& text,
  50294. Button& button,
  50295. TabbedButtonBar::Orientation orientation,
  50296. const bool isMouseOver,
  50297. const bool isMouseDown,
  50298. const bool isFrontTab)
  50299. {
  50300. int length = w;
  50301. int depth = h;
  50302. if (orientation == TabbedButtonBar::TabsAtLeft
  50303. || orientation == TabbedButtonBar::TabsAtRight)
  50304. {
  50305. swapVariables (length, depth);
  50306. }
  50307. Path tabShape;
  50308. createTabButtonShape (tabShape, w, h,
  50309. tabIndex, text, button, orientation,
  50310. isMouseOver, isMouseDown, isFrontTab);
  50311. fillTabButtonShape (g, tabShape, preferredColour,
  50312. tabIndex, text, button, orientation,
  50313. isMouseOver, isMouseDown, isFrontTab);
  50314. const int indent = getTabButtonOverlap (depth);
  50315. int x = 0, y = 0;
  50316. if (orientation == TabbedButtonBar::TabsAtLeft
  50317. || orientation == TabbedButtonBar::TabsAtRight)
  50318. {
  50319. y += indent;
  50320. h -= indent * 2;
  50321. }
  50322. else
  50323. {
  50324. x += indent;
  50325. w -= indent * 2;
  50326. }
  50327. drawTabButtonText (g, x, y, w, h, preferredColour,
  50328. tabIndex, text, button, orientation,
  50329. isMouseOver, isMouseDown, isFrontTab);
  50330. }
  50331. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  50332. int w, int h,
  50333. TabbedButtonBar& tabBar,
  50334. TabbedButtonBar::Orientation orientation)
  50335. {
  50336. const float shadowSize = 0.2f;
  50337. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  50338. Rectangle shadowRect;
  50339. if (orientation == TabbedButtonBar::TabsAtLeft)
  50340. {
  50341. x1 = (float) w;
  50342. x2 = w * (1.0f - shadowSize);
  50343. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  50344. }
  50345. else if (orientation == TabbedButtonBar::TabsAtRight)
  50346. {
  50347. x2 = w * shadowSize;
  50348. shadowRect.setBounds (0, 0, (int) x2, h);
  50349. }
  50350. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50351. {
  50352. y2 = h * shadowSize;
  50353. shadowRect.setBounds (0, 0, w, (int) y2);
  50354. }
  50355. else
  50356. {
  50357. y1 = (float) h;
  50358. y2 = h * (1.0f - shadowSize);
  50359. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  50360. }
  50361. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  50362. Colours::transparentBlack, x2, y2,
  50363. false);
  50364. g.setBrush (&gb);
  50365. shadowRect.expand (2, 2);
  50366. g.fillRect (shadowRect);
  50367. g.setColour (Colour (0x80000000));
  50368. if (orientation == TabbedButtonBar::TabsAtLeft)
  50369. {
  50370. g.fillRect (w - 1, 0, 1, h);
  50371. }
  50372. else if (orientation == TabbedButtonBar::TabsAtRight)
  50373. {
  50374. g.fillRect (0, 0, 1, h);
  50375. }
  50376. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50377. {
  50378. g.fillRect (0, 0, w, 1);
  50379. }
  50380. else
  50381. {
  50382. g.fillRect (0, h - 1, w, 1);
  50383. }
  50384. }
  50385. Button* LookAndFeel::createTabBarExtrasButton()
  50386. {
  50387. const float thickness = 7.0f;
  50388. const float indent = 22.0f;
  50389. Path p;
  50390. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  50391. DrawablePath ellipse;
  50392. ellipse.setPath (p);
  50393. ellipse.setSolidFill (Colour (0x99ffffff));
  50394. p.clear();
  50395. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  50396. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  50397. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  50398. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  50399. p.setUsingNonZeroWinding (false);
  50400. DrawablePath dp;
  50401. dp.setPath (p);
  50402. dp.setSolidFill (Colour (0x59000000));
  50403. DrawableComposite normalImage;
  50404. normalImage.insertDrawable (ellipse);
  50405. normalImage.insertDrawable (dp);
  50406. dp.setSolidFill (Colour (0xcc000000));
  50407. DrawableComposite overImage;
  50408. overImage.insertDrawable (ellipse);
  50409. overImage.insertDrawable (dp);
  50410. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  50411. db->setImages (&normalImage, &overImage, 0);
  50412. return db;
  50413. }
  50414. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  50415. {
  50416. g.fillAll (Colours::white);
  50417. const int w = header.getWidth();
  50418. const int h = header.getHeight();
  50419. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  50420. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  50421. false);
  50422. g.setBrush (&gb);
  50423. g.fillRect (0, h / 2, w, h);
  50424. g.setColour (Colour (0x33000000));
  50425. g.fillRect (0, h - 1, w, 1);
  50426. for (int i = header.getNumColumns (true); --i >= 0;)
  50427. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  50428. }
  50429. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  50430. int width, int height,
  50431. bool isMouseOver, bool isMouseDown,
  50432. int columnFlags)
  50433. {
  50434. if (isMouseDown)
  50435. g.fillAll (Colour (0x8899aadd));
  50436. else if (isMouseOver)
  50437. g.fillAll (Colour (0x5599aadd));
  50438. int rightOfText = width - 4;
  50439. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  50440. {
  50441. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  50442. const float bottom = height - top;
  50443. const float w = height * 0.5f;
  50444. const float x = rightOfText - (w * 1.25f);
  50445. rightOfText = (int) x;
  50446. Path sortArrow;
  50447. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  50448. g.setColour (Colour (0x99000000));
  50449. g.fillPath (sortArrow);
  50450. }
  50451. g.setColour (Colours::black);
  50452. g.setFont (height * 0.5f, Font::bold);
  50453. const int textX = 4;
  50454. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  50455. }
  50456. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  50457. {
  50458. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  50459. GradientBrush gb (background, 0.0f, 0.0f,
  50460. background.darker (0.1f),
  50461. toolbar.isVertical() ? w - 1.0f : 0.0f,
  50462. toolbar.isVertical() ? 0.0f : h - 1.0f,
  50463. false);
  50464. g.setBrush (&gb);
  50465. g.fillAll();
  50466. }
  50467. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  50468. {
  50469. return createTabBarExtrasButton();
  50470. }
  50471. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  50472. bool isMouseOver, bool isMouseDown,
  50473. ToolbarItemComponent& component)
  50474. {
  50475. if (isMouseDown)
  50476. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  50477. else if (isMouseOver)
  50478. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  50479. }
  50480. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  50481. const String& text, ToolbarItemComponent& component)
  50482. {
  50483. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  50484. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  50485. const float fontHeight = jmin (14.0f, height * 0.85f);
  50486. g.setFont (fontHeight);
  50487. g.drawFittedText (text,
  50488. x, y, width, height,
  50489. Justification::centred,
  50490. jmax (1, height / (int) fontHeight));
  50491. }
  50492. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  50493. bool isOpen, int width, int height)
  50494. {
  50495. const int buttonSize = (height * 3) / 4;
  50496. const int buttonIndent = (height - buttonSize) / 2;
  50497. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  50498. const int textX = buttonIndent * 2 + buttonSize + 2;
  50499. g.setColour (Colours::black);
  50500. g.setFont (height * 0.7f, Font::bold);
  50501. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  50502. }
  50503. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  50504. PropertyComponent&)
  50505. {
  50506. g.setColour (Colour (0x66ffffff));
  50507. g.fillRect (0, 0, width, height - 1);
  50508. }
  50509. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  50510. PropertyComponent& component)
  50511. {
  50512. g.setColour (Colours::black);
  50513. if (! component.isEnabled())
  50514. g.setOpacity (g.getCurrentColour().getFloatAlpha() * 0.6f);
  50515. g.setFont (jmin (height, 24) * 0.65f);
  50516. const Rectangle r (getPropertyComponentContentPosition (component));
  50517. g.drawFittedText (component.getName(),
  50518. 3, r.getY(), r.getX() - 5, r.getHeight(),
  50519. Justification::centredLeft, 2);
  50520. }
  50521. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  50522. {
  50523. return Rectangle (component.getWidth() / 3, 1,
  50524. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  50525. }
  50526. void LookAndFeel::createFileChooserHeaderText (const String& title,
  50527. const String& instructions,
  50528. GlyphArrangement& text,
  50529. int width)
  50530. {
  50531. text.clear();
  50532. text.addJustifiedText (Font (17.0f, Font::bold), title,
  50533. 8.0f, 22.0f, width - 16.0f,
  50534. Justification::centred);
  50535. text.addJustifiedText (Font (14.0f), instructions,
  50536. 8.0f, 24.0f + 16.0f, width - 16.0f,
  50537. Justification::centred);
  50538. }
  50539. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  50540. const String& filename, Image* icon,
  50541. const String& fileSizeDescription,
  50542. const String& fileTimeDescription,
  50543. const bool isDirectory,
  50544. const bool isItemSelected,
  50545. const int /*itemIndex*/)
  50546. {
  50547. if (isItemSelected)
  50548. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  50549. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  50550. g.setFont (height * 0.7f);
  50551. Image* im = icon;
  50552. Image* toRelease = 0;
  50553. if (im == 0)
  50554. {
  50555. toRelease = im = (isDirectory ? getDefaultFolderImage()
  50556. : getDefaultDocumentFileImage());
  50557. }
  50558. const int x = 32;
  50559. if (im != 0)
  50560. {
  50561. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  50562. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  50563. false);
  50564. ImageCache::release (toRelease);
  50565. }
  50566. if (width > 450 && ! isDirectory)
  50567. {
  50568. const int sizeX = roundFloatToInt (width * 0.7f);
  50569. const int dateX = roundFloatToInt (width * 0.8f);
  50570. g.drawFittedText (filename,
  50571. x, 0, sizeX - x, height,
  50572. Justification::centredLeft, 1);
  50573. g.setFont (height * 0.5f);
  50574. g.setColour (Colours::darkgrey);
  50575. if (! isDirectory)
  50576. {
  50577. g.drawFittedText (fileSizeDescription,
  50578. sizeX, 0, dateX - sizeX - 8, height,
  50579. Justification::centredRight, 1);
  50580. g.drawFittedText (fileTimeDescription,
  50581. dateX, 0, width - 8 - dateX, height,
  50582. Justification::centredRight, 1);
  50583. }
  50584. }
  50585. else
  50586. {
  50587. g.drawFittedText (filename,
  50588. x, 0, width - x, height,
  50589. Justification::centredLeft, 1);
  50590. }
  50591. }
  50592. Button* LookAndFeel::createFileBrowserGoUpButton()
  50593. {
  50594. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  50595. Path arrowPath;
  50596. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  50597. DrawablePath arrowImage;
  50598. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  50599. arrowImage.setPath (arrowPath);
  50600. goUpButton->setImages (&arrowImage);
  50601. return goUpButton;
  50602. }
  50603. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  50604. DirectoryContentsDisplayComponent* fileListComponent,
  50605. FilePreviewComponent* previewComp,
  50606. ComboBox* currentPathBox,
  50607. TextEditor* filenameBox,
  50608. Button* goUpButton)
  50609. {
  50610. const int x = 8;
  50611. int w = browserComp.getWidth() - x - x;
  50612. if (previewComp != 0)
  50613. {
  50614. const int previewWidth = w / 3;
  50615. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  50616. w -= previewWidth + 4;
  50617. }
  50618. int y = 4;
  50619. const int controlsHeight = 22;
  50620. const int bottomSectionHeight = controlsHeight + 8;
  50621. const int upButtonWidth = 50;
  50622. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  50623. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  50624. y += controlsHeight + 4;
  50625. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  50626. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  50627. y = listAsComp->getBottom() + 4;
  50628. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  50629. }
  50630. Image* LookAndFeel::getDefaultFolderImage()
  50631. {
  50632. 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,
  50633. 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,
  50634. 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,
  50635. 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,
  50636. 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,
  50637. 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,
  50638. 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,
  50639. 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,
  50640. 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,
  50641. 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,
  50642. 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,
  50643. 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,
  50644. 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,
  50645. 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,
  50646. 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,
  50647. 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,
  50648. 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,
  50649. 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,
  50650. 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,
  50651. 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,
  50652. 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,
  50653. 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,
  50654. 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,
  50655. 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,
  50656. 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,
  50657. 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,
  50658. 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,
  50659. 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,
  50660. 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,
  50661. 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,
  50662. 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,
  50663. 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,
  50664. 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,
  50665. 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,
  50666. 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,
  50667. 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,
  50668. 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,
  50669. 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,
  50670. 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,
  50671. 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,
  50672. 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,
  50673. 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,
  50674. 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,
  50675. 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};
  50676. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  50677. }
  50678. Image* LookAndFeel::getDefaultDocumentFileImage()
  50679. {
  50680. 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,
  50681. 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,
  50682. 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,
  50683. 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,
  50684. 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,
  50685. 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,
  50686. 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,
  50687. 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,
  50688. 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,
  50689. 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,
  50690. 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,
  50691. 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,
  50692. 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,
  50693. 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,
  50694. 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,
  50695. 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,
  50696. 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,
  50697. 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,
  50698. 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,
  50699. 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,
  50700. 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,
  50701. 174,66,96,130,0,0};
  50702. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  50703. }
  50704. void LookAndFeel::playAlertSound()
  50705. {
  50706. PlatformUtilities::beep();
  50707. }
  50708. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  50709. {
  50710. g.setColour (Colours::white.withAlpha (0.7f));
  50711. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  50712. g.setColour (Colours::black.withAlpha (0.2f));
  50713. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  50714. const int totalBlocks = 7;
  50715. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  50716. const float w = (width - 6.0f) / (float) totalBlocks;
  50717. for (int i = 0; i < totalBlocks; ++i)
  50718. {
  50719. if (i >= numBlocks)
  50720. g.setColour (Colours::lightblue.withAlpha (0.6f));
  50721. else
  50722. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  50723. : Colours::red);
  50724. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  50725. }
  50726. }
  50727. static void createRoundedPath (Path& p,
  50728. const float x, const float y,
  50729. const float w, const float h,
  50730. const float cs,
  50731. const bool curveTopLeft, const bool curveTopRight,
  50732. const bool curveBottomLeft, const bool curveBottomRight) throw()
  50733. {
  50734. const float cs2 = 2.0f * cs;
  50735. if (curveTopLeft)
  50736. {
  50737. p.startNewSubPath (x, y + cs);
  50738. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50739. }
  50740. else
  50741. {
  50742. p.startNewSubPath (x, y);
  50743. }
  50744. if (curveTopRight)
  50745. {
  50746. p.lineTo (x + w - cs, y);
  50747. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  50748. }
  50749. else
  50750. {
  50751. p.lineTo (x + w, y);
  50752. }
  50753. if (curveBottomRight)
  50754. {
  50755. p.lineTo (x + w, y + h - cs);
  50756. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50757. }
  50758. else
  50759. {
  50760. p.lineTo (x + w, y + h);
  50761. }
  50762. if (curveBottomLeft)
  50763. {
  50764. p.lineTo (x + cs, y + h);
  50765. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50766. }
  50767. else
  50768. {
  50769. p.lineTo (x, y + h);
  50770. }
  50771. p.closeSubPath();
  50772. }
  50773. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  50774. float x, float y, float w, float h,
  50775. float maxCornerSize,
  50776. const Colour& baseColour,
  50777. const float strokeWidth,
  50778. const bool flatOnLeft,
  50779. const bool flatOnRight,
  50780. const bool flatOnTop,
  50781. const bool flatOnBottom) throw()
  50782. {
  50783. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  50784. return;
  50785. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  50786. Path outline;
  50787. createRoundedPath (outline, x, y, w, h, cs,
  50788. ! (flatOnLeft || flatOnTop),
  50789. ! (flatOnRight || flatOnTop),
  50790. ! (flatOnLeft || flatOnBottom),
  50791. ! (flatOnRight || flatOnBottom));
  50792. ColourGradient cg (baseColour, 0.0f, y,
  50793. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  50794. false);
  50795. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  50796. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  50797. GradientBrush gb (cg);
  50798. g.setBrush (&gb);
  50799. g.fillPath (outline);
  50800. g.setColour (Colour (0x80000000));
  50801. g.strokePath (outline, PathStrokeType (strokeWidth));
  50802. }
  50803. void LookAndFeel::drawGlassSphere (Graphics& g,
  50804. const float x, const float y,
  50805. const float diameter,
  50806. const Colour& colour,
  50807. const float outlineThickness) throw()
  50808. {
  50809. if (diameter <= outlineThickness)
  50810. return;
  50811. Path p;
  50812. p.addEllipse (x, y, diameter, diameter);
  50813. {
  50814. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50815. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50816. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50817. GradientBrush gb (cg);
  50818. g.setBrush (&gb);
  50819. g.fillPath (p);
  50820. }
  50821. {
  50822. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  50823. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  50824. g.setBrush (&gb);
  50825. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  50826. }
  50827. {
  50828. ColourGradient cg (Colours::transparentBlack,
  50829. x + diameter * 0.5f, y + diameter * 0.5f,
  50830. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50831. x, y + diameter * 0.5f, true);
  50832. cg.addColour (0.7, Colours::transparentBlack);
  50833. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  50834. GradientBrush gb (cg);
  50835. g.setBrush (&gb);
  50836. g.fillPath (p);
  50837. }
  50838. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50839. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  50840. }
  50841. void LookAndFeel::drawGlassPointer (Graphics& g,
  50842. const float x, const float y,
  50843. const float diameter,
  50844. const Colour& colour, const float outlineThickness,
  50845. const int direction) throw()
  50846. {
  50847. if (diameter <= outlineThickness)
  50848. return;
  50849. Path p;
  50850. p.startNewSubPath (x + diameter * 0.5f, y);
  50851. p.lineTo (x + diameter, y + diameter * 0.6f);
  50852. p.lineTo (x + diameter, y + diameter);
  50853. p.lineTo (x, y + diameter);
  50854. p.lineTo (x, y + diameter * 0.6f);
  50855. p.closeSubPath();
  50856. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  50857. {
  50858. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50859. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50860. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50861. GradientBrush gb (cg);
  50862. g.setBrush (&gb);
  50863. g.fillPath (p);
  50864. }
  50865. {
  50866. ColourGradient cg (Colours::transparentBlack,
  50867. x + diameter * 0.5f, y + diameter * 0.5f,
  50868. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50869. x - diameter * 0.2f, y + diameter * 0.5f, true);
  50870. cg.addColour (0.5, Colours::transparentBlack);
  50871. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  50872. GradientBrush gb (cg);
  50873. g.setBrush (&gb);
  50874. g.fillPath (p);
  50875. }
  50876. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50877. g.strokePath (p, PathStrokeType (outlineThickness));
  50878. }
  50879. void LookAndFeel::drawGlassLozenge (Graphics& g,
  50880. const float x, const float y,
  50881. const float width, const float height,
  50882. const Colour& colour,
  50883. const float outlineThickness,
  50884. const float cornerSize,
  50885. const bool flatOnLeft,
  50886. const bool flatOnRight,
  50887. const bool flatOnTop,
  50888. const bool flatOnBottom) throw()
  50889. {
  50890. if (width <= outlineThickness || height <= outlineThickness)
  50891. return;
  50892. const int intX = (int) x;
  50893. const int intY = (int) y;
  50894. const int intW = (int) width;
  50895. const int intH = (int) height;
  50896. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  50897. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  50898. const int intEdge = (int) edgeBlurRadius;
  50899. Path outline;
  50900. createRoundedPath (outline, x, y, width, height, cs,
  50901. ! (flatOnLeft || flatOnTop),
  50902. ! (flatOnRight || flatOnTop),
  50903. ! (flatOnLeft || flatOnBottom),
  50904. ! (flatOnRight || flatOnBottom));
  50905. {
  50906. ColourGradient cg (colour.darker (0.2f), 0, y,
  50907. colour.darker (0.2f), 0, y + height, false);
  50908. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  50909. cg.addColour (0.4, colour);
  50910. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  50911. GradientBrush gb (cg);
  50912. g.setBrush (&gb);
  50913. g.fillPath (outline);
  50914. }
  50915. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  50916. colour.darker (0.2f), x, y + height * 0.5f, true);
  50917. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  50918. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  50919. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  50920. {
  50921. GradientBrush gb (cg);
  50922. g.saveState();
  50923. g.setBrush (&gb);
  50924. g.reduceClipRegion (intX, intY, intEdge, intH);
  50925. g.fillPath (outline);
  50926. g.restoreState();
  50927. }
  50928. if (! (flatOnRight || flatOnTop || flatOnBottom))
  50929. {
  50930. cg.x1 = x + width - edgeBlurRadius;
  50931. cg.x2 = x + width;
  50932. GradientBrush gb (cg);
  50933. g.saveState();
  50934. g.setBrush (&gb);
  50935. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  50936. g.fillPath (outline);
  50937. g.restoreState();
  50938. }
  50939. {
  50940. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  50941. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  50942. Path highlight;
  50943. createRoundedPath (highlight,
  50944. x + leftIndent,
  50945. y + cs * 0.1f,
  50946. width - (leftIndent + rightIndent),
  50947. height * 0.4f, cs * 0.4f,
  50948. ! (flatOnLeft || flatOnTop),
  50949. ! (flatOnRight || flatOnTop),
  50950. ! (flatOnLeft || flatOnBottom),
  50951. ! (flatOnRight || flatOnBottom));
  50952. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  50953. Colours::transparentWhite, 0, y + height * 0.4f, false);
  50954. g.setBrush (&gb);
  50955. g.fillPath (highlight);
  50956. }
  50957. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  50958. g.strokePath (outline, PathStrokeType (outlineThickness));
  50959. }
  50960. END_JUCE_NAMESPACE
  50961. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  50962. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  50963. BEGIN_JUCE_NAMESPACE
  50964. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  50965. {
  50966. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  50967. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  50968. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  50969. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  50970. setColour (Slider::thumbColourId, Colours::white);
  50971. setColour (Slider::trackColourId, Colour (0x7f000000));
  50972. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  50973. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  50974. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  50975. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  50976. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  50977. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  50978. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  50979. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  50980. }
  50981. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  50982. {
  50983. }
  50984. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  50985. Button& button,
  50986. const Colour& backgroundColour,
  50987. bool isMouseOverButton,
  50988. bool isButtonDown)
  50989. {
  50990. const int width = button.getWidth();
  50991. const int height = button.getHeight();
  50992. const float indent = 2.0f;
  50993. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  50994. roundFloatToInt (height * 0.4f));
  50995. Path p;
  50996. p.addRoundedRectangle (indent, indent,
  50997. width - indent * 2.0f,
  50998. height - indent * 2.0f,
  50999. (float) cornerSize);
  51000. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  51001. if (isMouseOverButton)
  51002. {
  51003. if (isButtonDown)
  51004. bc = bc.brighter();
  51005. else if (bc.getBrightness() > 0.5f)
  51006. bc = bc.darker (0.1f);
  51007. else
  51008. bc = bc.brighter (0.1f);
  51009. }
  51010. g.setColour (bc);
  51011. g.fillPath (p);
  51012. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  51013. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  51014. }
  51015. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  51016. Component& /*component*/,
  51017. int x, int y, int w, int h,
  51018. const bool ticked,
  51019. const bool isEnabled,
  51020. const bool /*isMouseOverButton*/,
  51021. const bool isButtonDown)
  51022. {
  51023. Path box;
  51024. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  51025. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  51026. : Colours::lightgrey.withAlpha (0.1f));
  51027. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51028. .translated ((float) x, (float) y));
  51029. g.fillPath (box, trans);
  51030. g.setColour (Colours::black.withAlpha (0.6f));
  51031. g.strokePath (box, PathStrokeType (0.9f), trans);
  51032. if (ticked)
  51033. {
  51034. Path tick;
  51035. tick.startNewSubPath (1.5f, 3.0f);
  51036. tick.lineTo (3.0f, 6.0f);
  51037. tick.lineTo (6.0f, 0.0f);
  51038. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51039. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51040. }
  51041. }
  51042. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  51043. ToggleButton& button,
  51044. bool isMouseOverButton,
  51045. bool isButtonDown)
  51046. {
  51047. if (button.hasKeyboardFocus (true))
  51048. {
  51049. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51050. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51051. }
  51052. const int tickWidth = jmin (20, button.getHeight() - 4);
  51053. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  51054. tickWidth, tickWidth,
  51055. button.getToggleState(),
  51056. button.isEnabled(),
  51057. isMouseOverButton,
  51058. isButtonDown);
  51059. g.setColour (button.findColour (ToggleButton::textColourId));
  51060. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  51061. if (! button.isEnabled())
  51062. g.setOpacity (0.5f);
  51063. const int textX = tickWidth + 5;
  51064. g.drawFittedText (button.getButtonText(),
  51065. textX, 4,
  51066. button.getWidth() - textX - 2, button.getHeight() - 8,
  51067. Justification::centredLeft, 10);
  51068. }
  51069. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51070. int width, int height,
  51071. double progress, const String& textToShow)
  51072. {
  51073. if (progress < 0 || progress >= 1.0)
  51074. {
  51075. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  51076. }
  51077. else
  51078. {
  51079. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51080. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51081. g.fillAll (background);
  51082. g.setColour (foreground);
  51083. g.fillRect (1, 1,
  51084. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  51085. height - 2);
  51086. if (textToShow.isNotEmpty())
  51087. {
  51088. g.setColour (Colour::contrasting (background, foreground));
  51089. g.setFont (height * 0.6f);
  51090. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51091. }
  51092. }
  51093. }
  51094. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  51095. ScrollBar& bar,
  51096. int width, int height,
  51097. int buttonDirection,
  51098. bool isScrollbarVertical,
  51099. bool isMouseOverButton,
  51100. bool isButtonDown)
  51101. {
  51102. if (isScrollbarVertical)
  51103. width -= 2;
  51104. else
  51105. height -= 2;
  51106. Path p;
  51107. if (buttonDirection == 0)
  51108. p.addTriangle (width * 0.5f, height * 0.2f,
  51109. width * 0.1f, height * 0.7f,
  51110. width * 0.9f, height * 0.7f);
  51111. else if (buttonDirection == 1)
  51112. p.addTriangle (width * 0.8f, height * 0.5f,
  51113. width * 0.3f, height * 0.1f,
  51114. width * 0.3f, height * 0.9f);
  51115. else if (buttonDirection == 2)
  51116. p.addTriangle (width * 0.5f, height * 0.8f,
  51117. width * 0.1f, height * 0.3f,
  51118. width * 0.9f, height * 0.3f);
  51119. else if (buttonDirection == 3)
  51120. p.addTriangle (width * 0.2f, height * 0.5f,
  51121. width * 0.7f, height * 0.1f,
  51122. width * 0.7f, height * 0.9f);
  51123. if (isButtonDown)
  51124. g.setColour (Colours::white);
  51125. else if (isMouseOverButton)
  51126. g.setColour (Colours::white.withAlpha (0.7f));
  51127. else
  51128. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  51129. g.fillPath (p);
  51130. g.setColour (Colours::black.withAlpha (0.5f));
  51131. g.strokePath (p, PathStrokeType (0.5f));
  51132. }
  51133. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  51134. ScrollBar& bar,
  51135. int x, int y,
  51136. int width, int height,
  51137. bool isScrollbarVertical,
  51138. int thumbStartPosition,
  51139. int thumbSize,
  51140. bool isMouseOver,
  51141. bool isMouseDown)
  51142. {
  51143. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  51144. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51145. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  51146. if (thumbSize > 0.0f)
  51147. {
  51148. Rectangle thumb;
  51149. if (isScrollbarVertical)
  51150. {
  51151. width -= 2;
  51152. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  51153. roundFloatToInt (width * 0.3f), height);
  51154. thumb.setBounds (x + 1, thumbStartPosition,
  51155. width - 2, thumbSize);
  51156. }
  51157. else
  51158. {
  51159. height -= 2;
  51160. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  51161. width, roundFloatToInt (height * 0.3f));
  51162. thumb.setBounds (thumbStartPosition, y + 1,
  51163. thumbSize, height - 2);
  51164. }
  51165. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51166. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  51167. g.fillRect (thumb);
  51168. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  51169. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  51170. if (thumbSize > 16)
  51171. {
  51172. for (int i = 3; --i >= 0;)
  51173. {
  51174. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  51175. g.setColour (Colours::black.withAlpha (0.15f));
  51176. if (isScrollbarVertical)
  51177. {
  51178. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  51179. g.setColour (Colours::white.withAlpha (0.15f));
  51180. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  51181. }
  51182. else
  51183. {
  51184. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  51185. g.setColour (Colours::white.withAlpha (0.15f));
  51186. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  51187. }
  51188. }
  51189. }
  51190. }
  51191. }
  51192. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  51193. {
  51194. return &scrollbarShadow;
  51195. }
  51196. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51197. {
  51198. g.fillAll (findColour (PopupMenu::backgroundColourId));
  51199. g.setColour (Colours::black.withAlpha (0.6f));
  51200. g.drawRect (0, 0, width, height);
  51201. }
  51202. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  51203. bool, MenuBarComponent& menuBar)
  51204. {
  51205. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  51206. }
  51207. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  51208. {
  51209. if (textEditor.isEnabled())
  51210. {
  51211. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  51212. g.drawRect (0, 0, width, height);
  51213. }
  51214. }
  51215. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  51216. const bool isButtonDown,
  51217. int buttonX, int buttonY,
  51218. int buttonW, int buttonH,
  51219. ComboBox& box)
  51220. {
  51221. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  51222. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  51223. : ComboBox::backgroundColourId));
  51224. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  51225. g.setColour (box.findColour (ComboBox::outlineColourId));
  51226. g.drawRect (0, 0, width, height);
  51227. const float arrowX = 0.2f;
  51228. const float arrowH = 0.3f;
  51229. if (box.isEnabled())
  51230. {
  51231. Path p;
  51232. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  51233. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  51234. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  51235. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  51236. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  51237. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  51238. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  51239. : ComboBox::buttonColourId));
  51240. g.fillPath (p);
  51241. }
  51242. }
  51243. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  51244. {
  51245. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  51246. f.setHorizontalScale (0.9f);
  51247. return f;
  51248. }
  51249. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  51250. {
  51251. Path p;
  51252. p.addTriangle (x1, y1, x2, y2, x3, y3);
  51253. g.setColour (fill);
  51254. g.fillPath (p);
  51255. g.setColour (outline);
  51256. g.strokePath (p, PathStrokeType (0.3f));
  51257. }
  51258. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  51259. int x, int y,
  51260. int w, int h,
  51261. float sliderPos,
  51262. float minSliderPos,
  51263. float maxSliderPos,
  51264. const Slider::SliderStyle style,
  51265. Slider& slider)
  51266. {
  51267. g.fillAll (slider.findColour (Slider::backgroundColourId));
  51268. if (style == Slider::LinearBar)
  51269. {
  51270. g.setColour (slider.findColour (Slider::thumbColourId));
  51271. g.fillRect (x, y, (int) sliderPos - x, h);
  51272. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  51273. g.drawRect (x, y, (int) sliderPos - x, h);
  51274. }
  51275. else
  51276. {
  51277. g.setColour (slider.findColour (Slider::trackColourId)
  51278. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  51279. if (slider.isHorizontal())
  51280. {
  51281. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  51282. w, roundFloatToInt (h * 0.2f));
  51283. }
  51284. else
  51285. {
  51286. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  51287. jmin (4, roundFloatToInt (w * 0.2f)), h);
  51288. }
  51289. float alpha = 0.35f;
  51290. if (slider.isEnabled())
  51291. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  51292. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  51293. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  51294. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  51295. {
  51296. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  51297. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  51298. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  51299. fill, outline);
  51300. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  51301. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  51302. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  51303. fill, outline);
  51304. }
  51305. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  51306. {
  51307. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51308. minSliderPos - 7.0f, y + h * 0.9f ,
  51309. minSliderPos, y + h * 0.9f,
  51310. fill, outline);
  51311. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51312. maxSliderPos, y + h * 0.9f,
  51313. maxSliderPos + 7.0f, y + h * 0.9f,
  51314. fill, outline);
  51315. }
  51316. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  51317. {
  51318. drawTriangle (g, sliderPos, y + h * 0.9f,
  51319. sliderPos - 7.0f, y + h * 0.2f,
  51320. sliderPos + 7.0f, y + h * 0.2f,
  51321. fill, outline);
  51322. }
  51323. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  51324. {
  51325. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  51326. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  51327. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  51328. fill, outline);
  51329. }
  51330. }
  51331. }
  51332. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  51333. {
  51334. if (isIncrement)
  51335. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  51336. else
  51337. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  51338. }
  51339. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  51340. {
  51341. return &scrollbarShadow;
  51342. }
  51343. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  51344. {
  51345. return 8;
  51346. }
  51347. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  51348. int w, int h,
  51349. bool isMouseOver,
  51350. bool isMouseDragging)
  51351. {
  51352. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  51353. : Colours::darkgrey);
  51354. const float lineThickness = jmin (w, h) * 0.1f;
  51355. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  51356. {
  51357. g.drawLine (w * i,
  51358. h + 1.0f,
  51359. w + 1.0f,
  51360. h * i,
  51361. lineThickness);
  51362. }
  51363. }
  51364. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  51365. {
  51366. Path shape;
  51367. if (buttonType == DocumentWindow::closeButton)
  51368. {
  51369. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  51370. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  51371. ShapeButton* const b = new ShapeButton ("close",
  51372. Colour (0x7fff3333),
  51373. Colour (0xd7ff3333),
  51374. Colour (0xf7ff3333));
  51375. b->setShape (shape, true, true, true);
  51376. return b;
  51377. }
  51378. else if (buttonType == DocumentWindow::minimiseButton)
  51379. {
  51380. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51381. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  51382. DrawablePath dp;
  51383. dp.setPath (shape);
  51384. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51385. b->setImages (&dp);
  51386. return b;
  51387. }
  51388. else if (buttonType == DocumentWindow::maximiseButton)
  51389. {
  51390. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  51391. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51392. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  51393. DrawablePath dp;
  51394. dp.setPath (shape);
  51395. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51396. b->setImages (&dp);
  51397. return b;
  51398. }
  51399. jassertfalse
  51400. return 0;
  51401. }
  51402. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  51403. int titleBarX,
  51404. int titleBarY,
  51405. int titleBarW,
  51406. int titleBarH,
  51407. Button* minimiseButton,
  51408. Button* maximiseButton,
  51409. Button* closeButton,
  51410. bool positionTitleBarButtonsOnLeft)
  51411. {
  51412. titleBarY += titleBarH / 8;
  51413. titleBarH -= titleBarH / 4;
  51414. const int buttonW = titleBarH;
  51415. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  51416. : titleBarX + titleBarW - buttonW - 4;
  51417. if (closeButton != 0)
  51418. {
  51419. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  51420. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  51421. : -(buttonW + buttonW / 5);
  51422. }
  51423. if (positionTitleBarButtonsOnLeft)
  51424. swapVariables (minimiseButton, maximiseButton);
  51425. if (maximiseButton != 0)
  51426. {
  51427. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51428. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  51429. }
  51430. if (minimiseButton != 0)
  51431. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51432. }
  51433. END_JUCE_NAMESPACE
  51434. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  51435. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  51436. BEGIN_JUCE_NAMESPACE
  51437. class DummyMenuComponent : public Component
  51438. {
  51439. DummyMenuComponent (const DummyMenuComponent&);
  51440. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  51441. public:
  51442. DummyMenuComponent() {}
  51443. ~DummyMenuComponent() {}
  51444. void inputAttemptWhenModal()
  51445. {
  51446. exitModalState (0);
  51447. }
  51448. };
  51449. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  51450. : model (0),
  51451. itemUnderMouse (-1),
  51452. currentPopupIndex (-1),
  51453. indexToShowAgain (-1),
  51454. lastMouseX (0),
  51455. lastMouseY (0),
  51456. inModalState (false),
  51457. currentPopup (0)
  51458. {
  51459. setRepaintsOnMouseActivity (true);
  51460. setWantsKeyboardFocus (false);
  51461. setMouseClickGrabsKeyboardFocus (false);
  51462. setModel (model_);
  51463. }
  51464. MenuBarComponent::~MenuBarComponent()
  51465. {
  51466. setModel (0);
  51467. Desktop::getInstance().removeGlobalMouseListener (this);
  51468. deleteAndZero (currentPopup);
  51469. }
  51470. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  51471. {
  51472. if (model != newModel)
  51473. {
  51474. if (model != 0)
  51475. model->removeListener (this);
  51476. model = newModel;
  51477. if (model != 0)
  51478. model->addListener (this);
  51479. repaint();
  51480. menuBarItemsChanged (0);
  51481. }
  51482. }
  51483. void MenuBarComponent::paint (Graphics& g)
  51484. {
  51485. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  51486. getLookAndFeel().drawMenuBarBackground (g,
  51487. getWidth(),
  51488. getHeight(),
  51489. isMouseOverBar,
  51490. *this);
  51491. if (model != 0)
  51492. {
  51493. for (int i = 0; i < menuNames.size(); ++i)
  51494. {
  51495. g.saveState();
  51496. g.setOrigin (xPositions [i], 0);
  51497. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  51498. getLookAndFeel().drawMenuBarItem (g,
  51499. xPositions[i + 1] - xPositions[i],
  51500. getHeight(),
  51501. i,
  51502. menuNames[i],
  51503. i == itemUnderMouse,
  51504. i == currentPopupIndex,
  51505. isMouseOverBar,
  51506. *this);
  51507. g.restoreState();
  51508. }
  51509. }
  51510. }
  51511. void MenuBarComponent::resized()
  51512. {
  51513. xPositions.clear();
  51514. int x = 2;
  51515. xPositions.add (x);
  51516. for (int i = 0; i < menuNames.size(); ++i)
  51517. {
  51518. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  51519. xPositions.add (x);
  51520. }
  51521. }
  51522. int MenuBarComponent::getItemAt (const int x, const int y)
  51523. {
  51524. for (int i = 0; i < xPositions.size(); ++i)
  51525. if (x >= xPositions[i] && x < xPositions[i + 1])
  51526. return reallyContains (x, y, true) ? i : -1;
  51527. return -1;
  51528. }
  51529. void MenuBarComponent::repaintMenuItem (int index)
  51530. {
  51531. if (((unsigned int) index) < (unsigned int) xPositions.size())
  51532. {
  51533. const int x1 = xPositions [index];
  51534. const int x2 = xPositions [index + 1];
  51535. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  51536. }
  51537. }
  51538. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  51539. {
  51540. const int newItem = getItemAt (x, y);
  51541. if (itemUnderMouse != newItem)
  51542. {
  51543. repaintMenuItem (itemUnderMouse);
  51544. itemUnderMouse = newItem;
  51545. repaintMenuItem (itemUnderMouse);
  51546. }
  51547. }
  51548. void MenuBarComponent::hideCurrentMenu()
  51549. {
  51550. deleteAndZero (currentPopup);
  51551. repaint();
  51552. }
  51553. void MenuBarComponent::showMenu (int index)
  51554. {
  51555. if (index != currentPopupIndex)
  51556. {
  51557. if (inModalState)
  51558. {
  51559. hideCurrentMenu();
  51560. indexToShowAgain = index;
  51561. return;
  51562. }
  51563. indexToShowAgain = -1;
  51564. currentPopupIndex = -1;
  51565. itemUnderMouse = index;
  51566. deleteAndZero (currentPopup);
  51567. menuBarItemsChanged (0);
  51568. Component* const prevFocused = getCurrentlyFocusedComponent();
  51569. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  51570. if (prevFocused != 0)
  51571. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  51572. ComponentDeletionWatcher deletionChecker (this);
  51573. enterModalState (false);
  51574. inModalState = true;
  51575. int result = 0;
  51576. ApplicationCommandManager* managerOfChosenCommand = 0;
  51577. Desktop::getInstance().addGlobalMouseListener (this);
  51578. for (;;)
  51579. {
  51580. const int x = getScreenX() + xPositions [itemUnderMouse];
  51581. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  51582. currentPopupIndex = itemUnderMouse;
  51583. indexToShowAgain = -1;
  51584. repaint();
  51585. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  51586. {
  51587. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  51588. menuNames [itemUnderMouse]));
  51589. currentPopup = m.createMenuComponent (x, getScreenY(),
  51590. w, getHeight(),
  51591. 0, w, 0, 0,
  51592. true, this,
  51593. &managerOfChosenCommand,
  51594. this);
  51595. }
  51596. if (currentPopup == 0)
  51597. {
  51598. currentPopup = new DummyMenuComponent();
  51599. addAndMakeVisible (currentPopup);
  51600. }
  51601. currentPopup->enterModalState (false);
  51602. currentPopup->toFront (false); // need to do this after making it modal, or it could
  51603. // be stuck behind other comps that are already modal..
  51604. result = currentPopup->runModalLoop();
  51605. if (deletionChecker.hasBeenDeleted())
  51606. {
  51607. delete prevCompDeletionChecker;
  51608. return;
  51609. }
  51610. const int lastPopupIndex = currentPopupIndex;
  51611. deleteAndZero (currentPopup);
  51612. currentPopupIndex = -1;
  51613. if (result != 0)
  51614. {
  51615. topLevelIndexClicked = lastPopupIndex;
  51616. break;
  51617. }
  51618. else if (indexToShowAgain >= 0)
  51619. {
  51620. menuBarItemsChanged (0);
  51621. repaint();
  51622. itemUnderMouse = indexToShowAgain;
  51623. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  51624. break;
  51625. }
  51626. else
  51627. {
  51628. break;
  51629. }
  51630. }
  51631. Desktop::getInstance().removeGlobalMouseListener (this);
  51632. inModalState = false;
  51633. exitModalState (0);
  51634. if (prevCompDeletionChecker != 0)
  51635. {
  51636. if (! prevCompDeletionChecker->hasBeenDeleted())
  51637. prevFocused->grabKeyboardFocus();
  51638. delete prevCompDeletionChecker;
  51639. }
  51640. int mx, my;
  51641. getMouseXYRelative (mx, my);
  51642. updateItemUnderMouse (mx, my);
  51643. repaint();
  51644. if (result != 0)
  51645. {
  51646. if (managerOfChosenCommand != 0)
  51647. {
  51648. ApplicationCommandTarget::InvocationInfo info (result);
  51649. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  51650. managerOfChosenCommand->invoke (info, true);
  51651. }
  51652. postCommandMessage (result);
  51653. }
  51654. }
  51655. }
  51656. void MenuBarComponent::handleCommandMessage (int commandId)
  51657. {
  51658. if (model != 0)
  51659. model->menuItemSelected (commandId, topLevelIndexClicked);
  51660. }
  51661. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  51662. {
  51663. if (e.eventComponent == this)
  51664. updateItemUnderMouse (e.x, e.y);
  51665. }
  51666. void MenuBarComponent::mouseExit (const MouseEvent& e)
  51667. {
  51668. if (e.eventComponent == this)
  51669. updateItemUnderMouse (e.x, e.y);
  51670. }
  51671. void MenuBarComponent::mouseDown (const MouseEvent& e)
  51672. {
  51673. const MouseEvent e2 (e.getEventRelativeTo (this));
  51674. if (currentPopupIndex < 0)
  51675. {
  51676. updateItemUnderMouse (e2.x, e2.y);
  51677. currentPopupIndex = -2;
  51678. showMenu (itemUnderMouse);
  51679. }
  51680. }
  51681. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  51682. {
  51683. const MouseEvent e2 (e.getEventRelativeTo (this));
  51684. const int item = getItemAt (e2.x, e2.y);
  51685. if (item >= 0)
  51686. showMenu (item);
  51687. }
  51688. void MenuBarComponent::mouseUp (const MouseEvent& e)
  51689. {
  51690. const MouseEvent e2 (e.getEventRelativeTo (this));
  51691. updateItemUnderMouse (e2.x, e2.y);
  51692. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  51693. hideCurrentMenu();
  51694. }
  51695. void MenuBarComponent::mouseMove (const MouseEvent& e)
  51696. {
  51697. const MouseEvent e2 (e.getEventRelativeTo (this));
  51698. if (lastMouseX != e2.x || lastMouseY != e2.y)
  51699. {
  51700. if (currentPopupIndex >= 0)
  51701. {
  51702. const int item = getItemAt (e2.x, e2.y);
  51703. if (item >= 0)
  51704. showMenu (item);
  51705. }
  51706. else
  51707. {
  51708. updateItemUnderMouse (e2.x, e2.y);
  51709. }
  51710. lastMouseX = e2.x;
  51711. lastMouseY = e2.y;
  51712. }
  51713. }
  51714. bool MenuBarComponent::keyPressed (const KeyPress& key)
  51715. {
  51716. bool used = false;
  51717. const int numMenus = menuNames.size();
  51718. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  51719. if (key.isKeyCode (KeyPress::leftKey))
  51720. {
  51721. showMenu ((currentIndex + numMenus - 1) % numMenus);
  51722. used = true;
  51723. }
  51724. else if (key.isKeyCode (KeyPress::rightKey))
  51725. {
  51726. showMenu ((currentIndex + 1) % numMenus);
  51727. used = true;
  51728. }
  51729. return used;
  51730. }
  51731. void MenuBarComponent::inputAttemptWhenModal()
  51732. {
  51733. hideCurrentMenu();
  51734. }
  51735. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  51736. {
  51737. StringArray newNames;
  51738. if (model != 0)
  51739. newNames = model->getMenuBarNames();
  51740. if (newNames != menuNames)
  51741. {
  51742. menuNames = newNames;
  51743. repaint();
  51744. resized();
  51745. }
  51746. }
  51747. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  51748. const ApplicationCommandTarget::InvocationInfo& info)
  51749. {
  51750. if (model == 0
  51751. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  51752. return;
  51753. for (int i = 0; i < menuNames.size(); ++i)
  51754. {
  51755. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  51756. if (menu.containsCommandItem (info.commandID))
  51757. {
  51758. itemUnderMouse = i;
  51759. repaintMenuItem (i);
  51760. startTimer (200);
  51761. break;
  51762. }
  51763. }
  51764. }
  51765. void MenuBarComponent::timerCallback()
  51766. {
  51767. stopTimer();
  51768. int mx, my;
  51769. getMouseXYRelative (mx, my);
  51770. updateItemUnderMouse (mx, my);
  51771. }
  51772. END_JUCE_NAMESPACE
  51773. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  51774. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  51775. BEGIN_JUCE_NAMESPACE
  51776. MenuBarModel::MenuBarModel() throw()
  51777. : manager (0)
  51778. {
  51779. }
  51780. MenuBarModel::~MenuBarModel()
  51781. {
  51782. setApplicationCommandManagerToWatch (0);
  51783. }
  51784. void MenuBarModel::menuItemsChanged()
  51785. {
  51786. triggerAsyncUpdate();
  51787. }
  51788. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  51789. {
  51790. if (manager != newManager)
  51791. {
  51792. if (manager != 0)
  51793. manager->removeListener (this);
  51794. manager = newManager;
  51795. if (manager != 0)
  51796. manager->addListener (this);
  51797. }
  51798. }
  51799. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  51800. {
  51801. jassert (newListener != 0);
  51802. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  51803. if (newListener != 0)
  51804. listeners.add (newListener);
  51805. }
  51806. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  51807. {
  51808. // Trying to remove a listener that isn't on the list!
  51809. // If this assertion happens because this object is a dangling pointer, make sure you've not
  51810. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  51811. jassert (listeners.contains (listenerToRemove));
  51812. listeners.removeValue (listenerToRemove);
  51813. }
  51814. void MenuBarModel::handleAsyncUpdate()
  51815. {
  51816. for (int i = listeners.size(); --i >= 0;)
  51817. {
  51818. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  51819. i = jmin (i, listeners.size());
  51820. }
  51821. }
  51822. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  51823. {
  51824. for (int i = listeners.size(); --i >= 0;)
  51825. {
  51826. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  51827. i = jmin (i, listeners.size());
  51828. }
  51829. }
  51830. void MenuBarModel::applicationCommandListChanged()
  51831. {
  51832. menuItemsChanged();
  51833. }
  51834. END_JUCE_NAMESPACE
  51835. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  51836. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  51837. BEGIN_JUCE_NAMESPACE
  51838. static VoidArray activeMenuWindows;
  51839. class MenuItemInfo
  51840. {
  51841. public:
  51842. const int itemId;
  51843. String text;
  51844. const Colour textColour;
  51845. const bool active, isSeparator, isTicked, usesColour;
  51846. Image* image;
  51847. PopupMenuCustomComponent* const customComp;
  51848. PopupMenu* subMenu;
  51849. ApplicationCommandManager* const commandManager;
  51850. MenuItemInfo() throw()
  51851. : itemId (0),
  51852. active (true),
  51853. isSeparator (true),
  51854. isTicked (false),
  51855. usesColour (false),
  51856. image (0),
  51857. customComp (0),
  51858. subMenu (0),
  51859. commandManager (0)
  51860. {
  51861. }
  51862. MenuItemInfo (const int itemId_,
  51863. const String& text_,
  51864. const bool active_,
  51865. const bool isTicked_,
  51866. const Image* im,
  51867. const Colour& textColour_,
  51868. const bool usesColour_,
  51869. PopupMenuCustomComponent* const customComp_,
  51870. const PopupMenu* const subMenu_,
  51871. ApplicationCommandManager* const commandManager_) throw()
  51872. : itemId (itemId_),
  51873. text (text_),
  51874. textColour (textColour_),
  51875. active (active_),
  51876. isSeparator (false),
  51877. isTicked (isTicked_),
  51878. usesColour (usesColour_),
  51879. image (0),
  51880. customComp (customComp_),
  51881. commandManager (commandManager_)
  51882. {
  51883. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  51884. if (customComp != 0)
  51885. customComp->refCount_++;
  51886. if (im != 0)
  51887. image = im->createCopy();
  51888. if (commandManager_ != 0 && itemId_ != 0)
  51889. {
  51890. String shortcutKey;
  51891. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  51892. ->getKeyPressesAssignedToCommand (itemId_));
  51893. for (int i = 0; i < keyPresses.size(); ++i)
  51894. {
  51895. const String key (keyPresses.getReference(i).getTextDescription());
  51896. if (shortcutKey.isNotEmpty())
  51897. shortcutKey << ", ";
  51898. if (key.length() == 1)
  51899. shortcutKey << "shortcut: '" << key << '\'';
  51900. else
  51901. shortcutKey << key;
  51902. }
  51903. shortcutKey = shortcutKey.trim();
  51904. if (shortcutKey.isNotEmpty())
  51905. text << "<end>" << shortcutKey;
  51906. }
  51907. }
  51908. MenuItemInfo (const MenuItemInfo& other) throw()
  51909. : itemId (other.itemId),
  51910. text (other.text),
  51911. textColour (other.textColour),
  51912. active (other.active),
  51913. isSeparator (other.isSeparator),
  51914. isTicked (other.isTicked),
  51915. usesColour (other.usesColour),
  51916. customComp (other.customComp),
  51917. commandManager (other.commandManager)
  51918. {
  51919. if (other.subMenu != 0)
  51920. subMenu = new PopupMenu (*(other.subMenu));
  51921. else
  51922. subMenu = 0;
  51923. if (other.image != 0)
  51924. image = other.image->createCopy();
  51925. else
  51926. image = 0;
  51927. if (customComp != 0)
  51928. customComp->refCount_++;
  51929. }
  51930. ~MenuItemInfo() throw()
  51931. {
  51932. delete subMenu;
  51933. delete image;
  51934. if (customComp != 0 && --(customComp->refCount_) == 0)
  51935. delete customComp;
  51936. }
  51937. bool canBeTriggered() const throw()
  51938. {
  51939. return active && ! (isSeparator || (subMenu != 0));
  51940. }
  51941. bool hasActiveSubMenu() const throw()
  51942. {
  51943. return active && (subMenu != 0);
  51944. }
  51945. juce_UseDebuggingNewOperator
  51946. private:
  51947. const MenuItemInfo& operator= (const MenuItemInfo&);
  51948. };
  51949. class MenuItemComponent : public Component
  51950. {
  51951. bool isHighlighted;
  51952. public:
  51953. MenuItemInfo itemInfo;
  51954. MenuItemComponent (const MenuItemInfo& itemInfo_)
  51955. : isHighlighted (false),
  51956. itemInfo (itemInfo_)
  51957. {
  51958. if (itemInfo.customComp != 0)
  51959. addAndMakeVisible (itemInfo.customComp);
  51960. }
  51961. ~MenuItemComponent()
  51962. {
  51963. if (itemInfo.customComp != 0)
  51964. removeChildComponent (itemInfo.customComp);
  51965. }
  51966. void getIdealSize (int& idealWidth,
  51967. int& idealHeight,
  51968. const int standardItemHeight)
  51969. {
  51970. if (itemInfo.customComp != 0)
  51971. {
  51972. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  51973. }
  51974. else
  51975. {
  51976. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  51977. itemInfo.isSeparator,
  51978. standardItemHeight,
  51979. idealWidth,
  51980. idealHeight);
  51981. }
  51982. }
  51983. void paint (Graphics& g)
  51984. {
  51985. if (itemInfo.customComp == 0)
  51986. {
  51987. String mainText (itemInfo.text);
  51988. String endText;
  51989. const int endIndex = mainText.indexOf (T("<end>"));
  51990. if (endIndex >= 0)
  51991. {
  51992. endText = mainText.substring (endIndex + 5).trim();
  51993. mainText = mainText.substring (0, endIndex);
  51994. }
  51995. getLookAndFeel()
  51996. .drawPopupMenuItem (g, getWidth(), getHeight(),
  51997. itemInfo.isSeparator,
  51998. itemInfo.active,
  51999. isHighlighted,
  52000. itemInfo.isTicked,
  52001. itemInfo.subMenu != 0,
  52002. mainText, endText,
  52003. itemInfo.image,
  52004. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  52005. }
  52006. }
  52007. void resized()
  52008. {
  52009. if (getNumChildComponents() > 0)
  52010. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  52011. }
  52012. void setHighlighted (bool shouldBeHighlighted)
  52013. {
  52014. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  52015. if (isHighlighted != shouldBeHighlighted)
  52016. {
  52017. isHighlighted = shouldBeHighlighted;
  52018. if (itemInfo.customComp != 0)
  52019. {
  52020. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  52021. itemInfo.customComp->repaint();
  52022. }
  52023. repaint();
  52024. }
  52025. }
  52026. private:
  52027. MenuItemComponent (const MenuItemComponent&);
  52028. const MenuItemComponent& operator= (const MenuItemComponent&);
  52029. };
  52030. static const int scrollZone = 24;
  52031. static const int borderSize = 2;
  52032. static const int timerInterval = 50;
  52033. static const int dismissCommandId = 0x6287345f;
  52034. static bool wasHiddenBecauseOfAppChange = false;
  52035. class PopupMenuWindow : public Component,
  52036. private Timer
  52037. {
  52038. public:
  52039. PopupMenuWindow() throw()
  52040. : Component (T("menu")),
  52041. owner (0),
  52042. currentChild (0),
  52043. activeSubMenu (0),
  52044. menuBarComponent (0),
  52045. managerOfChosenCommand (0),
  52046. componentAttachedTo (0),
  52047. attachedCompWatcher (0),
  52048. lastMouseX (0),
  52049. lastMouseY (0),
  52050. minimumWidth (0),
  52051. maximumNumColumns (7),
  52052. standardItemHeight (0),
  52053. isOver (false),
  52054. hasBeenOver (false),
  52055. isDown (false),
  52056. needsToScroll (false),
  52057. hideOnExit (false),
  52058. disableMouseMoves (false),
  52059. hasAnyJuceCompHadFocus (false),
  52060. numColumns (0),
  52061. contentHeight (0),
  52062. childYOffset (0),
  52063. timeEnteredCurrentChildComp (0),
  52064. scrollAcceleration (1.0)
  52065. {
  52066. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  52067. setWantsKeyboardFocus (true);
  52068. setMouseClickGrabsKeyboardFocus (false);
  52069. setOpaque (true);
  52070. setAlwaysOnTop (true);
  52071. Desktop::getInstance().addGlobalMouseListener (this);
  52072. activeMenuWindows.add (this);
  52073. }
  52074. ~PopupMenuWindow()
  52075. {
  52076. activeMenuWindows.removeValue (this);
  52077. Desktop::getInstance().removeGlobalMouseListener (this);
  52078. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52079. delete activeSubMenu;
  52080. deleteAllChildren();
  52081. delete attachedCompWatcher;
  52082. }
  52083. static PopupMenuWindow* create (const PopupMenu& menu,
  52084. const bool dismissOnMouseUp,
  52085. PopupMenuWindow* const owner_,
  52086. const int minX, const int maxX,
  52087. const int minY, const int maxY,
  52088. const int minimumWidth,
  52089. const int maximumNumColumns,
  52090. const int standardItemHeight,
  52091. const bool alignToRectangle,
  52092. const int itemIdThatMustBeVisible,
  52093. Component* const menuBarComponent,
  52094. ApplicationCommandManager** managerOfChosenCommand,
  52095. Component* const componentAttachedTo) throw()
  52096. {
  52097. if (menu.items.size() > 0)
  52098. {
  52099. int totalItems = 0;
  52100. PopupMenuWindow* const mw = new PopupMenuWindow();
  52101. mw->setLookAndFeel (menu.lookAndFeel);
  52102. mw->setWantsKeyboardFocus (false);
  52103. mw->minimumWidth = minimumWidth;
  52104. mw->maximumNumColumns = maximumNumColumns;
  52105. mw->standardItemHeight = standardItemHeight;
  52106. mw->dismissOnMouseUp = dismissOnMouseUp;
  52107. for (int i = 0; i < menu.items.size(); ++i)
  52108. {
  52109. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  52110. mw->addItem (*item);
  52111. ++totalItems;
  52112. }
  52113. if (totalItems == 0)
  52114. {
  52115. delete mw;
  52116. }
  52117. else
  52118. {
  52119. mw->owner = owner_;
  52120. mw->menuBarComponent = menuBarComponent;
  52121. mw->managerOfChosenCommand = managerOfChosenCommand;
  52122. mw->componentAttachedTo = componentAttachedTo;
  52123. delete mw->attachedCompWatcher;
  52124. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  52125. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  52126. mw->setTopLeftPosition (mw->windowPos.getX(),
  52127. mw->windowPos.getY());
  52128. mw->updateYPositions();
  52129. if (itemIdThatMustBeVisible != 0)
  52130. {
  52131. const int y = minY - mw->windowPos.getY();
  52132. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  52133. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  52134. }
  52135. mw->resizeToBestWindowPos();
  52136. mw->addToDesktop (ComponentPeer::windowIsTemporary
  52137. | mw->getLookAndFeel().getMenuWindowFlags());
  52138. return mw;
  52139. }
  52140. }
  52141. return 0;
  52142. }
  52143. void paint (Graphics& g)
  52144. {
  52145. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  52146. }
  52147. void paintOverChildren (Graphics& g)
  52148. {
  52149. if (isScrolling())
  52150. {
  52151. LookAndFeel& lf = getLookAndFeel();
  52152. if (isScrollZoneActive (false))
  52153. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  52154. if (isScrollZoneActive (true))
  52155. {
  52156. g.setOrigin (0, getHeight() - scrollZone);
  52157. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  52158. }
  52159. }
  52160. }
  52161. bool isScrollZoneActive (bool bottomOne) const
  52162. {
  52163. return isScrolling()
  52164. && (bottomOne
  52165. ? childYOffset < contentHeight - windowPos.getHeight()
  52166. : childYOffset > 0);
  52167. }
  52168. void addItem (const MenuItemInfo& item) throw()
  52169. {
  52170. MenuItemComponent* const mic = new MenuItemComponent (item);
  52171. addAndMakeVisible (mic);
  52172. int itemW = 80;
  52173. int itemH = 16;
  52174. mic->getIdealSize (itemW, itemH, standardItemHeight);
  52175. mic->setSize (itemW, jlimit (2, 600, itemH));
  52176. mic->addMouseListener (this, false);
  52177. }
  52178. // hide this and all sub-comps
  52179. void hide (const MenuItemInfo* const item) throw()
  52180. {
  52181. if (isVisible())
  52182. {
  52183. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52184. deleteAndZero (activeSubMenu);
  52185. currentChild = 0;
  52186. exitModalState (item != 0 ? item->itemId : 0);
  52187. setVisible (false);
  52188. if (item != 0
  52189. && item->commandManager != 0
  52190. && item->itemId != 0)
  52191. {
  52192. *managerOfChosenCommand = item->commandManager;
  52193. }
  52194. }
  52195. }
  52196. void dismissMenu (const MenuItemInfo* const item) throw()
  52197. {
  52198. if (owner != 0)
  52199. {
  52200. owner->dismissMenu (item);
  52201. }
  52202. else
  52203. {
  52204. if (item != 0)
  52205. {
  52206. // need a copy of this on the stack as the one passed in will get deleted during this call
  52207. const MenuItemInfo mi (*item);
  52208. hide (&mi);
  52209. }
  52210. else
  52211. {
  52212. hide (0);
  52213. }
  52214. }
  52215. }
  52216. void mouseMove (const MouseEvent&)
  52217. {
  52218. timerCallback();
  52219. }
  52220. void mouseDown (const MouseEvent&)
  52221. {
  52222. timerCallback();
  52223. }
  52224. void mouseDrag (const MouseEvent&)
  52225. {
  52226. timerCallback();
  52227. }
  52228. void mouseUp (const MouseEvent&)
  52229. {
  52230. timerCallback();
  52231. }
  52232. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  52233. {
  52234. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  52235. lastMouseX = -1;
  52236. }
  52237. bool keyPressed (const KeyPress& key)
  52238. {
  52239. if (key.isKeyCode (KeyPress::downKey))
  52240. {
  52241. selectNextItem (1);
  52242. }
  52243. else if (key.isKeyCode (KeyPress::upKey))
  52244. {
  52245. selectNextItem (-1);
  52246. }
  52247. else if (key.isKeyCode (KeyPress::leftKey))
  52248. {
  52249. PopupMenuWindow* parentWindow = owner;
  52250. if (parentWindow != 0)
  52251. {
  52252. MenuItemComponent* currentChildOfParent
  52253. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  52254. hide (0);
  52255. if (parentWindow->isValidComponent())
  52256. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  52257. disableTimerUntilMouseMoves();
  52258. }
  52259. else if (menuBarComponent != 0)
  52260. {
  52261. menuBarComponent->keyPressed (key);
  52262. }
  52263. }
  52264. else if (key.isKeyCode (KeyPress::rightKey))
  52265. {
  52266. disableTimerUntilMouseMoves();
  52267. if (showSubMenuFor (currentChild))
  52268. {
  52269. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52270. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  52271. activeSubMenu->selectNextItem (1);
  52272. }
  52273. else if (menuBarComponent != 0)
  52274. {
  52275. menuBarComponent->keyPressed (key);
  52276. }
  52277. }
  52278. else if (key.isKeyCode (KeyPress::returnKey))
  52279. {
  52280. triggerCurrentlyHighlightedItem();
  52281. }
  52282. else if (key.isKeyCode (KeyPress::escapeKey))
  52283. {
  52284. dismissMenu (0);
  52285. }
  52286. else
  52287. {
  52288. return false;
  52289. }
  52290. return true;
  52291. }
  52292. void inputAttemptWhenModal()
  52293. {
  52294. timerCallback();
  52295. if (! isOverAnyMenu())
  52296. {
  52297. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  52298. {
  52299. // we want to dismiss the menu, but if we do it synchronously, then
  52300. // the mouse-click will be allowed to pass through. That's good, except
  52301. // when the user clicks on the button that orginally popped the menu up,
  52302. // as they'll expect the menu to go away, and in fact it'll just
  52303. // come back. So only dismiss synchronously if they're not on the original
  52304. // comp that we're attached to.
  52305. int mx, my;
  52306. componentAttachedTo->getMouseXYRelative (mx, my);
  52307. if (componentAttachedTo->reallyContains (mx, my, true))
  52308. {
  52309. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  52310. return;
  52311. }
  52312. }
  52313. dismissMenu (0);
  52314. }
  52315. }
  52316. void handleCommandMessage (int commandId)
  52317. {
  52318. Component::handleCommandMessage (commandId);
  52319. if (commandId == dismissCommandId)
  52320. dismissMenu (0);
  52321. }
  52322. void timerCallback()
  52323. {
  52324. if (! isVisible())
  52325. return;
  52326. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  52327. {
  52328. dismissMenu (0);
  52329. return;
  52330. }
  52331. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  52332. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  52333. return;
  52334. startTimer (timerInterval); // do this in case it was called from a mouse
  52335. // move rather than a real timer callback
  52336. int mx, my;
  52337. Desktop::getMousePosition (mx, my);
  52338. int x = mx, y = my;
  52339. globalPositionToRelative (x, y);
  52340. const uint32 now = Time::getMillisecondCounter();
  52341. if (now > timeEnteredCurrentChildComp + 100
  52342. && reallyContains (x, y, true)
  52343. && currentChild->isValidComponent()
  52344. && (! disableMouseMoves)
  52345. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  52346. {
  52347. showSubMenuFor (currentChild);
  52348. }
  52349. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  52350. {
  52351. highlightItemUnderMouse (mx, my, x, y);
  52352. }
  52353. bool overScrollArea = false;
  52354. if (isScrolling()
  52355. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  52356. && ((isScrollZoneActive (false) && y < scrollZone)
  52357. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  52358. {
  52359. if (now > lastScroll + 20)
  52360. {
  52361. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  52362. int amount = 0;
  52363. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  52364. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  52365. alterChildYPos (y < scrollZone ? -amount : amount);
  52366. lastScroll = now;
  52367. }
  52368. overScrollArea = true;
  52369. lastMouseX = -1; // trigger a mouse-move
  52370. }
  52371. else
  52372. {
  52373. scrollAcceleration = 1.0;
  52374. }
  52375. const bool wasDown = isDown;
  52376. bool isOverAny = isOverAnyMenu();
  52377. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  52378. {
  52379. activeSubMenu->updateMouseOverStatus (mx, my);
  52380. isOverAny = isOverAnyMenu();
  52381. }
  52382. if (hideOnExit && hasBeenOver && ! isOverAny)
  52383. {
  52384. hide (0);
  52385. }
  52386. else
  52387. {
  52388. isDown = hasBeenOver
  52389. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  52390. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  52391. bool anyFocused = Process::isForegroundProcess();
  52392. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  52393. {
  52394. // because no component at all may have focus, our test here will
  52395. // only be triggered when something has focus and then loses it.
  52396. anyFocused = ! hasAnyJuceCompHadFocus;
  52397. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  52398. {
  52399. if (ComponentPeer::getPeer (i)->isFocused())
  52400. {
  52401. anyFocused = true;
  52402. hasAnyJuceCompHadFocus = true;
  52403. break;
  52404. }
  52405. }
  52406. }
  52407. if (! anyFocused)
  52408. {
  52409. if (now > lastFocused + 10)
  52410. {
  52411. wasHiddenBecauseOfAppChange = true;
  52412. dismissMenu (0);
  52413. return; // may have been deleted by the previous call..
  52414. }
  52415. }
  52416. else if (wasDown && now > menuCreationTime + 250
  52417. && ! (isDown || overScrollArea))
  52418. {
  52419. isOver = reallyContains (x, y, true);
  52420. if (isOver)
  52421. {
  52422. triggerCurrentlyHighlightedItem();
  52423. }
  52424. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  52425. {
  52426. dismissMenu (0);
  52427. }
  52428. return; // may have been deleted by the previous calls..
  52429. }
  52430. else
  52431. {
  52432. lastFocused = now;
  52433. }
  52434. }
  52435. }
  52436. juce_UseDebuggingNewOperator
  52437. private:
  52438. PopupMenuWindow* owner;
  52439. MenuItemComponent* currentChild;
  52440. PopupMenuWindow* activeSubMenu;
  52441. Component* menuBarComponent;
  52442. ApplicationCommandManager** managerOfChosenCommand;
  52443. Component* componentAttachedTo;
  52444. ComponentDeletionWatcher* attachedCompWatcher;
  52445. Rectangle windowPos;
  52446. int lastMouseX, lastMouseY;
  52447. int minimumWidth, maximumNumColumns, standardItemHeight;
  52448. bool isOver, hasBeenOver, isDown, needsToScroll;
  52449. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  52450. int numColumns, contentHeight, childYOffset;
  52451. Array <int> columnWidths;
  52452. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  52453. double scrollAcceleration;
  52454. bool overlaps (const Rectangle& r) const throw()
  52455. {
  52456. return r.intersects (getBounds())
  52457. || (owner != 0 && owner->overlaps (r));
  52458. }
  52459. bool isOverAnyMenu() const throw()
  52460. {
  52461. return (owner != 0) ? owner->isOverAnyMenu()
  52462. : isOverChildren();
  52463. }
  52464. bool isOverChildren() const throw()
  52465. {
  52466. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52467. return isVisible()
  52468. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  52469. }
  52470. void updateMouseOverStatus (const int mx, const int my) throw()
  52471. {
  52472. int rx = mx, ry = my;
  52473. globalPositionToRelative (rx, ry);
  52474. isOver = reallyContains (rx, ry, true);
  52475. if (activeSubMenu != 0)
  52476. activeSubMenu->updateMouseOverStatus (mx, my);
  52477. }
  52478. bool treeContains (const PopupMenuWindow* const window) const throw()
  52479. {
  52480. const PopupMenuWindow* mw = this;
  52481. while (mw->owner != 0)
  52482. mw = mw->owner;
  52483. while (mw != 0)
  52484. {
  52485. if (mw == window)
  52486. return true;
  52487. mw = mw->activeSubMenu;
  52488. }
  52489. return false;
  52490. }
  52491. void calculateWindowPos (const int minX, const int maxX,
  52492. const int minY, const int maxY,
  52493. const bool alignToRectangle)
  52494. {
  52495. const Rectangle mon (Desktop::getInstance()
  52496. .getMonitorAreaContaining ((minX + maxX) / 2,
  52497. (minY + maxY) / 2,
  52498. #if JUCE_MAC
  52499. true));
  52500. #else
  52501. false)); // on windows, don't stop the menu overlapping the taskbar
  52502. #endif
  52503. int x, y, widthToUse, heightToUse;
  52504. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  52505. if (alignToRectangle)
  52506. {
  52507. x = minX;
  52508. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  52509. const int spaceOver = minY - mon.getY();
  52510. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  52511. y = maxY;
  52512. else
  52513. y = minY - heightToUse;
  52514. }
  52515. else
  52516. {
  52517. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  52518. if (owner != 0)
  52519. {
  52520. if (owner->owner != 0)
  52521. {
  52522. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  52523. > owner->owner->getX() + owner->owner->getWidth() / 2);
  52524. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  52525. tendTowardsRight = true;
  52526. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  52527. tendTowardsRight = false;
  52528. }
  52529. else if (maxX + widthToUse < mon.getRight() - 32)
  52530. {
  52531. tendTowardsRight = true;
  52532. }
  52533. }
  52534. const int biggestSpace = jmax (mon.getRight() - maxX,
  52535. minX - mon.getX()) - 32;
  52536. if (biggestSpace < widthToUse)
  52537. {
  52538. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  52539. if (numColumns > 1)
  52540. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  52541. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  52542. }
  52543. if (tendTowardsRight)
  52544. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  52545. else
  52546. x = jmax (mon.getX() + 4, minX - widthToUse);
  52547. y = minY;
  52548. if ((minY + maxY) / 2 > mon.getCentreY())
  52549. y = jmax (mon.getY(), maxY - heightToUse);
  52550. }
  52551. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  52552. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  52553. windowPos.setBounds (x, y, widthToUse, heightToUse);
  52554. // sets this flag if it's big enough to obscure any of its parent menus
  52555. hideOnExit = (owner != 0)
  52556. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  52557. }
  52558. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  52559. {
  52560. numColumns = 0;
  52561. contentHeight = 0;
  52562. const int maxMenuH = getParentHeight() - 24;
  52563. int totalW;
  52564. do
  52565. {
  52566. ++numColumns;
  52567. totalW = workOutBestSize (numColumns, maxMenuW);
  52568. if (totalW > maxMenuW)
  52569. {
  52570. numColumns = jmax (1, numColumns - 1);
  52571. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  52572. break;
  52573. }
  52574. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  52575. {
  52576. break;
  52577. }
  52578. } while (numColumns < maximumNumColumns);
  52579. const int actualH = jmin (contentHeight, maxMenuH);
  52580. needsToScroll = contentHeight > actualH;
  52581. width = updateYPositions();
  52582. height = actualH + borderSize * 2;
  52583. }
  52584. int workOutBestSize (const int numColumns, const int maxMenuW)
  52585. {
  52586. int totalW = 0;
  52587. contentHeight = 0;
  52588. int childNum = 0;
  52589. for (int col = 0; col < numColumns; ++col)
  52590. {
  52591. int i, colW = 50, colH = 0;
  52592. const int numChildren = jmin (getNumChildComponents() - childNum,
  52593. (getNumChildComponents() + numColumns - 1) / numColumns);
  52594. for (i = numChildren; --i >= 0;)
  52595. {
  52596. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  52597. colH += getChildComponent (childNum + i)->getHeight();
  52598. }
  52599. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  52600. columnWidths.set (col, colW);
  52601. totalW += colW;
  52602. contentHeight = jmax (contentHeight, colH);
  52603. childNum += numChildren;
  52604. }
  52605. if (totalW < minimumWidth)
  52606. {
  52607. totalW = minimumWidth;
  52608. for (int col = 0; col < numColumns; ++col)
  52609. columnWidths.set (0, totalW / numColumns);
  52610. }
  52611. return totalW;
  52612. }
  52613. void ensureItemIsVisible (const int itemId, int wantedY)
  52614. {
  52615. jassert (itemId != 0)
  52616. for (int i = getNumChildComponents(); --i >= 0;)
  52617. {
  52618. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  52619. if (m != 0
  52620. && m->itemInfo.itemId == itemId
  52621. && windowPos.getHeight() > scrollZone * 4)
  52622. {
  52623. const int currentY = m->getY();
  52624. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  52625. {
  52626. if (wantedY < 0)
  52627. wantedY = jlimit (scrollZone,
  52628. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  52629. currentY);
  52630. const Rectangle mon (Desktop::getInstance()
  52631. .getMonitorAreaContaining (windowPos.getX(),
  52632. windowPos.getY(),
  52633. true));
  52634. int deltaY = wantedY - currentY;
  52635. const int newY = jlimit (mon.getY(),
  52636. mon.getBottom() - windowPos.getHeight(),
  52637. windowPos.getY() + deltaY);
  52638. deltaY -= newY - windowPos.getY();
  52639. childYOffset -= deltaY;
  52640. windowPos.setPosition (windowPos.getX(), newY);
  52641. updateYPositions();
  52642. }
  52643. break;
  52644. }
  52645. }
  52646. }
  52647. void resizeToBestWindowPos()
  52648. {
  52649. Rectangle r (windowPos);
  52650. if (childYOffset < 0)
  52651. {
  52652. r.setBounds (r.getX(), r.getY() - childYOffset,
  52653. r.getWidth(), r.getHeight() + childYOffset);
  52654. }
  52655. else if (childYOffset > 0)
  52656. {
  52657. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  52658. if (spaceAtBottom > 0)
  52659. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  52660. }
  52661. setBounds (r);
  52662. updateYPositions();
  52663. }
  52664. void alterChildYPos (const int delta)
  52665. {
  52666. if (isScrolling())
  52667. {
  52668. childYOffset += delta;
  52669. if (delta < 0)
  52670. {
  52671. childYOffset = jmax (childYOffset, 0);
  52672. }
  52673. else if (delta > 0)
  52674. {
  52675. childYOffset = jmin (childYOffset,
  52676. contentHeight - windowPos.getHeight() + borderSize);
  52677. }
  52678. updateYPositions();
  52679. }
  52680. else
  52681. {
  52682. childYOffset = 0;
  52683. }
  52684. resizeToBestWindowPos();
  52685. repaint();
  52686. }
  52687. int updateYPositions()
  52688. {
  52689. int x = 0;
  52690. int childNum = 0;
  52691. for (int col = 0; col < numColumns; ++col)
  52692. {
  52693. const int numChildren = jmin (getNumChildComponents() - childNum,
  52694. (getNumChildComponents() + numColumns - 1) / numColumns);
  52695. const int colW = columnWidths [col];
  52696. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  52697. for (int i = 0; i < numChildren; ++i)
  52698. {
  52699. Component* const c = getChildComponent (childNum + i);
  52700. c->setBounds (x, y, colW, c->getHeight());
  52701. y += c->getHeight();
  52702. }
  52703. x += colW;
  52704. childNum += numChildren;
  52705. }
  52706. return x;
  52707. }
  52708. bool isScrolling() const throw()
  52709. {
  52710. return childYOffset != 0 || needsToScroll;
  52711. }
  52712. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  52713. {
  52714. if (currentChild->isValidComponent())
  52715. currentChild->setHighlighted (false);
  52716. currentChild = child;
  52717. if (currentChild != 0)
  52718. {
  52719. currentChild->setHighlighted (true);
  52720. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  52721. }
  52722. }
  52723. bool showSubMenuFor (MenuItemComponent* const childComp)
  52724. {
  52725. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52726. deleteAndZero (activeSubMenu);
  52727. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  52728. {
  52729. int left = 0, top = 0;
  52730. childComp->relativePositionToGlobal (left, top);
  52731. int right = childComp->getWidth(), bottom = childComp->getHeight();
  52732. childComp->relativePositionToGlobal (right, bottom);
  52733. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  52734. dismissOnMouseUp,
  52735. this,
  52736. left, right, top, bottom,
  52737. 0, maximumNumColumns,
  52738. standardItemHeight,
  52739. false, 0, menuBarComponent,
  52740. managerOfChosenCommand,
  52741. componentAttachedTo);
  52742. if (activeSubMenu != 0)
  52743. {
  52744. activeSubMenu->setVisible (true);
  52745. activeSubMenu->enterModalState (false);
  52746. activeSubMenu->toFront (false);
  52747. return true;
  52748. }
  52749. }
  52750. return false;
  52751. }
  52752. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  52753. {
  52754. isOver = reallyContains (x, y, true);
  52755. if (isOver)
  52756. hasBeenOver = true;
  52757. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  52758. {
  52759. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  52760. if (disableMouseMoves && isOver)
  52761. disableMouseMoves = false;
  52762. }
  52763. if (disableMouseMoves)
  52764. return;
  52765. bool isMovingTowardsMenu = false;
  52766. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  52767. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  52768. {
  52769. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  52770. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  52771. // extends from the last mouse pos to the submenu's rectangle..
  52772. float subX = (float) activeSubMenu->getScreenX();
  52773. if (activeSubMenu->getX() > getX())
  52774. {
  52775. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  52776. }
  52777. else
  52778. {
  52779. lastMouseX += 2;
  52780. subX += activeSubMenu->getWidth();
  52781. }
  52782. Path areaTowardsSubMenu;
  52783. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  52784. (float) lastMouseY,
  52785. subX,
  52786. (float) activeSubMenu->getScreenY(),
  52787. subX,
  52788. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  52789. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  52790. }
  52791. lastMouseX = mx;
  52792. lastMouseY = my;
  52793. if (! isMovingTowardsMenu)
  52794. {
  52795. Component* c = getComponentAt (x, y);
  52796. if (c == this)
  52797. c = 0;
  52798. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  52799. if (mic == 0 && c != 0)
  52800. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  52801. if (mic != currentChild
  52802. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  52803. {
  52804. if (isOver && (c != 0) && (activeSubMenu != 0))
  52805. {
  52806. activeSubMenu->hide (0);
  52807. }
  52808. if (! isOver)
  52809. mic = 0;
  52810. setCurrentlyHighlightedChild (mic);
  52811. }
  52812. }
  52813. }
  52814. void triggerCurrentlyHighlightedItem()
  52815. {
  52816. if (currentChild->isValidComponent()
  52817. && currentChild->itemInfo.canBeTriggered()
  52818. && (currentChild->itemInfo.customComp == 0
  52819. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  52820. {
  52821. dismissMenu (&currentChild->itemInfo);
  52822. }
  52823. }
  52824. void selectNextItem (const int delta)
  52825. {
  52826. disableTimerUntilMouseMoves();
  52827. MenuItemComponent* mic = 0;
  52828. bool wasLastOne = (currentChild == 0);
  52829. const int numItems = getNumChildComponents();
  52830. for (int i = 0; i < numItems + 1; ++i)
  52831. {
  52832. int index = (delta > 0) ? i : (numItems - 1 - i);
  52833. index = (index + numItems) % numItems;
  52834. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  52835. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  52836. && wasLastOne)
  52837. break;
  52838. if (mic == currentChild)
  52839. wasLastOne = true;
  52840. }
  52841. setCurrentlyHighlightedChild (mic);
  52842. }
  52843. void disableTimerUntilMouseMoves() throw()
  52844. {
  52845. disableMouseMoves = true;
  52846. if (owner != 0)
  52847. owner->disableTimerUntilMouseMoves();
  52848. }
  52849. PopupMenuWindow (const PopupMenuWindow&);
  52850. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  52851. };
  52852. PopupMenu::PopupMenu() throw()
  52853. : items (8),
  52854. lookAndFeel (0),
  52855. separatorPending (false)
  52856. {
  52857. }
  52858. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  52859. : items (8),
  52860. lookAndFeel (other.lookAndFeel),
  52861. separatorPending (false)
  52862. {
  52863. items.ensureStorageAllocated (other.items.size());
  52864. for (int i = 0; i < other.items.size(); ++i)
  52865. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  52866. }
  52867. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  52868. {
  52869. if (this != &other)
  52870. {
  52871. lookAndFeel = other.lookAndFeel;
  52872. clear();
  52873. items.ensureStorageAllocated (other.items.size());
  52874. for (int i = 0; i < other.items.size(); ++i)
  52875. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  52876. }
  52877. return *this;
  52878. }
  52879. PopupMenu::~PopupMenu() throw()
  52880. {
  52881. clear();
  52882. }
  52883. void PopupMenu::clear() throw()
  52884. {
  52885. for (int i = items.size(); --i >= 0;)
  52886. {
  52887. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  52888. delete mi;
  52889. }
  52890. items.clear();
  52891. separatorPending = false;
  52892. }
  52893. void PopupMenu::addSeparatorIfPending()
  52894. {
  52895. if (separatorPending)
  52896. {
  52897. separatorPending = false;
  52898. if (items.size() > 0)
  52899. items.add (new MenuItemInfo());
  52900. }
  52901. }
  52902. void PopupMenu::addItem (const int itemResultId,
  52903. const String& itemText,
  52904. const bool isActive,
  52905. const bool isTicked,
  52906. const Image* const iconToUse) throw()
  52907. {
  52908. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52909. // didn't pick anything, so you shouldn't use it as the id
  52910. // for an item..
  52911. addSeparatorIfPending();
  52912. items.add (new MenuItemInfo (itemResultId,
  52913. itemText,
  52914. isActive,
  52915. isTicked,
  52916. iconToUse,
  52917. Colours::black,
  52918. false,
  52919. 0, 0, 0));
  52920. }
  52921. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  52922. const int commandID,
  52923. const String& displayName) throw()
  52924. {
  52925. jassert (commandManager != 0 && commandID != 0);
  52926. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  52927. if (registeredInfo != 0)
  52928. {
  52929. ApplicationCommandInfo info (*registeredInfo);
  52930. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  52931. addSeparatorIfPending();
  52932. items.add (new MenuItemInfo (commandID,
  52933. displayName.isNotEmpty() ? displayName
  52934. : info.shortName,
  52935. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  52936. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  52937. 0,
  52938. Colours::black,
  52939. false,
  52940. 0, 0,
  52941. commandManager));
  52942. }
  52943. }
  52944. void PopupMenu::addColouredItem (const int itemResultId,
  52945. const String& itemText,
  52946. const Colour& itemTextColour,
  52947. const bool isActive,
  52948. const bool isTicked,
  52949. const Image* const iconToUse) throw()
  52950. {
  52951. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52952. // didn't pick anything, so you shouldn't use it as the id
  52953. // for an item..
  52954. addSeparatorIfPending();
  52955. items.add (new MenuItemInfo (itemResultId,
  52956. itemText,
  52957. isActive,
  52958. isTicked,
  52959. iconToUse,
  52960. itemTextColour,
  52961. true,
  52962. 0, 0, 0));
  52963. }
  52964. void PopupMenu::addCustomItem (const int itemResultId,
  52965. PopupMenuCustomComponent* const customComponent) throw()
  52966. {
  52967. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52968. // didn't pick anything, so you shouldn't use it as the id
  52969. // for an item..
  52970. addSeparatorIfPending();
  52971. items.add (new MenuItemInfo (itemResultId,
  52972. String::empty,
  52973. true,
  52974. false,
  52975. 0,
  52976. Colours::black,
  52977. false,
  52978. customComponent,
  52979. 0, 0));
  52980. }
  52981. class NormalComponentWrapper : public PopupMenuCustomComponent
  52982. {
  52983. public:
  52984. NormalComponentWrapper (Component* const comp,
  52985. const int w, const int h,
  52986. const bool triggerMenuItemAutomaticallyWhenClicked)
  52987. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  52988. width (w),
  52989. height (h)
  52990. {
  52991. addAndMakeVisible (comp);
  52992. }
  52993. ~NormalComponentWrapper() {}
  52994. void getIdealSize (int& idealWidth, int& idealHeight)
  52995. {
  52996. idealWidth = width;
  52997. idealHeight = height;
  52998. }
  52999. void resized()
  53000. {
  53001. if (getChildComponent(0) != 0)
  53002. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  53003. }
  53004. juce_UseDebuggingNewOperator
  53005. private:
  53006. const int width, height;
  53007. NormalComponentWrapper (const NormalComponentWrapper&);
  53008. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  53009. };
  53010. void PopupMenu::addCustomItem (const int itemResultId,
  53011. Component* customComponent,
  53012. int idealWidth, int idealHeight,
  53013. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  53014. {
  53015. addCustomItem (itemResultId,
  53016. new NormalComponentWrapper (customComponent,
  53017. idealWidth, idealHeight,
  53018. triggerMenuItemAutomaticallyWhenClicked));
  53019. }
  53020. void PopupMenu::addSubMenu (const String& subMenuName,
  53021. const PopupMenu& subMenu,
  53022. const bool isActive,
  53023. Image* const iconToUse,
  53024. const bool isTicked) throw()
  53025. {
  53026. addSeparatorIfPending();
  53027. items.add (new MenuItemInfo (0,
  53028. subMenuName,
  53029. isActive && (subMenu.getNumItems() > 0),
  53030. isTicked,
  53031. iconToUse,
  53032. Colours::black,
  53033. false,
  53034. 0,
  53035. &subMenu,
  53036. 0));
  53037. }
  53038. void PopupMenu::addSeparator() throw()
  53039. {
  53040. separatorPending = true;
  53041. }
  53042. class HeaderItemComponent : public PopupMenuCustomComponent
  53043. {
  53044. public:
  53045. HeaderItemComponent (const String& name)
  53046. : PopupMenuCustomComponent (false)
  53047. {
  53048. setName (name);
  53049. }
  53050. ~HeaderItemComponent()
  53051. {
  53052. }
  53053. void paint (Graphics& g)
  53054. {
  53055. Font f (getLookAndFeel().getPopupMenuFont());
  53056. f.setBold (true);
  53057. g.setFont (f);
  53058. g.setColour (findColour (PopupMenu::headerTextColourId));
  53059. g.drawFittedText (getName(),
  53060. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  53061. Justification::bottomLeft, 1);
  53062. }
  53063. void getIdealSize (int& idealWidth,
  53064. int& idealHeight)
  53065. {
  53066. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  53067. idealHeight += idealHeight / 2;
  53068. idealWidth += idealWidth / 4;
  53069. }
  53070. juce_UseDebuggingNewOperator
  53071. };
  53072. void PopupMenu::addSectionHeader (const String& title) throw()
  53073. {
  53074. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  53075. }
  53076. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  53077. const int itemIdThatMustBeVisible,
  53078. const int minimumWidth,
  53079. const int maximumNumColumns,
  53080. const int standardItemHeight,
  53081. const bool alignToRectangle,
  53082. Component* menuBarComponent,
  53083. ApplicationCommandManager** managerOfChosenCommand,
  53084. Component* const componentAttachedTo) throw()
  53085. {
  53086. PopupMenuWindow* const pw
  53087. = PopupMenuWindow::create (*this,
  53088. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  53089. 0,
  53090. x, x + w,
  53091. y, y + h,
  53092. minimumWidth,
  53093. maximumNumColumns,
  53094. standardItemHeight,
  53095. alignToRectangle,
  53096. itemIdThatMustBeVisible,
  53097. menuBarComponent,
  53098. managerOfChosenCommand,
  53099. componentAttachedTo);
  53100. if (pw != 0)
  53101. pw->setVisible (true);
  53102. return pw;
  53103. }
  53104. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  53105. const int itemIdThatMustBeVisible,
  53106. const int minimumWidth,
  53107. const int maximumNumColumns,
  53108. const int standardItemHeight,
  53109. const bool alignToRectangle,
  53110. Component* const componentAttachedTo) throw()
  53111. {
  53112. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  53113. ComponentDeletionWatcher* deletionChecker1 = 0;
  53114. if (prevFocused != 0)
  53115. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  53116. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  53117. ComponentDeletionWatcher* deletionChecker2 = 0;
  53118. if (prevTopLevel != 0)
  53119. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  53120. wasHiddenBecauseOfAppChange = false;
  53121. int result = 0;
  53122. ApplicationCommandManager* managerOfChosenCommand = 0;
  53123. Component* const popupComp = createMenuComponent (x, y, w, h,
  53124. itemIdThatMustBeVisible,
  53125. minimumWidth,
  53126. maximumNumColumns > 0 ? maximumNumColumns : 7,
  53127. standardItemHeight,
  53128. alignToRectangle, 0,
  53129. &managerOfChosenCommand,
  53130. componentAttachedTo);
  53131. if (popupComp != 0)
  53132. {
  53133. popupComp->enterModalState (false);
  53134. popupComp->toFront (false); // need to do this after making it modal, or it could
  53135. // be stuck behind other comps that are already modal..
  53136. result = popupComp->runModalLoop();
  53137. delete popupComp;
  53138. if (! wasHiddenBecauseOfAppChange)
  53139. {
  53140. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  53141. prevTopLevel->toFront (true);
  53142. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  53143. prevFocused->grabKeyboardFocus();
  53144. }
  53145. }
  53146. delete deletionChecker1;
  53147. delete deletionChecker2;
  53148. if (managerOfChosenCommand != 0 && result != 0)
  53149. {
  53150. ApplicationCommandTarget::InvocationInfo info (result);
  53151. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  53152. managerOfChosenCommand->invoke (info, true);
  53153. }
  53154. return result;
  53155. }
  53156. int PopupMenu::show (const int itemIdThatMustBeVisible,
  53157. const int minimumWidth,
  53158. const int maximumNumColumns,
  53159. const int standardItemHeight)
  53160. {
  53161. int x, y;
  53162. Desktop::getMousePosition (x, y);
  53163. return showAt (x, y,
  53164. itemIdThatMustBeVisible,
  53165. minimumWidth,
  53166. maximumNumColumns,
  53167. standardItemHeight);
  53168. }
  53169. int PopupMenu::showAt (const int screenX,
  53170. const int screenY,
  53171. const int itemIdThatMustBeVisible,
  53172. const int minimumWidth,
  53173. const int maximumNumColumns,
  53174. const int standardItemHeight)
  53175. {
  53176. return showMenu (screenX, screenY, 1, 1,
  53177. itemIdThatMustBeVisible,
  53178. minimumWidth, maximumNumColumns,
  53179. standardItemHeight,
  53180. false, 0);
  53181. }
  53182. int PopupMenu::showAt (Component* componentToAttachTo,
  53183. const int itemIdThatMustBeVisible,
  53184. const int minimumWidth,
  53185. const int maximumNumColumns,
  53186. const int standardItemHeight)
  53187. {
  53188. if (componentToAttachTo != 0)
  53189. {
  53190. return showMenu (componentToAttachTo->getScreenX(),
  53191. componentToAttachTo->getScreenY(),
  53192. componentToAttachTo->getWidth(),
  53193. componentToAttachTo->getHeight(),
  53194. itemIdThatMustBeVisible,
  53195. minimumWidth,
  53196. maximumNumColumns,
  53197. standardItemHeight,
  53198. true, componentToAttachTo);
  53199. }
  53200. else
  53201. {
  53202. return show (itemIdThatMustBeVisible,
  53203. minimumWidth,
  53204. maximumNumColumns,
  53205. standardItemHeight);
  53206. }
  53207. }
  53208. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  53209. {
  53210. for (int i = activeMenuWindows.size(); --i >= 0;)
  53211. {
  53212. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  53213. if (pmw != 0)
  53214. pmw->dismissMenu (0);
  53215. }
  53216. }
  53217. int PopupMenu::getNumItems() const throw()
  53218. {
  53219. int num = 0;
  53220. for (int i = items.size(); --i >= 0;)
  53221. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  53222. ++num;
  53223. return num;
  53224. }
  53225. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  53226. {
  53227. for (int i = items.size(); --i >= 0;)
  53228. {
  53229. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  53230. if ((mi->itemId == commandID && mi->commandManager != 0)
  53231. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  53232. {
  53233. return true;
  53234. }
  53235. }
  53236. return false;
  53237. }
  53238. bool PopupMenu::containsAnyActiveItems() const throw()
  53239. {
  53240. for (int i = items.size(); --i >= 0;)
  53241. {
  53242. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  53243. if (mi->subMenu != 0)
  53244. {
  53245. if (mi->subMenu->containsAnyActiveItems())
  53246. return true;
  53247. }
  53248. else if (mi->active)
  53249. {
  53250. return true;
  53251. }
  53252. }
  53253. return false;
  53254. }
  53255. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  53256. {
  53257. lookAndFeel = newLookAndFeel;
  53258. }
  53259. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  53260. : refCount_ (0),
  53261. isHighlighted (false),
  53262. isTriggeredAutomatically (isTriggeredAutomatically_)
  53263. {
  53264. }
  53265. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  53266. {
  53267. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  53268. }
  53269. void PopupMenuCustomComponent::triggerMenuItem()
  53270. {
  53271. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  53272. if (mic != 0)
  53273. {
  53274. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  53275. if (pmw != 0)
  53276. {
  53277. pmw->dismissMenu (&mic->itemInfo);
  53278. }
  53279. else
  53280. {
  53281. // something must have gone wrong with the component hierarchy if this happens..
  53282. jassertfalse
  53283. }
  53284. }
  53285. else
  53286. {
  53287. // why isn't this component inside a menu? Not much point triggering the item if
  53288. // there's no menu.
  53289. jassertfalse
  53290. }
  53291. }
  53292. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  53293. : subMenu (0),
  53294. itemId (0),
  53295. isSeparator (false),
  53296. isTicked (false),
  53297. isEnabled (false),
  53298. isCustomComponent (false),
  53299. isSectionHeader (false),
  53300. customColour (0),
  53301. customImage (0),
  53302. menu (menu_),
  53303. index (0)
  53304. {
  53305. }
  53306. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  53307. {
  53308. }
  53309. bool PopupMenu::MenuItemIterator::next() throw()
  53310. {
  53311. if (index >= menu.items.size())
  53312. return false;
  53313. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  53314. ++index;
  53315. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  53316. subMenu = item->subMenu;
  53317. itemId = item->itemId;
  53318. isSeparator = item->isSeparator;
  53319. isTicked = item->isTicked;
  53320. isEnabled = item->active;
  53321. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  53322. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  53323. customColour = item->usesColour ? &(item->textColour) : 0;
  53324. customImage = item->image;
  53325. commandManager = item->commandManager;
  53326. return true;
  53327. }
  53328. END_JUCE_NAMESPACE
  53329. /********* End of inlined file: juce_PopupMenu.cpp *********/
  53330. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  53331. BEGIN_JUCE_NAMESPACE
  53332. ComponentDragger::ComponentDragger()
  53333. : constrainer (0),
  53334. originalX (0),
  53335. originalY (0)
  53336. {
  53337. }
  53338. ComponentDragger::~ComponentDragger()
  53339. {
  53340. }
  53341. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  53342. ComponentBoundsConstrainer* const constrainer_)
  53343. {
  53344. jassert (componentToDrag->isValidComponent());
  53345. if (componentToDrag->isValidComponent())
  53346. {
  53347. constrainer = constrainer_;
  53348. originalX = 0;
  53349. originalY = 0;
  53350. componentToDrag->relativePositionToGlobal (originalX, originalY);
  53351. }
  53352. }
  53353. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  53354. {
  53355. jassert (componentToDrag->isValidComponent());
  53356. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  53357. if (componentToDrag->isValidComponent())
  53358. {
  53359. int x = originalX;
  53360. int y = originalY;
  53361. int w = componentToDrag->getWidth();
  53362. int h = componentToDrag->getHeight();
  53363. const Component* const parentComp = componentToDrag->getParentComponent();
  53364. if (parentComp != 0)
  53365. parentComp->globalPositionToRelative (x, y);
  53366. x += e.getDistanceFromDragStartX();
  53367. y += e.getDistanceFromDragStartY();
  53368. if (constrainer != 0)
  53369. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  53370. false, false, false, false);
  53371. else
  53372. componentToDrag->setBounds (x, y, w, h);
  53373. }
  53374. }
  53375. END_JUCE_NAMESPACE
  53376. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  53377. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  53378. BEGIN_JUCE_NAMESPACE
  53379. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  53380. bool juce_performDragDropText (const String& text, bool& shouldStop);
  53381. class DragImageComponent : public Component,
  53382. public Timer
  53383. {
  53384. private:
  53385. Image* image;
  53386. Component* const source;
  53387. DragAndDropContainer* const owner;
  53388. ComponentDeletionWatcher* sourceWatcher;
  53389. Component* mouseDragSource;
  53390. ComponentDeletionWatcher* mouseDragSourceWatcher;
  53391. DragAndDropTarget* currentlyOver;
  53392. ComponentDeletionWatcher* currentlyOverWatcher;
  53393. String dragDesc;
  53394. int xOff, yOff;
  53395. bool hasCheckedForExternalDrag, drawImage;
  53396. DragImageComponent (const DragImageComponent&);
  53397. const DragImageComponent& operator= (const DragImageComponent&);
  53398. public:
  53399. DragImageComponent (Image* const im,
  53400. const String& desc,
  53401. Component* const s,
  53402. DragAndDropContainer* const o)
  53403. : image (im),
  53404. source (s),
  53405. owner (o),
  53406. currentlyOver (0),
  53407. currentlyOverWatcher (0),
  53408. dragDesc (desc),
  53409. hasCheckedForExternalDrag (false),
  53410. drawImage (true)
  53411. {
  53412. setSize (im->getWidth(), im->getHeight());
  53413. sourceWatcher = new ComponentDeletionWatcher (source);
  53414. mouseDragSource = Component::getComponentUnderMouse();
  53415. if (mouseDragSource == 0)
  53416. mouseDragSource = source;
  53417. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  53418. mouseDragSource->addMouseListener (this, false);
  53419. int mx, my;
  53420. Desktop::getLastMouseDownPosition (mx, my);
  53421. source->globalPositionToRelative (mx, my);
  53422. xOff = jlimit (0, im->getWidth(), mx);
  53423. yOff = jlimit (0, im->getHeight(), my);
  53424. startTimer (200);
  53425. setInterceptsMouseClicks (false, false);
  53426. setAlwaysOnTop (true);
  53427. }
  53428. ~DragImageComponent()
  53429. {
  53430. if (owner->dragImageComponent == this)
  53431. owner->dragImageComponent = 0;
  53432. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53433. {
  53434. mouseDragSource->removeMouseListener (this);
  53435. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53436. if (currentlyOver->isInterestedInDragSource (dragDesc, source))
  53437. currentlyOver->itemDragExit (dragDesc, source);
  53438. }
  53439. delete mouseDragSourceWatcher;
  53440. delete sourceWatcher;
  53441. delete image;
  53442. delete currentlyOverWatcher;
  53443. }
  53444. void paint (Graphics& g)
  53445. {
  53446. if (isOpaque())
  53447. g.fillAll (Colours::white);
  53448. if (drawImage)
  53449. {
  53450. g.setOpacity (1.0f);
  53451. g.drawImageAt (image, 0, 0);
  53452. }
  53453. }
  53454. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  53455. int& relX, int& relY) const throw()
  53456. {
  53457. Component* hit = getParentComponent();
  53458. if (hit == 0)
  53459. {
  53460. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  53461. }
  53462. else
  53463. {
  53464. int rx = screenX, ry = screenY;
  53465. hit->globalPositionToRelative (rx, ry);
  53466. hit = hit->getComponentAt (rx, ry);
  53467. }
  53468. // (note: use a local copy of the dragDesc member in case the callback runs
  53469. // a modal loop and deletes this object before the method completes)
  53470. const String dragDescLocal (dragDesc);
  53471. while (hit != 0)
  53472. {
  53473. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  53474. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  53475. {
  53476. relX = screenX;
  53477. relY = screenY;
  53478. hit->globalPositionToRelative (relX, relY);
  53479. return ddt;
  53480. }
  53481. hit = hit->getParentComponent();
  53482. }
  53483. return 0;
  53484. }
  53485. void mouseUp (const MouseEvent& e)
  53486. {
  53487. if (e.originalComponent != this)
  53488. {
  53489. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53490. mouseDragSource->removeMouseListener (this);
  53491. bool dropAccepted = false;
  53492. DragAndDropTarget* ddt = 0;
  53493. int relX = 0, relY = 0;
  53494. if (isVisible())
  53495. {
  53496. setVisible (false);
  53497. ddt = findTarget (e.getScreenX(),
  53498. e.getScreenY(),
  53499. relX, relY);
  53500. // fade this component and remove it - it'll be deleted later by the timer callback
  53501. dropAccepted = ddt != 0;
  53502. setVisible (true);
  53503. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  53504. {
  53505. fadeOutComponent (120);
  53506. }
  53507. else
  53508. {
  53509. int targetX = source->getWidth() / 2;
  53510. int targetY = source->getHeight() / 2;
  53511. source->relativePositionToGlobal (targetX, targetY);
  53512. int ourCentreX = getWidth() / 2;
  53513. int ourCentreY = getHeight() / 2;
  53514. relativePositionToGlobal (ourCentreX, ourCentreY);
  53515. fadeOutComponent (120,
  53516. targetX - ourCentreX,
  53517. targetY - ourCentreY);
  53518. }
  53519. }
  53520. if (getParentComponent() != 0)
  53521. getParentComponent()->removeChildComponent (this);
  53522. if (dropAccepted && ddt != 0)
  53523. {
  53524. // (note: use a local copy of the dragDesc member in case the callback runs
  53525. // a modal loop and deletes this object before the method completes)
  53526. const String dragDescLocal (dragDesc);
  53527. currentlyOver = 0;
  53528. deleteAndZero (currentlyOverWatcher);
  53529. ddt->itemDropped (dragDescLocal, source, relX, relY);
  53530. }
  53531. // careful - this object could now be deleted..
  53532. }
  53533. }
  53534. void updateLocation (const bool canDoExternalDrag, int x, int y)
  53535. {
  53536. // (note: use a local copy of the dragDesc member in case the callback runs
  53537. // a modal loop and deletes this object before it returns)
  53538. const String dragDescLocal (dragDesc);
  53539. int newX = x - xOff;
  53540. int newY = y - yOff;
  53541. if (getParentComponent() != 0)
  53542. getParentComponent()->globalPositionToRelative (newX, newY);
  53543. if (newX != getX() || newY != getY())
  53544. {
  53545. setTopLeftPosition (newX, newY);
  53546. int relX = 0, relY = 0;
  53547. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  53548. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  53549. if (ddt != currentlyOver)
  53550. {
  53551. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53552. {
  53553. Component* const over = dynamic_cast <Component*> (currentlyOver);
  53554. if (over != 0
  53555. && over->isValidComponent()
  53556. && ! (sourceWatcher->hasBeenDeleted())
  53557. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53558. {
  53559. currentlyOver->itemDragExit (dragDescLocal, source);
  53560. }
  53561. }
  53562. currentlyOver = ddt;
  53563. deleteAndZero (currentlyOverWatcher);
  53564. if (ddt != 0)
  53565. {
  53566. currentlyOverWatcher = new ComponentDeletionWatcher (dynamic_cast <Component*> (ddt));
  53567. if (currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53568. currentlyOver->itemDragEnter (dragDescLocal, source, relX, relY);
  53569. }
  53570. }
  53571. else if (currentlyOverWatcher != 0 && currentlyOverWatcher->hasBeenDeleted())
  53572. {
  53573. currentlyOver = 0;
  53574. deleteAndZero (currentlyOverWatcher);
  53575. }
  53576. if (currentlyOver != 0
  53577. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53578. currentlyOver->itemDragMove (dragDescLocal, source, relX, relY);
  53579. if (currentlyOver == 0
  53580. && canDoExternalDrag
  53581. && ! hasCheckedForExternalDrag)
  53582. {
  53583. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  53584. {
  53585. hasCheckedForExternalDrag = true;
  53586. StringArray files;
  53587. bool canMoveFiles = false;
  53588. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  53589. && files.size() > 0)
  53590. {
  53591. ComponentDeletionWatcher cdw (this);
  53592. setVisible (false);
  53593. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  53594. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  53595. if (! cdw.hasBeenDeleted())
  53596. delete this;
  53597. return;
  53598. }
  53599. }
  53600. }
  53601. }
  53602. }
  53603. void mouseDrag (const MouseEvent& e)
  53604. {
  53605. if (e.originalComponent != this)
  53606. updateLocation (true, e.getScreenX(), e.getScreenY());
  53607. }
  53608. void timerCallback()
  53609. {
  53610. if (sourceWatcher->hasBeenDeleted())
  53611. {
  53612. delete this;
  53613. }
  53614. else if (! isMouseButtonDownAnywhere())
  53615. {
  53616. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53617. mouseDragSource->removeMouseListener (this);
  53618. delete this;
  53619. }
  53620. }
  53621. };
  53622. DragAndDropContainer::DragAndDropContainer()
  53623. : dragImageComponent (0)
  53624. {
  53625. }
  53626. DragAndDropContainer::~DragAndDropContainer()
  53627. {
  53628. if (dragImageComponent != 0)
  53629. delete dragImageComponent;
  53630. }
  53631. void DragAndDropContainer::startDragging (const String& sourceDescription,
  53632. Component* sourceComponent,
  53633. Image* im,
  53634. const bool allowDraggingToExternalWindows)
  53635. {
  53636. if (dragImageComponent != 0)
  53637. {
  53638. if (im != 0)
  53639. delete im;
  53640. }
  53641. else
  53642. {
  53643. Component* const thisComp = dynamic_cast <Component*> (this);
  53644. if (thisComp != 0)
  53645. {
  53646. int mx, my;
  53647. Desktop::getLastMouseDownPosition (mx, my);
  53648. if (im == 0)
  53649. {
  53650. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  53651. if (im->getFormat() != Image::ARGB)
  53652. {
  53653. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  53654. Graphics g2 (*newIm);
  53655. g2.drawImageAt (im, 0, 0);
  53656. delete im;
  53657. im = newIm;
  53658. }
  53659. im->multiplyAllAlphas (0.6f);
  53660. const int lo = 150;
  53661. const int hi = 400;
  53662. int rx = mx, ry = my;
  53663. sourceComponent->globalPositionToRelative (rx, ry);
  53664. const int cx = jlimit (0, im->getWidth(), rx);
  53665. const int cy = jlimit (0, im->getHeight(), ry);
  53666. for (int y = im->getHeight(); --y >= 0;)
  53667. {
  53668. const double dy = (y - cy) * (y - cy);
  53669. for (int x = im->getWidth(); --x >= 0;)
  53670. {
  53671. const int dx = x - cx;
  53672. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  53673. if (distance > lo)
  53674. {
  53675. const float alpha = (distance > hi) ? 0
  53676. : (hi - distance) / (float) (hi - lo)
  53677. + Random::getSystemRandom().nextFloat() * 0.008f;
  53678. im->multiplyAlphaAt (x, y, alpha);
  53679. }
  53680. }
  53681. }
  53682. }
  53683. DragImageComponent* const dic
  53684. = new DragImageComponent (im,
  53685. sourceDescription,
  53686. sourceComponent,
  53687. this);
  53688. dragImageComponent = dic;
  53689. currentDragDesc = sourceDescription;
  53690. if (allowDraggingToExternalWindows)
  53691. {
  53692. if (! Desktop::canUseSemiTransparentWindows())
  53693. dic->setOpaque (true);
  53694. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53695. | ComponentPeer::windowIsTemporary);
  53696. }
  53697. else
  53698. thisComp->addChildComponent (dic);
  53699. dic->updateLocation (false, mx, my);
  53700. dic->setVisible (true);
  53701. }
  53702. else
  53703. {
  53704. // this class must only be implemented by an object that
  53705. // is also a Component.
  53706. jassertfalse
  53707. if (im != 0)
  53708. delete im;
  53709. }
  53710. }
  53711. }
  53712. bool DragAndDropContainer::isDragAndDropActive() const
  53713. {
  53714. return dragImageComponent != 0;
  53715. }
  53716. const String DragAndDropContainer::getCurrentDragDescription() const
  53717. {
  53718. return (dragImageComponent != 0) ? currentDragDesc
  53719. : String::empty;
  53720. }
  53721. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  53722. {
  53723. if (c == 0)
  53724. return 0;
  53725. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  53726. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  53727. }
  53728. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  53729. {
  53730. return false;
  53731. }
  53732. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  53733. {
  53734. }
  53735. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  53736. {
  53737. }
  53738. void DragAndDropTarget::itemDragExit (const String&, Component*)
  53739. {
  53740. }
  53741. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  53742. {
  53743. return true;
  53744. }
  53745. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  53746. {
  53747. }
  53748. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  53749. {
  53750. }
  53751. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  53752. {
  53753. }
  53754. END_JUCE_NAMESPACE
  53755. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  53756. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  53757. BEGIN_JUCE_NAMESPACE
  53758. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  53759. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  53760. // isStandard set depending on which interface was used to create the cursor
  53761. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  53762. static CriticalSection mouseCursorLock;
  53763. static VoidArray standardCursors (2);
  53764. class RefCountedMouseCursor
  53765. {
  53766. public:
  53767. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  53768. : refCount (1),
  53769. standardType (t),
  53770. isStandard (true)
  53771. {
  53772. handle = juce_createStandardMouseCursor (standardType);
  53773. standardCursors.add (this);
  53774. }
  53775. RefCountedMouseCursor (Image& image,
  53776. const int hotSpotX,
  53777. const int hotSpotY) throw()
  53778. : refCount (1),
  53779. standardType (MouseCursor::NormalCursor),
  53780. isStandard (false)
  53781. {
  53782. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  53783. }
  53784. ~RefCountedMouseCursor() throw()
  53785. {
  53786. juce_deleteMouseCursor (handle, isStandard);
  53787. standardCursors.removeValue (this);
  53788. }
  53789. void decRef() throw()
  53790. {
  53791. if (--refCount == 0)
  53792. delete this;
  53793. }
  53794. void incRef() throw()
  53795. {
  53796. ++refCount;
  53797. }
  53798. void* getHandle() const throw()
  53799. {
  53800. return handle;
  53801. }
  53802. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  53803. {
  53804. const ScopedLock sl (mouseCursorLock);
  53805. for (int i = 0; i < standardCursors.size(); i++)
  53806. {
  53807. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  53808. if (r->standardType == type)
  53809. {
  53810. r->incRef();
  53811. return r;
  53812. }
  53813. }
  53814. return new RefCountedMouseCursor (type);
  53815. }
  53816. juce_UseDebuggingNewOperator
  53817. private:
  53818. void* handle;
  53819. int refCount;
  53820. const MouseCursor::StandardCursorType standardType;
  53821. const bool isStandard;
  53822. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  53823. };
  53824. MouseCursor::MouseCursor() throw()
  53825. {
  53826. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  53827. }
  53828. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  53829. {
  53830. cursorHandle = RefCountedMouseCursor::findInstance (type);
  53831. }
  53832. MouseCursor::MouseCursor (Image& image,
  53833. const int hotSpotX,
  53834. const int hotSpotY) throw()
  53835. {
  53836. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  53837. }
  53838. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  53839. : cursorHandle (other.cursorHandle)
  53840. {
  53841. const ScopedLock sl (mouseCursorLock);
  53842. cursorHandle->incRef();
  53843. }
  53844. MouseCursor::~MouseCursor() throw()
  53845. {
  53846. const ScopedLock sl (mouseCursorLock);
  53847. cursorHandle->decRef();
  53848. }
  53849. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  53850. {
  53851. if (this != &other)
  53852. {
  53853. const ScopedLock sl (mouseCursorLock);
  53854. cursorHandle->decRef();
  53855. cursorHandle = other.cursorHandle;
  53856. cursorHandle->incRef();
  53857. }
  53858. return *this;
  53859. }
  53860. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  53861. {
  53862. return cursorHandle == other.cursorHandle;
  53863. }
  53864. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  53865. {
  53866. return cursorHandle != other.cursorHandle;
  53867. }
  53868. void* MouseCursor::getHandle() const throw()
  53869. {
  53870. return cursorHandle->getHandle();
  53871. }
  53872. void MouseCursor::showWaitCursor() throw()
  53873. {
  53874. const MouseCursor mc (MouseCursor::WaitCursor);
  53875. mc.showInAllWindows();
  53876. }
  53877. void MouseCursor::hideWaitCursor() throw()
  53878. {
  53879. if (Component::getComponentUnderMouse()->isValidComponent())
  53880. {
  53881. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  53882. }
  53883. else
  53884. {
  53885. const MouseCursor mc (MouseCursor::NormalCursor);
  53886. mc.showInAllWindows();
  53887. }
  53888. }
  53889. END_JUCE_NAMESPACE
  53890. /********* End of inlined file: juce_MouseCursor.cpp *********/
  53891. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  53892. BEGIN_JUCE_NAMESPACE
  53893. MouseEvent::MouseEvent (const int x_,
  53894. const int y_,
  53895. const ModifierKeys& mods_,
  53896. Component* const originator,
  53897. const Time& eventTime_,
  53898. const int mouseDownX_,
  53899. const int mouseDownY_,
  53900. const Time& mouseDownTime_,
  53901. const int numberOfClicks_,
  53902. const bool mouseWasDragged) throw()
  53903. : x (x_),
  53904. y (y_),
  53905. mods (mods_),
  53906. eventComponent (originator),
  53907. originalComponent (originator),
  53908. eventTime (eventTime_),
  53909. mouseDownX (mouseDownX_),
  53910. mouseDownY (mouseDownY_),
  53911. mouseDownTime (mouseDownTime_),
  53912. numberOfClicks (numberOfClicks_),
  53913. wasMovedSinceMouseDown (mouseWasDragged)
  53914. {
  53915. }
  53916. MouseEvent::~MouseEvent() throw()
  53917. {
  53918. }
  53919. bool MouseEvent::mouseWasClicked() const throw()
  53920. {
  53921. return ! wasMovedSinceMouseDown;
  53922. }
  53923. int MouseEvent::getMouseDownX() const throw()
  53924. {
  53925. return mouseDownX;
  53926. }
  53927. int MouseEvent::getMouseDownY() const throw()
  53928. {
  53929. return mouseDownY;
  53930. }
  53931. int MouseEvent::getDistanceFromDragStartX() const throw()
  53932. {
  53933. return x - mouseDownX;
  53934. }
  53935. int MouseEvent::getDistanceFromDragStartY() const throw()
  53936. {
  53937. return y - mouseDownY;
  53938. }
  53939. int MouseEvent::getDistanceFromDragStart() const throw()
  53940. {
  53941. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  53942. getDistanceFromDragStartY()));
  53943. }
  53944. int MouseEvent::getLengthOfMousePress() const throw()
  53945. {
  53946. if (mouseDownTime.toMilliseconds() > 0)
  53947. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  53948. return 0;
  53949. }
  53950. int MouseEvent::getScreenX() const throw()
  53951. {
  53952. int sx = x, sy = y;
  53953. eventComponent->relativePositionToGlobal (sx, sy);
  53954. return sx;
  53955. }
  53956. int MouseEvent::getScreenY() const throw()
  53957. {
  53958. int sx = x, sy = y;
  53959. eventComponent->relativePositionToGlobal (sx, sy);
  53960. return sy;
  53961. }
  53962. int MouseEvent::getMouseDownScreenX() const throw()
  53963. {
  53964. int sx = mouseDownX, sy = mouseDownY;
  53965. eventComponent->relativePositionToGlobal (sx, sy);
  53966. return sx;
  53967. }
  53968. int MouseEvent::getMouseDownScreenY() const throw()
  53969. {
  53970. int sx = mouseDownX, sy = mouseDownY;
  53971. eventComponent->relativePositionToGlobal (sx, sy);
  53972. return sy;
  53973. }
  53974. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  53975. {
  53976. if (otherComponent == 0)
  53977. {
  53978. jassertfalse
  53979. return *this;
  53980. }
  53981. MouseEvent me (*this);
  53982. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  53983. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  53984. me.eventComponent = otherComponent;
  53985. return me;
  53986. }
  53987. static int doubleClickTimeOutMs = 400;
  53988. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  53989. {
  53990. doubleClickTimeOutMs = newTime;
  53991. }
  53992. int MouseEvent::getDoubleClickTimeout() throw()
  53993. {
  53994. return doubleClickTimeOutMs;
  53995. }
  53996. END_JUCE_NAMESPACE
  53997. /********* End of inlined file: juce_MouseEvent.cpp *********/
  53998. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  53999. BEGIN_JUCE_NAMESPACE
  54000. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  54001. : source (0),
  54002. hoverTimeMillisecs (hoverTimeMillisecs_),
  54003. hasJustHovered (false)
  54004. {
  54005. internalTimer.owner = this;
  54006. }
  54007. MouseHoverDetector::~MouseHoverDetector()
  54008. {
  54009. setHoverComponent (0);
  54010. }
  54011. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  54012. {
  54013. hoverTimeMillisecs = newTimeInMillisecs;
  54014. }
  54015. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  54016. {
  54017. if (source != newSourceComponent)
  54018. {
  54019. internalTimer.stopTimer();
  54020. hasJustHovered = false;
  54021. if (source != 0)
  54022. {
  54023. // ! you need to delete the hover detector before deleting its component
  54024. jassert (source->isValidComponent());
  54025. source->removeMouseListener (&internalTimer);
  54026. }
  54027. source = newSourceComponent;
  54028. if (newSourceComponent != 0)
  54029. newSourceComponent->addMouseListener (&internalTimer, false);
  54030. }
  54031. }
  54032. void MouseHoverDetector::hoverTimerCallback()
  54033. {
  54034. internalTimer.stopTimer();
  54035. if (source != 0)
  54036. {
  54037. int mx, my;
  54038. source->getMouseXYRelative (mx, my);
  54039. if (source->reallyContains (mx, my, false))
  54040. {
  54041. hasJustHovered = true;
  54042. mouseHovered (mx, my);
  54043. }
  54044. }
  54045. }
  54046. void MouseHoverDetector::checkJustHoveredCallback()
  54047. {
  54048. if (hasJustHovered)
  54049. {
  54050. hasJustHovered = false;
  54051. mouseMovedAfterHover();
  54052. }
  54053. }
  54054. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  54055. {
  54056. owner->hoverTimerCallback();
  54057. }
  54058. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  54059. {
  54060. stopTimer();
  54061. owner->checkJustHoveredCallback();
  54062. }
  54063. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  54064. {
  54065. stopTimer();
  54066. owner->checkJustHoveredCallback();
  54067. }
  54068. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  54069. {
  54070. stopTimer();
  54071. owner->checkJustHoveredCallback();
  54072. }
  54073. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  54074. {
  54075. stopTimer();
  54076. owner->checkJustHoveredCallback();
  54077. }
  54078. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  54079. {
  54080. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  54081. {
  54082. lastX = e.x;
  54083. lastY = e.y;
  54084. if (owner->source != 0)
  54085. startTimer (owner->hoverTimeMillisecs);
  54086. owner->checkJustHoveredCallback();
  54087. }
  54088. }
  54089. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  54090. {
  54091. stopTimer();
  54092. owner->checkJustHoveredCallback();
  54093. }
  54094. END_JUCE_NAMESPACE
  54095. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  54096. /********* Start of inlined file: juce_MouseListener.cpp *********/
  54097. BEGIN_JUCE_NAMESPACE
  54098. void MouseListener::mouseEnter (const MouseEvent&)
  54099. {
  54100. }
  54101. void MouseListener::mouseExit (const MouseEvent&)
  54102. {
  54103. }
  54104. void MouseListener::mouseDown (const MouseEvent&)
  54105. {
  54106. }
  54107. void MouseListener::mouseUp (const MouseEvent&)
  54108. {
  54109. }
  54110. void MouseListener::mouseDrag (const MouseEvent&)
  54111. {
  54112. }
  54113. void MouseListener::mouseMove (const MouseEvent&)
  54114. {
  54115. }
  54116. void MouseListener::mouseDoubleClick (const MouseEvent&)
  54117. {
  54118. }
  54119. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  54120. {
  54121. }
  54122. END_JUCE_NAMESPACE
  54123. /********* End of inlined file: juce_MouseListener.cpp *********/
  54124. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54125. BEGIN_JUCE_NAMESPACE
  54126. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  54127. const String& buttonTextWhenTrue,
  54128. const String& buttonTextWhenFalse)
  54129. : PropertyComponent (name),
  54130. onText (buttonTextWhenTrue),
  54131. offText (buttonTextWhenFalse)
  54132. {
  54133. addAndMakeVisible (button = new ToggleButton (String::empty));
  54134. button->setClickingTogglesState (false);
  54135. button->addButtonListener (this);
  54136. }
  54137. BooleanPropertyComponent::~BooleanPropertyComponent()
  54138. {
  54139. deleteAllChildren();
  54140. }
  54141. void BooleanPropertyComponent::paint (Graphics& g)
  54142. {
  54143. PropertyComponent::paint (g);
  54144. const Rectangle r (button->getBounds());
  54145. g.setColour (Colours::white);
  54146. g.fillRect (r);
  54147. g.setColour (findColour (ComboBox::outlineColourId));
  54148. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  54149. }
  54150. void BooleanPropertyComponent::refresh()
  54151. {
  54152. button->setToggleState (getState(), false);
  54153. button->setButtonText (button->getToggleState() ? onText : offText);
  54154. }
  54155. void BooleanPropertyComponent::buttonClicked (Button*)
  54156. {
  54157. setState (! getState());
  54158. }
  54159. END_JUCE_NAMESPACE
  54160. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54161. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54162. BEGIN_JUCE_NAMESPACE
  54163. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  54164. const bool triggerOnMouseDown)
  54165. : PropertyComponent (name)
  54166. {
  54167. addAndMakeVisible (button = new TextButton (String::empty));
  54168. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  54169. button->addButtonListener (this);
  54170. }
  54171. ButtonPropertyComponent::~ButtonPropertyComponent()
  54172. {
  54173. deleteAllChildren();
  54174. }
  54175. void ButtonPropertyComponent::refresh()
  54176. {
  54177. button->setButtonText (getButtonText());
  54178. }
  54179. void ButtonPropertyComponent::buttonClicked (Button*)
  54180. {
  54181. buttonClicked();
  54182. }
  54183. END_JUCE_NAMESPACE
  54184. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54185. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54186. BEGIN_JUCE_NAMESPACE
  54187. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  54188. : PropertyComponent (name),
  54189. comboBox (0)
  54190. {
  54191. }
  54192. ChoicePropertyComponent::~ChoicePropertyComponent()
  54193. {
  54194. deleteAllChildren();
  54195. }
  54196. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  54197. {
  54198. return choices;
  54199. }
  54200. void ChoicePropertyComponent::refresh()
  54201. {
  54202. if (comboBox == 0)
  54203. {
  54204. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  54205. for (int i = 0; i < choices.size(); ++i)
  54206. {
  54207. if (choices[i].isNotEmpty())
  54208. comboBox->addItem (choices[i], i + 1);
  54209. else
  54210. comboBox->addSeparator();
  54211. }
  54212. comboBox->setEditableText (false);
  54213. comboBox->addListener (this);
  54214. }
  54215. comboBox->setSelectedId (getIndex() + 1, true);
  54216. }
  54217. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  54218. {
  54219. const int newIndex = comboBox->getSelectedId() - 1;
  54220. if (newIndex != getIndex())
  54221. setIndex (newIndex);
  54222. }
  54223. END_JUCE_NAMESPACE
  54224. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54225. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  54226. BEGIN_JUCE_NAMESPACE
  54227. PropertyComponent::PropertyComponent (const String& name,
  54228. const int preferredHeight_)
  54229. : Component (name),
  54230. preferredHeight (preferredHeight_)
  54231. {
  54232. jassert (name.isNotEmpty());
  54233. }
  54234. PropertyComponent::~PropertyComponent()
  54235. {
  54236. }
  54237. void PropertyComponent::paint (Graphics& g)
  54238. {
  54239. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  54240. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  54241. }
  54242. void PropertyComponent::resized()
  54243. {
  54244. if (getNumChildComponents() > 0)
  54245. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  54246. }
  54247. void PropertyComponent::enablementChanged()
  54248. {
  54249. repaint();
  54250. }
  54251. END_JUCE_NAMESPACE
  54252. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  54253. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  54254. BEGIN_JUCE_NAMESPACE
  54255. class PropertyHolderComponent : public Component
  54256. {
  54257. public:
  54258. PropertyHolderComponent()
  54259. {
  54260. }
  54261. ~PropertyHolderComponent()
  54262. {
  54263. deleteAllChildren();
  54264. }
  54265. void paint (Graphics&)
  54266. {
  54267. }
  54268. void updateLayout (const int width);
  54269. void refreshAll() const;
  54270. };
  54271. class PropertySectionComponent : public Component
  54272. {
  54273. public:
  54274. PropertySectionComponent (const String& sectionTitle,
  54275. const Array <PropertyComponent*>& newProperties,
  54276. const bool open)
  54277. : Component (sectionTitle),
  54278. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  54279. isOpen_ (open)
  54280. {
  54281. for (int i = newProperties.size(); --i >= 0;)
  54282. {
  54283. addAndMakeVisible (newProperties.getUnchecked(i));
  54284. newProperties.getUnchecked(i)->refresh();
  54285. }
  54286. }
  54287. ~PropertySectionComponent()
  54288. {
  54289. deleteAllChildren();
  54290. }
  54291. void paint (Graphics& g)
  54292. {
  54293. if (titleHeight > 0)
  54294. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  54295. }
  54296. void resized()
  54297. {
  54298. int y = titleHeight;
  54299. for (int i = getNumChildComponents(); --i >= 0;)
  54300. {
  54301. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54302. if (pec != 0)
  54303. {
  54304. const int prefH = pec->getPreferredHeight();
  54305. pec->setBounds (1, y, getWidth() - 2, prefH);
  54306. y += prefH;
  54307. }
  54308. }
  54309. }
  54310. int getPreferredHeight() const
  54311. {
  54312. int y = titleHeight;
  54313. if (isOpen())
  54314. {
  54315. for (int i = 0; i < getNumChildComponents(); ++i)
  54316. {
  54317. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54318. if (pec != 0)
  54319. y += pec->getPreferredHeight();
  54320. }
  54321. }
  54322. return y;
  54323. }
  54324. void setOpen (const bool open)
  54325. {
  54326. if (isOpen_ != open)
  54327. {
  54328. isOpen_ = open;
  54329. for (int i = 0; i < getNumChildComponents(); ++i)
  54330. {
  54331. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54332. if (pec != 0)
  54333. pec->setVisible (open);
  54334. }
  54335. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  54336. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  54337. if (pp != 0)
  54338. pp->resized();
  54339. }
  54340. }
  54341. bool isOpen() const throw()
  54342. {
  54343. return isOpen_;
  54344. }
  54345. void refreshAll() const
  54346. {
  54347. for (int i = 0; i < getNumChildComponents(); ++i)
  54348. {
  54349. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54350. if (pec != 0)
  54351. pec->refresh();
  54352. }
  54353. }
  54354. void mouseDown (const MouseEvent&)
  54355. {
  54356. }
  54357. void mouseUp (const MouseEvent& e)
  54358. {
  54359. if (e.getMouseDownX() < titleHeight
  54360. && e.x < titleHeight
  54361. && e.y < titleHeight
  54362. && e.getNumberOfClicks() != 2)
  54363. {
  54364. setOpen (! isOpen());
  54365. }
  54366. }
  54367. void mouseDoubleClick (const MouseEvent& e)
  54368. {
  54369. if (e.y < titleHeight)
  54370. setOpen (! isOpen());
  54371. }
  54372. private:
  54373. int titleHeight;
  54374. bool isOpen_;
  54375. };
  54376. void PropertyHolderComponent::updateLayout (const int width)
  54377. {
  54378. int y = 0;
  54379. for (int i = getNumChildComponents(); --i >= 0;)
  54380. {
  54381. PropertySectionComponent* const section
  54382. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54383. if (section != 0)
  54384. {
  54385. const int prefH = section->getPreferredHeight();
  54386. section->setBounds (0, y, width, prefH);
  54387. y += prefH;
  54388. }
  54389. }
  54390. setSize (width, y);
  54391. repaint();
  54392. }
  54393. void PropertyHolderComponent::refreshAll() const
  54394. {
  54395. for (int i = getNumChildComponents(); --i >= 0;)
  54396. {
  54397. PropertySectionComponent* const section
  54398. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54399. if (section != 0)
  54400. section->refreshAll();
  54401. }
  54402. }
  54403. PropertyPanel::PropertyPanel()
  54404. {
  54405. messageWhenEmpty = TRANS("(nothing selected)");
  54406. addAndMakeVisible (viewport = new Viewport());
  54407. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  54408. viewport->setFocusContainer (true);
  54409. }
  54410. PropertyPanel::~PropertyPanel()
  54411. {
  54412. clear();
  54413. deleteAllChildren();
  54414. }
  54415. void PropertyPanel::paint (Graphics& g)
  54416. {
  54417. if (propertyHolderComponent->getNumChildComponents() == 0)
  54418. {
  54419. g.setColour (Colours::black.withAlpha (0.5f));
  54420. g.setFont (14.0f);
  54421. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  54422. Justification::centred, true);
  54423. }
  54424. }
  54425. void PropertyPanel::resized()
  54426. {
  54427. viewport->setBounds (0, 0, getWidth(), getHeight());
  54428. updatePropHolderLayout();
  54429. }
  54430. void PropertyPanel::clear()
  54431. {
  54432. if (propertyHolderComponent->getNumChildComponents() > 0)
  54433. {
  54434. propertyHolderComponent->deleteAllChildren();
  54435. repaint();
  54436. }
  54437. }
  54438. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  54439. {
  54440. if (propertyHolderComponent->getNumChildComponents() == 0)
  54441. repaint();
  54442. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  54443. newProperties,
  54444. true), 0);
  54445. updatePropHolderLayout();
  54446. }
  54447. void PropertyPanel::addSection (const String& sectionTitle,
  54448. const Array <PropertyComponent*>& newProperties,
  54449. const bool shouldBeOpen)
  54450. {
  54451. jassert (sectionTitle.isNotEmpty());
  54452. if (propertyHolderComponent->getNumChildComponents() == 0)
  54453. repaint();
  54454. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  54455. newProperties,
  54456. shouldBeOpen), 0);
  54457. updatePropHolderLayout();
  54458. }
  54459. void PropertyPanel::updatePropHolderLayout() const
  54460. {
  54461. const int maxWidth = viewport->getMaximumVisibleWidth();
  54462. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  54463. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  54464. if (maxWidth != newMaxWidth)
  54465. {
  54466. // need to do this twice because of scrollbars changing the size, etc.
  54467. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  54468. }
  54469. }
  54470. void PropertyPanel::refreshAll() const
  54471. {
  54472. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  54473. }
  54474. const StringArray PropertyPanel::getSectionNames() const
  54475. {
  54476. StringArray s;
  54477. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54478. {
  54479. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54480. if (section != 0 && section->getName().isNotEmpty())
  54481. s.add (section->getName());
  54482. }
  54483. return s;
  54484. }
  54485. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  54486. {
  54487. int index = 0;
  54488. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54489. {
  54490. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54491. if (section != 0 && section->getName().isNotEmpty())
  54492. {
  54493. if (index == sectionIndex)
  54494. return section->isOpen();
  54495. ++index;
  54496. }
  54497. }
  54498. return false;
  54499. }
  54500. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  54501. {
  54502. int index = 0;
  54503. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54504. {
  54505. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54506. if (section != 0 && section->getName().isNotEmpty())
  54507. {
  54508. if (index == sectionIndex)
  54509. {
  54510. section->setOpen (shouldBeOpen);
  54511. break;
  54512. }
  54513. ++index;
  54514. }
  54515. }
  54516. }
  54517. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  54518. {
  54519. int index = 0;
  54520. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54521. {
  54522. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54523. if (section != 0 && section->getName().isNotEmpty())
  54524. {
  54525. if (index == sectionIndex)
  54526. {
  54527. section->setEnabled (shouldBeEnabled);
  54528. break;
  54529. }
  54530. ++index;
  54531. }
  54532. }
  54533. }
  54534. XmlElement* PropertyPanel::getOpennessState() const
  54535. {
  54536. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  54537. const StringArray sections (getSectionNames());
  54538. for (int i = 0; i < sections.size(); ++i)
  54539. {
  54540. if (sections[i].isNotEmpty())
  54541. {
  54542. XmlElement* const e = new XmlElement (T("SECTION"));
  54543. e->setAttribute (T("name"), sections[i]);
  54544. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  54545. xml->addChildElement (e);
  54546. }
  54547. }
  54548. return xml;
  54549. }
  54550. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  54551. {
  54552. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  54553. {
  54554. const StringArray sections (getSectionNames());
  54555. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  54556. {
  54557. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  54558. e->getBoolAttribute (T("open")));
  54559. }
  54560. }
  54561. }
  54562. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  54563. {
  54564. if (messageWhenEmpty != newMessage)
  54565. {
  54566. messageWhenEmpty = newMessage;
  54567. repaint();
  54568. }
  54569. }
  54570. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  54571. {
  54572. return messageWhenEmpty;
  54573. }
  54574. END_JUCE_NAMESPACE
  54575. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  54576. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  54577. BEGIN_JUCE_NAMESPACE
  54578. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  54579. const double rangeMin,
  54580. const double rangeMax,
  54581. const double interval,
  54582. const double skewFactor)
  54583. : PropertyComponent (name)
  54584. {
  54585. addAndMakeVisible (slider = new Slider (name));
  54586. slider->setRange (rangeMin, rangeMax, interval);
  54587. slider->setSkewFactor (skewFactor);
  54588. slider->setSliderStyle (Slider::LinearBar);
  54589. slider->addListener (this);
  54590. }
  54591. SliderPropertyComponent::~SliderPropertyComponent()
  54592. {
  54593. deleteAllChildren();
  54594. }
  54595. void SliderPropertyComponent::refresh()
  54596. {
  54597. slider->setValue (getValue(), false);
  54598. }
  54599. void SliderPropertyComponent::sliderValueChanged (Slider*)
  54600. {
  54601. if (getValue() != slider->getValue())
  54602. setValue (slider->getValue());
  54603. }
  54604. END_JUCE_NAMESPACE
  54605. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  54606. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  54607. BEGIN_JUCE_NAMESPACE
  54608. class TextPropLabel : public Label
  54609. {
  54610. TextPropertyComponent& owner;
  54611. int maxChars;
  54612. bool isMultiline;
  54613. public:
  54614. TextPropLabel (TextPropertyComponent& owner_,
  54615. const int maxChars_, const bool isMultiline_)
  54616. : Label (String::empty, String::empty),
  54617. owner (owner_),
  54618. maxChars (maxChars_),
  54619. isMultiline (isMultiline_)
  54620. {
  54621. setEditable (true, true, false);
  54622. setColour (backgroundColourId, Colours::white);
  54623. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  54624. }
  54625. ~TextPropLabel()
  54626. {
  54627. }
  54628. TextEditor* createEditorComponent()
  54629. {
  54630. TextEditor* const textEditor = Label::createEditorComponent();
  54631. textEditor->setInputRestrictions (maxChars);
  54632. if (isMultiline)
  54633. {
  54634. textEditor->setMultiLine (true, true);
  54635. textEditor->setReturnKeyStartsNewLine (true);
  54636. }
  54637. return textEditor;
  54638. }
  54639. void textWasEdited()
  54640. {
  54641. owner.textWasEdited();
  54642. }
  54643. };
  54644. TextPropertyComponent::TextPropertyComponent (const String& name,
  54645. const int maxNumChars,
  54646. const bool isMultiLine)
  54647. : PropertyComponent (name)
  54648. {
  54649. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  54650. if (isMultiLine)
  54651. {
  54652. textEditor->setJustificationType (Justification::topLeft);
  54653. preferredHeight = 120;
  54654. }
  54655. }
  54656. TextPropertyComponent::~TextPropertyComponent()
  54657. {
  54658. deleteAllChildren();
  54659. }
  54660. void TextPropertyComponent::refresh()
  54661. {
  54662. textEditor->setText (getText(), false);
  54663. }
  54664. void TextPropertyComponent::textWasEdited()
  54665. {
  54666. const String newText (textEditor->getText());
  54667. if (getText() != newText)
  54668. setText (newText);
  54669. }
  54670. END_JUCE_NAMESPACE
  54671. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  54672. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  54673. BEGIN_JUCE_NAMESPACE
  54674. class SimpleDeviceManagerInputLevelMeter : public Component,
  54675. public Timer
  54676. {
  54677. public:
  54678. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  54679. : manager (manager_),
  54680. level (0)
  54681. {
  54682. startTimer (50);
  54683. manager->enableInputLevelMeasurement (true);
  54684. }
  54685. ~SimpleDeviceManagerInputLevelMeter()
  54686. {
  54687. manager->enableInputLevelMeasurement (false);
  54688. }
  54689. void timerCallback()
  54690. {
  54691. const float newLevel = (float) manager->getCurrentInputLevel();
  54692. if (fabsf (level - newLevel) > 0.005f)
  54693. {
  54694. level = newLevel;
  54695. repaint();
  54696. }
  54697. }
  54698. void paint (Graphics& g)
  54699. {
  54700. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(), level);
  54701. }
  54702. private:
  54703. AudioDeviceManager* const manager;
  54704. float level;
  54705. };
  54706. class MidiInputSelectorComponentListBox : public ListBox,
  54707. public ListBoxModel
  54708. {
  54709. public:
  54710. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  54711. const String& noItemsMessage_,
  54712. const int minNumber_,
  54713. const int maxNumber_)
  54714. : ListBox (String::empty, 0),
  54715. deviceManager (deviceManager_),
  54716. noItemsMessage (noItemsMessage_),
  54717. minNumber (minNumber_),
  54718. maxNumber (maxNumber_)
  54719. {
  54720. items = MidiInput::getDevices();
  54721. setModel (this);
  54722. setOutlineThickness (1);
  54723. }
  54724. ~MidiInputSelectorComponentListBox()
  54725. {
  54726. }
  54727. int getNumRows()
  54728. {
  54729. return items.size();
  54730. }
  54731. void paintListBoxItem (int row,
  54732. Graphics& g,
  54733. int width, int height,
  54734. bool rowIsSelected)
  54735. {
  54736. if (((unsigned int) row) < (unsigned int) items.size())
  54737. {
  54738. if (rowIsSelected)
  54739. g.fillAll (findColour (TextEditor::highlightColourId)
  54740. .withMultipliedAlpha (0.3f));
  54741. const String item (items [row]);
  54742. bool enabled = deviceManager.isMidiInputEnabled (item);
  54743. const int x = getTickX();
  54744. const int tickW = height - height / 4;
  54745. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  54746. enabled, true, true, false);
  54747. g.setFont (height * 0.6f);
  54748. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  54749. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  54750. }
  54751. }
  54752. void listBoxItemClicked (int row, const MouseEvent& e)
  54753. {
  54754. selectRow (row);
  54755. if (e.x < getTickX())
  54756. flipEnablement (row);
  54757. }
  54758. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  54759. {
  54760. flipEnablement (row);
  54761. }
  54762. void returnKeyPressed (int row)
  54763. {
  54764. flipEnablement (row);
  54765. }
  54766. void paint (Graphics& g)
  54767. {
  54768. ListBox::paint (g);
  54769. if (items.size() == 0)
  54770. {
  54771. g.setColour (Colours::grey);
  54772. g.setFont (13.0f);
  54773. g.drawText (noItemsMessage,
  54774. 0, 0, getWidth(), getHeight() / 2,
  54775. Justification::centred, true);
  54776. }
  54777. }
  54778. int getBestHeight (const int preferredHeight)
  54779. {
  54780. const int extra = getOutlineThickness() * 2;
  54781. return jmax (getRowHeight() * 2 + extra,
  54782. jmin (getRowHeight() * getNumRows() + extra,
  54783. preferredHeight));
  54784. }
  54785. juce_UseDebuggingNewOperator
  54786. private:
  54787. AudioDeviceManager& deviceManager;
  54788. const String noItemsMessage;
  54789. StringArray items;
  54790. int minNumber, maxNumber;
  54791. void flipEnablement (const int row)
  54792. {
  54793. if (((unsigned int) row) < (unsigned int) items.size())
  54794. {
  54795. const String item (items [row]);
  54796. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  54797. }
  54798. }
  54799. int getTickX() const throw()
  54800. {
  54801. return getRowHeight() + 5;
  54802. }
  54803. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  54804. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  54805. };
  54806. class AudioDeviceSettingsPanel : public Component,
  54807. public ComboBoxListener,
  54808. public ChangeListener,
  54809. public ButtonListener
  54810. {
  54811. public:
  54812. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  54813. AudioIODeviceType::DeviceSetupDetails& setup_,
  54814. const bool hideAdvancedOptionsWithButton)
  54815. : type (type_),
  54816. setup (setup_)
  54817. {
  54818. sampleRateDropDown = 0;
  54819. sampleRateLabel = 0;
  54820. bufferSizeDropDown = 0;
  54821. bufferSizeLabel = 0;
  54822. outputDeviceDropDown = 0;
  54823. outputDeviceLabel = 0;
  54824. inputDeviceDropDown = 0;
  54825. inputDeviceLabel = 0;
  54826. testButton = 0;
  54827. inputLevelMeter = 0;
  54828. showUIButton = 0;
  54829. inputChanList = 0;
  54830. outputChanList = 0;
  54831. inputChanLabel = 0;
  54832. outputChanLabel = 0;
  54833. showAdvancedSettingsButton = 0;
  54834. if (hideAdvancedOptionsWithButton)
  54835. {
  54836. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  54837. showAdvancedSettingsButton->addButtonListener (this);
  54838. }
  54839. type->scanForDevices();
  54840. setup.manager->addChangeListener (this);
  54841. changeListenerCallback (0);
  54842. }
  54843. ~AudioDeviceSettingsPanel()
  54844. {
  54845. setup.manager->removeChangeListener (this);
  54846. deleteAndZero (outputDeviceLabel);
  54847. deleteAndZero (inputDeviceLabel);
  54848. deleteAndZero (sampleRateLabel);
  54849. deleteAndZero (bufferSizeLabel);
  54850. deleteAndZero (showUIButton);
  54851. deleteAndZero (inputChanLabel);
  54852. deleteAndZero (outputChanLabel);
  54853. deleteAndZero (showAdvancedSettingsButton);
  54854. deleteAllChildren();
  54855. }
  54856. void resized()
  54857. {
  54858. const int lx = proportionOfWidth (0.35f);
  54859. const int w = proportionOfWidth (0.4f);
  54860. const int h = 24;
  54861. const int space = 6;
  54862. const int dh = h + space;
  54863. int y = 0;
  54864. if (outputDeviceDropDown != 0)
  54865. {
  54866. outputDeviceDropDown->setBounds (lx, y, w, h);
  54867. if (testButton != 0)
  54868. testButton->setBounds (proportionOfWidth (0.77f),
  54869. outputDeviceDropDown->getY(),
  54870. proportionOfWidth (0.18f),
  54871. h);
  54872. y += dh;
  54873. }
  54874. if (inputDeviceDropDown != 0)
  54875. {
  54876. inputDeviceDropDown->setBounds (lx, y, w, h);
  54877. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  54878. inputDeviceDropDown->getY(),
  54879. proportionOfWidth (0.18f),
  54880. h);
  54881. y += dh;
  54882. }
  54883. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  54884. if (outputChanList != 0)
  54885. {
  54886. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  54887. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  54888. y += bh + space;
  54889. }
  54890. if (inputChanList != 0)
  54891. {
  54892. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  54893. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  54894. y += bh + space;
  54895. }
  54896. y += space * 2;
  54897. if (showAdvancedSettingsButton != 0)
  54898. {
  54899. showAdvancedSettingsButton->changeWidthToFitText (h);
  54900. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  54901. }
  54902. if (sampleRateDropDown != 0)
  54903. {
  54904. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  54905. || ! showAdvancedSettingsButton->isVisible());
  54906. sampleRateDropDown->setBounds (lx, y, w, h);
  54907. y += dh;
  54908. }
  54909. if (bufferSizeDropDown != 0)
  54910. {
  54911. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  54912. || ! showAdvancedSettingsButton->isVisible());
  54913. bufferSizeDropDown->setBounds (lx, y, w, h);
  54914. y += dh;
  54915. }
  54916. if (showUIButton != 0)
  54917. {
  54918. showUIButton->setVisible (showAdvancedSettingsButton == 0
  54919. || ! showAdvancedSettingsButton->isVisible());
  54920. showUIButton->changeWidthToFitText (h);
  54921. showUIButton->setTopLeftPosition (lx, y);
  54922. }
  54923. }
  54924. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  54925. {
  54926. if (comboBoxThatHasChanged == 0)
  54927. return;
  54928. AudioDeviceManager::AudioDeviceSetup config;
  54929. setup.manager->getAudioDeviceSetup (config);
  54930. String error;
  54931. if (comboBoxThatHasChanged == outputDeviceDropDown
  54932. || comboBoxThatHasChanged == inputDeviceDropDown)
  54933. {
  54934. if (outputDeviceDropDown != 0)
  54935. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  54936. : outputDeviceDropDown->getText();
  54937. if (inputDeviceDropDown != 0)
  54938. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  54939. : inputDeviceDropDown->getText();
  54940. if (! type->hasSeparateInputsAndOutputs())
  54941. config.inputDeviceName = config.outputDeviceName;
  54942. if (comboBoxThatHasChanged == inputDeviceDropDown)
  54943. config.useDefaultInputChannels = true;
  54944. else
  54945. config.useDefaultOutputChannels = true;
  54946. error = setup.manager->setAudioDeviceSetup (config, true);
  54947. showCorrectDeviceName (inputDeviceDropDown, true);
  54948. showCorrectDeviceName (outputDeviceDropDown, false);
  54949. updateControlPanelButton();
  54950. resized();
  54951. }
  54952. else if (comboBoxThatHasChanged == sampleRateDropDown)
  54953. {
  54954. if (sampleRateDropDown->getSelectedId() > 0)
  54955. {
  54956. config.sampleRate = sampleRateDropDown->getSelectedId();
  54957. error = setup.manager->setAudioDeviceSetup (config, true);
  54958. }
  54959. }
  54960. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  54961. {
  54962. if (bufferSizeDropDown->getSelectedId() > 0)
  54963. {
  54964. config.bufferSize = bufferSizeDropDown->getSelectedId();
  54965. error = setup.manager->setAudioDeviceSetup (config, true);
  54966. }
  54967. }
  54968. if (error.isNotEmpty())
  54969. {
  54970. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  54971. T("Error when trying to open audio device!"),
  54972. error);
  54973. }
  54974. }
  54975. void buttonClicked (Button* button)
  54976. {
  54977. if (button == showAdvancedSettingsButton)
  54978. {
  54979. showAdvancedSettingsButton->setVisible (false);
  54980. resized();
  54981. }
  54982. else if (button == showUIButton)
  54983. {
  54984. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  54985. if (device != 0 && device->showControlPanel())
  54986. {
  54987. setup.manager->closeAudioDevice();
  54988. setup.manager->restartLastAudioDevice();
  54989. getTopLevelComponent()->toFront (true);
  54990. }
  54991. }
  54992. else if (button == testButton && testButton != 0)
  54993. {
  54994. setup.manager->playTestSound();
  54995. }
  54996. }
  54997. void updateControlPanelButton()
  54998. {
  54999. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55000. deleteAndZero (showUIButton);
  55001. if (currentDevice != 0 && currentDevice->hasControlPanel())
  55002. {
  55003. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  55004. TRANS ("opens the device's own control panel")));
  55005. showUIButton->addButtonListener (this);
  55006. }
  55007. resized();
  55008. }
  55009. void changeListenerCallback (void*)
  55010. {
  55011. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55012. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  55013. {
  55014. if (outputDeviceDropDown == 0)
  55015. {
  55016. outputDeviceDropDown = new ComboBox (String::empty);
  55017. outputDeviceDropDown->addListener (this);
  55018. addAndMakeVisible (outputDeviceDropDown);
  55019. outputDeviceLabel = new Label (String::empty,
  55020. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  55021. : TRANS ("device:"));
  55022. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  55023. if (setup.maxNumOutputChannels > 0)
  55024. {
  55025. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  55026. testButton->addButtonListener (this);
  55027. }
  55028. }
  55029. addNamesToDeviceBox (*outputDeviceDropDown, false);
  55030. }
  55031. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  55032. {
  55033. if (inputDeviceDropDown == 0)
  55034. {
  55035. inputDeviceDropDown = new ComboBox (String::empty);
  55036. inputDeviceDropDown->addListener (this);
  55037. addAndMakeVisible (inputDeviceDropDown);
  55038. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  55039. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  55040. addAndMakeVisible (inputLevelMeter
  55041. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  55042. }
  55043. addNamesToDeviceBox (*inputDeviceDropDown, true);
  55044. }
  55045. updateControlPanelButton();
  55046. showCorrectDeviceName (inputDeviceDropDown, true);
  55047. showCorrectDeviceName (outputDeviceDropDown, false);
  55048. if (currentDevice != 0)
  55049. {
  55050. if (setup.maxNumOutputChannels > 0
  55051. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  55052. {
  55053. if (outputChanList == 0)
  55054. {
  55055. addAndMakeVisible (outputChanList
  55056. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  55057. TRANS ("(no audio output channels found)")));
  55058. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  55059. outputChanLabel->attachToComponent (outputChanList, true);
  55060. }
  55061. outputChanList->refresh();
  55062. }
  55063. else
  55064. {
  55065. deleteAndZero (outputChanLabel);
  55066. deleteAndZero (outputChanList);
  55067. }
  55068. if (setup.maxNumInputChannels > 0
  55069. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  55070. {
  55071. if (inputChanList == 0)
  55072. {
  55073. addAndMakeVisible (inputChanList
  55074. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  55075. TRANS ("(no audio input channels found)")));
  55076. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  55077. inputChanLabel->attachToComponent (inputChanList, true);
  55078. }
  55079. inputChanList->refresh();
  55080. }
  55081. else
  55082. {
  55083. deleteAndZero (inputChanLabel);
  55084. deleteAndZero (inputChanList);
  55085. }
  55086. // sample rate..
  55087. {
  55088. if (sampleRateDropDown == 0)
  55089. {
  55090. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  55091. sampleRateDropDown->addListener (this);
  55092. delete sampleRateLabel;
  55093. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  55094. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  55095. }
  55096. else
  55097. {
  55098. sampleRateDropDown->clear();
  55099. sampleRateDropDown->removeListener (this);
  55100. }
  55101. const int numRates = currentDevice->getNumSampleRates();
  55102. for (int i = 0; i < numRates; ++i)
  55103. {
  55104. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  55105. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  55106. }
  55107. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  55108. sampleRateDropDown->addListener (this);
  55109. }
  55110. // buffer size
  55111. {
  55112. if (bufferSizeDropDown == 0)
  55113. {
  55114. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  55115. bufferSizeDropDown->addListener (this);
  55116. delete bufferSizeLabel;
  55117. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  55118. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  55119. }
  55120. else
  55121. {
  55122. bufferSizeDropDown->clear();
  55123. }
  55124. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  55125. double currentRate = currentDevice->getCurrentSampleRate();
  55126. if (currentRate == 0)
  55127. currentRate = 48000.0;
  55128. for (int i = 0; i < numBufferSizes; ++i)
  55129. {
  55130. const int bs = currentDevice->getBufferSizeSamples (i);
  55131. bufferSizeDropDown->addItem (String (bs)
  55132. + T(" samples (")
  55133. + String (bs * 1000.0 / currentRate, 1)
  55134. + T(" ms)"),
  55135. bs);
  55136. }
  55137. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  55138. }
  55139. }
  55140. else
  55141. {
  55142. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  55143. deleteAndZero (sampleRateLabel);
  55144. deleteAndZero (bufferSizeLabel);
  55145. deleteAndZero (sampleRateDropDown);
  55146. deleteAndZero (bufferSizeDropDown);
  55147. if (outputDeviceDropDown != 0)
  55148. outputDeviceDropDown->setSelectedId (-1, true);
  55149. if (inputDeviceDropDown != 0)
  55150. inputDeviceDropDown->setSelectedId (-1, true);
  55151. }
  55152. resized();
  55153. setSize (getWidth(), getLowestY() + 4);
  55154. }
  55155. private:
  55156. AudioIODeviceType* const type;
  55157. const AudioIODeviceType::DeviceSetupDetails setup;
  55158. ComboBox* outputDeviceDropDown;
  55159. ComboBox* inputDeviceDropDown;
  55160. ComboBox* sampleRateDropDown;
  55161. ComboBox* bufferSizeDropDown;
  55162. Label* outputDeviceLabel;
  55163. Label* inputDeviceLabel;
  55164. Label* sampleRateLabel;
  55165. Label* bufferSizeLabel;
  55166. Label* inputChanLabel;
  55167. Label* outputChanLabel;
  55168. TextButton* testButton;
  55169. Component* inputLevelMeter;
  55170. TextButton* showUIButton;
  55171. TextButton* showAdvancedSettingsButton;
  55172. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  55173. {
  55174. if (box != 0)
  55175. {
  55176. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  55177. const int index = type->getIndexOfDevice (currentDevice, isInput);
  55178. box->setSelectedId (index + 1, true);
  55179. if (testButton != 0 && ! isInput)
  55180. testButton->setEnabled (index >= 0);
  55181. }
  55182. }
  55183. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  55184. {
  55185. const StringArray devs (type->getDeviceNames (isInputs));
  55186. combo.clear (true);
  55187. for (int i = 0; i < devs.size(); ++i)
  55188. combo.addItem (devs[i], i + 1);
  55189. combo.addItem (TRANS("<< none >>"), -1);
  55190. combo.setSelectedId (-1, true);
  55191. }
  55192. int getLowestY() const
  55193. {
  55194. int y = 0;
  55195. for (int i = getNumChildComponents(); --i >= 0;)
  55196. y = jmax (y, getChildComponent (i)->getBottom());
  55197. return y;
  55198. }
  55199. class ChannelSelectorListBox : public ListBox,
  55200. public ListBoxModel
  55201. {
  55202. public:
  55203. enum BoxType
  55204. {
  55205. audioInputType,
  55206. audioOutputType
  55207. };
  55208. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  55209. const BoxType type_,
  55210. const String& noItemsMessage_)
  55211. : ListBox (String::empty, 0),
  55212. setup (setup_),
  55213. type (type_),
  55214. noItemsMessage (noItemsMessage_)
  55215. {
  55216. refresh();
  55217. setModel (this);
  55218. setOutlineThickness (1);
  55219. }
  55220. ~ChannelSelectorListBox()
  55221. {
  55222. }
  55223. void refresh()
  55224. {
  55225. items.clear();
  55226. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55227. if (currentDevice != 0)
  55228. {
  55229. if (type == audioInputType)
  55230. items = currentDevice->getInputChannelNames();
  55231. else if (type == audioOutputType)
  55232. items = currentDevice->getOutputChannelNames();
  55233. if (setup.useStereoPairs)
  55234. {
  55235. StringArray pairs;
  55236. for (int i = 0; i < items.size(); i += 2)
  55237. {
  55238. String name (items[i]);
  55239. String name2 (items[i + 1]);
  55240. String commonBit;
  55241. for (int j = 0; j < name.length(); ++j)
  55242. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  55243. commonBit = name.substring (0, j);
  55244. pairs.add (name.trim()
  55245. + " + "
  55246. + name2.substring (commonBit.length()).trim());
  55247. }
  55248. items = pairs;
  55249. }
  55250. }
  55251. updateContent();
  55252. repaint();
  55253. }
  55254. int getNumRows()
  55255. {
  55256. return items.size();
  55257. }
  55258. void paintListBoxItem (int row,
  55259. Graphics& g,
  55260. int width, int height,
  55261. bool rowIsSelected)
  55262. {
  55263. if (((unsigned int) row) < (unsigned int) items.size())
  55264. {
  55265. if (rowIsSelected)
  55266. g.fillAll (findColour (TextEditor::highlightColourId)
  55267. .withMultipliedAlpha (0.3f));
  55268. const String item (items [row]);
  55269. bool enabled = false;
  55270. AudioDeviceManager::AudioDeviceSetup config;
  55271. setup.manager->getAudioDeviceSetup (config);
  55272. if (setup.useStereoPairs)
  55273. {
  55274. if (type == audioInputType)
  55275. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  55276. else if (type == audioOutputType)
  55277. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  55278. }
  55279. else
  55280. {
  55281. if (type == audioInputType)
  55282. enabled = config.inputChannels [row];
  55283. else if (type == audioOutputType)
  55284. enabled = config.outputChannels [row];
  55285. }
  55286. const int x = getTickX();
  55287. const int tickW = height - height / 4;
  55288. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  55289. enabled, true, true, false);
  55290. g.setFont (height * 0.6f);
  55291. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  55292. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  55293. }
  55294. }
  55295. void listBoxItemClicked (int row, const MouseEvent& e)
  55296. {
  55297. selectRow (row);
  55298. if (e.x < getTickX())
  55299. flipEnablement (row);
  55300. }
  55301. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  55302. {
  55303. flipEnablement (row);
  55304. }
  55305. void returnKeyPressed (int row)
  55306. {
  55307. flipEnablement (row);
  55308. }
  55309. void paint (Graphics& g)
  55310. {
  55311. ListBox::paint (g);
  55312. if (items.size() == 0)
  55313. {
  55314. g.setColour (Colours::grey);
  55315. g.setFont (13.0f);
  55316. g.drawText (noItemsMessage,
  55317. 0, 0, getWidth(), getHeight() / 2,
  55318. Justification::centred, true);
  55319. }
  55320. }
  55321. int getBestHeight (int maxHeight)
  55322. {
  55323. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  55324. getNumRows())
  55325. + getOutlineThickness() * 2;
  55326. }
  55327. juce_UseDebuggingNewOperator
  55328. private:
  55329. const AudioIODeviceType::DeviceSetupDetails setup;
  55330. const BoxType type;
  55331. const String noItemsMessage;
  55332. StringArray items;
  55333. void flipEnablement (const int row)
  55334. {
  55335. jassert (type == audioInputType || type == audioOutputType);
  55336. if (((unsigned int) row) < (unsigned int) items.size())
  55337. {
  55338. AudioDeviceManager::AudioDeviceSetup config;
  55339. setup.manager->getAudioDeviceSetup (config);
  55340. if (setup.useStereoPairs)
  55341. {
  55342. BitArray bits;
  55343. BitArray& original = (type == audioInputType ? config.inputChannels
  55344. : config.outputChannels);
  55345. int i;
  55346. for (i = 0; i < 256; i += 2)
  55347. bits.setBit (i / 2, original [i] || original [i + 1]);
  55348. if (type == audioInputType)
  55349. {
  55350. config.useDefaultInputChannels = false;
  55351. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  55352. }
  55353. else
  55354. {
  55355. config.useDefaultOutputChannels = false;
  55356. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  55357. }
  55358. for (i = 0; i < 256; ++i)
  55359. original.setBit (i, bits [i / 2]);
  55360. }
  55361. else
  55362. {
  55363. if (type == audioInputType)
  55364. {
  55365. config.useDefaultInputChannels = false;
  55366. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  55367. }
  55368. else
  55369. {
  55370. config.useDefaultOutputChannels = false;
  55371. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  55372. }
  55373. }
  55374. String error (setup.manager->setAudioDeviceSetup (config, true));
  55375. if (! error.isEmpty())
  55376. {
  55377. //xxx
  55378. }
  55379. }
  55380. }
  55381. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  55382. {
  55383. const int numActive = chans.countNumberOfSetBits();
  55384. if (chans [index])
  55385. {
  55386. if (numActive > minNumber)
  55387. chans.setBit (index, false);
  55388. }
  55389. else
  55390. {
  55391. if (numActive >= maxNumber)
  55392. {
  55393. const int firstActiveChan = chans.findNextSetBit();
  55394. chans.setBit (index > firstActiveChan
  55395. ? firstActiveChan : chans.getHighestBit(),
  55396. false);
  55397. }
  55398. chans.setBit (index, true);
  55399. }
  55400. }
  55401. int getTickX() const throw()
  55402. {
  55403. return getRowHeight() + 5;
  55404. }
  55405. ChannelSelectorListBox (const ChannelSelectorListBox&);
  55406. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  55407. };
  55408. ChannelSelectorListBox* inputChanList;
  55409. ChannelSelectorListBox* outputChanList;
  55410. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  55411. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  55412. };
  55413. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  55414. const int minInputChannels_,
  55415. const int maxInputChannels_,
  55416. const int minOutputChannels_,
  55417. const int maxOutputChannels_,
  55418. const bool showMidiInputOptions,
  55419. const bool showMidiOutputSelector,
  55420. const bool showChannelsAsStereoPairs_,
  55421. const bool hideAdvancedOptionsWithButton_)
  55422. : deviceManager (deviceManager_),
  55423. deviceTypeDropDown (0),
  55424. deviceTypeDropDownLabel (0),
  55425. audioDeviceSettingsComp (0),
  55426. minOutputChannels (minOutputChannels_),
  55427. maxOutputChannels (maxOutputChannels_),
  55428. minInputChannels (minInputChannels_),
  55429. maxInputChannels (maxInputChannels_),
  55430. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  55431. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  55432. {
  55433. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  55434. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  55435. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  55436. {
  55437. deviceTypeDropDown = new ComboBox (String::empty);
  55438. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  55439. {
  55440. deviceTypeDropDown
  55441. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  55442. i + 1);
  55443. }
  55444. addAndMakeVisible (deviceTypeDropDown);
  55445. deviceTypeDropDown->addListener (this);
  55446. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  55447. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  55448. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  55449. }
  55450. if (showMidiInputOptions)
  55451. {
  55452. addAndMakeVisible (midiInputsList
  55453. = new MidiInputSelectorComponentListBox (deviceManager,
  55454. TRANS("(no midi inputs available)"),
  55455. 0, 0));
  55456. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  55457. midiInputsLabel->setJustificationType (Justification::topRight);
  55458. midiInputsLabel->attachToComponent (midiInputsList, true);
  55459. }
  55460. else
  55461. {
  55462. midiInputsList = 0;
  55463. midiInputsLabel = 0;
  55464. }
  55465. if (showMidiOutputSelector)
  55466. {
  55467. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  55468. midiOutputSelector->addListener (this);
  55469. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  55470. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  55471. }
  55472. else
  55473. {
  55474. midiOutputSelector = 0;
  55475. midiOutputLabel = 0;
  55476. }
  55477. deviceManager_.addChangeListener (this);
  55478. changeListenerCallback (0);
  55479. }
  55480. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  55481. {
  55482. deviceManager.removeChangeListener (this);
  55483. deleteAllChildren();
  55484. }
  55485. void AudioDeviceSelectorComponent::resized()
  55486. {
  55487. const int lx = proportionOfWidth (0.35f);
  55488. const int w = proportionOfWidth (0.4f);
  55489. const int h = 24;
  55490. const int space = 6;
  55491. const int dh = h + space;
  55492. int y = 15;
  55493. if (deviceTypeDropDown != 0)
  55494. {
  55495. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  55496. y += dh + space * 2;
  55497. }
  55498. if (audioDeviceSettingsComp != 0)
  55499. {
  55500. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  55501. y += audioDeviceSettingsComp->getHeight() + space;
  55502. }
  55503. if (midiInputsList != 0)
  55504. {
  55505. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  55506. midiInputsList->setBounds (lx, y, w, bh);
  55507. y += bh + space;
  55508. }
  55509. if (midiOutputSelector != 0)
  55510. midiOutputSelector->setBounds (lx, y, w, h);
  55511. }
  55512. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  55513. {
  55514. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  55515. if (device != 0 && device->hasControlPanel())
  55516. {
  55517. if (device->showControlPanel())
  55518. deviceManager.restartLastAudioDevice();
  55519. getTopLevelComponent()->toFront (true);
  55520. }
  55521. }
  55522. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  55523. {
  55524. if (comboBoxThatHasChanged == deviceTypeDropDown)
  55525. {
  55526. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  55527. if (type != 0)
  55528. {
  55529. deleteAndZero (audioDeviceSettingsComp);
  55530. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  55531. changeListenerCallback (0); // needed in case the type hasn't actally changed
  55532. }
  55533. }
  55534. else if (comboBoxThatHasChanged == midiOutputSelector)
  55535. {
  55536. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  55537. }
  55538. }
  55539. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  55540. {
  55541. if (deviceTypeDropDown != 0)
  55542. {
  55543. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  55544. }
  55545. if (audioDeviceSettingsComp == 0
  55546. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  55547. {
  55548. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  55549. deleteAndZero (audioDeviceSettingsComp);
  55550. AudioIODeviceType* const type
  55551. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  55552. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  55553. if (type != 0)
  55554. {
  55555. AudioIODeviceType::DeviceSetupDetails details;
  55556. details.manager = &deviceManager;
  55557. details.minNumInputChannels = minInputChannels;
  55558. details.maxNumInputChannels = maxInputChannels;
  55559. details.minNumOutputChannels = minOutputChannels;
  55560. details.maxNumOutputChannels = maxOutputChannels;
  55561. details.useStereoPairs = showChannelsAsStereoPairs;
  55562. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  55563. if (audioDeviceSettingsComp != 0)
  55564. {
  55565. addAndMakeVisible (audioDeviceSettingsComp);
  55566. audioDeviceSettingsComp->resized();
  55567. }
  55568. }
  55569. }
  55570. if (midiInputsList != 0)
  55571. {
  55572. midiInputsList->updateContent();
  55573. midiInputsList->repaint();
  55574. }
  55575. if (midiOutputSelector != 0)
  55576. {
  55577. midiOutputSelector->clear();
  55578. const StringArray midiOuts (MidiOutput::getDevices());
  55579. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  55580. midiOutputSelector->addSeparator();
  55581. for (int i = 0; i < midiOuts.size(); ++i)
  55582. midiOutputSelector->addItem (midiOuts[i], i + 1);
  55583. int current = -1;
  55584. if (deviceManager.getDefaultMidiOutput() != 0)
  55585. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  55586. midiOutputSelector->setSelectedId (current, true);
  55587. }
  55588. resized();
  55589. }
  55590. END_JUCE_NAMESPACE
  55591. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  55592. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  55593. BEGIN_JUCE_NAMESPACE
  55594. BubbleComponent::BubbleComponent()
  55595. : side (0),
  55596. allowablePlacements (above | below | left | right),
  55597. arrowTipX (0.0f),
  55598. arrowTipY (0.0f)
  55599. {
  55600. setInterceptsMouseClicks (false, false);
  55601. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  55602. setComponentEffect (&shadow);
  55603. }
  55604. BubbleComponent::~BubbleComponent()
  55605. {
  55606. }
  55607. void BubbleComponent::paint (Graphics& g)
  55608. {
  55609. int x = content.getX();
  55610. int y = content.getY();
  55611. int w = content.getWidth();
  55612. int h = content.getHeight();
  55613. int cw, ch;
  55614. getContentSize (cw, ch);
  55615. if (side == 3)
  55616. x += w - cw;
  55617. else if (side != 1)
  55618. x += (w - cw) / 2;
  55619. w = cw;
  55620. if (side == 2)
  55621. y += h - ch;
  55622. else if (side != 0)
  55623. y += (h - ch) / 2;
  55624. h = ch;
  55625. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  55626. (float) x, (float) y,
  55627. (float) w, (float) h);
  55628. const int cx = x + (w - cw) / 2;
  55629. const int cy = y + (h - ch) / 2;
  55630. const int indent = 3;
  55631. g.setOrigin (cx + indent, cy + indent);
  55632. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  55633. paintContent (g, cw - indent * 2, ch - indent * 2);
  55634. }
  55635. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  55636. {
  55637. allowablePlacements = newPlacement;
  55638. }
  55639. void BubbleComponent::setPosition (Component* componentToPointTo)
  55640. {
  55641. jassert (componentToPointTo->isValidComponent());
  55642. int tx = 0;
  55643. int ty = 0;
  55644. if (getParentComponent() != 0)
  55645. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  55646. else
  55647. componentToPointTo->relativePositionToGlobal (tx, ty);
  55648. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  55649. }
  55650. void BubbleComponent::setPosition (const int arrowTipX,
  55651. const int arrowTipY)
  55652. {
  55653. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  55654. }
  55655. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  55656. {
  55657. Rectangle availableSpace;
  55658. if (getParentComponent() != 0)
  55659. {
  55660. availableSpace.setSize (getParentComponent()->getWidth(),
  55661. getParentComponent()->getHeight());
  55662. }
  55663. else
  55664. {
  55665. availableSpace = getParentMonitorArea();
  55666. }
  55667. int x = 0;
  55668. int y = 0;
  55669. int w = 150;
  55670. int h = 30;
  55671. getContentSize (w, h);
  55672. w += 30;
  55673. h += 30;
  55674. const float edgeIndent = 2.0f;
  55675. const int arrowLength = jmin (10, h / 3, w / 3);
  55676. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  55677. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  55678. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  55679. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  55680. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  55681. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  55682. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  55683. {
  55684. spaceLeft = spaceRight = 0;
  55685. }
  55686. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  55687. && (spaceLeft > w + 20 || spaceRight > w + 20))
  55688. {
  55689. spaceAbove = spaceBelow = 0;
  55690. }
  55691. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  55692. {
  55693. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  55694. arrowTipX = w * 0.5f;
  55695. content.setSize (w, h - arrowLength);
  55696. if (spaceAbove >= spaceBelow)
  55697. {
  55698. // above
  55699. y = rectangleToPointTo.getY() - h;
  55700. content.setPosition (0, 0);
  55701. arrowTipY = h - edgeIndent;
  55702. side = 2;
  55703. }
  55704. else
  55705. {
  55706. // below
  55707. y = rectangleToPointTo.getBottom();
  55708. content.setPosition (0, arrowLength);
  55709. arrowTipY = edgeIndent;
  55710. side = 0;
  55711. }
  55712. }
  55713. else
  55714. {
  55715. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  55716. arrowTipY = h * 0.5f;
  55717. content.setSize (w - arrowLength, h);
  55718. if (spaceLeft > spaceRight)
  55719. {
  55720. // on the left
  55721. x = rectangleToPointTo.getX() - w;
  55722. content.setPosition (0, 0);
  55723. arrowTipX = w - edgeIndent;
  55724. side = 3;
  55725. }
  55726. else
  55727. {
  55728. // on the right
  55729. x = rectangleToPointTo.getRight();
  55730. content.setPosition (arrowLength, 0);
  55731. arrowTipX = edgeIndent;
  55732. side = 1;
  55733. }
  55734. }
  55735. setBounds (x, y, w, h);
  55736. }
  55737. END_JUCE_NAMESPACE
  55738. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  55739. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  55740. BEGIN_JUCE_NAMESPACE
  55741. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  55742. : fadeOutLength (fadeOutLengthMs),
  55743. deleteAfterUse (false)
  55744. {
  55745. }
  55746. BubbleMessageComponent::~BubbleMessageComponent()
  55747. {
  55748. fadeOutComponent (fadeOutLength);
  55749. }
  55750. void BubbleMessageComponent::showAt (int x, int y,
  55751. const String& text,
  55752. const int numMillisecondsBeforeRemoving,
  55753. const bool removeWhenMouseClicked,
  55754. const bool deleteSelfAfterUse)
  55755. {
  55756. textLayout.clear();
  55757. textLayout.setText (text, Font (14.0f));
  55758. textLayout.layout (256, Justification::centredLeft, true);
  55759. setPosition (x, y);
  55760. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55761. }
  55762. void BubbleMessageComponent::showAt (Component* const component,
  55763. const String& text,
  55764. const int numMillisecondsBeforeRemoving,
  55765. const bool removeWhenMouseClicked,
  55766. const bool deleteSelfAfterUse)
  55767. {
  55768. textLayout.clear();
  55769. textLayout.setText (text, Font (14.0f));
  55770. textLayout.layout (256, Justification::centredLeft, true);
  55771. setPosition (component);
  55772. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55773. }
  55774. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  55775. const bool removeWhenMouseClicked,
  55776. const bool deleteSelfAfterUse)
  55777. {
  55778. setVisible (true);
  55779. deleteAfterUse = deleteSelfAfterUse;
  55780. if (numMillisecondsBeforeRemoving > 0)
  55781. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  55782. else
  55783. expiryTime = 0;
  55784. startTimer (77);
  55785. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  55786. if (! (removeWhenMouseClicked && isShowing()))
  55787. mouseClickCounter += 0xfffff;
  55788. repaint();
  55789. }
  55790. void BubbleMessageComponent::getContentSize (int& w, int& h)
  55791. {
  55792. w = textLayout.getWidth() + 16;
  55793. h = textLayout.getHeight() + 16;
  55794. }
  55795. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  55796. {
  55797. g.setColour (findColour (TooltipWindow::textColourId));
  55798. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  55799. }
  55800. void BubbleMessageComponent::timerCallback()
  55801. {
  55802. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  55803. {
  55804. stopTimer();
  55805. setVisible (false);
  55806. if (deleteAfterUse)
  55807. delete this;
  55808. }
  55809. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  55810. {
  55811. stopTimer();
  55812. fadeOutComponent (fadeOutLength);
  55813. if (deleteAfterUse)
  55814. delete this;
  55815. }
  55816. }
  55817. END_JUCE_NAMESPACE
  55818. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  55819. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  55820. BEGIN_JUCE_NAMESPACE
  55821. static const int swatchesPerRow = 8;
  55822. static const int swatchHeight = 22;
  55823. class ColourComponentSlider : public Slider
  55824. {
  55825. public:
  55826. ColourComponentSlider (const String& name)
  55827. : Slider (name)
  55828. {
  55829. setRange (0.0, 255.0, 1.0);
  55830. }
  55831. ~ColourComponentSlider()
  55832. {
  55833. }
  55834. const String getTextFromValue (double currentValue)
  55835. {
  55836. return String::formatted (T("%02X"), (int)currentValue);
  55837. }
  55838. double getValueFromText (const String& text)
  55839. {
  55840. return (double) text.getHexValue32();
  55841. }
  55842. private:
  55843. ColourComponentSlider (const ColourComponentSlider&);
  55844. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  55845. };
  55846. class ColourSpaceMarker : public Component
  55847. {
  55848. public:
  55849. ColourSpaceMarker()
  55850. {
  55851. setInterceptsMouseClicks (false, false);
  55852. }
  55853. ~ColourSpaceMarker()
  55854. {
  55855. }
  55856. void paint (Graphics& g)
  55857. {
  55858. g.setColour (Colour::greyLevel (0.1f));
  55859. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  55860. g.setColour (Colour::greyLevel (0.9f));
  55861. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  55862. }
  55863. private:
  55864. ColourSpaceMarker (const ColourSpaceMarker&);
  55865. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  55866. };
  55867. class ColourSpaceView : public Component
  55868. {
  55869. ColourSelector* const owner;
  55870. float& h;
  55871. float& s;
  55872. float& v;
  55873. float lastHue;
  55874. ColourSpaceMarker* marker;
  55875. const int edge;
  55876. public:
  55877. ColourSpaceView (ColourSelector* owner_,
  55878. float& h_, float& s_, float& v_,
  55879. const int edgeSize)
  55880. : owner (owner_),
  55881. h (h_), s (s_), v (v_),
  55882. lastHue (0.0f),
  55883. edge (edgeSize)
  55884. {
  55885. addAndMakeVisible (marker = new ColourSpaceMarker());
  55886. setMouseCursor (MouseCursor::CrosshairCursor);
  55887. }
  55888. ~ColourSpaceView()
  55889. {
  55890. deleteAllChildren();
  55891. }
  55892. void paint (Graphics& g)
  55893. {
  55894. const float hue = h;
  55895. const float xScale = 1.0f / (getWidth() - edge * 2);
  55896. const float yScale = 1.0f / (getHeight() - edge * 2);
  55897. const Rectangle clip (g.getClipBounds());
  55898. const int x1 = jmax (clip.getX(), edge) & ~1;
  55899. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  55900. const int y1 = jmax (clip.getY(), edge) & ~1;
  55901. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  55902. for (int y = y1; y < y2; y += 2)
  55903. {
  55904. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  55905. for (int x = x1; x < x2; x += 2)
  55906. {
  55907. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  55908. g.setColour (Colour (hue, s, v, 1.0f));
  55909. g.fillRect (x, y, 2, 2);
  55910. }
  55911. }
  55912. }
  55913. void mouseDown (const MouseEvent& e)
  55914. {
  55915. mouseDrag (e);
  55916. }
  55917. void mouseDrag (const MouseEvent& e)
  55918. {
  55919. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  55920. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  55921. owner->setSV (s, v);
  55922. }
  55923. void updateIfNeeded()
  55924. {
  55925. if (lastHue != h)
  55926. {
  55927. lastHue = h;
  55928. repaint();
  55929. }
  55930. resized();
  55931. }
  55932. void resized()
  55933. {
  55934. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  55935. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  55936. edge * 2, edge * 2);
  55937. }
  55938. private:
  55939. ColourSpaceView (const ColourSpaceView&);
  55940. const ColourSpaceView& operator= (const ColourSpaceView&);
  55941. };
  55942. class HueSelectorMarker : public Component
  55943. {
  55944. public:
  55945. HueSelectorMarker()
  55946. {
  55947. setInterceptsMouseClicks (false, false);
  55948. }
  55949. ~HueSelectorMarker()
  55950. {
  55951. }
  55952. void paint (Graphics& g)
  55953. {
  55954. Path p;
  55955. p.addTriangle (1.0f, 1.0f,
  55956. getWidth() * 0.3f, getHeight() * 0.5f,
  55957. 1.0f, getHeight() - 1.0f);
  55958. p.addTriangle (getWidth() - 1.0f, 1.0f,
  55959. getWidth() * 0.7f, getHeight() * 0.5f,
  55960. getWidth() - 1.0f, getHeight() - 1.0f);
  55961. g.setColour (Colours::white.withAlpha (0.75f));
  55962. g.fillPath (p);
  55963. g.setColour (Colours::black.withAlpha (0.75f));
  55964. g.strokePath (p, PathStrokeType (1.2f));
  55965. }
  55966. private:
  55967. HueSelectorMarker (const HueSelectorMarker&);
  55968. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  55969. };
  55970. class HueSelectorComp : public Component
  55971. {
  55972. public:
  55973. HueSelectorComp (ColourSelector* owner_,
  55974. float& h_, float& s_, float& v_,
  55975. const int edgeSize)
  55976. : owner (owner_),
  55977. h (h_), s (s_), v (v_),
  55978. lastHue (0.0f),
  55979. edge (edgeSize)
  55980. {
  55981. addAndMakeVisible (marker = new HueSelectorMarker());
  55982. }
  55983. ~HueSelectorComp()
  55984. {
  55985. deleteAllChildren();
  55986. }
  55987. void paint (Graphics& g)
  55988. {
  55989. const float yScale = 1.0f / (getHeight() - edge * 2);
  55990. const Rectangle clip (g.getClipBounds());
  55991. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  55992. {
  55993. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  55994. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  55995. }
  55996. }
  55997. void resized()
  55998. {
  55999. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  56000. getWidth(), edge * 2);
  56001. }
  56002. void mouseDown (const MouseEvent& e)
  56003. {
  56004. mouseDrag (e);
  56005. }
  56006. void mouseDrag (const MouseEvent& e)
  56007. {
  56008. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  56009. owner->setHue (hue);
  56010. }
  56011. void updateIfNeeded()
  56012. {
  56013. resized();
  56014. }
  56015. private:
  56016. ColourSelector* const owner;
  56017. float& h;
  56018. float& s;
  56019. float& v;
  56020. float lastHue;
  56021. HueSelectorMarker* marker;
  56022. const int edge;
  56023. HueSelectorComp (const HueSelectorComp&);
  56024. const HueSelectorComp& operator= (const HueSelectorComp&);
  56025. };
  56026. class SwatchComponent : public Component
  56027. {
  56028. public:
  56029. SwatchComponent (ColourSelector* owner_, int index_)
  56030. : owner (owner_),
  56031. index (index_)
  56032. {
  56033. }
  56034. ~SwatchComponent()
  56035. {
  56036. }
  56037. void paint (Graphics& g)
  56038. {
  56039. const Colour colour (owner->getSwatchColour (index));
  56040. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  56041. 6, 6,
  56042. Colour (0xffdddddd).overlaidWith (colour),
  56043. Colour (0xffffffff).overlaidWith (colour));
  56044. }
  56045. void mouseDown (const MouseEvent&)
  56046. {
  56047. PopupMenu m;
  56048. m.addItem (1, TRANS("Use this swatch as the current colour"));
  56049. m.addSeparator();
  56050. m.addItem (2, TRANS("Set this swatch to the current colour"));
  56051. const int r = m.showAt (this);
  56052. if (r == 1)
  56053. {
  56054. owner->setCurrentColour (owner->getSwatchColour (index));
  56055. }
  56056. else if (r == 2)
  56057. {
  56058. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  56059. {
  56060. owner->setSwatchColour (index, owner->getCurrentColour());
  56061. repaint();
  56062. }
  56063. }
  56064. }
  56065. private:
  56066. ColourSelector* const owner;
  56067. const int index;
  56068. SwatchComponent (const SwatchComponent&);
  56069. const SwatchComponent& operator= (const SwatchComponent&);
  56070. };
  56071. ColourSelector::ColourSelector (const int flags_,
  56072. const int edgeGap_,
  56073. const int gapAroundColourSpaceComponent)
  56074. : colour (Colours::white),
  56075. flags (flags_),
  56076. topSpace (0),
  56077. edgeGap (edgeGap_)
  56078. {
  56079. // not much point having a selector with no components in it!
  56080. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  56081. updateHSV();
  56082. if ((flags & showSliders) != 0)
  56083. {
  56084. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  56085. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  56086. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  56087. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  56088. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  56089. for (int i = 4; --i >= 0;)
  56090. sliders[i]->addListener (this);
  56091. }
  56092. else
  56093. {
  56094. zeromem (sliders, sizeof (sliders));
  56095. }
  56096. if ((flags & showColourspace) != 0)
  56097. {
  56098. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  56099. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  56100. }
  56101. else
  56102. {
  56103. colourSpace = 0;
  56104. hueSelector = 0;
  56105. }
  56106. update();
  56107. }
  56108. ColourSelector::~ColourSelector()
  56109. {
  56110. dispatchPendingMessages();
  56111. deleteAllChildren();
  56112. }
  56113. const Colour ColourSelector::getCurrentColour() const
  56114. {
  56115. return ((flags & showAlphaChannel) != 0) ? colour
  56116. : colour.withAlpha ((uint8) 0xff);
  56117. }
  56118. void ColourSelector::setCurrentColour (const Colour& c)
  56119. {
  56120. if (c != colour)
  56121. {
  56122. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  56123. updateHSV();
  56124. update();
  56125. }
  56126. }
  56127. void ColourSelector::setHue (float newH)
  56128. {
  56129. newH = jlimit (0.0f, 1.0f, newH);
  56130. if (h != newH)
  56131. {
  56132. h = newH;
  56133. colour = Colour (h, s, v, colour.getFloatAlpha());
  56134. update();
  56135. }
  56136. }
  56137. void ColourSelector::setSV (float newS, float newV)
  56138. {
  56139. newS = jlimit (0.0f, 1.0f, newS);
  56140. newV = jlimit (0.0f, 1.0f, newV);
  56141. if (s != newS || v != newV)
  56142. {
  56143. s = newS;
  56144. v = newV;
  56145. colour = Colour (h, s, v, colour.getFloatAlpha());
  56146. update();
  56147. }
  56148. }
  56149. void ColourSelector::updateHSV()
  56150. {
  56151. colour.getHSB (h, s, v);
  56152. }
  56153. void ColourSelector::update()
  56154. {
  56155. if (sliders[0] != 0)
  56156. {
  56157. sliders[0]->setValue ((int) colour.getRed());
  56158. sliders[1]->setValue ((int) colour.getGreen());
  56159. sliders[2]->setValue ((int) colour.getBlue());
  56160. sliders[3]->setValue ((int) colour.getAlpha());
  56161. }
  56162. if (colourSpace != 0)
  56163. {
  56164. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  56165. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  56166. }
  56167. if ((flags & showColourAtTop) != 0)
  56168. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  56169. sendChangeMessage (this);
  56170. }
  56171. void ColourSelector::paint (Graphics& g)
  56172. {
  56173. g.fillAll (findColour (backgroundColourId));
  56174. if ((flags & showColourAtTop) != 0)
  56175. {
  56176. const Colour colour (getCurrentColour());
  56177. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  56178. 10, 10,
  56179. Colour (0xffdddddd).overlaidWith (colour),
  56180. Colour (0xffffffff).overlaidWith (colour));
  56181. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  56182. g.setFont (14.0f, true);
  56183. g.drawText (((flags & showAlphaChannel) != 0)
  56184. ? String::formatted (T("#%02X%02X%02X%02X"),
  56185. (int) colour.getAlpha(),
  56186. (int) colour.getRed(),
  56187. (int) colour.getGreen(),
  56188. (int) colour.getBlue())
  56189. : String::formatted (T("#%02X%02X%02X"),
  56190. (int) colour.getRed(),
  56191. (int) colour.getGreen(),
  56192. (int) colour.getBlue()),
  56193. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  56194. Justification::centred, false);
  56195. }
  56196. if ((flags & showSliders) != 0)
  56197. {
  56198. g.setColour (findColour (labelTextColourId));
  56199. g.setFont (11.0f);
  56200. for (int i = 4; --i >= 0;)
  56201. {
  56202. if (sliders[i]->isVisible())
  56203. g.drawText (sliders[i]->getName() + T(":"),
  56204. 0, sliders[i]->getY(),
  56205. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  56206. Justification::centredRight, false);
  56207. }
  56208. }
  56209. }
  56210. void ColourSelector::resized()
  56211. {
  56212. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  56213. const int numSwatches = getNumSwatches();
  56214. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  56215. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  56216. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  56217. int y = topSpace;
  56218. if ((flags & showColourspace) != 0)
  56219. {
  56220. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  56221. colourSpace->setBounds (edgeGap, y,
  56222. getWidth() - hueWidth - edgeGap - 4,
  56223. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  56224. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  56225. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  56226. colourSpace->getHeight());
  56227. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  56228. }
  56229. if ((flags & showSliders) != 0)
  56230. {
  56231. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  56232. for (int i = 0; i < numSliders; ++i)
  56233. {
  56234. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  56235. proportionOfWidth (0.72f), sliderHeight - 2);
  56236. y += sliderHeight;
  56237. }
  56238. }
  56239. if (numSwatches > 0)
  56240. {
  56241. const int startX = 8;
  56242. const int xGap = 4;
  56243. const int yGap = 4;
  56244. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  56245. y += edgeGap;
  56246. if (swatchComponents.size() != numSwatches)
  56247. {
  56248. int i;
  56249. for (i = swatchComponents.size(); --i >= 0;)
  56250. {
  56251. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56252. delete sc;
  56253. }
  56254. for (i = 0; i < numSwatches; ++i)
  56255. {
  56256. SwatchComponent* const sc = new SwatchComponent (this, i);
  56257. swatchComponents.add (sc);
  56258. addAndMakeVisible (sc);
  56259. }
  56260. }
  56261. int x = startX;
  56262. for (int i = 0; i < swatchComponents.size(); ++i)
  56263. {
  56264. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56265. sc->setBounds (x + xGap / 2,
  56266. y + yGap / 2,
  56267. swatchWidth - xGap,
  56268. swatchHeight - yGap);
  56269. if (((i + 1) % swatchesPerRow) == 0)
  56270. {
  56271. x = startX;
  56272. y += swatchHeight;
  56273. }
  56274. else
  56275. {
  56276. x += swatchWidth;
  56277. }
  56278. }
  56279. }
  56280. }
  56281. void ColourSelector::sliderValueChanged (Slider*)
  56282. {
  56283. if (sliders[0] != 0)
  56284. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  56285. (uint8) sliders[1]->getValue(),
  56286. (uint8) sliders[2]->getValue(),
  56287. (uint8) sliders[3]->getValue()));
  56288. }
  56289. int ColourSelector::getNumSwatches() const
  56290. {
  56291. return 0;
  56292. }
  56293. const Colour ColourSelector::getSwatchColour (const int) const
  56294. {
  56295. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56296. return Colours::black;
  56297. }
  56298. void ColourSelector::setSwatchColour (const int, const Colour&) const
  56299. {
  56300. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56301. }
  56302. END_JUCE_NAMESPACE
  56303. /********* End of inlined file: juce_ColourSelector.cpp *********/
  56304. /********* Start of inlined file: juce_DropShadower.cpp *********/
  56305. BEGIN_JUCE_NAMESPACE
  56306. class ShadowWindow : public Component
  56307. {
  56308. Component* owner;
  56309. Image** shadowImageSections;
  56310. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  56311. public:
  56312. ShadowWindow (Component* const owner_,
  56313. const int type_,
  56314. Image** const shadowImageSections_)
  56315. : owner (owner_),
  56316. shadowImageSections (shadowImageSections_),
  56317. type (type_)
  56318. {
  56319. setInterceptsMouseClicks (false, false);
  56320. if (owner_->isOnDesktop())
  56321. {
  56322. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  56323. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56324. | ComponentPeer::windowIsTemporary);
  56325. }
  56326. else if (owner_->getParentComponent() != 0)
  56327. {
  56328. owner_->getParentComponent()->addChildComponent (this);
  56329. }
  56330. }
  56331. ~ShadowWindow()
  56332. {
  56333. }
  56334. void paint (Graphics& g)
  56335. {
  56336. Image* const topLeft = shadowImageSections [type * 3];
  56337. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  56338. Image* const filler = shadowImageSections [type * 3 + 2];
  56339. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  56340. g.setOpacity (1.0f);
  56341. if (type < 2)
  56342. {
  56343. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  56344. g.drawImage (topLeft,
  56345. 0, 0, topLeft->getWidth(), imH,
  56346. 0, 0, topLeft->getWidth(), imH);
  56347. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  56348. g.drawImage (bottomRight,
  56349. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  56350. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  56351. g.setBrush (&fillBrush);
  56352. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  56353. }
  56354. else
  56355. {
  56356. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  56357. g.drawImage (topLeft,
  56358. 0, 0, imW, topLeft->getHeight(),
  56359. 0, 0, imW, topLeft->getHeight());
  56360. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  56361. g.drawImage (bottomRight,
  56362. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  56363. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  56364. g.setBrush (&fillBrush);
  56365. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  56366. }
  56367. }
  56368. void resized()
  56369. {
  56370. repaint(); // (needed for correct repainting)
  56371. }
  56372. private:
  56373. ShadowWindow (const ShadowWindow&);
  56374. const ShadowWindow& operator= (const ShadowWindow&);
  56375. };
  56376. DropShadower::DropShadower (const float alpha_,
  56377. const int xOffset_,
  56378. const int yOffset_,
  56379. const float blurRadius_)
  56380. : owner (0),
  56381. numShadows (0),
  56382. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  56383. xOffset (xOffset_),
  56384. yOffset (yOffset_),
  56385. alpha (alpha_),
  56386. blurRadius (blurRadius_),
  56387. inDestructor (false),
  56388. reentrant (false)
  56389. {
  56390. }
  56391. DropShadower::~DropShadower()
  56392. {
  56393. if (owner != 0)
  56394. owner->removeComponentListener (this);
  56395. inDestructor = true;
  56396. deleteShadowWindows();
  56397. }
  56398. void DropShadower::deleteShadowWindows()
  56399. {
  56400. if (numShadows > 0)
  56401. {
  56402. int i;
  56403. for (i = numShadows; --i >= 0;)
  56404. delete shadowWindows[i];
  56405. for (i = 12; --i >= 0;)
  56406. delete shadowImageSections[i];
  56407. numShadows = 0;
  56408. }
  56409. }
  56410. void DropShadower::setOwner (Component* componentToFollow)
  56411. {
  56412. if (componentToFollow != owner)
  56413. {
  56414. if (owner != 0)
  56415. owner->removeComponentListener (this);
  56416. // (the component can't be null)
  56417. jassert (componentToFollow != 0);
  56418. owner = componentToFollow;
  56419. jassert (owner != 0);
  56420. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  56421. owner->addComponentListener (this);
  56422. updateShadows();
  56423. }
  56424. }
  56425. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  56426. {
  56427. updateShadows();
  56428. }
  56429. void DropShadower::componentBroughtToFront (Component&)
  56430. {
  56431. bringShadowWindowsToFront();
  56432. }
  56433. void DropShadower::componentChildrenChanged (Component&)
  56434. {
  56435. }
  56436. void DropShadower::componentParentHierarchyChanged (Component&)
  56437. {
  56438. deleteShadowWindows();
  56439. updateShadows();
  56440. }
  56441. void DropShadower::componentVisibilityChanged (Component&)
  56442. {
  56443. updateShadows();
  56444. }
  56445. void DropShadower::updateShadows()
  56446. {
  56447. if (reentrant || inDestructor || (owner == 0))
  56448. return;
  56449. reentrant = true;
  56450. ComponentPeer* const nw = owner->getPeer();
  56451. const bool isOwnerVisible = owner->isVisible()
  56452. && (nw == 0 || ! nw->isMinimised());
  56453. const bool createShadowWindows = numShadows == 0
  56454. && owner->getWidth() > 0
  56455. && owner->getHeight() > 0
  56456. && isOwnerVisible
  56457. && (Desktop::canUseSemiTransparentWindows()
  56458. || owner->getParentComponent() != 0);
  56459. if (createShadowWindows)
  56460. {
  56461. // keep a cached version of the image to save doing the gaussian too often
  56462. String imageId;
  56463. imageId << shadowEdge << T(',')
  56464. << xOffset << T(',')
  56465. << yOffset << T(',')
  56466. << alpha;
  56467. const int hash = imageId.hashCode();
  56468. Image* bigIm = ImageCache::getFromHashCode (hash);
  56469. if (bigIm == 0)
  56470. {
  56471. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  56472. Graphics bigG (*bigIm);
  56473. bigG.setColour (Colours::black.withAlpha (alpha));
  56474. bigG.fillRect (shadowEdge + xOffset,
  56475. shadowEdge + yOffset,
  56476. bigIm->getWidth() - (shadowEdge * 2),
  56477. bigIm->getHeight() - (shadowEdge * 2));
  56478. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  56479. blurKernel.createGaussianBlur (blurRadius);
  56480. blurKernel.applyToImage (*bigIm, 0,
  56481. xOffset,
  56482. yOffset,
  56483. bigIm->getWidth(),
  56484. bigIm->getHeight());
  56485. ImageCache::addImageToCache (bigIm, hash);
  56486. }
  56487. const int iw = bigIm->getWidth();
  56488. const int ih = bigIm->getHeight();
  56489. const int shadowEdge2 = shadowEdge * 2;
  56490. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  56491. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  56492. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  56493. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  56494. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  56495. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  56496. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  56497. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  56498. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  56499. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  56500. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  56501. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  56502. ImageCache::release (bigIm);
  56503. for (int i = 0; i < 4; ++i)
  56504. {
  56505. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  56506. ++numShadows;
  56507. }
  56508. }
  56509. if (numShadows > 0)
  56510. {
  56511. for (int i = numShadows; --i >= 0;)
  56512. {
  56513. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  56514. shadowWindows[i]->setVisible (isOwnerVisible);
  56515. }
  56516. const int x = owner->getX();
  56517. const int y = owner->getY() - shadowEdge;
  56518. const int w = owner->getWidth();
  56519. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  56520. shadowWindows[0]->setBounds (x - shadowEdge,
  56521. y,
  56522. shadowEdge,
  56523. h);
  56524. shadowWindows[1]->setBounds (x + w,
  56525. y,
  56526. shadowEdge,
  56527. h);
  56528. shadowWindows[2]->setBounds (x,
  56529. y,
  56530. w,
  56531. shadowEdge);
  56532. shadowWindows[3]->setBounds (x,
  56533. owner->getBottom(),
  56534. w,
  56535. shadowEdge);
  56536. }
  56537. reentrant = false;
  56538. if (createShadowWindows)
  56539. bringShadowWindowsToFront();
  56540. }
  56541. void DropShadower::setShadowImage (Image* const src,
  56542. const int num,
  56543. const int w,
  56544. const int h,
  56545. const int sx,
  56546. const int sy) throw()
  56547. {
  56548. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  56549. Graphics g (*shadowImageSections[num]);
  56550. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  56551. }
  56552. void DropShadower::bringShadowWindowsToFront()
  56553. {
  56554. if (! (inDestructor || reentrant))
  56555. {
  56556. updateShadows();
  56557. reentrant = true;
  56558. for (int i = numShadows; --i >= 0;)
  56559. shadowWindows[i]->toBehind (owner);
  56560. reentrant = false;
  56561. }
  56562. }
  56563. END_JUCE_NAMESPACE
  56564. /********* End of inlined file: juce_DropShadower.cpp *********/
  56565. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  56566. BEGIN_JUCE_NAMESPACE
  56567. class MagnifyingPeer : public ComponentPeer
  56568. {
  56569. public:
  56570. MagnifyingPeer (Component* const component_,
  56571. MagnifierComponent* const magnifierComp_)
  56572. : ComponentPeer (component_, 0),
  56573. magnifierComp (magnifierComp_)
  56574. {
  56575. }
  56576. ~MagnifyingPeer()
  56577. {
  56578. }
  56579. void* getNativeHandle() const { return 0; }
  56580. void setVisible (bool) {}
  56581. void setTitle (const String&) {}
  56582. void setPosition (int, int) {}
  56583. void setSize (int, int) {}
  56584. void setBounds (int, int, int, int, const bool) {}
  56585. void setMinimised (bool) {}
  56586. bool isMinimised() const { return false; }
  56587. void setFullScreen (bool) {}
  56588. bool isFullScreen() const { return false; }
  56589. const BorderSize getFrameSize() const { return BorderSize (0); }
  56590. bool setAlwaysOnTop (bool) { return true; }
  56591. void toFront (bool) {}
  56592. void toBehind (ComponentPeer*) {}
  56593. void setIcon (const Image&) {}
  56594. bool isFocused() const
  56595. {
  56596. return magnifierComp->hasKeyboardFocus (true);
  56597. }
  56598. void grabFocus()
  56599. {
  56600. ComponentPeer* peer = magnifierComp->getPeer();
  56601. if (peer != 0)
  56602. peer->grabFocus();
  56603. }
  56604. void textInputRequired (int x, int y)
  56605. {
  56606. ComponentPeer* peer = magnifierComp->getPeer();
  56607. if (peer != 0)
  56608. peer->textInputRequired (x, y);
  56609. }
  56610. void getBounds (int& x, int& y, int& w, int& h) const
  56611. {
  56612. x = magnifierComp->getScreenX();
  56613. y = magnifierComp->getScreenY();
  56614. w = component->getWidth();
  56615. h = component->getHeight();
  56616. }
  56617. int getScreenX() const { return magnifierComp->getScreenX(); }
  56618. int getScreenY() const { return magnifierComp->getScreenY(); }
  56619. void relativePositionToGlobal (int& x, int& y)
  56620. {
  56621. const double zoom = magnifierComp->getScaleFactor();
  56622. x = roundDoubleToInt (x * zoom);
  56623. y = roundDoubleToInt (y * zoom);
  56624. magnifierComp->relativePositionToGlobal (x, y);
  56625. }
  56626. void globalPositionToRelative (int& x, int& y)
  56627. {
  56628. magnifierComp->globalPositionToRelative (x, y);
  56629. const double zoom = magnifierComp->getScaleFactor();
  56630. x = roundDoubleToInt (x / zoom);
  56631. y = roundDoubleToInt (y / zoom);
  56632. }
  56633. bool contains (int x, int y, bool) const
  56634. {
  56635. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  56636. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  56637. }
  56638. void repaint (int x, int y, int w, int h)
  56639. {
  56640. const double zoom = magnifierComp->getScaleFactor();
  56641. magnifierComp->repaint ((int) (x * zoom),
  56642. (int) (y * zoom),
  56643. roundDoubleToInt (w * zoom) + 1,
  56644. roundDoubleToInt (h * zoom) + 1);
  56645. }
  56646. void performAnyPendingRepaintsNow()
  56647. {
  56648. }
  56649. juce_UseDebuggingNewOperator
  56650. private:
  56651. MagnifierComponent* const magnifierComp;
  56652. MagnifyingPeer (const MagnifyingPeer&);
  56653. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  56654. };
  56655. class PeerHolderComp : public Component
  56656. {
  56657. public:
  56658. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  56659. : magnifierComp (magnifierComp_)
  56660. {
  56661. setVisible (true);
  56662. }
  56663. ~PeerHolderComp()
  56664. {
  56665. }
  56666. ComponentPeer* createNewPeer (int, void*)
  56667. {
  56668. return new MagnifyingPeer (this, magnifierComp);
  56669. }
  56670. void childBoundsChanged (Component* c)
  56671. {
  56672. if (c != 0)
  56673. {
  56674. setSize (c->getWidth(), c->getHeight());
  56675. magnifierComp->childBoundsChanged (this);
  56676. }
  56677. }
  56678. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56679. {
  56680. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  56681. Component* const p = magnifierComp->getParentComponent();
  56682. if (p != 0)
  56683. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  56684. }
  56685. private:
  56686. MagnifierComponent* const magnifierComp;
  56687. PeerHolderComp (const PeerHolderComp&);
  56688. const PeerHolderComp& operator= (const PeerHolderComp&);
  56689. };
  56690. MagnifierComponent::MagnifierComponent (Component* const content_,
  56691. const bool deleteContentCompWhenNoLongerNeeded)
  56692. : content (content_),
  56693. scaleFactor (0.0),
  56694. peer (0),
  56695. deleteContent (deleteContentCompWhenNoLongerNeeded),
  56696. quality (Graphics::lowResamplingQuality)
  56697. {
  56698. holderComp = new PeerHolderComp (this);
  56699. setScaleFactor (1.0);
  56700. }
  56701. MagnifierComponent::~MagnifierComponent()
  56702. {
  56703. delete holderComp;
  56704. if (deleteContent)
  56705. delete content;
  56706. }
  56707. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  56708. {
  56709. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  56710. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  56711. if (scaleFactor != newScaleFactor)
  56712. {
  56713. scaleFactor = newScaleFactor;
  56714. if (scaleFactor == 1.0)
  56715. {
  56716. holderComp->removeFromDesktop();
  56717. peer = 0;
  56718. addChildComponent (content);
  56719. childBoundsChanged (content);
  56720. }
  56721. else
  56722. {
  56723. holderComp->addAndMakeVisible (content);
  56724. holderComp->childBoundsChanged (content);
  56725. childBoundsChanged (holderComp);
  56726. holderComp->addToDesktop (0);
  56727. peer = holderComp->getPeer();
  56728. }
  56729. repaint();
  56730. }
  56731. }
  56732. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  56733. {
  56734. quality = newQuality;
  56735. }
  56736. void MagnifierComponent::paint (Graphics& g)
  56737. {
  56738. const int w = holderComp->getWidth();
  56739. const int h = holderComp->getHeight();
  56740. if (w == 0 || h == 0)
  56741. return;
  56742. const Rectangle r (g.getClipBounds());
  56743. const int srcX = (int) (r.getX() / scaleFactor);
  56744. const int srcY = (int) (r.getY() / scaleFactor);
  56745. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  56746. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  56747. if (scaleFactor >= 1.0)
  56748. {
  56749. ++srcW;
  56750. ++srcH;
  56751. }
  56752. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  56753. temp.clear (srcX, srcY, srcW, srcH);
  56754. Graphics g2 (temp);
  56755. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  56756. holderComp->paintEntireComponent (g2);
  56757. g.setImageResamplingQuality (quality);
  56758. g.drawImage (&temp,
  56759. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  56760. 0, 0, w, h,
  56761. false);
  56762. }
  56763. void MagnifierComponent::childBoundsChanged (Component* c)
  56764. {
  56765. if (c != 0)
  56766. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  56767. roundDoubleToInt (c->getHeight() * scaleFactor));
  56768. }
  56769. void MagnifierComponent::mouseDown (const MouseEvent& e)
  56770. {
  56771. if (peer != 0)
  56772. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56773. }
  56774. void MagnifierComponent::mouseUp (const MouseEvent& e)
  56775. {
  56776. if (peer != 0)
  56777. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56778. }
  56779. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  56780. {
  56781. if (peer != 0)
  56782. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56783. }
  56784. void MagnifierComponent::mouseMove (const MouseEvent& e)
  56785. {
  56786. if (peer != 0)
  56787. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56788. }
  56789. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  56790. {
  56791. if (peer != 0)
  56792. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56793. }
  56794. void MagnifierComponent::mouseExit (const MouseEvent& e)
  56795. {
  56796. if (peer != 0)
  56797. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56798. }
  56799. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56800. {
  56801. if (peer != 0)
  56802. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  56803. roundFloatToInt (iy * 256.0f),
  56804. e.eventTime.toMilliseconds());
  56805. else
  56806. Component::mouseWheelMove (e, ix, iy);
  56807. }
  56808. int MagnifierComponent::scaleInt (const int n) const throw()
  56809. {
  56810. return roundDoubleToInt (n / scaleFactor);
  56811. }
  56812. END_JUCE_NAMESPACE
  56813. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  56814. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  56815. BEGIN_JUCE_NAMESPACE
  56816. class MidiKeyboardUpDownButton : public Button
  56817. {
  56818. public:
  56819. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  56820. const int delta_)
  56821. : Button (String::empty),
  56822. owner (owner_),
  56823. delta (delta_)
  56824. {
  56825. setOpaque (true);
  56826. }
  56827. ~MidiKeyboardUpDownButton()
  56828. {
  56829. }
  56830. void clicked()
  56831. {
  56832. int note = owner->getLowestVisibleKey();
  56833. if (delta < 0)
  56834. note = (note - 1) / 12;
  56835. else
  56836. note = note / 12 + 1;
  56837. owner->setLowestVisibleKey (note * 12);
  56838. }
  56839. void paintButton (Graphics& g,
  56840. bool isMouseOverButton,
  56841. bool isButtonDown)
  56842. {
  56843. owner->drawUpDownButton (g, getWidth(), getHeight(),
  56844. isMouseOverButton, isButtonDown,
  56845. delta > 0);
  56846. }
  56847. private:
  56848. MidiKeyboardComponent* const owner;
  56849. const int delta;
  56850. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  56851. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  56852. };
  56853. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  56854. const Orientation orientation_)
  56855. : state (state_),
  56856. xOffset (0),
  56857. blackNoteLength (1),
  56858. keyWidth (16.0f),
  56859. orientation (orientation_),
  56860. midiChannel (1),
  56861. midiInChannelMask (0xffff),
  56862. velocity (1.0f),
  56863. noteUnderMouse (-1),
  56864. mouseDownNote (-1),
  56865. rangeStart (0),
  56866. rangeEnd (127),
  56867. firstKey (12 * 4),
  56868. canScroll (true),
  56869. mouseDragging (false),
  56870. keyPresses (4),
  56871. keyPressNotes (16),
  56872. keyMappingOctave (6),
  56873. octaveNumForMiddleC (3)
  56874. {
  56875. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  56876. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  56877. // initialise with a default set of querty key-mappings..
  56878. const char* const keymap = "awsedftgyhujkolp;";
  56879. for (int i = String (keymap).length(); --i >= 0;)
  56880. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  56881. setOpaque (true);
  56882. setWantsKeyboardFocus (true);
  56883. state.addListener (this);
  56884. }
  56885. MidiKeyboardComponent::~MidiKeyboardComponent()
  56886. {
  56887. state.removeListener (this);
  56888. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  56889. deleteAllChildren();
  56890. }
  56891. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  56892. {
  56893. keyWidth = widthInPixels;
  56894. resized();
  56895. }
  56896. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  56897. {
  56898. if (orientation != newOrientation)
  56899. {
  56900. orientation = newOrientation;
  56901. resized();
  56902. }
  56903. }
  56904. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  56905. const int highestNote)
  56906. {
  56907. jassert (lowestNote >= 0 && lowestNote <= 127);
  56908. jassert (highestNote >= 0 && highestNote <= 127);
  56909. jassert (lowestNote <= highestNote);
  56910. if (rangeStart != lowestNote || rangeEnd != highestNote)
  56911. {
  56912. rangeStart = jlimit (0, 127, lowestNote);
  56913. rangeEnd = jlimit (0, 127, highestNote);
  56914. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  56915. resized();
  56916. }
  56917. }
  56918. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  56919. {
  56920. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  56921. if (noteNumber != firstKey)
  56922. {
  56923. firstKey = noteNumber;
  56924. sendChangeMessage (this);
  56925. resized();
  56926. }
  56927. }
  56928. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  56929. {
  56930. if (canScroll != canScroll_)
  56931. {
  56932. canScroll = canScroll_;
  56933. resized();
  56934. }
  56935. }
  56936. void MidiKeyboardComponent::colourChanged()
  56937. {
  56938. repaint();
  56939. }
  56940. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  56941. {
  56942. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  56943. if (midiChannel != midiChannelNumber)
  56944. {
  56945. resetAnyKeysInUse();
  56946. midiChannel = jlimit (1, 16, midiChannelNumber);
  56947. }
  56948. }
  56949. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  56950. {
  56951. midiInChannelMask = midiChannelMask;
  56952. triggerAsyncUpdate();
  56953. }
  56954. void MidiKeyboardComponent::setVelocity (const float velocity_)
  56955. {
  56956. velocity = jlimit (0.0f, 1.0f, velocity_);
  56957. }
  56958. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  56959. {
  56960. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  56961. static const float blackNoteWidth = 0.7f;
  56962. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  56963. 1.0f, 2 - blackNoteWidth * 0.4f,
  56964. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  56965. 4.0f, 5 - blackNoteWidth * 0.5f,
  56966. 5.0f, 6 - blackNoteWidth * 0.3f,
  56967. 6.0f };
  56968. static const float widths[] = { 1.0f, blackNoteWidth,
  56969. 1.0f, blackNoteWidth,
  56970. 1.0f, 1.0f, blackNoteWidth,
  56971. 1.0f, blackNoteWidth,
  56972. 1.0f, blackNoteWidth,
  56973. 1.0f };
  56974. const int octave = midiNoteNumber / 12;
  56975. const int note = midiNoteNumber % 12;
  56976. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  56977. w = roundFloatToInt (widths [note] * keyWidth);
  56978. }
  56979. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  56980. {
  56981. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  56982. int rx, rw;
  56983. getKeyPosition (rangeStart, keyWidth, rx, rw);
  56984. x -= xOffset + rx;
  56985. }
  56986. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  56987. {
  56988. int x, y;
  56989. getKeyPos (midiNoteNumber, x, y);
  56990. return x;
  56991. }
  56992. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  56993. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  56994. int MidiKeyboardComponent::xyToNote (int x, int y)
  56995. {
  56996. if (! reallyContains (x, y, false))
  56997. return -1;
  56998. if (orientation != horizontalKeyboard)
  56999. {
  57000. swapVariables (x, y);
  57001. if (orientation == verticalKeyboardFacingLeft)
  57002. y = getWidth() - y;
  57003. else
  57004. x = getHeight() - x;
  57005. }
  57006. return remappedXYToNote (x + xOffset, y);
  57007. }
  57008. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  57009. {
  57010. if (y < blackNoteLength)
  57011. {
  57012. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57013. {
  57014. for (int i = 0; i < 5; ++i)
  57015. {
  57016. const int note = octaveStart + blackNotes [i];
  57017. if (note >= rangeStart && note <= rangeEnd)
  57018. {
  57019. int kx, kw;
  57020. getKeyPos (note, kx, kw);
  57021. kx += xOffset;
  57022. if (x >= kx && x < kx + kw)
  57023. return note;
  57024. }
  57025. }
  57026. }
  57027. }
  57028. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57029. {
  57030. for (int i = 0; i < 7; ++i)
  57031. {
  57032. const int note = octaveStart + whiteNotes [i];
  57033. if (note >= rangeStart && note <= rangeEnd)
  57034. {
  57035. int kx, kw;
  57036. getKeyPos (note, kx, kw);
  57037. kx += xOffset;
  57038. if (x >= kx && x < kx + kw)
  57039. return note;
  57040. }
  57041. }
  57042. }
  57043. return -1;
  57044. }
  57045. void MidiKeyboardComponent::repaintNote (const int noteNum)
  57046. {
  57047. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57048. {
  57049. int x, w;
  57050. getKeyPos (noteNum, x, w);
  57051. if (orientation == horizontalKeyboard)
  57052. repaint (x, 0, w, getHeight());
  57053. else if (orientation == verticalKeyboardFacingLeft)
  57054. repaint (0, x, getWidth(), w);
  57055. else if (orientation == verticalKeyboardFacingRight)
  57056. repaint (0, getHeight() - x - w, getWidth(), w);
  57057. }
  57058. }
  57059. void MidiKeyboardComponent::paint (Graphics& g)
  57060. {
  57061. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  57062. const Colour lineColour (findColour (keySeparatorLineColourId));
  57063. const Colour textColour (findColour (textLabelColourId));
  57064. int x, w, octave;
  57065. for (octave = 0; octave < 128; octave += 12)
  57066. {
  57067. for (int white = 0; white < 7; ++white)
  57068. {
  57069. const int noteNum = octave + whiteNotes [white];
  57070. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57071. {
  57072. getKeyPos (noteNum, x, w);
  57073. if (orientation == horizontalKeyboard)
  57074. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  57075. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57076. noteUnderMouse == noteNum,
  57077. lineColour, textColour);
  57078. else if (orientation == verticalKeyboardFacingLeft)
  57079. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  57080. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57081. noteUnderMouse == noteNum,
  57082. lineColour, textColour);
  57083. else if (orientation == verticalKeyboardFacingRight)
  57084. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  57085. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57086. noteUnderMouse == noteNum,
  57087. lineColour, textColour);
  57088. }
  57089. }
  57090. }
  57091. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  57092. if (orientation == verticalKeyboardFacingLeft)
  57093. {
  57094. x1 = getWidth() - 1.0f;
  57095. x2 = getWidth() - 5.0f;
  57096. }
  57097. else if (orientation == verticalKeyboardFacingRight)
  57098. x2 = 5.0f;
  57099. else
  57100. y2 = 5.0f;
  57101. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  57102. Colours::transparentBlack, x2, y2, false);
  57103. g.setBrush (&gb);
  57104. getKeyPos (rangeEnd, x, w);
  57105. x += w;
  57106. if (orientation == verticalKeyboardFacingLeft)
  57107. g.fillRect (getWidth() - 5, 0, 5, x);
  57108. else if (orientation == verticalKeyboardFacingRight)
  57109. g.fillRect (0, 0, 5, x);
  57110. else
  57111. g.fillRect (0, 0, x, 5);
  57112. g.setColour (lineColour);
  57113. if (orientation == verticalKeyboardFacingLeft)
  57114. g.fillRect (0, 0, 1, x);
  57115. else if (orientation == verticalKeyboardFacingRight)
  57116. g.fillRect (getWidth() - 1, 0, 1, x);
  57117. else
  57118. g.fillRect (0, getHeight() - 1, x, 1);
  57119. const Colour blackNoteColour (findColour (blackNoteColourId));
  57120. for (octave = 0; octave < 128; octave += 12)
  57121. {
  57122. for (int black = 0; black < 5; ++black)
  57123. {
  57124. const int noteNum = octave + blackNotes [black];
  57125. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57126. {
  57127. getKeyPos (noteNum, x, w);
  57128. if (orientation == horizontalKeyboard)
  57129. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  57130. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57131. noteUnderMouse == noteNum,
  57132. blackNoteColour);
  57133. else if (orientation == verticalKeyboardFacingLeft)
  57134. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  57135. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57136. noteUnderMouse == noteNum,
  57137. blackNoteColour);
  57138. else if (orientation == verticalKeyboardFacingRight)
  57139. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  57140. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57141. noteUnderMouse == noteNum,
  57142. blackNoteColour);
  57143. }
  57144. }
  57145. }
  57146. }
  57147. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  57148. Graphics& g, int x, int y, int w, int h,
  57149. bool isDown, bool isOver,
  57150. const Colour& lineColour,
  57151. const Colour& textColour)
  57152. {
  57153. Colour c (Colours::transparentWhite);
  57154. if (isDown)
  57155. c = findColour (keyDownOverlayColourId);
  57156. if (isOver)
  57157. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57158. g.setColour (c);
  57159. g.fillRect (x, y, w, h);
  57160. const String text (getWhiteNoteText (midiNoteNumber));
  57161. if (! text.isEmpty())
  57162. {
  57163. g.setColour (textColour);
  57164. Font f (jmin (12.0f, keyWidth * 0.9f));
  57165. f.setHorizontalScale (0.8f);
  57166. g.setFont (f);
  57167. Justification justification (Justification::centredBottom);
  57168. if (orientation == verticalKeyboardFacingLeft)
  57169. justification = Justification::centredLeft;
  57170. else if (orientation == verticalKeyboardFacingRight)
  57171. justification = Justification::centredRight;
  57172. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  57173. }
  57174. g.setColour (lineColour);
  57175. if (orientation == horizontalKeyboard)
  57176. g.fillRect (x, y, 1, h);
  57177. else if (orientation == verticalKeyboardFacingLeft)
  57178. g.fillRect (x, y, w, 1);
  57179. else if (orientation == verticalKeyboardFacingRight)
  57180. g.fillRect (x, y + h - 1, w, 1);
  57181. if (midiNoteNumber == rangeEnd)
  57182. {
  57183. if (orientation == horizontalKeyboard)
  57184. g.fillRect (x + w, y, 1, h);
  57185. else if (orientation == verticalKeyboardFacingLeft)
  57186. g.fillRect (x, y + h, w, 1);
  57187. else if (orientation == verticalKeyboardFacingRight)
  57188. g.fillRect (x, y - 1, w, 1);
  57189. }
  57190. }
  57191. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  57192. Graphics& g, int x, int y, int w, int h,
  57193. bool isDown, bool isOver,
  57194. const Colour& noteFillColour)
  57195. {
  57196. Colour c (noteFillColour);
  57197. if (isDown)
  57198. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  57199. if (isOver)
  57200. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57201. g.setColour (c);
  57202. g.fillRect (x, y, w, h);
  57203. if (isDown)
  57204. {
  57205. g.setColour (noteFillColour);
  57206. g.drawRect (x, y, w, h);
  57207. }
  57208. else
  57209. {
  57210. const int xIndent = jmax (1, jmin (w, h) / 8);
  57211. g.setColour (c.brighter());
  57212. if (orientation == horizontalKeyboard)
  57213. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  57214. else if (orientation == verticalKeyboardFacingLeft)
  57215. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  57216. else if (orientation == verticalKeyboardFacingRight)
  57217. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  57218. }
  57219. }
  57220. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  57221. {
  57222. octaveNumForMiddleC = octaveNumForMiddleC_;
  57223. repaint();
  57224. }
  57225. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  57226. {
  57227. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  57228. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  57229. return String::empty;
  57230. }
  57231. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  57232. const bool isMouseOver,
  57233. const bool isButtonDown,
  57234. const bool movesOctavesUp)
  57235. {
  57236. g.fillAll (findColour (upDownButtonBackgroundColourId));
  57237. float angle;
  57238. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  57239. angle = movesOctavesUp ? 0.0f : 0.5f;
  57240. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  57241. angle = movesOctavesUp ? 0.25f : 0.75f;
  57242. else
  57243. angle = movesOctavesUp ? 0.75f : 0.25f;
  57244. Path path;
  57245. path.lineTo (0.0f, 1.0f);
  57246. path.lineTo (1.0f, 0.5f);
  57247. path.closeSubPath();
  57248. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  57249. g.setColour (findColour (upDownButtonArrowColourId)
  57250. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  57251. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  57252. w - 2.0f,
  57253. h - 2.0f,
  57254. true));
  57255. }
  57256. void MidiKeyboardComponent::resized()
  57257. {
  57258. int w = getWidth();
  57259. int h = getHeight();
  57260. if (w > 0 && h > 0)
  57261. {
  57262. if (orientation != horizontalKeyboard)
  57263. swapVariables (w, h);
  57264. blackNoteLength = roundFloatToInt (h * 0.7f);
  57265. int kx2, kw2;
  57266. getKeyPos (rangeEnd, kx2, kw2);
  57267. kx2 += kw2;
  57268. if (firstKey != rangeStart)
  57269. {
  57270. int kx1, kw1;
  57271. getKeyPos (rangeStart, kx1, kw1);
  57272. if (kx2 - kx1 <= w)
  57273. {
  57274. firstKey = rangeStart;
  57275. sendChangeMessage (this);
  57276. repaint();
  57277. }
  57278. }
  57279. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  57280. scrollDown->setVisible (showScrollButtons);
  57281. scrollUp->setVisible (showScrollButtons);
  57282. xOffset = 0;
  57283. if (showScrollButtons)
  57284. {
  57285. const int scrollButtonW = jmin (12, w / 2);
  57286. if (orientation == horizontalKeyboard)
  57287. {
  57288. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  57289. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  57290. }
  57291. else if (orientation == verticalKeyboardFacingLeft)
  57292. {
  57293. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  57294. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57295. }
  57296. else if (orientation == verticalKeyboardFacingRight)
  57297. {
  57298. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57299. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  57300. }
  57301. int endOfLastKey, kw;
  57302. getKeyPos (rangeEnd, endOfLastKey, kw);
  57303. endOfLastKey += kw;
  57304. const int spaceAvailable = w - scrollButtonW * 2;
  57305. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  57306. if (lastStartKey >= 0 && firstKey > lastStartKey)
  57307. {
  57308. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  57309. sendChangeMessage (this);
  57310. }
  57311. int newOffset = 0;
  57312. getKeyPos (firstKey, newOffset, kw);
  57313. xOffset = newOffset - scrollButtonW;
  57314. }
  57315. else
  57316. {
  57317. firstKey = rangeStart;
  57318. }
  57319. timerCallback();
  57320. repaint();
  57321. }
  57322. }
  57323. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  57324. {
  57325. triggerAsyncUpdate();
  57326. }
  57327. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  57328. {
  57329. triggerAsyncUpdate();
  57330. }
  57331. void MidiKeyboardComponent::handleAsyncUpdate()
  57332. {
  57333. for (int i = rangeStart; i <= rangeEnd; ++i)
  57334. {
  57335. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  57336. {
  57337. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  57338. repaintNote (i);
  57339. }
  57340. }
  57341. }
  57342. void MidiKeyboardComponent::resetAnyKeysInUse()
  57343. {
  57344. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  57345. {
  57346. state.allNotesOff (midiChannel);
  57347. keysPressed.clear();
  57348. mouseDownNote = -1;
  57349. }
  57350. }
  57351. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  57352. {
  57353. const int newNote = (mouseDragging || isMouseOver())
  57354. ? xyToNote (x, y) : -1;
  57355. if (noteUnderMouse != newNote)
  57356. {
  57357. if (mouseDownNote >= 0)
  57358. {
  57359. state.noteOff (midiChannel, mouseDownNote);
  57360. mouseDownNote = -1;
  57361. }
  57362. if (mouseDragging && newNote >= 0)
  57363. {
  57364. state.noteOn (midiChannel, newNote, velocity);
  57365. mouseDownNote = newNote;
  57366. }
  57367. repaintNote (noteUnderMouse);
  57368. noteUnderMouse = newNote;
  57369. repaintNote (noteUnderMouse);
  57370. }
  57371. else if (mouseDownNote >= 0 && ! mouseDragging)
  57372. {
  57373. state.noteOff (midiChannel, mouseDownNote);
  57374. mouseDownNote = -1;
  57375. }
  57376. }
  57377. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  57378. {
  57379. updateNoteUnderMouse (e.x, e.y);
  57380. stopTimer();
  57381. }
  57382. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  57383. {
  57384. const int newNote = xyToNote (e.x, e.y);
  57385. if (newNote >= 0)
  57386. mouseDraggedToKey (newNote, e);
  57387. updateNoteUnderMouse (e.x, e.y);
  57388. }
  57389. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  57390. {
  57391. return true;
  57392. }
  57393. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  57394. {
  57395. }
  57396. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  57397. {
  57398. const int newNote = xyToNote (e.x, e.y);
  57399. mouseDragging = false;
  57400. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  57401. {
  57402. repaintNote (noteUnderMouse);
  57403. noteUnderMouse = -1;
  57404. mouseDragging = true;
  57405. updateNoteUnderMouse (e.x, e.y);
  57406. startTimer (500);
  57407. }
  57408. }
  57409. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  57410. {
  57411. mouseDragging = false;
  57412. updateNoteUnderMouse (e.x, e.y);
  57413. stopTimer();
  57414. }
  57415. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  57416. {
  57417. updateNoteUnderMouse (e.x, e.y);
  57418. }
  57419. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  57420. {
  57421. updateNoteUnderMouse (e.x, e.y);
  57422. }
  57423. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  57424. {
  57425. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  57426. }
  57427. void MidiKeyboardComponent::timerCallback()
  57428. {
  57429. int mx, my;
  57430. getMouseXYRelative (mx, my);
  57431. updateNoteUnderMouse (mx, my);
  57432. }
  57433. void MidiKeyboardComponent::clearKeyMappings()
  57434. {
  57435. resetAnyKeysInUse();
  57436. keyPressNotes.clear();
  57437. keyPresses.clear();
  57438. }
  57439. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  57440. const int midiNoteOffsetFromC)
  57441. {
  57442. removeKeyPressForNote (midiNoteOffsetFromC);
  57443. keyPressNotes.add (midiNoteOffsetFromC);
  57444. keyPresses.add (key);
  57445. }
  57446. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  57447. {
  57448. for (int i = keyPressNotes.size(); --i >= 0;)
  57449. {
  57450. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  57451. {
  57452. keyPressNotes.remove (i);
  57453. keyPresses.remove (i);
  57454. }
  57455. }
  57456. }
  57457. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  57458. {
  57459. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  57460. keyMappingOctave = newOctaveNumber;
  57461. }
  57462. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  57463. {
  57464. bool keyPressUsed = false;
  57465. for (int i = keyPresses.size(); --i >= 0;)
  57466. {
  57467. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  57468. if (keyPresses.getReference(i).isCurrentlyDown())
  57469. {
  57470. if (! keysPressed [note])
  57471. {
  57472. keysPressed.setBit (note);
  57473. state.noteOn (midiChannel, note, velocity);
  57474. keyPressUsed = true;
  57475. }
  57476. }
  57477. else
  57478. {
  57479. if (keysPressed [note])
  57480. {
  57481. keysPressed.clearBit (note);
  57482. state.noteOff (midiChannel, note);
  57483. keyPressUsed = true;
  57484. }
  57485. }
  57486. }
  57487. return keyPressUsed;
  57488. }
  57489. void MidiKeyboardComponent::focusLost (FocusChangeType)
  57490. {
  57491. resetAnyKeysInUse();
  57492. }
  57493. END_JUCE_NAMESPACE
  57494. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  57495. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  57496. #if JUCE_OPENGL
  57497. BEGIN_JUCE_NAMESPACE
  57498. extern void juce_glViewport (const int w, const int h);
  57499. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  57500. const int alphaBits_,
  57501. const int depthBufferBits_,
  57502. const int stencilBufferBits_) throw()
  57503. : redBits (bitsPerRGBComponent),
  57504. greenBits (bitsPerRGBComponent),
  57505. blueBits (bitsPerRGBComponent),
  57506. alphaBits (alphaBits_),
  57507. depthBufferBits (depthBufferBits_),
  57508. stencilBufferBits (stencilBufferBits_),
  57509. accumulationBufferRedBits (0),
  57510. accumulationBufferGreenBits (0),
  57511. accumulationBufferBlueBits (0),
  57512. accumulationBufferAlphaBits (0),
  57513. fullSceneAntiAliasingNumSamples (0)
  57514. {
  57515. }
  57516. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  57517. {
  57518. return memcmp (this, &other, sizeof (other)) == 0;
  57519. }
  57520. static VoidArray knownContexts;
  57521. OpenGLContext::OpenGLContext() throw()
  57522. {
  57523. knownContexts.add (this);
  57524. }
  57525. OpenGLContext::~OpenGLContext()
  57526. {
  57527. knownContexts.removeValue (this);
  57528. }
  57529. OpenGLContext* OpenGLContext::getCurrentContext()
  57530. {
  57531. for (int i = knownContexts.size(); --i >= 0;)
  57532. {
  57533. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  57534. if (oglc->isActive())
  57535. return oglc;
  57536. }
  57537. return 0;
  57538. }
  57539. class OpenGLComponentWatcher : public ComponentMovementWatcher
  57540. {
  57541. public:
  57542. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  57543. : ComponentMovementWatcher (owner_),
  57544. owner (owner_),
  57545. wasShowing (false)
  57546. {
  57547. }
  57548. ~OpenGLComponentWatcher() {}
  57549. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  57550. {
  57551. owner->updateContextPosition();
  57552. }
  57553. void componentPeerChanged()
  57554. {
  57555. const ScopedLock sl (owner->getContextLock());
  57556. owner->deleteContext();
  57557. }
  57558. void componentVisibilityChanged (Component&)
  57559. {
  57560. const bool isShowingNow = owner->isShowing();
  57561. if (wasShowing != isShowingNow)
  57562. {
  57563. wasShowing = isShowingNow;
  57564. owner->updateContextPosition();
  57565. }
  57566. }
  57567. juce_UseDebuggingNewOperator
  57568. private:
  57569. OpenGLComponent* const owner;
  57570. bool wasShowing;
  57571. };
  57572. OpenGLComponent::OpenGLComponent()
  57573. : context (0),
  57574. contextToShareListsWith (0),
  57575. needToUpdateViewport (true)
  57576. {
  57577. setOpaque (true);
  57578. componentWatcher = new OpenGLComponentWatcher (this);
  57579. }
  57580. OpenGLComponent::~OpenGLComponent()
  57581. {
  57582. deleteContext();
  57583. delete componentWatcher;
  57584. }
  57585. void OpenGLComponent::deleteContext()
  57586. {
  57587. const ScopedLock sl (contextLock);
  57588. deleteAndZero (context);
  57589. }
  57590. void OpenGLComponent::updateContextPosition()
  57591. {
  57592. needToUpdateViewport = true;
  57593. if (getWidth() > 0 && getHeight() > 0)
  57594. {
  57595. Component* const topComp = getTopLevelComponent();
  57596. if (topComp->getPeer() != 0)
  57597. {
  57598. const ScopedLock sl (contextLock);
  57599. if (context != 0)
  57600. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  57601. getScreenY() - topComp->getScreenY(),
  57602. getWidth(),
  57603. getHeight(),
  57604. topComp->getHeight());
  57605. }
  57606. }
  57607. }
  57608. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  57609. {
  57610. OpenGLPixelFormat pf;
  57611. const ScopedLock sl (contextLock);
  57612. if (context != 0)
  57613. pf = context->getPixelFormat();
  57614. return pf;
  57615. }
  57616. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  57617. {
  57618. if (! (preferredPixelFormat == formatToUse))
  57619. {
  57620. const ScopedLock sl (contextLock);
  57621. deleteContext();
  57622. preferredPixelFormat = formatToUse;
  57623. }
  57624. }
  57625. void OpenGLComponent::shareWith (OpenGLContext* context)
  57626. {
  57627. if (contextToShareListsWith != context)
  57628. {
  57629. const ScopedLock sl (contextLock);
  57630. deleteContext();
  57631. contextToShareListsWith = context;
  57632. }
  57633. }
  57634. bool OpenGLComponent::makeCurrentContextActive()
  57635. {
  57636. if (context == 0)
  57637. {
  57638. const ScopedLock sl (contextLock);
  57639. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  57640. {
  57641. context = OpenGLContext::createContextForWindow (this,
  57642. preferredPixelFormat,
  57643. contextToShareListsWith);
  57644. if (context != 0)
  57645. {
  57646. updateContextPosition();
  57647. if (context->makeActive())
  57648. newOpenGLContextCreated();
  57649. }
  57650. }
  57651. }
  57652. return context != 0 && context->makeActive();
  57653. }
  57654. void OpenGLComponent::makeCurrentContextInactive()
  57655. {
  57656. if (context != 0)
  57657. context->makeInactive();
  57658. }
  57659. bool OpenGLComponent::isActiveContext() const throw()
  57660. {
  57661. return context != 0 && context->isActive();
  57662. }
  57663. void OpenGLComponent::swapBuffers()
  57664. {
  57665. if (context != 0)
  57666. context->swapBuffers();
  57667. }
  57668. void OpenGLComponent::paint (Graphics&)
  57669. {
  57670. if (renderAndSwapBuffers())
  57671. {
  57672. ComponentPeer* const peer = getPeer();
  57673. if (peer != 0)
  57674. {
  57675. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  57676. getScreenY() - peer->getScreenY(),
  57677. getWidth(), getHeight());
  57678. }
  57679. }
  57680. }
  57681. bool OpenGLComponent::renderAndSwapBuffers()
  57682. {
  57683. const ScopedLock sl (contextLock);
  57684. if (! makeCurrentContextActive())
  57685. return false;
  57686. if (needToUpdateViewport)
  57687. {
  57688. needToUpdateViewport = false;
  57689. juce_glViewport (getWidth(), getHeight());
  57690. }
  57691. renderOpenGL();
  57692. swapBuffers();
  57693. return true;
  57694. }
  57695. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  57696. {
  57697. Component::internalRepaint (x, y, w, h);
  57698. if (context != 0)
  57699. context->repaint();
  57700. }
  57701. END_JUCE_NAMESPACE
  57702. #endif
  57703. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  57704. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  57705. BEGIN_JUCE_NAMESPACE
  57706. PreferencesPanel::PreferencesPanel()
  57707. : currentPage (0),
  57708. buttonSize (70)
  57709. {
  57710. }
  57711. PreferencesPanel::~PreferencesPanel()
  57712. {
  57713. deleteAllChildren();
  57714. }
  57715. void PreferencesPanel::addSettingsPage (const String& title,
  57716. const Drawable* icon,
  57717. const Drawable* overIcon,
  57718. const Drawable* downIcon)
  57719. {
  57720. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  57721. button->setImages (icon, overIcon, downIcon);
  57722. button->setRadioGroupId (1);
  57723. button->addButtonListener (this);
  57724. button->setClickingTogglesState (true);
  57725. button->setWantsKeyboardFocus (false);
  57726. addAndMakeVisible (button);
  57727. resized();
  57728. if (currentPage == 0)
  57729. setCurrentPage (title);
  57730. }
  57731. void PreferencesPanel::addSettingsPage (const String& title,
  57732. const char* imageData,
  57733. const int imageDataSize)
  57734. {
  57735. DrawableImage icon, iconOver, iconDown;
  57736. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57737. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57738. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  57739. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57740. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  57741. addSettingsPage (title, &icon, &iconOver, &iconDown);
  57742. }
  57743. class PrefsDialogWindow : public DialogWindow
  57744. {
  57745. public:
  57746. PrefsDialogWindow (const String& dialogtitle,
  57747. const Colour& backgroundColour)
  57748. : DialogWindow (dialogtitle, backgroundColour, true)
  57749. {
  57750. }
  57751. ~PrefsDialogWindow()
  57752. {
  57753. }
  57754. void closeButtonPressed()
  57755. {
  57756. exitModalState (0);
  57757. }
  57758. private:
  57759. PrefsDialogWindow (const PrefsDialogWindow&);
  57760. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  57761. };
  57762. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  57763. int dialogWidth,
  57764. int dialogHeight,
  57765. const Colour& backgroundColour)
  57766. {
  57767. setSize (dialogWidth, dialogHeight);
  57768. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  57769. dw.setContentComponent (this, true, true);
  57770. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  57771. dw.runModalLoop();
  57772. dw.setContentComponent (0, false, false);
  57773. }
  57774. void PreferencesPanel::resized()
  57775. {
  57776. int x = 0;
  57777. for (int i = 0; i < getNumChildComponents(); ++i)
  57778. {
  57779. Component* c = getChildComponent (i);
  57780. if (dynamic_cast <DrawableButton*> (c) == 0)
  57781. {
  57782. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  57783. }
  57784. else
  57785. {
  57786. c->setBounds (x, 0, buttonSize, buttonSize);
  57787. x += buttonSize;
  57788. }
  57789. }
  57790. }
  57791. void PreferencesPanel::paint (Graphics& g)
  57792. {
  57793. g.setColour (Colours::grey);
  57794. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  57795. }
  57796. void PreferencesPanel::setCurrentPage (const String& pageName)
  57797. {
  57798. if (currentPageName != pageName)
  57799. {
  57800. currentPageName = pageName;
  57801. deleteAndZero (currentPage);
  57802. currentPage = createComponentForPage (pageName);
  57803. if (currentPage != 0)
  57804. {
  57805. addAndMakeVisible (currentPage);
  57806. currentPage->toBack();
  57807. resized();
  57808. }
  57809. for (int i = 0; i < getNumChildComponents(); ++i)
  57810. {
  57811. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57812. if (db != 0 && db->getName() == pageName)
  57813. {
  57814. db->setToggleState (true, false);
  57815. break;
  57816. }
  57817. }
  57818. }
  57819. }
  57820. void PreferencesPanel::buttonClicked (Button*)
  57821. {
  57822. for (int i = 0; i < getNumChildComponents(); ++i)
  57823. {
  57824. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57825. if (db != 0 && db->getToggleState())
  57826. {
  57827. setCurrentPage (db->getName());
  57828. break;
  57829. }
  57830. }
  57831. }
  57832. END_JUCE_NAMESPACE
  57833. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  57834. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57835. #if JUCE_WIN32 || JUCE_LINUX
  57836. BEGIN_JUCE_NAMESPACE
  57837. SystemTrayIconComponent::SystemTrayIconComponent()
  57838. {
  57839. addToDesktop (0);
  57840. }
  57841. SystemTrayIconComponent::~SystemTrayIconComponent()
  57842. {
  57843. }
  57844. END_JUCE_NAMESPACE
  57845. #endif
  57846. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57847. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  57848. BEGIN_JUCE_NAMESPACE
  57849. static const int titleH = 24;
  57850. static const int iconWidth = 80;
  57851. class AlertWindowTextEditor : public TextEditor
  57852. {
  57853. public:
  57854. #if JUCE_LINUX
  57855. #define PASSWORD_CHAR 0x2022
  57856. #else
  57857. #define PASSWORD_CHAR 0x25cf
  57858. #endif
  57859. AlertWindowTextEditor (const String& name,
  57860. const bool isPasswordBox)
  57861. : TextEditor (name,
  57862. isPasswordBox ? (const tchar) PASSWORD_CHAR
  57863. : (const tchar) 0)
  57864. {
  57865. setSelectAllWhenFocused (true);
  57866. }
  57867. ~AlertWindowTextEditor()
  57868. {
  57869. }
  57870. void returnPressed()
  57871. {
  57872. // pass these up the component hierarchy to be trigger the buttons
  57873. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  57874. }
  57875. void escapePressed()
  57876. {
  57877. // pass these up the component hierarchy to be trigger the buttons
  57878. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  57879. }
  57880. private:
  57881. AlertWindowTextEditor (const AlertWindowTextEditor&);
  57882. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  57883. };
  57884. AlertWindow::AlertWindow (const String& title,
  57885. const String& message,
  57886. AlertIconType iconType,
  57887. Component* associatedComponent_)
  57888. : TopLevelWindow (title, true),
  57889. alertIconType (iconType),
  57890. associatedComponent (associatedComponent_)
  57891. {
  57892. if (message.isEmpty())
  57893. text = T(" "); // to force an update if the message is empty
  57894. setMessage (message);
  57895. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  57896. {
  57897. Component* const c = Desktop::getInstance().getComponent (i);
  57898. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  57899. {
  57900. setAlwaysOnTop (true);
  57901. break;
  57902. }
  57903. }
  57904. if (JUCEApplication::getInstance() == 0)
  57905. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  57906. lookAndFeelChanged();
  57907. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  57908. }
  57909. AlertWindow::~AlertWindow()
  57910. {
  57911. for (int i = customComps.size(); --i >= 0;)
  57912. removeChildComponent ((Component*) customComps[i]);
  57913. deleteAllChildren();
  57914. }
  57915. void AlertWindow::userTriedToCloseWindow()
  57916. {
  57917. exitModalState (0);
  57918. }
  57919. void AlertWindow::setMessage (const String& message)
  57920. {
  57921. const String newMessage (message.substring (0, 2048));
  57922. if (text != newMessage)
  57923. {
  57924. text = newMessage;
  57925. font.setHeight (15.0f);
  57926. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  57927. textLayout.setText (getName() + T("\n\n"), titleFont);
  57928. textLayout.appendText (text, font);
  57929. updateLayout (true);
  57930. repaint();
  57931. }
  57932. }
  57933. void AlertWindow::buttonClicked (Button* button)
  57934. {
  57935. for (int i = 0; i < buttons.size(); i++)
  57936. {
  57937. TextButton* const c = (TextButton*) buttons[i];
  57938. if (button->getName() == c->getName())
  57939. {
  57940. if (c->getParentComponent() != 0)
  57941. c->getParentComponent()->exitModalState (c->getCommandID());
  57942. break;
  57943. }
  57944. }
  57945. }
  57946. void AlertWindow::addButton (const String& name,
  57947. const int returnValue,
  57948. const KeyPress& shortcutKey1,
  57949. const KeyPress& shortcutKey2)
  57950. {
  57951. TextButton* const b = new TextButton (name, String::empty);
  57952. b->setWantsKeyboardFocus (true);
  57953. b->setMouseClickGrabsKeyboardFocus (false);
  57954. b->setCommandToTrigger (0, returnValue, false);
  57955. b->addShortcut (shortcutKey1);
  57956. b->addShortcut (shortcutKey2);
  57957. b->addButtonListener (this);
  57958. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  57959. addAndMakeVisible (b, 0);
  57960. buttons.add (b);
  57961. updateLayout (false);
  57962. }
  57963. int AlertWindow::getNumButtons() const
  57964. {
  57965. return buttons.size();
  57966. }
  57967. void AlertWindow::addTextEditor (const String& name,
  57968. const String& initialContents,
  57969. const String& onScreenLabel,
  57970. const bool isPasswordBox)
  57971. {
  57972. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  57973. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  57974. tc->setFont (font);
  57975. tc->setText (initialContents);
  57976. tc->setCaretPosition (initialContents.length());
  57977. addAndMakeVisible (tc);
  57978. textBoxes.add (tc);
  57979. allComps.add (tc);
  57980. textboxNames.add (onScreenLabel);
  57981. updateLayout (false);
  57982. }
  57983. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  57984. {
  57985. for (int i = textBoxes.size(); --i >= 0;)
  57986. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  57987. return ((TextEditor*)textBoxes[i])->getText();
  57988. return String::empty;
  57989. }
  57990. void AlertWindow::addComboBox (const String& name,
  57991. const StringArray& items,
  57992. const String& onScreenLabel)
  57993. {
  57994. ComboBox* const cb = new ComboBox (name);
  57995. for (int i = 0; i < items.size(); ++i)
  57996. cb->addItem (items[i], i + 1);
  57997. addAndMakeVisible (cb);
  57998. cb->setSelectedItemIndex (0);
  57999. comboBoxes.add (cb);
  58000. allComps.add (cb);
  58001. comboBoxNames.add (onScreenLabel);
  58002. updateLayout (false);
  58003. }
  58004. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  58005. {
  58006. for (int i = comboBoxes.size(); --i >= 0;)
  58007. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  58008. return (ComboBox*) comboBoxes[i];
  58009. return 0;
  58010. }
  58011. class AlertTextComp : public TextEditor
  58012. {
  58013. AlertTextComp (const AlertTextComp&);
  58014. const AlertTextComp& operator= (const AlertTextComp&);
  58015. int bestWidth;
  58016. public:
  58017. AlertTextComp (const String& message,
  58018. const Font& font)
  58019. {
  58020. setReadOnly (true);
  58021. setMultiLine (true, true);
  58022. setCaretVisible (false);
  58023. setScrollbarsShown (true);
  58024. lookAndFeelChanged();
  58025. setWantsKeyboardFocus (false);
  58026. setFont (font);
  58027. setText (message, false);
  58028. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  58029. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  58030. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  58031. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  58032. }
  58033. ~AlertTextComp()
  58034. {
  58035. }
  58036. int getPreferredWidth() const throw() { return bestWidth; }
  58037. void updateLayout (const int width)
  58038. {
  58039. TextLayout text;
  58040. text.appendText (getText(), getFont());
  58041. text.layout (width - 8, Justification::topLeft, true);
  58042. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  58043. }
  58044. };
  58045. void AlertWindow::addTextBlock (const String& text)
  58046. {
  58047. AlertTextComp* const c = new AlertTextComp (text, font);
  58048. textBlocks.add (c);
  58049. allComps.add (c);
  58050. addAndMakeVisible (c);
  58051. updateLayout (false);
  58052. }
  58053. void AlertWindow::addProgressBarComponent (double& progressValue)
  58054. {
  58055. ProgressBar* const pb = new ProgressBar (progressValue);
  58056. progressBars.add (pb);
  58057. allComps.add (pb);
  58058. addAndMakeVisible (pb);
  58059. updateLayout (false);
  58060. }
  58061. void AlertWindow::addCustomComponent (Component* const component)
  58062. {
  58063. customComps.add (component);
  58064. allComps.add (component);
  58065. addAndMakeVisible (component);
  58066. updateLayout (false);
  58067. }
  58068. int AlertWindow::getNumCustomComponents() const
  58069. {
  58070. return customComps.size();
  58071. }
  58072. Component* AlertWindow::getCustomComponent (const int index) const
  58073. {
  58074. return (Component*) customComps [index];
  58075. }
  58076. Component* AlertWindow::removeCustomComponent (const int index)
  58077. {
  58078. Component* const c = getCustomComponent (index);
  58079. if (c != 0)
  58080. {
  58081. customComps.removeValue (c);
  58082. allComps.removeValue (c);
  58083. removeChildComponent (c);
  58084. updateLayout (false);
  58085. }
  58086. return c;
  58087. }
  58088. void AlertWindow::paint (Graphics& g)
  58089. {
  58090. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  58091. g.setColour (findColour (textColourId));
  58092. g.setFont (getLookAndFeel().getAlertWindowFont());
  58093. int i;
  58094. for (i = textBoxes.size(); --i >= 0;)
  58095. {
  58096. if (textboxNames[i].isNotEmpty())
  58097. {
  58098. const TextEditor* const te = (TextEditor*) textBoxes[i];
  58099. g.drawFittedText (textboxNames[i],
  58100. te->getX(), te->getY() - 14,
  58101. te->getWidth(), 14,
  58102. Justification::centredLeft, 1);
  58103. }
  58104. }
  58105. for (i = comboBoxNames.size(); --i >= 0;)
  58106. {
  58107. if (comboBoxNames[i].isNotEmpty())
  58108. {
  58109. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  58110. g.drawFittedText (comboBoxNames[i],
  58111. cb->getX(), cb->getY() - 14,
  58112. cb->getWidth(), 14,
  58113. Justification::centredLeft, 1);
  58114. }
  58115. }
  58116. }
  58117. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  58118. {
  58119. const int wid = jmax (font.getStringWidth (text),
  58120. font.getStringWidth (getName()));
  58121. const int sw = (int) sqrt (font.getHeight() * wid);
  58122. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  58123. const int edgeGap = 10;
  58124. int iconSpace;
  58125. if (alertIconType == NoIcon)
  58126. {
  58127. textLayout.layout (w, Justification::horizontallyCentred, true);
  58128. iconSpace = 0;
  58129. }
  58130. else
  58131. {
  58132. textLayout.layout (w, Justification::left, true);
  58133. iconSpace = iconWidth;
  58134. }
  58135. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  58136. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58137. const int textLayoutH = textLayout.getHeight();
  58138. const int textBottom = 16 + titleH + textLayoutH;
  58139. int h = textBottom;
  58140. int buttonW = 40;
  58141. int i;
  58142. for (i = 0; i < buttons.size(); ++i)
  58143. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  58144. w = jmax (buttonW, w);
  58145. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  58146. if (buttons.size() > 0)
  58147. h += 20 + ((TextButton*) buttons[0])->getHeight();
  58148. for (i = customComps.size(); --i >= 0;)
  58149. {
  58150. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  58151. h += 10 + ((Component*) customComps[i])->getHeight();
  58152. }
  58153. for (i = textBlocks.size(); --i >= 0;)
  58154. {
  58155. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58156. w = jmax (w, ac->getPreferredWidth());
  58157. }
  58158. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58159. for (i = textBlocks.size(); --i >= 0;)
  58160. {
  58161. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58162. ac->updateLayout ((int) (w * 0.8f));
  58163. h += ac->getHeight() + 10;
  58164. }
  58165. h = jmin (getParentHeight() - 50, h);
  58166. if (onlyIncreaseSize)
  58167. {
  58168. w = jmax (w, getWidth());
  58169. h = jmax (h, getHeight());
  58170. }
  58171. if (! isVisible())
  58172. {
  58173. centreAroundComponent (associatedComponent, w, h);
  58174. }
  58175. else
  58176. {
  58177. const int cx = getX() + getWidth() / 2;
  58178. const int cy = getY() + getHeight() / 2;
  58179. setBounds (cx - w / 2,
  58180. cy - h / 2,
  58181. w, h);
  58182. }
  58183. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  58184. const int spacer = 16;
  58185. int totalWidth = -spacer;
  58186. for (i = buttons.size(); --i >= 0;)
  58187. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  58188. int x = (w - totalWidth) / 2;
  58189. int y = (int) (getHeight() * 0.95f);
  58190. for (i = 0; i < buttons.size(); ++i)
  58191. {
  58192. TextButton* const c = (TextButton*) buttons[i];
  58193. int ny = proportionOfHeight (0.95f) - c->getHeight();
  58194. c->setTopLeftPosition (x, ny);
  58195. if (ny < y)
  58196. y = ny;
  58197. x += c->getWidth() + spacer;
  58198. c->toFront (false);
  58199. }
  58200. y = textBottom;
  58201. for (i = 0; i < allComps.size(); ++i)
  58202. {
  58203. Component* const c = (Component*) allComps[i];
  58204. const int h = 22;
  58205. const int comboIndex = comboBoxes.indexOf (c);
  58206. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  58207. y += 18;
  58208. const int tbIndex = textBoxes.indexOf (c);
  58209. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  58210. y += 18;
  58211. if (customComps.contains (c) || textBlocks.contains (c))
  58212. {
  58213. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  58214. y += c->getHeight() + 10;
  58215. }
  58216. else
  58217. {
  58218. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  58219. y += h + 10;
  58220. }
  58221. }
  58222. setWantsKeyboardFocus (getNumChildComponents() == 0);
  58223. }
  58224. bool AlertWindow::containsAnyExtraComponents() const
  58225. {
  58226. return textBoxes.size()
  58227. + comboBoxes.size()
  58228. + progressBars.size()
  58229. + customComps.size() > 0;
  58230. }
  58231. void AlertWindow::mouseDown (const MouseEvent&)
  58232. {
  58233. dragger.startDraggingComponent (this, &constrainer);
  58234. }
  58235. void AlertWindow::mouseDrag (const MouseEvent& e)
  58236. {
  58237. dragger.dragComponent (this, e);
  58238. }
  58239. bool AlertWindow::keyPressed (const KeyPress& key)
  58240. {
  58241. for (int i = buttons.size(); --i >= 0;)
  58242. {
  58243. TextButton* const b = (TextButton*) buttons[i];
  58244. if (b->isRegisteredForShortcut (key))
  58245. {
  58246. b->triggerClick();
  58247. return true;
  58248. }
  58249. }
  58250. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  58251. {
  58252. exitModalState (0);
  58253. return true;
  58254. }
  58255. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  58256. {
  58257. ((TextButton*) buttons.getFirst())->triggerClick();
  58258. return true;
  58259. }
  58260. return false;
  58261. }
  58262. void AlertWindow::lookAndFeelChanged()
  58263. {
  58264. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  58265. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  58266. setDropShadowEnabled (isOpaque() && (flags & ComponentPeer::windowHasDropShadow) != 0);
  58267. }
  58268. int AlertWindow::getDesktopWindowStyleFlags() const
  58269. {
  58270. return getLookAndFeel().getAlertBoxWindowFlags();
  58271. }
  58272. struct AlertWindowInfo
  58273. {
  58274. String title, message, button1, button2, button3;
  58275. AlertWindow::AlertIconType iconType;
  58276. int numButtons;
  58277. Component* associatedComponent;
  58278. int run() const
  58279. {
  58280. return (int) (pointer_sized_int)
  58281. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  58282. }
  58283. private:
  58284. int show() const
  58285. {
  58286. jassert (associatedComponent == 0 || associatedComponent->isValidComponent()); // has your comp been deleted?
  58287. LookAndFeel& lf = associatedComponent->isValidComponent() ? associatedComponent->getLookAndFeel()
  58288. : LookAndFeel::getDefaultLookAndFeel();
  58289. Component* const alertBox = lf.createAlertWindow (title, message, button1, button2, button3,
  58290. iconType, numButtons, associatedComponent);
  58291. jassert (alertBox != 0); // you have to return one of these!
  58292. const int result = alertBox->runModalLoop();
  58293. delete alertBox;
  58294. return result;
  58295. }
  58296. static void* showCallback (void* userData)
  58297. {
  58298. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  58299. }
  58300. };
  58301. void AlertWindow::showMessageBox (AlertIconType iconType,
  58302. const String& title,
  58303. const String& message,
  58304. const String& buttonText,
  58305. Component* associatedComponent)
  58306. {
  58307. AlertWindowInfo info;
  58308. info.title = title;
  58309. info.message = message;
  58310. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  58311. info.iconType = iconType;
  58312. info.numButtons = 1;
  58313. info.associatedComponent = associatedComponent;
  58314. info.run();
  58315. }
  58316. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  58317. const String& title,
  58318. const String& message,
  58319. const String& button1Text,
  58320. const String& button2Text,
  58321. Component* associatedComponent)
  58322. {
  58323. AlertWindowInfo info;
  58324. info.title = title;
  58325. info.message = message;
  58326. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  58327. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  58328. info.iconType = iconType;
  58329. info.numButtons = 2;
  58330. info.associatedComponent = associatedComponent;
  58331. return info.run() != 0;
  58332. }
  58333. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  58334. const String& title,
  58335. const String& message,
  58336. const String& button1Text,
  58337. const String& button2Text,
  58338. const String& button3Text,
  58339. Component* associatedComponent)
  58340. {
  58341. AlertWindowInfo info;
  58342. info.title = title;
  58343. info.message = message;
  58344. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  58345. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  58346. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  58347. info.iconType = iconType;
  58348. info.numButtons = 3;
  58349. info.associatedComponent = associatedComponent;
  58350. return info.run();
  58351. }
  58352. END_JUCE_NAMESPACE
  58353. /********* End of inlined file: juce_AlertWindow.cpp *********/
  58354. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  58355. BEGIN_JUCE_NAMESPACE
  58356. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  58357. // these are over in juce_component.cpp
  58358. extern int64 juce_recentMouseDownTimes[4];
  58359. extern int juce_recentMouseDownX [4];
  58360. extern int juce_recentMouseDownY [4];
  58361. extern Component* juce_recentMouseDownComponent [4];
  58362. extern int juce_LastMousePosX;
  58363. extern int juce_LastMousePosY;
  58364. extern int juce_MouseClickCounter;
  58365. extern bool juce_MouseHasMovedSignificantlySincePressed;
  58366. static const int fakeMouseMoveMessage = 0x7fff00ff;
  58367. static VoidArray heavyweightPeers (4);
  58368. ComponentPeer::ComponentPeer (Component* const component_,
  58369. const int styleFlags_) throw()
  58370. : component (component_),
  58371. styleFlags (styleFlags_),
  58372. lastPaintTime (0),
  58373. constrainer (0),
  58374. lastFocusedComponent (0),
  58375. dragAndDropTargetComponent (0),
  58376. lastDragAndDropCompUnderMouse (0),
  58377. fakeMouseMessageSent (false),
  58378. isWindowMinimised (false)
  58379. {
  58380. heavyweightPeers.add (this);
  58381. }
  58382. ComponentPeer::~ComponentPeer()
  58383. {
  58384. heavyweightPeers.removeValue (this);
  58385. delete dragAndDropTargetComponent;
  58386. Desktop::getInstance().triggerFocusCallback();
  58387. }
  58388. int ComponentPeer::getNumPeers() throw()
  58389. {
  58390. return heavyweightPeers.size();
  58391. }
  58392. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  58393. {
  58394. return (ComponentPeer*) heavyweightPeers [index];
  58395. }
  58396. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  58397. {
  58398. for (int i = heavyweightPeers.size(); --i >= 0;)
  58399. {
  58400. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  58401. if (peer->getComponent() == component)
  58402. return peer;
  58403. }
  58404. return 0;
  58405. }
  58406. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  58407. {
  58408. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  58409. }
  58410. void ComponentPeer::updateCurrentModifiers() throw()
  58411. {
  58412. ModifierKeys::updateCurrentModifiers();
  58413. }
  58414. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  58415. {
  58416. jassert (component->isValidComponent());
  58417. updateCurrentModifiers();
  58418. Component* c = component->getComponentAt (x, y);
  58419. const ComponentDeletionWatcher deletionChecker (component);
  58420. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  58421. {
  58422. jassert (Component::componentUnderMouse->isValidComponent());
  58423. const int oldX = x;
  58424. const int oldY = y;
  58425. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58426. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58427. Component::componentUnderMouse = 0;
  58428. if (deletionChecker.hasBeenDeleted())
  58429. return;
  58430. c = component->getComponentAt (oldX, oldY);
  58431. }
  58432. Component::componentUnderMouse = c;
  58433. if (Component::componentUnderMouse != 0)
  58434. {
  58435. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58436. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58437. }
  58438. }
  58439. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  58440. {
  58441. jassert (component->isValidComponent());
  58442. updateCurrentModifiers();
  58443. fakeMouseMessageSent = false;
  58444. const ComponentDeletionWatcher deletionChecker (component);
  58445. Component* c = component->getComponentAt (x, y);
  58446. if (c != Component::componentUnderMouse)
  58447. {
  58448. const int oldX = x;
  58449. const int oldY = y;
  58450. if (Component::componentUnderMouse != 0)
  58451. {
  58452. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58453. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58454. x = oldX;
  58455. y = oldY;
  58456. Component::componentUnderMouse = 0;
  58457. if (deletionChecker.hasBeenDeleted())
  58458. return; // if this window has just been deleted..
  58459. c = component->getComponentAt (x, y);
  58460. }
  58461. Component::componentUnderMouse = c;
  58462. if (c != 0)
  58463. {
  58464. component->relativePositionToOtherComponent (c, x, y);
  58465. c->internalMouseEnter (x, y, time);
  58466. x = oldX;
  58467. y = oldY;
  58468. if (deletionChecker.hasBeenDeleted())
  58469. return; // if this window has just been deleted..
  58470. }
  58471. }
  58472. if (Component::componentUnderMouse != 0)
  58473. {
  58474. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58475. Component::componentUnderMouse->internalMouseMove (x, y, time);
  58476. }
  58477. }
  58478. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  58479. {
  58480. ++juce_MouseClickCounter;
  58481. updateCurrentModifiers();
  58482. int numMouseButtonsDown = 0;
  58483. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  58484. ++numMouseButtonsDown;
  58485. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  58486. ++numMouseButtonsDown;
  58487. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  58488. ++numMouseButtonsDown;
  58489. if (numMouseButtonsDown == 1)
  58490. {
  58491. Component::componentUnderMouse = component->getComponentAt (x, y);
  58492. if (Component::componentUnderMouse != 0)
  58493. {
  58494. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  58495. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  58496. {
  58497. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  58498. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  58499. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  58500. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  58501. }
  58502. juce_recentMouseDownTimes[0] = time;
  58503. juce_recentMouseDownX[0] = x;
  58504. juce_recentMouseDownY[0] = y;
  58505. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  58506. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  58507. juce_MouseHasMovedSignificantlySincePressed = false;
  58508. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58509. Component::componentUnderMouse->internalMouseDown (x, y);
  58510. }
  58511. }
  58512. }
  58513. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  58514. {
  58515. updateCurrentModifiers();
  58516. if (Component::componentUnderMouse != 0)
  58517. {
  58518. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58519. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  58520. }
  58521. }
  58522. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  58523. {
  58524. updateCurrentModifiers();
  58525. int numMouseButtonsDown = 0;
  58526. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  58527. ++numMouseButtonsDown;
  58528. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  58529. ++numMouseButtonsDown;
  58530. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  58531. ++numMouseButtonsDown;
  58532. if (numMouseButtonsDown == 1)
  58533. {
  58534. const ComponentDeletionWatcher deletionChecker (component);
  58535. Component* c = component->getComponentAt (x, y);
  58536. if (c != Component::componentUnderMouse)
  58537. {
  58538. const int oldX = x;
  58539. const int oldY = y;
  58540. if (Component::componentUnderMouse != 0)
  58541. {
  58542. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58543. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58544. x = oldX;
  58545. y = oldY;
  58546. if (Component::componentUnderMouse != 0)
  58547. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58548. if (deletionChecker.hasBeenDeleted())
  58549. return;
  58550. c = component->getComponentAt (oldX, oldY);
  58551. }
  58552. Component::componentUnderMouse = c;
  58553. if (Component::componentUnderMouse != 0)
  58554. {
  58555. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58556. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58557. }
  58558. }
  58559. else
  58560. {
  58561. if (Component::componentUnderMouse != 0)
  58562. {
  58563. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58564. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58565. }
  58566. }
  58567. }
  58568. }
  58569. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  58570. {
  58571. jassert (component->isValidComponent());
  58572. updateCurrentModifiers();
  58573. if (Component::componentUnderMouse != 0)
  58574. {
  58575. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58576. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58577. Component::componentUnderMouse = 0;
  58578. }
  58579. }
  58580. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  58581. {
  58582. updateCurrentModifiers();
  58583. if (Component::componentUnderMouse != 0)
  58584. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  58585. }
  58586. void ComponentPeer::sendFakeMouseMove() throw()
  58587. {
  58588. if ((! fakeMouseMessageSent)
  58589. && component->flags.hasHeavyweightPeerFlag
  58590. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58591. {
  58592. if (! isMinimised())
  58593. {
  58594. int realX, realY, realW, realH;
  58595. getBounds (realX, realY, realW, realH);
  58596. component->bounds_.setBounds (realX, realY, realW, realH);
  58597. }
  58598. int x, y;
  58599. component->getMouseXYRelative (x, y);
  58600. if (((unsigned int) x) < (unsigned int) component->getWidth()
  58601. && ((unsigned int) y) < (unsigned int) component->getHeight()
  58602. && contains (x, y, false))
  58603. {
  58604. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  58605. }
  58606. fakeMouseMessageSent = true;
  58607. }
  58608. }
  58609. void ComponentPeer::handleMessage (const Message& message)
  58610. {
  58611. if (message.intParameter1 == fakeMouseMoveMessage)
  58612. {
  58613. if (! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58614. handleMouseMove (message.intParameter2,
  58615. message.intParameter3,
  58616. Time::currentTimeMillis());
  58617. }
  58618. }
  58619. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  58620. {
  58621. Graphics g (&contextToPaintTo);
  58622. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58623. g.saveState();
  58624. #endif
  58625. JUCE_TRY
  58626. {
  58627. component->paintEntireComponent (g);
  58628. }
  58629. JUCE_CATCH_EXCEPTION
  58630. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58631. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  58632. // clearly when things are being repainted.
  58633. {
  58634. g.restoreState();
  58635. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  58636. (uint8) Random::getSystemRandom().nextInt (255),
  58637. (uint8) Random::getSystemRandom().nextInt (255),
  58638. (uint8) 0x50));
  58639. }
  58640. #endif
  58641. }
  58642. bool ComponentPeer::handleKeyPress (const int keyCode,
  58643. const juce_wchar textCharacter)
  58644. {
  58645. updateCurrentModifiers();
  58646. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58647. ? Component::currentlyFocusedComponent
  58648. : component;
  58649. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58650. {
  58651. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58652. if (currentModalComp != 0)
  58653. target = currentModalComp;
  58654. }
  58655. const KeyPress keyInfo (keyCode,
  58656. ModifierKeys::getCurrentModifiers().getRawFlags()
  58657. & ModifierKeys::allKeyboardModifiers,
  58658. textCharacter);
  58659. bool keyWasUsed = false;
  58660. while (target != 0)
  58661. {
  58662. const ComponentDeletionWatcher deletionChecker (target);
  58663. if (target->keyListeners_ != 0)
  58664. {
  58665. for (int i = target->keyListeners_->size(); --i >= 0;)
  58666. {
  58667. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  58668. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58669. return keyWasUsed;
  58670. i = jmin (i, target->keyListeners_->size());
  58671. }
  58672. }
  58673. keyWasUsed = target->keyPressed (keyInfo);
  58674. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58675. break;
  58676. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  58677. {
  58678. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  58679. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  58680. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  58681. break;
  58682. }
  58683. target = target->parentComponent_;
  58684. }
  58685. return keyWasUsed;
  58686. }
  58687. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  58688. {
  58689. updateCurrentModifiers();
  58690. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58691. ? Component::currentlyFocusedComponent
  58692. : component;
  58693. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58694. {
  58695. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58696. if (currentModalComp != 0)
  58697. target = currentModalComp;
  58698. }
  58699. bool keyWasUsed = false;
  58700. while (target != 0)
  58701. {
  58702. const ComponentDeletionWatcher deletionChecker (target);
  58703. keyWasUsed = target->keyStateChanged (isKeyDown);
  58704. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58705. break;
  58706. if (target->keyListeners_ != 0)
  58707. {
  58708. for (int i = target->keyListeners_->size(); --i >= 0;)
  58709. {
  58710. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  58711. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58712. return keyWasUsed;
  58713. i = jmin (i, target->keyListeners_->size());
  58714. }
  58715. }
  58716. target = target->parentComponent_;
  58717. }
  58718. return keyWasUsed;
  58719. }
  58720. void ComponentPeer::handleModifierKeysChange()
  58721. {
  58722. updateCurrentModifiers();
  58723. Component* target = Component::getComponentUnderMouse();
  58724. if (target == 0)
  58725. target = Component::getCurrentlyFocusedComponent();
  58726. if (target == 0)
  58727. target = component;
  58728. if (target->isValidComponent())
  58729. target->internalModifierKeysChanged();
  58730. }
  58731. void ComponentPeer::handleBroughtToFront()
  58732. {
  58733. updateCurrentModifiers();
  58734. if (component != 0)
  58735. component->internalBroughtToFront();
  58736. }
  58737. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  58738. {
  58739. constrainer = newConstrainer;
  58740. }
  58741. void ComponentPeer::handleMovedOrResized()
  58742. {
  58743. jassert (component->isValidComponent());
  58744. updateCurrentModifiers();
  58745. const bool nowMinimised = isMinimised();
  58746. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  58747. {
  58748. const ComponentDeletionWatcher deletionChecker (component);
  58749. int realX, realY, realW, realH;
  58750. getBounds (realX, realY, realW, realH);
  58751. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  58752. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  58753. if (wasMoved || wasResized)
  58754. {
  58755. component->bounds_.setBounds (realX, realY, realW, realH);
  58756. if (wasResized)
  58757. component->repaint();
  58758. component->sendMovedResizedMessages (wasMoved, wasResized);
  58759. if (deletionChecker.hasBeenDeleted())
  58760. return;
  58761. }
  58762. }
  58763. if (isWindowMinimised != nowMinimised)
  58764. {
  58765. isWindowMinimised = nowMinimised;
  58766. component->minimisationStateChanged (nowMinimised);
  58767. component->sendVisibilityChangeMessage();
  58768. }
  58769. if (! isFullScreen())
  58770. lastNonFullscreenBounds = component->getBounds();
  58771. }
  58772. void ComponentPeer::handleFocusGain()
  58773. {
  58774. updateCurrentModifiers();
  58775. if (component->isParentOf (lastFocusedComponent))
  58776. {
  58777. Component::currentlyFocusedComponent = lastFocusedComponent;
  58778. Desktop::getInstance().triggerFocusCallback();
  58779. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  58780. }
  58781. else
  58782. {
  58783. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  58784. component->grabKeyboardFocus();
  58785. else
  58786. Component::bringModalComponentToFront();
  58787. }
  58788. }
  58789. void ComponentPeer::handleFocusLoss()
  58790. {
  58791. updateCurrentModifiers();
  58792. if (component->hasKeyboardFocus (true))
  58793. {
  58794. lastFocusedComponent = Component::currentlyFocusedComponent;
  58795. if (lastFocusedComponent != 0)
  58796. {
  58797. Component::currentlyFocusedComponent = 0;
  58798. Desktop::getInstance().triggerFocusCallback();
  58799. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  58800. }
  58801. }
  58802. }
  58803. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  58804. {
  58805. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  58806. ? lastFocusedComponent
  58807. : component;
  58808. }
  58809. void ComponentPeer::handleScreenSizeChange()
  58810. {
  58811. updateCurrentModifiers();
  58812. component->parentSizeChanged();
  58813. handleMovedOrResized();
  58814. }
  58815. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  58816. {
  58817. lastNonFullscreenBounds = newBounds;
  58818. }
  58819. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  58820. {
  58821. return lastNonFullscreenBounds;
  58822. }
  58823. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  58824. const StringArray& files,
  58825. FileDragAndDropTarget* const lastOne)
  58826. {
  58827. while (c != 0)
  58828. {
  58829. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  58830. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  58831. return t;
  58832. c = c->getParentComponent();
  58833. }
  58834. return 0;
  58835. }
  58836. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  58837. {
  58838. updateCurrentModifiers();
  58839. FileDragAndDropTarget* lastTarget = 0;
  58840. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58841. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58842. FileDragAndDropTarget* newTarget = 0;
  58843. Component* const compUnderMouse = component->getComponentAt (x, y);
  58844. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  58845. {
  58846. lastDragAndDropCompUnderMouse = compUnderMouse;
  58847. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  58848. if (newTarget != lastTarget)
  58849. {
  58850. if (lastTarget != 0)
  58851. lastTarget->fileDragExit (files);
  58852. deleteAndZero (dragAndDropTargetComponent);
  58853. if (newTarget != 0)
  58854. {
  58855. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  58856. int mx = x, my = y;
  58857. component->relativePositionToOtherComponent (targetComp, mx, my);
  58858. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  58859. newTarget->fileDragEnter (files, mx, my);
  58860. }
  58861. }
  58862. }
  58863. else
  58864. {
  58865. newTarget = lastTarget;
  58866. }
  58867. if (newTarget != 0)
  58868. {
  58869. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  58870. component->relativePositionToOtherComponent (targetComp, x, y);
  58871. newTarget->fileDragMove (files, x, y);
  58872. }
  58873. }
  58874. void ComponentPeer::handleFileDragExit (const StringArray& files)
  58875. {
  58876. handleFileDragMove (files, -1, -1);
  58877. jassert (dragAndDropTargetComponent == 0);
  58878. lastDragAndDropCompUnderMouse = 0;
  58879. }
  58880. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  58881. {
  58882. handleFileDragMove (files, x, y);
  58883. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58884. {
  58885. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58886. deleteAndZero (dragAndDropTargetComponent);
  58887. lastDragAndDropCompUnderMouse = 0;
  58888. if (target != 0)
  58889. {
  58890. Component* const targetComp = dynamic_cast <Component*> (target);
  58891. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  58892. {
  58893. targetComp->internalModalInputAttempt();
  58894. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  58895. return;
  58896. }
  58897. component->relativePositionToOtherComponent (targetComp, x, y);
  58898. target->filesDropped (files, x, y);
  58899. }
  58900. }
  58901. }
  58902. void ComponentPeer::handleUserClosingWindow()
  58903. {
  58904. updateCurrentModifiers();
  58905. component->userTriedToCloseWindow();
  58906. }
  58907. void ComponentPeer::bringModalComponentToFront()
  58908. {
  58909. Component::bringModalComponentToFront();
  58910. }
  58911. void ComponentPeer::clearMaskedRegion() throw()
  58912. {
  58913. maskedRegion.clear();
  58914. }
  58915. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  58916. {
  58917. maskedRegion.add (x, y, w, h);
  58918. }
  58919. END_JUCE_NAMESPACE
  58920. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  58921. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  58922. BEGIN_JUCE_NAMESPACE
  58923. DialogWindow::DialogWindow (const String& name,
  58924. const Colour& backgroundColour_,
  58925. const bool escapeKeyTriggersCloseButton_,
  58926. const bool addToDesktop_)
  58927. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  58928. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  58929. {
  58930. }
  58931. DialogWindow::~DialogWindow()
  58932. {
  58933. }
  58934. void DialogWindow::resized()
  58935. {
  58936. DocumentWindow::resized();
  58937. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  58938. if (escapeKeyTriggersCloseButton
  58939. && getCloseButton() != 0
  58940. && ! getCloseButton()->isRegisteredForShortcut (esc))
  58941. {
  58942. getCloseButton()->addShortcut (esc);
  58943. }
  58944. }
  58945. class TempDialogWindow : public DialogWindow
  58946. {
  58947. public:
  58948. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  58949. : DialogWindow (title, colour, escapeCloses, true)
  58950. {
  58951. }
  58952. ~TempDialogWindow()
  58953. {
  58954. }
  58955. void closeButtonPressed()
  58956. {
  58957. setVisible (false);
  58958. }
  58959. private:
  58960. TempDialogWindow (const TempDialogWindow&);
  58961. const TempDialogWindow& operator= (const TempDialogWindow&);
  58962. };
  58963. int DialogWindow::showModalDialog (const String& dialogTitle,
  58964. Component* contentComponent,
  58965. Component* componentToCentreAround,
  58966. const Colour& colour,
  58967. const bool escapeKeyTriggersCloseButton,
  58968. const bool shouldBeResizable,
  58969. const bool useBottomRightCornerResizer)
  58970. {
  58971. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  58972. dw.setContentComponent (contentComponent, true, true);
  58973. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  58974. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  58975. const int result = dw.runModalLoop();
  58976. dw.setContentComponent (0, false);
  58977. return result;
  58978. }
  58979. END_JUCE_NAMESPACE
  58980. /********* End of inlined file: juce_DialogWindow.cpp *********/
  58981. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  58982. BEGIN_JUCE_NAMESPACE
  58983. DocumentWindow::DocumentWindow (const String& title,
  58984. const Colour& backgroundColour,
  58985. const int requiredButtons_,
  58986. const bool addToDesktop_)
  58987. : ResizableWindow (title, backgroundColour, addToDesktop_),
  58988. titleBarHeight (26),
  58989. menuBarHeight (24),
  58990. requiredButtons (requiredButtons_),
  58991. #if JUCE_MAC
  58992. positionTitleBarButtonsOnLeft (true),
  58993. #else
  58994. positionTitleBarButtonsOnLeft (false),
  58995. #endif
  58996. drawTitleTextCentred (true),
  58997. titleBarIcon (0),
  58998. menuBar (0),
  58999. menuBarModel (0)
  59000. {
  59001. zeromem (titleBarButtons, sizeof (titleBarButtons));
  59002. setResizeLimits (128, 128, 32768, 32768);
  59003. lookAndFeelChanged();
  59004. }
  59005. DocumentWindow::~DocumentWindow()
  59006. {
  59007. for (int i = 0; i < 3; ++i)
  59008. delete titleBarButtons[i];
  59009. delete titleBarIcon;
  59010. delete menuBar;
  59011. }
  59012. void DocumentWindow::repaintTitleBar()
  59013. {
  59014. const int border = getBorderSize();
  59015. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  59016. }
  59017. void DocumentWindow::setName (const String& newName)
  59018. {
  59019. if (newName != getName())
  59020. {
  59021. Component::setName (newName);
  59022. repaintTitleBar();
  59023. }
  59024. }
  59025. void DocumentWindow::setIcon (const Image* imageToUse)
  59026. {
  59027. deleteAndZero (titleBarIcon);
  59028. if (imageToUse != 0)
  59029. titleBarIcon = imageToUse->createCopy();
  59030. repaintTitleBar();
  59031. }
  59032. void DocumentWindow::setTitleBarHeight (const int newHeight)
  59033. {
  59034. titleBarHeight = newHeight;
  59035. resized();
  59036. repaintTitleBar();
  59037. }
  59038. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  59039. const bool positionTitleBarButtonsOnLeft_)
  59040. {
  59041. requiredButtons = requiredButtons_;
  59042. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  59043. lookAndFeelChanged();
  59044. }
  59045. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  59046. {
  59047. drawTitleTextCentred = textShouldBeCentred;
  59048. repaintTitleBar();
  59049. }
  59050. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  59051. const int menuBarHeight_)
  59052. {
  59053. if (menuBarModel != menuBarModel_)
  59054. {
  59055. delete menuBar;
  59056. menuBar = 0;
  59057. menuBarModel = menuBarModel_;
  59058. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  59059. : getLookAndFeel().getDefaultMenuBarHeight();
  59060. if (menuBarModel != 0)
  59061. {
  59062. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59063. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  59064. menuBar->setEnabled (isActiveWindow());
  59065. }
  59066. resized();
  59067. }
  59068. }
  59069. void DocumentWindow::closeButtonPressed()
  59070. {
  59071. /* If you've got a close button, you have to override this method to get
  59072. rid of your window!
  59073. If the window is just a pop-up, you should override this method and make
  59074. it delete the window in whatever way is appropriate for your app. E.g. you
  59075. might just want to call "delete this".
  59076. If your app is centred around this window such that the whole app should quit when
  59077. the window is closed, then you will probably want to use this method as an opportunity
  59078. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  59079. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  59080. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  59081. or closing it via the taskbar icon on Windows).
  59082. */
  59083. jassertfalse
  59084. }
  59085. void DocumentWindow::minimiseButtonPressed()
  59086. {
  59087. setMinimised (true);
  59088. }
  59089. void DocumentWindow::maximiseButtonPressed()
  59090. {
  59091. setFullScreen (! isFullScreen());
  59092. }
  59093. void DocumentWindow::paint (Graphics& g)
  59094. {
  59095. ResizableWindow::paint (g);
  59096. if (resizableBorder == 0 && getBorderSize() == 1)
  59097. {
  59098. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  59099. g.drawRect (0, 0, getWidth(), getHeight());
  59100. }
  59101. const int border = getBorderSize();
  59102. g.setOrigin (border, border);
  59103. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  59104. int titleSpaceX1 = 6;
  59105. int titleSpaceX2 = getWidth() - 6;
  59106. for (int i = 0; i < 3; ++i)
  59107. {
  59108. if (titleBarButtons[i] != 0)
  59109. {
  59110. if (positionTitleBarButtonsOnLeft)
  59111. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  59112. else
  59113. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  59114. }
  59115. }
  59116. getLookAndFeel()
  59117. .drawDocumentWindowTitleBar (*this, g,
  59118. getWidth() - border * 2,
  59119. getTitleBarHeight(),
  59120. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  59121. titleBarIcon, ! drawTitleTextCentred);
  59122. }
  59123. void DocumentWindow::resized()
  59124. {
  59125. ResizableWindow::resized();
  59126. if (titleBarButtons[1] != 0)
  59127. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  59128. const int border = getBorderSize();
  59129. getLookAndFeel()
  59130. .positionDocumentWindowButtons (*this,
  59131. border, border,
  59132. getWidth() - border * 2, getTitleBarHeight(),
  59133. titleBarButtons[0],
  59134. titleBarButtons[1],
  59135. titleBarButtons[2],
  59136. positionTitleBarButtonsOnLeft);
  59137. if (menuBar != 0)
  59138. menuBar->setBounds (border, border + getTitleBarHeight(),
  59139. getWidth() - border * 2, menuBarHeight);
  59140. }
  59141. Button* DocumentWindow::getCloseButton() const throw()
  59142. {
  59143. return titleBarButtons[2];
  59144. }
  59145. Button* DocumentWindow::getMinimiseButton() const throw()
  59146. {
  59147. return titleBarButtons[0];
  59148. }
  59149. Button* DocumentWindow::getMaximiseButton() const throw()
  59150. {
  59151. return titleBarButtons[1];
  59152. }
  59153. int DocumentWindow::getDesktopWindowStyleFlags() const
  59154. {
  59155. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  59156. if ((requiredButtons & minimiseButton) != 0)
  59157. flags |= ComponentPeer::windowHasMinimiseButton;
  59158. if ((requiredButtons & maximiseButton) != 0)
  59159. flags |= ComponentPeer::windowHasMaximiseButton;
  59160. if ((requiredButtons & closeButton) != 0)
  59161. flags |= ComponentPeer::windowHasCloseButton;
  59162. return flags;
  59163. }
  59164. void DocumentWindow::lookAndFeelChanged()
  59165. {
  59166. int i;
  59167. for (i = 0; i < 3; ++i)
  59168. deleteAndZero (titleBarButtons[i]);
  59169. if (! isUsingNativeTitleBar())
  59170. {
  59171. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  59172. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  59173. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  59174. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  59175. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  59176. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  59177. for (i = 0; i < 3; ++i)
  59178. {
  59179. if (titleBarButtons[i] != 0)
  59180. {
  59181. buttonListener.owner = this;
  59182. titleBarButtons[i]->addButtonListener (&buttonListener);
  59183. titleBarButtons[i]->setWantsKeyboardFocus (false);
  59184. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59185. Component::addAndMakeVisible (titleBarButtons[i]);
  59186. }
  59187. }
  59188. if (getCloseButton() != 0)
  59189. {
  59190. #if JUCE_MAC
  59191. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  59192. #else
  59193. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  59194. #endif
  59195. }
  59196. }
  59197. activeWindowStatusChanged();
  59198. ResizableWindow::lookAndFeelChanged();
  59199. }
  59200. void DocumentWindow::parentHierarchyChanged()
  59201. {
  59202. lookAndFeelChanged();
  59203. }
  59204. void DocumentWindow::activeWindowStatusChanged()
  59205. {
  59206. ResizableWindow::activeWindowStatusChanged();
  59207. for (int i = 0; i < 3; ++i)
  59208. if (titleBarButtons[i] != 0)
  59209. titleBarButtons[i]->setEnabled (isActiveWindow());
  59210. if (menuBar != 0)
  59211. menuBar->setEnabled (isActiveWindow());
  59212. }
  59213. const BorderSize DocumentWindow::getBorderThickness()
  59214. {
  59215. return BorderSize (getBorderSize());
  59216. }
  59217. const BorderSize DocumentWindow::getContentComponentBorder()
  59218. {
  59219. const int size = getBorderSize();
  59220. return BorderSize (size
  59221. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  59222. + (menuBar != 0 ? menuBarHeight : 0),
  59223. size, size, size);
  59224. }
  59225. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  59226. {
  59227. const int border = getBorderSize();
  59228. if (e.x >= border
  59229. && e.y >= border
  59230. && e.x < getWidth() - border
  59231. && e.y < border + getTitleBarHeight()
  59232. && getMaximiseButton() != 0)
  59233. {
  59234. getMaximiseButton()->triggerClick();
  59235. }
  59236. }
  59237. void DocumentWindow::userTriedToCloseWindow()
  59238. {
  59239. closeButtonPressed();
  59240. }
  59241. int DocumentWindow::getTitleBarHeight() const
  59242. {
  59243. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  59244. }
  59245. int DocumentWindow::getBorderSize() const
  59246. {
  59247. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  59248. }
  59249. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  59250. {
  59251. }
  59252. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  59253. {
  59254. if (button == owner->getMinimiseButton())
  59255. {
  59256. owner->minimiseButtonPressed();
  59257. }
  59258. else if (button == owner->getMaximiseButton())
  59259. {
  59260. owner->maximiseButtonPressed();
  59261. }
  59262. else if (button == owner->getCloseButton())
  59263. {
  59264. owner->closeButtonPressed();
  59265. }
  59266. }
  59267. END_JUCE_NAMESPACE
  59268. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  59269. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  59270. BEGIN_JUCE_NAMESPACE
  59271. ResizableWindow::ResizableWindow (const String& name,
  59272. const bool addToDesktop_)
  59273. : TopLevelWindow (name, addToDesktop_),
  59274. resizableCorner (0),
  59275. resizableBorder (0),
  59276. contentComponent (0),
  59277. resizeToFitContent (false),
  59278. fullscreen (false),
  59279. lastNonFullScreenPos (50, 50, 256, 256),
  59280. constrainer (0)
  59281. #ifdef JUCE_DEBUG
  59282. , hasBeenResized (false)
  59283. #endif
  59284. {
  59285. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59286. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  59287. if (addToDesktop_)
  59288. Component::addToDesktop (getDesktopWindowStyleFlags());
  59289. }
  59290. ResizableWindow::ResizableWindow (const String& name,
  59291. const Colour& backgroundColour_,
  59292. const bool addToDesktop_)
  59293. : TopLevelWindow (name, addToDesktop_),
  59294. resizableCorner (0),
  59295. resizableBorder (0),
  59296. contentComponent (0),
  59297. resizeToFitContent (false),
  59298. fullscreen (false),
  59299. lastNonFullScreenPos (50, 50, 256, 256),
  59300. constrainer (0)
  59301. #ifdef JUCE_DEBUG
  59302. , hasBeenResized (false)
  59303. #endif
  59304. {
  59305. setBackgroundColour (backgroundColour_);
  59306. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59307. if (addToDesktop_)
  59308. Component::addToDesktop (getDesktopWindowStyleFlags());
  59309. }
  59310. ResizableWindow::~ResizableWindow()
  59311. {
  59312. deleteAndZero (resizableCorner);
  59313. deleteAndZero (resizableBorder);
  59314. deleteAndZero (contentComponent);
  59315. // have you been adding your own components directly to this window..? tut tut tut.
  59316. // Read the instructions for using a ResizableWindow!
  59317. jassert (getNumChildComponents() == 0);
  59318. }
  59319. int ResizableWindow::getDesktopWindowStyleFlags() const
  59320. {
  59321. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  59322. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  59323. flags |= ComponentPeer::windowIsResizable;
  59324. return flags;
  59325. }
  59326. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  59327. const bool deleteOldOne,
  59328. const bool resizeToFit)
  59329. {
  59330. resizeToFitContent = resizeToFit;
  59331. if (contentComponent != newContentComponent)
  59332. {
  59333. if (deleteOldOne)
  59334. delete contentComponent;
  59335. else
  59336. removeChildComponent (contentComponent);
  59337. contentComponent = newContentComponent;
  59338. Component::addAndMakeVisible (contentComponent);
  59339. }
  59340. if (resizeToFit)
  59341. childBoundsChanged (contentComponent);
  59342. resized(); // must always be called to position the new content comp
  59343. }
  59344. void ResizableWindow::setContentComponentSize (int width, int height)
  59345. {
  59346. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  59347. const BorderSize border (getContentComponentBorder());
  59348. setSize (width + border.getLeftAndRight(),
  59349. height + border.getTopAndBottom());
  59350. }
  59351. const BorderSize ResizableWindow::getBorderThickness()
  59352. {
  59353. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  59354. }
  59355. const BorderSize ResizableWindow::getContentComponentBorder()
  59356. {
  59357. return getBorderThickness();
  59358. }
  59359. void ResizableWindow::moved()
  59360. {
  59361. updateLastPos();
  59362. }
  59363. void ResizableWindow::visibilityChanged()
  59364. {
  59365. TopLevelWindow::visibilityChanged();
  59366. updateLastPos();
  59367. }
  59368. void ResizableWindow::resized()
  59369. {
  59370. if (resizableBorder != 0)
  59371. {
  59372. resizableBorder->setVisible (! isFullScreen());
  59373. resizableBorder->setBorderThickness (getBorderThickness());
  59374. resizableBorder->setSize (getWidth(), getHeight());
  59375. resizableBorder->toBack();
  59376. }
  59377. if (resizableCorner != 0)
  59378. {
  59379. resizableCorner->setVisible (! isFullScreen());
  59380. const int resizerSize = 18;
  59381. resizableCorner->setBounds (getWidth() - resizerSize,
  59382. getHeight() - resizerSize,
  59383. resizerSize, resizerSize);
  59384. }
  59385. if (contentComponent != 0)
  59386. contentComponent->setBoundsInset (getContentComponentBorder());
  59387. updateLastPos();
  59388. #ifdef JUCE_DEBUG
  59389. hasBeenResized = true;
  59390. #endif
  59391. }
  59392. void ResizableWindow::childBoundsChanged (Component* child)
  59393. {
  59394. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  59395. {
  59396. // not going to look very good if this component has a zero size..
  59397. jassert (child->getWidth() > 0);
  59398. jassert (child->getHeight() > 0);
  59399. const BorderSize borders (getContentComponentBorder());
  59400. setSize (child->getWidth() + borders.getLeftAndRight(),
  59401. child->getHeight() + borders.getTopAndBottom());
  59402. }
  59403. }
  59404. void ResizableWindow::activeWindowStatusChanged()
  59405. {
  59406. const BorderSize borders (getContentComponentBorder());
  59407. repaint (0, 0, getWidth(), borders.getTop());
  59408. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  59409. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  59410. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  59411. }
  59412. void ResizableWindow::setResizable (const bool shouldBeResizable,
  59413. const bool useBottomRightCornerResizer)
  59414. {
  59415. if (shouldBeResizable)
  59416. {
  59417. if (useBottomRightCornerResizer)
  59418. {
  59419. deleteAndZero (resizableBorder);
  59420. if (resizableCorner == 0)
  59421. {
  59422. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  59423. resizableCorner->setAlwaysOnTop (true);
  59424. }
  59425. }
  59426. else
  59427. {
  59428. deleteAndZero (resizableCorner);
  59429. if (resizableBorder == 0)
  59430. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  59431. }
  59432. }
  59433. else
  59434. {
  59435. deleteAndZero (resizableCorner);
  59436. deleteAndZero (resizableBorder);
  59437. }
  59438. if (isUsingNativeTitleBar())
  59439. recreateDesktopWindow();
  59440. childBoundsChanged (contentComponent);
  59441. resized();
  59442. }
  59443. bool ResizableWindow::isResizable() const throw()
  59444. {
  59445. return resizableCorner != 0
  59446. || resizableBorder != 0;
  59447. }
  59448. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  59449. const int newMinimumHeight,
  59450. const int newMaximumWidth,
  59451. const int newMaximumHeight) throw()
  59452. {
  59453. // if you've set up a custom constrainer then these settings won't have any effect..
  59454. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  59455. if (constrainer == 0)
  59456. setConstrainer (&defaultConstrainer);
  59457. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  59458. newMaximumWidth, newMaximumHeight);
  59459. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  59460. }
  59461. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  59462. {
  59463. if (constrainer != newConstrainer)
  59464. {
  59465. constrainer = newConstrainer;
  59466. const bool useBottomRightCornerResizer = resizableCorner != 0;
  59467. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  59468. deleteAndZero (resizableCorner);
  59469. deleteAndZero (resizableBorder);
  59470. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  59471. ComponentPeer* const peer = getPeer();
  59472. if (peer != 0)
  59473. peer->setConstrainer (newConstrainer);
  59474. }
  59475. }
  59476. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  59477. {
  59478. if (constrainer != 0)
  59479. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  59480. else
  59481. setBounds (x, y, w, h);
  59482. }
  59483. void ResizableWindow::paint (Graphics& g)
  59484. {
  59485. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  59486. getBorderThickness(), *this);
  59487. if (! isFullScreen())
  59488. {
  59489. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  59490. getBorderThickness(), *this);
  59491. }
  59492. #ifdef JUCE_DEBUG
  59493. /* If this fails, then you've probably written a subclass with a resized()
  59494. callback but forgotten to make it call its parent class's resized() method.
  59495. It's important when you override methods like resized(), moved(),
  59496. etc., that you make sure the base class methods also get called.
  59497. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  59498. because your content should all be inside the content component - and it's the
  59499. content component's resized() method that you should be using to do your
  59500. layout.
  59501. */
  59502. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  59503. #endif
  59504. }
  59505. void ResizableWindow::lookAndFeelChanged()
  59506. {
  59507. resized();
  59508. if (isOnDesktop())
  59509. {
  59510. Component::addToDesktop (getDesktopWindowStyleFlags());
  59511. ComponentPeer* const peer = getPeer();
  59512. if (peer != 0)
  59513. peer->setConstrainer (constrainer);
  59514. }
  59515. }
  59516. const Colour ResizableWindow::getBackgroundColour() const throw()
  59517. {
  59518. return findColour (backgroundColourId, false);
  59519. }
  59520. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  59521. {
  59522. Colour backgroundColour (newColour);
  59523. if (! Desktop::canUseSemiTransparentWindows())
  59524. backgroundColour = newColour.withAlpha (1.0f);
  59525. setColour (backgroundColourId, backgroundColour);
  59526. setOpaque (backgroundColour.isOpaque());
  59527. repaint();
  59528. }
  59529. bool ResizableWindow::isFullScreen() const
  59530. {
  59531. if (isOnDesktop())
  59532. {
  59533. ComponentPeer* const peer = getPeer();
  59534. return peer != 0 && peer->isFullScreen();
  59535. }
  59536. return fullscreen;
  59537. }
  59538. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  59539. {
  59540. if (shouldBeFullScreen != isFullScreen())
  59541. {
  59542. updateLastPos();
  59543. fullscreen = shouldBeFullScreen;
  59544. if (isOnDesktop())
  59545. {
  59546. ComponentPeer* const peer = getPeer();
  59547. if (peer != 0)
  59548. {
  59549. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  59550. const Rectangle lastPos (lastNonFullScreenPos);
  59551. peer->setFullScreen (shouldBeFullScreen);
  59552. if (! shouldBeFullScreen)
  59553. setBounds (lastPos);
  59554. }
  59555. else
  59556. {
  59557. jassertfalse
  59558. }
  59559. }
  59560. else
  59561. {
  59562. if (shouldBeFullScreen)
  59563. setBounds (0, 0, getParentWidth(), getParentHeight());
  59564. else
  59565. setBounds (lastNonFullScreenPos);
  59566. }
  59567. resized();
  59568. }
  59569. }
  59570. bool ResizableWindow::isMinimised() const
  59571. {
  59572. ComponentPeer* const peer = getPeer();
  59573. return (peer != 0) && peer->isMinimised();
  59574. }
  59575. void ResizableWindow::setMinimised (const bool shouldMinimise)
  59576. {
  59577. if (shouldMinimise != isMinimised())
  59578. {
  59579. ComponentPeer* const peer = getPeer();
  59580. if (peer != 0)
  59581. {
  59582. updateLastPos();
  59583. peer->setMinimised (shouldMinimise);
  59584. }
  59585. else
  59586. {
  59587. jassertfalse
  59588. }
  59589. }
  59590. }
  59591. void ResizableWindow::updateLastPos()
  59592. {
  59593. if (isShowing() && ! (isFullScreen() || isMinimised()))
  59594. {
  59595. lastNonFullScreenPos = getBounds();
  59596. }
  59597. }
  59598. void ResizableWindow::parentSizeChanged()
  59599. {
  59600. if (isFullScreen() && getParentComponent() != 0)
  59601. {
  59602. setBounds (0, 0, getParentWidth(), getParentHeight());
  59603. }
  59604. }
  59605. const String ResizableWindow::getWindowStateAsString()
  59606. {
  59607. updateLastPos();
  59608. String s;
  59609. if (isFullScreen())
  59610. s << "fs ";
  59611. s << lastNonFullScreenPos.getX() << T(' ')
  59612. << lastNonFullScreenPos.getY() << T(' ')
  59613. << lastNonFullScreenPos.getWidth() << T(' ')
  59614. << lastNonFullScreenPos.getHeight();
  59615. return s;
  59616. }
  59617. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  59618. {
  59619. StringArray tokens;
  59620. tokens.addTokens (s, false);
  59621. tokens.removeEmptyStrings();
  59622. tokens.trim();
  59623. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  59624. const int n = fs ? 1 : 0;
  59625. if (tokens.size() != 4 + n)
  59626. return false;
  59627. Rectangle r (tokens[n].getIntValue(),
  59628. tokens[n + 1].getIntValue(),
  59629. tokens[n + 2].getIntValue(),
  59630. tokens[n + 3].getIntValue());
  59631. if (r.isEmpty())
  59632. return false;
  59633. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  59634. if (! screen.contains (r))
  59635. {
  59636. r.setSize (jmin (r.getWidth(), screen.getWidth()),
  59637. jmin (r.getHeight(), screen.getHeight()));
  59638. r.setPosition (jlimit (screen.getX(), screen.getRight() - r.getWidth(), r.getX()),
  59639. jlimit (screen.getY(), screen.getBottom() - r.getHeight(), r.getY()));
  59640. }
  59641. lastNonFullScreenPos = r;
  59642. if (isOnDesktop())
  59643. {
  59644. ComponentPeer* const peer = getPeer();
  59645. if (peer != 0)
  59646. peer->setNonFullScreenBounds (r);
  59647. }
  59648. setFullScreen (fs);
  59649. if (! fs)
  59650. setBoundsConstrained (r.getX(),
  59651. r.getY(),
  59652. r.getWidth(),
  59653. r.getHeight());
  59654. return true;
  59655. }
  59656. void ResizableWindow::mouseDown (const MouseEvent&)
  59657. {
  59658. if (! isFullScreen())
  59659. dragger.startDraggingComponent (this, constrainer);
  59660. }
  59661. void ResizableWindow::mouseDrag (const MouseEvent& e)
  59662. {
  59663. if (! isFullScreen())
  59664. dragger.dragComponent (this, e);
  59665. }
  59666. #ifdef JUCE_DEBUG
  59667. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  59668. {
  59669. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59670. manages its child components automatically, and if you add your own it'll cause
  59671. trouble. Instead, use setContentComponent() to give it a component which
  59672. will be automatically resized and kept in the right place - then you can add
  59673. subcomponents to the content comp. See the notes for the ResizableWindow class
  59674. for more info.
  59675. If you really know what you're doing and want to avoid this assertion, just call
  59676. Component::addChildComponent directly.
  59677. */
  59678. jassertfalse
  59679. Component::addChildComponent (child, zOrder);
  59680. }
  59681. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  59682. {
  59683. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59684. manages its child components automatically, and if you add your own it'll cause
  59685. trouble. Instead, use setContentComponent() to give it a component which
  59686. will be automatically resized and kept in the right place - then you can add
  59687. subcomponents to the content comp. See the notes for the ResizableWindow class
  59688. for more info.
  59689. If you really know what you're doing and want to avoid this assertion, just call
  59690. Component::addAndMakeVisible directly.
  59691. */
  59692. jassertfalse
  59693. Component::addAndMakeVisible (child, zOrder);
  59694. }
  59695. #endif
  59696. END_JUCE_NAMESPACE
  59697. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  59698. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  59699. BEGIN_JUCE_NAMESPACE
  59700. SplashScreen::SplashScreen()
  59701. : backgroundImage (0),
  59702. isImageInCache (false)
  59703. {
  59704. setOpaque (true);
  59705. }
  59706. SplashScreen::~SplashScreen()
  59707. {
  59708. if (isImageInCache)
  59709. ImageCache::release (backgroundImage);
  59710. else
  59711. delete backgroundImage;
  59712. }
  59713. void SplashScreen::show (const String& title,
  59714. Image* const backgroundImage_,
  59715. const int minimumTimeToDisplayFor,
  59716. const bool useDropShadow,
  59717. const bool removeOnMouseClick)
  59718. {
  59719. backgroundImage = backgroundImage_;
  59720. jassert (backgroundImage_ != 0);
  59721. if (backgroundImage_ != 0)
  59722. {
  59723. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  59724. setOpaque (! backgroundImage_->hasAlphaChannel());
  59725. show (title,
  59726. backgroundImage_->getWidth(),
  59727. backgroundImage_->getHeight(),
  59728. minimumTimeToDisplayFor,
  59729. useDropShadow,
  59730. removeOnMouseClick);
  59731. }
  59732. }
  59733. void SplashScreen::show (const String& title,
  59734. const int width,
  59735. const int height,
  59736. const int minimumTimeToDisplayFor,
  59737. const bool useDropShadow,
  59738. const bool removeOnMouseClick)
  59739. {
  59740. setName (title);
  59741. setAlwaysOnTop (true);
  59742. setVisible (true);
  59743. centreWithSize (width, height);
  59744. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  59745. toFront (false);
  59746. MessageManager::getInstance()->runDispatchLoopUntil (300);
  59747. repaint();
  59748. originalClickCounter = removeOnMouseClick
  59749. ? Desktop::getMouseButtonClickCounter()
  59750. : INT_MAX;
  59751. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  59752. startTimer (50);
  59753. }
  59754. void SplashScreen::paint (Graphics& g)
  59755. {
  59756. if (backgroundImage != 0)
  59757. {
  59758. g.setOpacity (1.0f);
  59759. g.drawImage (backgroundImage,
  59760. 0, 0, getWidth(), getHeight(),
  59761. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  59762. }
  59763. }
  59764. void SplashScreen::timerCallback()
  59765. {
  59766. if (Time::getCurrentTime() > earliestTimeToDelete
  59767. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  59768. {
  59769. delete this;
  59770. }
  59771. }
  59772. END_JUCE_NAMESPACE
  59773. /********* End of inlined file: juce_SplashScreen.cpp *********/
  59774. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59775. BEGIN_JUCE_NAMESPACE
  59776. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  59777. const bool hasProgressBar,
  59778. const bool hasCancelButton,
  59779. const int timeOutMsWhenCancelling_,
  59780. const String& cancelButtonText)
  59781. : Thread ("Juce Progress Window"),
  59782. progress (0.0),
  59783. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  59784. {
  59785. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  59786. .createAlertWindow (title, String::empty, cancelButtonText,
  59787. String::empty, String::empty,
  59788. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  59789. if (hasProgressBar)
  59790. alertWindow->addProgressBarComponent (progress);
  59791. }
  59792. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  59793. {
  59794. stopThread (timeOutMsWhenCancelling);
  59795. delete alertWindow;
  59796. }
  59797. bool ThreadWithProgressWindow::runThread (const int priority)
  59798. {
  59799. startThread (priority);
  59800. startTimer (100);
  59801. {
  59802. const ScopedLock sl (messageLock);
  59803. alertWindow->setMessage (message);
  59804. }
  59805. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  59806. stopThread (timeOutMsWhenCancelling);
  59807. alertWindow->setVisible (false);
  59808. return finishedNaturally;
  59809. }
  59810. void ThreadWithProgressWindow::setProgress (const double newProgress)
  59811. {
  59812. progress = newProgress;
  59813. }
  59814. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  59815. {
  59816. const ScopedLock sl (messageLock);
  59817. message = newStatusMessage;
  59818. }
  59819. void ThreadWithProgressWindow::timerCallback()
  59820. {
  59821. if (! isThreadRunning())
  59822. {
  59823. // thread has finished normally..
  59824. alertWindow->exitModalState (1);
  59825. alertWindow->setVisible (false);
  59826. }
  59827. else
  59828. {
  59829. const ScopedLock sl (messageLock);
  59830. alertWindow->setMessage (message);
  59831. }
  59832. }
  59833. END_JUCE_NAMESPACE
  59834. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59835. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  59836. BEGIN_JUCE_NAMESPACE
  59837. TooltipWindow::TooltipWindow (Component* const parentComponent,
  59838. const int millisecondsBeforeTipAppears_)
  59839. : Component ("tooltip"),
  59840. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  59841. mouseX (0),
  59842. mouseY (0),
  59843. lastHideTime (0),
  59844. lastComponentUnderMouse (0),
  59845. changedCompsSinceShown (true)
  59846. {
  59847. startTimer (123);
  59848. setAlwaysOnTop (true);
  59849. setOpaque (true);
  59850. if (parentComponent != 0)
  59851. parentComponent->addChildComponent (this);
  59852. }
  59853. TooltipWindow::~TooltipWindow()
  59854. {
  59855. hide();
  59856. }
  59857. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  59858. {
  59859. millisecondsBeforeTipAppears = newTimeMs;
  59860. }
  59861. void TooltipWindow::paint (Graphics& g)
  59862. {
  59863. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  59864. }
  59865. void TooltipWindow::mouseEnter (const MouseEvent&)
  59866. {
  59867. hide();
  59868. }
  59869. void TooltipWindow::showFor (Component* const c, const String& tip)
  59870. {
  59871. jassert (tip.isNotEmpty());
  59872. tipShowing = tip;
  59873. int mx, my;
  59874. Desktop::getMousePosition (mx, my);
  59875. if (getParentComponent() != 0)
  59876. getParentComponent()->globalPositionToRelative (mx, my);
  59877. int x, y, w, h;
  59878. getLookAndFeel().getTooltipSize (tip, w, h);
  59879. if (mx > getParentWidth() / 2)
  59880. x = mx - (w + 12);
  59881. else
  59882. x = mx + 24;
  59883. if (my > getParentHeight() / 2)
  59884. y = my - (h + 6);
  59885. else
  59886. y = my + 6;
  59887. setBounds (x, y, w, h);
  59888. setVisible (true);
  59889. if (getParentComponent() == 0)
  59890. {
  59891. addToDesktop (ComponentPeer::windowHasDropShadow
  59892. | ComponentPeer::windowIsTemporary);
  59893. }
  59894. toFront (false);
  59895. }
  59896. const String TooltipWindow::getTipFor (Component* const c)
  59897. {
  59898. if (c->isValidComponent()
  59899. && Process::isForegroundProcess()
  59900. && ! Component::isMouseButtonDownAnywhere())
  59901. {
  59902. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  59903. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  59904. return ttc->getTooltip();
  59905. }
  59906. return String::empty;
  59907. }
  59908. void TooltipWindow::hide()
  59909. {
  59910. tipShowing = String::empty;
  59911. removeFromDesktop();
  59912. setVisible (false);
  59913. }
  59914. void TooltipWindow::timerCallback()
  59915. {
  59916. const unsigned int now = Time::getApproximateMillisecondCounter();
  59917. Component* const newComp = Component::getComponentUnderMouse();
  59918. const String newTip (getTipFor (newComp));
  59919. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  59920. lastComponentUnderMouse = newComp;
  59921. lastTipUnderMouse = newTip;
  59922. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  59923. const bool mouseWasClicked = clickCount > mouseClicks;
  59924. mouseClicks = clickCount;
  59925. int mx, my;
  59926. Desktop::getMousePosition (mx, my);
  59927. const bool mouseMovedQuickly = (abs (mx - mouseX) + abs (my - mouseY) > 12);
  59928. mouseX = mx;
  59929. mouseY = my;
  59930. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  59931. lastCompChangeTime = now;
  59932. if (isVisible() || now < lastHideTime + 500)
  59933. {
  59934. // if a tip is currently visible (or has just disappeared), update to a new one
  59935. // immediately if needed..
  59936. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  59937. {
  59938. if (isVisible())
  59939. {
  59940. lastHideTime = now;
  59941. hide();
  59942. }
  59943. }
  59944. else if (tipChanged)
  59945. {
  59946. showFor (newComp, newTip);
  59947. }
  59948. }
  59949. else
  59950. {
  59951. // if there isn't currently a tip, but one is needed, only let it
  59952. // appear after a timeout..
  59953. if (newTip.isNotEmpty()
  59954. && newTip != tipShowing
  59955. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  59956. {
  59957. showFor (newComp, newTip);
  59958. }
  59959. }
  59960. }
  59961. END_JUCE_NAMESPACE
  59962. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  59963. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  59964. BEGIN_JUCE_NAMESPACE
  59965. /** Keeps track of the active top level window.
  59966. */
  59967. class TopLevelWindowManager : public Timer,
  59968. public DeletedAtShutdown
  59969. {
  59970. public:
  59971. TopLevelWindowManager()
  59972. : windows (8),
  59973. currentActive (0)
  59974. {
  59975. }
  59976. ~TopLevelWindowManager()
  59977. {
  59978. clearSingletonInstance();
  59979. }
  59980. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  59981. void timerCallback()
  59982. {
  59983. startTimer (jmin (1731, getTimerInterval() * 2));
  59984. TopLevelWindow* active = 0;
  59985. if (Process::isForegroundProcess())
  59986. {
  59987. active = currentActive;
  59988. Component* const c = Component::getCurrentlyFocusedComponent();
  59989. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  59990. if (tlw == 0 && c != 0)
  59991. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  59992. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  59993. if (tlw != 0)
  59994. active = tlw;
  59995. }
  59996. if (active != currentActive)
  59997. {
  59998. currentActive = active;
  59999. for (int i = windows.size(); --i >= 0;)
  60000. {
  60001. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  60002. tlw->setWindowActive (isWindowActive (tlw));
  60003. i = jmin (i, windows.size() - 1);
  60004. }
  60005. Desktop::getInstance().triggerFocusCallback();
  60006. }
  60007. }
  60008. bool addWindow (TopLevelWindow* const w) throw()
  60009. {
  60010. windows.add (w);
  60011. startTimer (10);
  60012. return isWindowActive (w);
  60013. }
  60014. void removeWindow (TopLevelWindow* const w) throw()
  60015. {
  60016. startTimer (10);
  60017. if (currentActive == w)
  60018. currentActive = 0;
  60019. windows.removeValue (w);
  60020. if (windows.size() == 0)
  60021. deleteInstance();
  60022. }
  60023. VoidArray windows;
  60024. private:
  60025. TopLevelWindow* currentActive;
  60026. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  60027. {
  60028. return (tlw == currentActive
  60029. || tlw->isParentOf (currentActive)
  60030. || tlw->hasKeyboardFocus (true))
  60031. && tlw->isShowing();
  60032. }
  60033. TopLevelWindowManager (const TopLevelWindowManager&);
  60034. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  60035. };
  60036. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  60037. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  60038. {
  60039. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  60040. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  60041. }
  60042. TopLevelWindow::TopLevelWindow (const String& name,
  60043. const bool addToDesktop_)
  60044. : Component (name),
  60045. useDropShadow (true),
  60046. useNativeTitleBar (false),
  60047. windowIsActive_ (false),
  60048. shadower (0)
  60049. {
  60050. setOpaque (true);
  60051. if (addToDesktop_)
  60052. Component::addToDesktop (getDesktopWindowStyleFlags());
  60053. else
  60054. setDropShadowEnabled (true);
  60055. setWantsKeyboardFocus (true);
  60056. setBroughtToFrontOnMouseClick (true);
  60057. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  60058. }
  60059. TopLevelWindow::~TopLevelWindow()
  60060. {
  60061. deleteAndZero (shadower);
  60062. TopLevelWindowManager::getInstance()->removeWindow (this);
  60063. }
  60064. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  60065. {
  60066. if (hasKeyboardFocus (true))
  60067. TopLevelWindowManager::getInstance()->timerCallback();
  60068. else
  60069. TopLevelWindowManager::getInstance()->startTimer (10);
  60070. }
  60071. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  60072. {
  60073. if (windowIsActive_ != isNowActive)
  60074. {
  60075. windowIsActive_ = isNowActive;
  60076. activeWindowStatusChanged();
  60077. }
  60078. }
  60079. void TopLevelWindow::activeWindowStatusChanged()
  60080. {
  60081. }
  60082. void TopLevelWindow::parentHierarchyChanged()
  60083. {
  60084. setDropShadowEnabled (useDropShadow);
  60085. }
  60086. void TopLevelWindow::visibilityChanged()
  60087. {
  60088. if (isShowing())
  60089. toFront (true);
  60090. }
  60091. int TopLevelWindow::getDesktopWindowStyleFlags() const
  60092. {
  60093. int flags = ComponentPeer::windowAppearsOnTaskbar;
  60094. if (useDropShadow)
  60095. flags |= ComponentPeer::windowHasDropShadow;
  60096. if (useNativeTitleBar)
  60097. flags |= ComponentPeer::windowHasTitleBar;
  60098. return flags;
  60099. }
  60100. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  60101. {
  60102. useDropShadow = useShadow;
  60103. if (isOnDesktop())
  60104. {
  60105. deleteAndZero (shadower);
  60106. Component::addToDesktop (getDesktopWindowStyleFlags());
  60107. }
  60108. else
  60109. {
  60110. if (useShadow && isOpaque())
  60111. {
  60112. if (shadower == 0)
  60113. {
  60114. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  60115. if (shadower != 0)
  60116. shadower->setOwner (this);
  60117. }
  60118. }
  60119. else
  60120. {
  60121. deleteAndZero (shadower);
  60122. }
  60123. }
  60124. }
  60125. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  60126. {
  60127. if (useNativeTitleBar != useNativeTitleBar_)
  60128. {
  60129. useNativeTitleBar = useNativeTitleBar_;
  60130. recreateDesktopWindow();
  60131. sendLookAndFeelChange();
  60132. }
  60133. }
  60134. void TopLevelWindow::recreateDesktopWindow()
  60135. {
  60136. if (isOnDesktop())
  60137. {
  60138. Component::addToDesktop (getDesktopWindowStyleFlags());
  60139. toFront (true);
  60140. }
  60141. }
  60142. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  60143. {
  60144. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  60145. because this class needs to make sure its layout corresponds with settings like whether
  60146. it's got a native title bar or not.
  60147. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  60148. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  60149. method, then add or remove whatever flags are necessary from this value before returning it.
  60150. */
  60151. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  60152. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  60153. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  60154. if (windowStyleFlags != getDesktopWindowStyleFlags())
  60155. sendLookAndFeelChange();
  60156. }
  60157. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  60158. {
  60159. if (c == 0)
  60160. c = TopLevelWindow::getActiveTopLevelWindow();
  60161. if (c == 0)
  60162. {
  60163. centreWithSize (width, height);
  60164. }
  60165. else
  60166. {
  60167. int x = (c->getWidth() - width) / 2;
  60168. int y = (c->getHeight() - height) / 2;
  60169. c->relativePositionToGlobal (x, y);
  60170. Rectangle parentArea (c->getParentMonitorArea());
  60171. if (getParentComponent() != 0)
  60172. {
  60173. getParentComponent()->globalPositionToRelative (x, y);
  60174. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  60175. }
  60176. parentArea.reduce (12, 12);
  60177. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  60178. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  60179. width, height);
  60180. }
  60181. }
  60182. int TopLevelWindow::getNumTopLevelWindows() throw()
  60183. {
  60184. return TopLevelWindowManager::getInstance()->windows.size();
  60185. }
  60186. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  60187. {
  60188. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  60189. }
  60190. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  60191. {
  60192. TopLevelWindow* best = 0;
  60193. int bestNumTWLParents = -1;
  60194. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  60195. {
  60196. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  60197. if (tlw->isActiveWindow())
  60198. {
  60199. int numTWLParents = 0;
  60200. const Component* c = tlw->getParentComponent();
  60201. while (c != 0)
  60202. {
  60203. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  60204. ++numTWLParents;
  60205. c = c->getParentComponent();
  60206. }
  60207. if (bestNumTWLParents < numTWLParents)
  60208. {
  60209. best = tlw;
  60210. bestNumTWLParents = numTWLParents;
  60211. }
  60212. }
  60213. }
  60214. return best;
  60215. }
  60216. END_JUCE_NAMESPACE
  60217. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  60218. /********* Start of inlined file: juce_Brush.cpp *********/
  60219. BEGIN_JUCE_NAMESPACE
  60220. Brush::Brush() throw()
  60221. {
  60222. }
  60223. Brush::~Brush() throw()
  60224. {
  60225. }
  60226. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  60227. int x, float y1, float y2) throw()
  60228. {
  60229. Path p;
  60230. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  60231. paintPath (context, p, AffineTransform::identity);
  60232. }
  60233. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60234. int y, float x1, float x2) throw()
  60235. {
  60236. Path p;
  60237. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  60238. paintPath (context, p, AffineTransform::identity);
  60239. }
  60240. void Brush::paintLine (LowLevelGraphicsContext& context,
  60241. float x1, float y1, float x2, float y2) throw()
  60242. {
  60243. Path p;
  60244. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  60245. paintPath (context, p, AffineTransform::identity);
  60246. }
  60247. END_JUCE_NAMESPACE
  60248. /********* End of inlined file: juce_Brush.cpp *********/
  60249. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  60250. BEGIN_JUCE_NAMESPACE
  60251. GradientBrush::GradientBrush (const Colour& colour1,
  60252. const float x1,
  60253. const float y1,
  60254. const Colour& colour2,
  60255. const float x2,
  60256. const float y2,
  60257. const bool isRadial) throw()
  60258. : gradient (colour1, x1, y1,
  60259. colour2, x2, y2,
  60260. isRadial)
  60261. {
  60262. }
  60263. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  60264. : gradient (gradient_)
  60265. {
  60266. }
  60267. GradientBrush::~GradientBrush() throw()
  60268. {
  60269. }
  60270. Brush* GradientBrush::createCopy() const throw()
  60271. {
  60272. return new GradientBrush (gradient);
  60273. }
  60274. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  60275. {
  60276. gradient.transform = gradient.transform.followedBy (transform);
  60277. }
  60278. void GradientBrush::multiplyOpacity (const float multiple) throw()
  60279. {
  60280. gradient.multiplyOpacity (multiple);
  60281. }
  60282. bool GradientBrush::isInvisible() const throw()
  60283. {
  60284. return gradient.isInvisible();
  60285. }
  60286. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  60287. const Path& path, const AffineTransform& transform) throw()
  60288. {
  60289. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  60290. }
  60291. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  60292. int x, int y, int w, int h) throw()
  60293. {
  60294. context.fillRectWithGradient (x, y, w, h, gradient);
  60295. }
  60296. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60297. const Image& alphaChannelImage, int imageX, int imageY,
  60298. int x, int y, int w, int h) throw()
  60299. {
  60300. context.saveState();
  60301. if (context.reduceClipRegion (x, y, w, h))
  60302. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  60303. context.restoreState();
  60304. }
  60305. END_JUCE_NAMESPACE
  60306. /********* End of inlined file: juce_GradientBrush.cpp *********/
  60307. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  60308. BEGIN_JUCE_NAMESPACE
  60309. ImageBrush::ImageBrush (Image* const image_,
  60310. const int anchorX_,
  60311. const int anchorY_,
  60312. const float opacity_) throw()
  60313. : image (image_),
  60314. anchorX (anchorX_),
  60315. anchorY (anchorY_),
  60316. opacity (opacity_)
  60317. {
  60318. jassert (image != 0); // not much point creating a brush without an image, is there?
  60319. if (image != 0)
  60320. {
  60321. if (image->getWidth() == 0 || image->getHeight() == 0)
  60322. {
  60323. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  60324. image = 0;
  60325. }
  60326. }
  60327. }
  60328. ImageBrush::~ImageBrush() throw()
  60329. {
  60330. }
  60331. Brush* ImageBrush::createCopy() const throw()
  60332. {
  60333. return new ImageBrush (image, anchorX, anchorY, opacity);
  60334. }
  60335. void ImageBrush::multiplyOpacity (const float multiple) throw()
  60336. {
  60337. opacity *= multiple;
  60338. }
  60339. bool ImageBrush::isInvisible() const throw()
  60340. {
  60341. return opacity == 0.0f;
  60342. }
  60343. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60344. {
  60345. //xxx should probably be smarter and warp the image
  60346. }
  60347. void ImageBrush::getStartXY (int& x, int& y) const throw()
  60348. {
  60349. x -= anchorX;
  60350. y -= anchorY;
  60351. const int iw = image->getWidth();
  60352. const int ih = image->getHeight();
  60353. if (x < 0)
  60354. x = ((x / iw) - 1) * iw;
  60355. else
  60356. x = (x / iw) * iw;
  60357. if (y < 0)
  60358. y = ((y / ih) - 1) * ih;
  60359. else
  60360. y = (y / ih) * ih;
  60361. x += anchorX;
  60362. y += anchorY;
  60363. }
  60364. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  60365. int x, int y, int w, int h) throw()
  60366. {
  60367. context.saveState();
  60368. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60369. {
  60370. const int right = x + w;
  60371. const int bottom = y + h;
  60372. const int iw = image->getWidth();
  60373. const int ih = image->getHeight();
  60374. int startX = x;
  60375. getStartXY (startX, y);
  60376. while (y < bottom)
  60377. {
  60378. x = startX;
  60379. while (x < right)
  60380. {
  60381. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  60382. x += iw;
  60383. }
  60384. y += ih;
  60385. }
  60386. }
  60387. context.restoreState();
  60388. }
  60389. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  60390. const Path& path, const AffineTransform& transform) throw()
  60391. {
  60392. if (image != 0)
  60393. {
  60394. Rectangle clip (context.getClipBounds());
  60395. {
  60396. float x, y, w, h;
  60397. path.getBoundsTransformed (transform, x, y, w, h);
  60398. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  60399. (int) floorf (y),
  60400. 2 + (int) floorf (w),
  60401. 2 + (int) floorf (h)));
  60402. }
  60403. int x = clip.getX();
  60404. int y = clip.getY();
  60405. const int right = clip.getRight();
  60406. const int bottom = clip.getBottom();
  60407. const int iw = image->getWidth();
  60408. const int ih = image->getHeight();
  60409. int startX = x;
  60410. getStartXY (startX, y);
  60411. while (y < bottom)
  60412. {
  60413. x = startX;
  60414. while (x < right)
  60415. {
  60416. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  60417. x += iw;
  60418. }
  60419. y += ih;
  60420. }
  60421. }
  60422. }
  60423. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60424. const Image& alphaChannelImage, int imageX, int imageY,
  60425. int x, int y, int w, int h) throw()
  60426. {
  60427. context.saveState();
  60428. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60429. {
  60430. const Rectangle clip (context.getClipBounds());
  60431. x = clip.getX();
  60432. y = clip.getY();
  60433. const int right = clip.getRight();
  60434. const int bottom = clip.getBottom();
  60435. const int iw = image->getWidth();
  60436. const int ih = image->getHeight();
  60437. int startX = x;
  60438. getStartXY (startX, y);
  60439. while (y < bottom)
  60440. {
  60441. x = startX;
  60442. while (x < right)
  60443. {
  60444. context.fillAlphaChannelWithImage (alphaChannelImage,
  60445. imageX, imageY, *image,
  60446. x, y, opacity);
  60447. x += iw;
  60448. }
  60449. y += ih;
  60450. }
  60451. }
  60452. context.restoreState();
  60453. }
  60454. END_JUCE_NAMESPACE
  60455. /********* End of inlined file: juce_ImageBrush.cpp *********/
  60456. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  60457. BEGIN_JUCE_NAMESPACE
  60458. SolidColourBrush::SolidColourBrush() throw()
  60459. : colour (0xff000000)
  60460. {
  60461. }
  60462. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  60463. : colour (colour_)
  60464. {
  60465. }
  60466. SolidColourBrush::~SolidColourBrush() throw()
  60467. {
  60468. }
  60469. Brush* SolidColourBrush::createCopy() const throw()
  60470. {
  60471. return new SolidColourBrush (colour);
  60472. }
  60473. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60474. {
  60475. }
  60476. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  60477. {
  60478. colour = colour.withMultipliedAlpha (multiple);
  60479. }
  60480. bool SolidColourBrush::isInvisible() const throw()
  60481. {
  60482. return colour.isTransparent();
  60483. }
  60484. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  60485. const Path& path, const AffineTransform& transform) throw()
  60486. {
  60487. if (! colour.isTransparent())
  60488. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  60489. }
  60490. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  60491. int x, int y, int w, int h) throw()
  60492. {
  60493. if (! colour.isTransparent())
  60494. context.fillRectWithColour (x, y, w, h, colour, false);
  60495. }
  60496. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60497. const Image& alphaChannelImage, int imageX, int imageY,
  60498. int x, int y, int w, int h) throw()
  60499. {
  60500. if (! colour.isTransparent())
  60501. {
  60502. context.saveState();
  60503. if (context.reduceClipRegion (x, y, w, h))
  60504. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  60505. context.restoreState();
  60506. }
  60507. }
  60508. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  60509. int x, float y1, float y2) throw()
  60510. {
  60511. context.drawVerticalLine (x, y1, y2, colour);
  60512. }
  60513. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60514. int y, float x1, float x2) throw()
  60515. {
  60516. context.drawHorizontalLine (y, x1, x2, colour);
  60517. }
  60518. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  60519. float x1, float y1, float x2, float y2) throw()
  60520. {
  60521. context.drawLine (x1, y1, x2, y2, colour);
  60522. }
  60523. END_JUCE_NAMESPACE
  60524. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  60525. /********* Start of inlined file: juce_Colour.cpp *********/
  60526. BEGIN_JUCE_NAMESPACE
  60527. static forcedinline uint8 floatAlphaToInt (const float alpha)
  60528. {
  60529. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  60530. }
  60531. static const float oneOver255 = 1.0f / 255.0f;
  60532. Colour::Colour() throw()
  60533. : argb (0)
  60534. {
  60535. }
  60536. Colour::Colour (const Colour& other) throw()
  60537. : argb (other.argb)
  60538. {
  60539. }
  60540. const Colour& Colour::operator= (const Colour& other) throw()
  60541. {
  60542. argb = other.argb;
  60543. return *this;
  60544. }
  60545. bool Colour::operator== (const Colour& other) const throw()
  60546. {
  60547. return argb.getARGB() == other.argb.getARGB();
  60548. }
  60549. bool Colour::operator!= (const Colour& other) const throw()
  60550. {
  60551. return argb.getARGB() != other.argb.getARGB();
  60552. }
  60553. Colour::Colour (const uint32 argb_) throw()
  60554. : argb (argb_)
  60555. {
  60556. }
  60557. Colour::Colour (const uint8 red,
  60558. const uint8 green,
  60559. const uint8 blue) throw()
  60560. {
  60561. argb.setARGB (0xff, red, green, blue);
  60562. }
  60563. const Colour Colour::fromRGB (const uint8 red,
  60564. const uint8 green,
  60565. const uint8 blue) throw()
  60566. {
  60567. return Colour (red, green, blue);
  60568. }
  60569. Colour::Colour (const uint8 red,
  60570. const uint8 green,
  60571. const uint8 blue,
  60572. const uint8 alpha) throw()
  60573. {
  60574. argb.setARGB (alpha, red, green, blue);
  60575. }
  60576. const Colour Colour::fromRGBA (const uint8 red,
  60577. const uint8 green,
  60578. const uint8 blue,
  60579. const uint8 alpha) throw()
  60580. {
  60581. return Colour (red, green, blue, alpha);
  60582. }
  60583. Colour::Colour (const uint8 red,
  60584. const uint8 green,
  60585. const uint8 blue,
  60586. const float alpha) throw()
  60587. {
  60588. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  60589. }
  60590. const Colour Colour::fromRGBAFloat (const uint8 red,
  60591. const uint8 green,
  60592. const uint8 blue,
  60593. const float alpha) throw()
  60594. {
  60595. return Colour (red, green, blue, alpha);
  60596. }
  60597. static void convertHSBtoRGB (float h, const float s, float v,
  60598. uint8& r, uint8& g, uint8& b) throw()
  60599. {
  60600. v *= 255.0f;
  60601. const uint8 intV = (uint8) roundFloatToInt (v);
  60602. if (s == 0)
  60603. {
  60604. r = intV;
  60605. g = intV;
  60606. b = intV;
  60607. }
  60608. else
  60609. {
  60610. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  60611. const float f = h - floorf (h);
  60612. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  60613. const float y = v * (1.0f - s * f);
  60614. const float z = v * (1.0f - (s * (1.0f - f)));
  60615. if (h < 1.0f)
  60616. {
  60617. r = intV;
  60618. g = (uint8) roundFloatToInt (z);
  60619. b = x;
  60620. }
  60621. else if (h < 2.0f)
  60622. {
  60623. r = (uint8) roundFloatToInt (y);
  60624. g = intV;
  60625. b = x;
  60626. }
  60627. else if (h < 3.0f)
  60628. {
  60629. r = x;
  60630. g = intV;
  60631. b = (uint8) roundFloatToInt (z);
  60632. }
  60633. else if (h < 4.0f)
  60634. {
  60635. r = x;
  60636. g = (uint8) roundFloatToInt (y);
  60637. b = intV;
  60638. }
  60639. else if (h < 5.0f)
  60640. {
  60641. r = (uint8) roundFloatToInt (z);
  60642. g = x;
  60643. b = intV;
  60644. }
  60645. else if (h < 6.0f)
  60646. {
  60647. r = intV;
  60648. g = x;
  60649. b = (uint8) roundFloatToInt (y);
  60650. }
  60651. else
  60652. {
  60653. r = 0;
  60654. g = 0;
  60655. b = 0;
  60656. }
  60657. }
  60658. }
  60659. Colour::Colour (const float hue,
  60660. const float saturation,
  60661. const float brightness,
  60662. const float alpha) throw()
  60663. {
  60664. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60665. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60666. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  60667. }
  60668. const Colour Colour::fromHSV (const float hue,
  60669. const float saturation,
  60670. const float brightness,
  60671. const float alpha) throw()
  60672. {
  60673. return Colour (hue, saturation, brightness, alpha);
  60674. }
  60675. Colour::Colour (const float hue,
  60676. const float saturation,
  60677. const float brightness,
  60678. const uint8 alpha) throw()
  60679. {
  60680. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60681. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60682. argb.setARGB (alpha, r, g, b);
  60683. }
  60684. Colour::~Colour() throw()
  60685. {
  60686. }
  60687. const PixelARGB Colour::getPixelARGB() const throw()
  60688. {
  60689. PixelARGB p (argb);
  60690. p.premultiply();
  60691. return p;
  60692. }
  60693. uint32 Colour::getARGB() const throw()
  60694. {
  60695. return argb.getARGB();
  60696. }
  60697. bool Colour::isTransparent() const throw()
  60698. {
  60699. return getAlpha() == 0;
  60700. }
  60701. bool Colour::isOpaque() const throw()
  60702. {
  60703. return getAlpha() == 0xff;
  60704. }
  60705. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  60706. {
  60707. PixelARGB newCol (argb);
  60708. newCol.setAlpha (newAlpha);
  60709. return Colour (newCol.getARGB());
  60710. }
  60711. const Colour Colour::withAlpha (const float newAlpha) const throw()
  60712. {
  60713. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  60714. PixelARGB newCol (argb);
  60715. newCol.setAlpha (floatAlphaToInt (newAlpha));
  60716. return Colour (newCol.getARGB());
  60717. }
  60718. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  60719. {
  60720. jassert (alphaMultiplier >= 0);
  60721. PixelARGB newCol (argb);
  60722. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  60723. return Colour (newCol.getARGB());
  60724. }
  60725. const Colour Colour::overlaidWith (const Colour& src) const throw()
  60726. {
  60727. const int destAlpha = getAlpha();
  60728. if (destAlpha > 0)
  60729. {
  60730. const int invA = 0xff - (int) src.getAlpha();
  60731. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  60732. if (resA > 0)
  60733. {
  60734. const int da = (invA * destAlpha) / resA;
  60735. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  60736. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  60737. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  60738. (uint8) resA);
  60739. }
  60740. return *this;
  60741. }
  60742. else
  60743. {
  60744. return src;
  60745. }
  60746. }
  60747. float Colour::getFloatRed() const throw()
  60748. {
  60749. return getRed() * oneOver255;
  60750. }
  60751. float Colour::getFloatGreen() const throw()
  60752. {
  60753. return getGreen() * oneOver255;
  60754. }
  60755. float Colour::getFloatBlue() const throw()
  60756. {
  60757. return getBlue() * oneOver255;
  60758. }
  60759. float Colour::getFloatAlpha() const throw()
  60760. {
  60761. return getAlpha() * oneOver255;
  60762. }
  60763. void Colour::getHSB (float& h, float& s, float& v) const throw()
  60764. {
  60765. const int r = getRed();
  60766. const int g = getGreen();
  60767. const int b = getBlue();
  60768. const int hi = jmax (r, g, b);
  60769. const int lo = jmin (r, g, b);
  60770. if (hi != 0)
  60771. {
  60772. s = (hi - lo) / (float) hi;
  60773. if (s != 0)
  60774. {
  60775. const float invDiff = 1.0f / (hi - lo);
  60776. const float red = (hi - r) * invDiff;
  60777. const float green = (hi - g) * invDiff;
  60778. const float blue = (hi - b) * invDiff;
  60779. if (r == hi)
  60780. h = blue - green;
  60781. else if (g == hi)
  60782. h = 2.0f + red - blue;
  60783. else
  60784. h = 4.0f + green - red;
  60785. h *= 1.0f / 6.0f;
  60786. if (h < 0)
  60787. ++h;
  60788. }
  60789. else
  60790. {
  60791. h = 0;
  60792. }
  60793. }
  60794. else
  60795. {
  60796. s = 0;
  60797. h = 0;
  60798. }
  60799. v = hi * oneOver255;
  60800. }
  60801. float Colour::getHue() const throw()
  60802. {
  60803. float h, s, b;
  60804. getHSB (h, s, b);
  60805. return h;
  60806. }
  60807. const Colour Colour::withHue (const float hue) const throw()
  60808. {
  60809. float h, s, b;
  60810. getHSB (h, s, b);
  60811. return Colour (hue, s, b, getAlpha());
  60812. }
  60813. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  60814. {
  60815. float h, s, b;
  60816. getHSB (h, s, b);
  60817. h += amountToRotate;
  60818. h -= floorf (h);
  60819. return Colour (h, s, b, getAlpha());
  60820. }
  60821. float Colour::getSaturation() const throw()
  60822. {
  60823. float h, s, b;
  60824. getHSB (h, s, b);
  60825. return s;
  60826. }
  60827. const Colour Colour::withSaturation (const float saturation) const throw()
  60828. {
  60829. float h, s, b;
  60830. getHSB (h, s, b);
  60831. return Colour (h, saturation, b, getAlpha());
  60832. }
  60833. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  60834. {
  60835. float h, s, b;
  60836. getHSB (h, s, b);
  60837. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  60838. }
  60839. float Colour::getBrightness() const throw()
  60840. {
  60841. float h, s, b;
  60842. getHSB (h, s, b);
  60843. return b;
  60844. }
  60845. const Colour Colour::withBrightness (const float brightness) const throw()
  60846. {
  60847. float h, s, b;
  60848. getHSB (h, s, b);
  60849. return Colour (h, s, brightness, getAlpha());
  60850. }
  60851. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  60852. {
  60853. float h, s, b;
  60854. getHSB (h, s, b);
  60855. b *= amount;
  60856. if (b > 1.0f)
  60857. b = 1.0f;
  60858. return Colour (h, s, b, getAlpha());
  60859. }
  60860. const Colour Colour::brighter (float amount) const throw()
  60861. {
  60862. amount = 1.0f / (1.0f + amount);
  60863. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  60864. (uint8) (255 - (amount * (255 - getGreen()))),
  60865. (uint8) (255 - (amount * (255 - getBlue()))),
  60866. getAlpha());
  60867. }
  60868. const Colour Colour::darker (float amount) const throw()
  60869. {
  60870. amount = 1.0f / (1.0f + amount);
  60871. return Colour ((uint8) (amount * getRed()),
  60872. (uint8) (amount * getGreen()),
  60873. (uint8) (amount * getBlue()),
  60874. getAlpha());
  60875. }
  60876. const Colour Colour::greyLevel (const float brightness) throw()
  60877. {
  60878. const uint8 level
  60879. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  60880. return Colour (level, level, level);
  60881. }
  60882. const Colour Colour::contrasting (const float amount) const throw()
  60883. {
  60884. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  60885. ? Colours::black
  60886. : Colours::white).withAlpha (amount));
  60887. }
  60888. const Colour Colour::contrasting (const Colour& colour1,
  60889. const Colour& colour2) throw()
  60890. {
  60891. const float b1 = colour1.getBrightness();
  60892. const float b2 = colour2.getBrightness();
  60893. float best = 0.0f;
  60894. float bestDist = 0.0f;
  60895. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  60896. {
  60897. const float d1 = fabsf (i - b1);
  60898. const float d2 = fabsf (i - b2);
  60899. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  60900. if (dist > bestDist)
  60901. {
  60902. best = i;
  60903. bestDist = dist;
  60904. }
  60905. }
  60906. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  60907. .withBrightness (best);
  60908. }
  60909. const String Colour::toString() const throw()
  60910. {
  60911. return String::toHexString ((int) argb.getARGB());
  60912. }
  60913. const Colour Colour::fromString (const String& encodedColourString)
  60914. {
  60915. return Colour ((uint32) encodedColourString.getHexValue32());
  60916. }
  60917. END_JUCE_NAMESPACE
  60918. /********* End of inlined file: juce_Colour.cpp *********/
  60919. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  60920. BEGIN_JUCE_NAMESPACE
  60921. ColourGradient::ColourGradient() throw()
  60922. : colours (4)
  60923. {
  60924. #ifdef JUCE_DEBUG
  60925. x1 = 987654.0f;
  60926. #endif
  60927. }
  60928. ColourGradient::ColourGradient (const Colour& colour1,
  60929. const float x1_,
  60930. const float y1_,
  60931. const Colour& colour2,
  60932. const float x2_,
  60933. const float y2_,
  60934. const bool isRadial_) throw()
  60935. : x1 (x1_),
  60936. y1 (y1_),
  60937. x2 (x2_),
  60938. y2 (y2_),
  60939. isRadial (isRadial_),
  60940. colours (4)
  60941. {
  60942. colours.add (0);
  60943. colours.add (colour1.getPixelARGB().getARGB());
  60944. colours.add (1 << 16);
  60945. colours.add (colour2.getPixelARGB().getARGB());
  60946. }
  60947. ColourGradient::~ColourGradient() throw()
  60948. {
  60949. }
  60950. void ColourGradient::clearColours() throw()
  60951. {
  60952. colours.clear();
  60953. }
  60954. void ColourGradient::addColour (const double proportionAlongGradient,
  60955. const Colour& colour) throw()
  60956. {
  60957. // must be within the two end-points
  60958. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  60959. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  60960. int i;
  60961. for (i = 0; i < colours.size(); i += 2)
  60962. if (colours.getUnchecked(i) > pos)
  60963. break;
  60964. colours.insert (i, pos);
  60965. colours.insert (i + 1, colour.getPixelARGB().getARGB());
  60966. }
  60967. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  60968. {
  60969. for (int i = 1; i < colours.size(); i += 2)
  60970. {
  60971. PixelARGB pix (colours.getUnchecked(i));
  60972. pix.multiplyAlpha (multiplier);
  60973. colours.set (i, pix.getARGB());
  60974. }
  60975. }
  60976. int ColourGradient::getNumColours() const throw()
  60977. {
  60978. return colours.size() >> 1;
  60979. }
  60980. double ColourGradient::getColourPosition (const int index) const throw()
  60981. {
  60982. return colours [index << 1];
  60983. }
  60984. const Colour ColourGradient::getColour (const int index) const throw()
  60985. {
  60986. PixelARGB pix (colours [(index << 1) + 1]);
  60987. pix.unpremultiply();
  60988. return Colour (pix.getARGB());
  60989. }
  60990. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  60991. {
  60992. #ifdef JUCE_DEBUG
  60993. // trying to use the object without setting its co-ordinates? Have a careful read of
  60994. // the comments for the constructors.
  60995. jassert (x1 != 987654.0f);
  60996. #endif
  60997. const int numColours = colours.size() >> 1;
  60998. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  60999. transform.transformPoint (tx1, ty1);
  61000. transform.transformPoint (tx2, ty2);
  61001. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  61002. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  61003. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  61004. if (numColours >= 2)
  61005. {
  61006. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  61007. PixelARGB pix1 (colours.getUnchecked (1));
  61008. int index = 0;
  61009. for (int j = 2; j < colours.size(); j += 2)
  61010. {
  61011. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  61012. const PixelARGB pix2 (colours.getUnchecked (j + 1));
  61013. for (int i = 0; i < numToDo; ++i)
  61014. {
  61015. jassert (index >= 0 && index < numEntries);
  61016. lookupTable[index] = pix1;
  61017. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  61018. ++index;
  61019. }
  61020. pix1 = pix2;
  61021. }
  61022. while (index < numEntries)
  61023. lookupTable [index++] = pix1;
  61024. }
  61025. else
  61026. {
  61027. jassertfalse // no colours specified!
  61028. }
  61029. return lookupTable;
  61030. }
  61031. bool ColourGradient::isOpaque() const throw()
  61032. {
  61033. for (int i = 1; i < colours.size(); i += 2)
  61034. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  61035. return false;
  61036. return true;
  61037. }
  61038. bool ColourGradient::isInvisible() const throw()
  61039. {
  61040. for (int i = 1; i < colours.size(); i += 2)
  61041. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  61042. return false;
  61043. return true;
  61044. }
  61045. END_JUCE_NAMESPACE
  61046. /********* End of inlined file: juce_ColourGradient.cpp *********/
  61047. /********* Start of inlined file: juce_Colours.cpp *********/
  61048. BEGIN_JUCE_NAMESPACE
  61049. const Colour Colours::transparentBlack (0);
  61050. const Colour Colours::transparentWhite (0x00ffffff);
  61051. const Colour Colours::aliceblue (0xfff0f8ff);
  61052. const Colour Colours::antiquewhite (0xfffaebd7);
  61053. const Colour Colours::aqua (0xff00ffff);
  61054. const Colour Colours::aquamarine (0xff7fffd4);
  61055. const Colour Colours::azure (0xfff0ffff);
  61056. const Colour Colours::beige (0xfff5f5dc);
  61057. const Colour Colours::bisque (0xffffe4c4);
  61058. const Colour Colours::black (0xff000000);
  61059. const Colour Colours::blanchedalmond (0xffffebcd);
  61060. const Colour Colours::blue (0xff0000ff);
  61061. const Colour Colours::blueviolet (0xff8a2be2);
  61062. const Colour Colours::brown (0xffa52a2a);
  61063. const Colour Colours::burlywood (0xffdeb887);
  61064. const Colour Colours::cadetblue (0xff5f9ea0);
  61065. const Colour Colours::chartreuse (0xff7fff00);
  61066. const Colour Colours::chocolate (0xffd2691e);
  61067. const Colour Colours::coral (0xffff7f50);
  61068. const Colour Colours::cornflowerblue (0xff6495ed);
  61069. const Colour Colours::cornsilk (0xfffff8dc);
  61070. const Colour Colours::crimson (0xffdc143c);
  61071. const Colour Colours::cyan (0xff00ffff);
  61072. const Colour Colours::darkblue (0xff00008b);
  61073. const Colour Colours::darkcyan (0xff008b8b);
  61074. const Colour Colours::darkgoldenrod (0xffb8860b);
  61075. const Colour Colours::darkgrey (0xff555555);
  61076. const Colour Colours::darkgreen (0xff006400);
  61077. const Colour Colours::darkkhaki (0xffbdb76b);
  61078. const Colour Colours::darkmagenta (0xff8b008b);
  61079. const Colour Colours::darkolivegreen (0xff556b2f);
  61080. const Colour Colours::darkorange (0xffff8c00);
  61081. const Colour Colours::darkorchid (0xff9932cc);
  61082. const Colour Colours::darkred (0xff8b0000);
  61083. const Colour Colours::darksalmon (0xffe9967a);
  61084. const Colour Colours::darkseagreen (0xff8fbc8f);
  61085. const Colour Colours::darkslateblue (0xff483d8b);
  61086. const Colour Colours::darkslategrey (0xff2f4f4f);
  61087. const Colour Colours::darkturquoise (0xff00ced1);
  61088. const Colour Colours::darkviolet (0xff9400d3);
  61089. const Colour Colours::deeppink (0xffff1493);
  61090. const Colour Colours::deepskyblue (0xff00bfff);
  61091. const Colour Colours::dimgrey (0xff696969);
  61092. const Colour Colours::dodgerblue (0xff1e90ff);
  61093. const Colour Colours::firebrick (0xffb22222);
  61094. const Colour Colours::floralwhite (0xfffffaf0);
  61095. const Colour Colours::forestgreen (0xff228b22);
  61096. const Colour Colours::fuchsia (0xffff00ff);
  61097. const Colour Colours::gainsboro (0xffdcdcdc);
  61098. const Colour Colours::gold (0xffffd700);
  61099. const Colour Colours::goldenrod (0xffdaa520);
  61100. const Colour Colours::grey (0xff808080);
  61101. const Colour Colours::green (0xff008000);
  61102. const Colour Colours::greenyellow (0xffadff2f);
  61103. const Colour Colours::honeydew (0xfff0fff0);
  61104. const Colour Colours::hotpink (0xffff69b4);
  61105. const Colour Colours::indianred (0xffcd5c5c);
  61106. const Colour Colours::indigo (0xff4b0082);
  61107. const Colour Colours::ivory (0xfffffff0);
  61108. const Colour Colours::khaki (0xfff0e68c);
  61109. const Colour Colours::lavender (0xffe6e6fa);
  61110. const Colour Colours::lavenderblush (0xfffff0f5);
  61111. const Colour Colours::lemonchiffon (0xfffffacd);
  61112. const Colour Colours::lightblue (0xffadd8e6);
  61113. const Colour Colours::lightcoral (0xfff08080);
  61114. const Colour Colours::lightcyan (0xffe0ffff);
  61115. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  61116. const Colour Colours::lightgreen (0xff90ee90);
  61117. const Colour Colours::lightgrey (0xffd3d3d3);
  61118. const Colour Colours::lightpink (0xffffb6c1);
  61119. const Colour Colours::lightsalmon (0xffffa07a);
  61120. const Colour Colours::lightseagreen (0xff20b2aa);
  61121. const Colour Colours::lightskyblue (0xff87cefa);
  61122. const Colour Colours::lightslategrey (0xff778899);
  61123. const Colour Colours::lightsteelblue (0xffb0c4de);
  61124. const Colour Colours::lightyellow (0xffffffe0);
  61125. const Colour Colours::lime (0xff00ff00);
  61126. const Colour Colours::limegreen (0xff32cd32);
  61127. const Colour Colours::linen (0xfffaf0e6);
  61128. const Colour Colours::magenta (0xffff00ff);
  61129. const Colour Colours::maroon (0xff800000);
  61130. const Colour Colours::mediumaquamarine (0xff66cdaa);
  61131. const Colour Colours::mediumblue (0xff0000cd);
  61132. const Colour Colours::mediumorchid (0xffba55d3);
  61133. const Colour Colours::mediumpurple (0xff9370db);
  61134. const Colour Colours::mediumseagreen (0xff3cb371);
  61135. const Colour Colours::mediumslateblue (0xff7b68ee);
  61136. const Colour Colours::mediumspringgreen (0xff00fa9a);
  61137. const Colour Colours::mediumturquoise (0xff48d1cc);
  61138. const Colour Colours::mediumvioletred (0xffc71585);
  61139. const Colour Colours::midnightblue (0xff191970);
  61140. const Colour Colours::mintcream (0xfff5fffa);
  61141. const Colour Colours::mistyrose (0xffffe4e1);
  61142. const Colour Colours::navajowhite (0xffffdead);
  61143. const Colour Colours::navy (0xff000080);
  61144. const Colour Colours::oldlace (0xfffdf5e6);
  61145. const Colour Colours::olive (0xff808000);
  61146. const Colour Colours::olivedrab (0xff6b8e23);
  61147. const Colour Colours::orange (0xffffa500);
  61148. const Colour Colours::orangered (0xffff4500);
  61149. const Colour Colours::orchid (0xffda70d6);
  61150. const Colour Colours::palegoldenrod (0xffeee8aa);
  61151. const Colour Colours::palegreen (0xff98fb98);
  61152. const Colour Colours::paleturquoise (0xffafeeee);
  61153. const Colour Colours::palevioletred (0xffdb7093);
  61154. const Colour Colours::papayawhip (0xffffefd5);
  61155. const Colour Colours::peachpuff (0xffffdab9);
  61156. const Colour Colours::peru (0xffcd853f);
  61157. const Colour Colours::pink (0xffffc0cb);
  61158. const Colour Colours::plum (0xffdda0dd);
  61159. const Colour Colours::powderblue (0xffb0e0e6);
  61160. const Colour Colours::purple (0xff800080);
  61161. const Colour Colours::red (0xffff0000);
  61162. const Colour Colours::rosybrown (0xffbc8f8f);
  61163. const Colour Colours::royalblue (0xff4169e1);
  61164. const Colour Colours::saddlebrown (0xff8b4513);
  61165. const Colour Colours::salmon (0xfffa8072);
  61166. const Colour Colours::sandybrown (0xfff4a460);
  61167. const Colour Colours::seagreen (0xff2e8b57);
  61168. const Colour Colours::seashell (0xfffff5ee);
  61169. const Colour Colours::sienna (0xffa0522d);
  61170. const Colour Colours::silver (0xffc0c0c0);
  61171. const Colour Colours::skyblue (0xff87ceeb);
  61172. const Colour Colours::slateblue (0xff6a5acd);
  61173. const Colour Colours::slategrey (0xff708090);
  61174. const Colour Colours::snow (0xfffffafa);
  61175. const Colour Colours::springgreen (0xff00ff7f);
  61176. const Colour Colours::steelblue (0xff4682b4);
  61177. const Colour Colours::tan (0xffd2b48c);
  61178. const Colour Colours::teal (0xff008080);
  61179. const Colour Colours::thistle (0xffd8bfd8);
  61180. const Colour Colours::tomato (0xffff6347);
  61181. const Colour Colours::turquoise (0xff40e0d0);
  61182. const Colour Colours::violet (0xffee82ee);
  61183. const Colour Colours::wheat (0xfff5deb3);
  61184. const Colour Colours::white (0xffffffff);
  61185. const Colour Colours::whitesmoke (0xfff5f5f5);
  61186. const Colour Colours::yellow (0xffffff00);
  61187. const Colour Colours::yellowgreen (0xff9acd32);
  61188. const Colour Colours::findColourForName (const String& colourName,
  61189. const Colour& defaultColour)
  61190. {
  61191. static const int presets[] =
  61192. {
  61193. // (first value is the string's hashcode, second is ARGB)
  61194. 0x05978fff, 0xff000000, /* black */
  61195. 0x06bdcc29, 0xffffffff, /* white */
  61196. 0x002e305a, 0xff0000ff, /* blue */
  61197. 0x00308adf, 0xff808080, /* grey */
  61198. 0x05e0cf03, 0xff008000, /* green */
  61199. 0x0001b891, 0xffff0000, /* red */
  61200. 0xd43c6474, 0xffffff00, /* yellow */
  61201. 0x620886da, 0xfff0f8ff, /* aliceblue */
  61202. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  61203. 0x002dcebc, 0xff00ffff, /* aqua */
  61204. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  61205. 0x0590228f, 0xfff0ffff, /* azure */
  61206. 0x05947fe4, 0xfff5f5dc, /* beige */
  61207. 0xad388e35, 0xffffe4c4, /* bisque */
  61208. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  61209. 0x39129959, 0xff8a2be2, /* blueviolet */
  61210. 0x059a8136, 0xffa52a2a, /* brown */
  61211. 0x89cea8f9, 0xffdeb887, /* burlywood */
  61212. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  61213. 0x6b748956, 0xff7fff00, /* chartreuse */
  61214. 0x2903623c, 0xffd2691e, /* chocolate */
  61215. 0x05a74431, 0xffff7f50, /* coral */
  61216. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  61217. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  61218. 0x3d8c4edf, 0xffdc143c, /* crimson */
  61219. 0x002ed323, 0xff00ffff, /* cyan */
  61220. 0x67cc74d0, 0xff00008b, /* darkblue */
  61221. 0x67cd1799, 0xff008b8b, /* darkcyan */
  61222. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  61223. 0x67cecf55, 0xff555555, /* darkgrey */
  61224. 0x920b194d, 0xff006400, /* darkgreen */
  61225. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  61226. 0x5c293873, 0xff8b008b, /* darkmagenta */
  61227. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  61228. 0xbcfd2524, 0xffff8c00, /* darkorange */
  61229. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  61230. 0x55ee0d5b, 0xff8b0000, /* darkred */
  61231. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  61232. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  61233. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  61234. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  61235. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  61236. 0xc8769375, 0xff9400d3, /* darkviolet */
  61237. 0x25832862, 0xffff1493, /* deeppink */
  61238. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  61239. 0x634c8b67, 0xff696969, /* dimgrey */
  61240. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  61241. 0xef19e3cb, 0xffb22222, /* firebrick */
  61242. 0xb852b195, 0xfffffaf0, /* floralwhite */
  61243. 0xd086fd06, 0xff228b22, /* forestgreen */
  61244. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  61245. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  61246. 0x00308060, 0xffffd700, /* gold */
  61247. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  61248. 0xbab8a537, 0xffadff2f, /* greenyellow */
  61249. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  61250. 0x41892743, 0xffff69b4, /* hotpink */
  61251. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  61252. 0xb969fed2, 0xff4b0082, /* indigo */
  61253. 0x05fef6a9, 0xfffffff0, /* ivory */
  61254. 0x06149302, 0xfff0e68c, /* khaki */
  61255. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  61256. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  61257. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  61258. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  61259. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  61260. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  61261. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  61262. 0xf40157ad, 0xff90ee90, /* lightgreen */
  61263. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  61264. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  61265. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  61266. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  61267. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  61268. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  61269. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  61270. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  61271. 0x0032afd5, 0xff00ff00, /* lime */
  61272. 0x607bbc4e, 0xff32cd32, /* limegreen */
  61273. 0x06234efa, 0xfffaf0e6, /* linen */
  61274. 0x316858a9, 0xffff00ff, /* magenta */
  61275. 0xbf8ca470, 0xff800000, /* maroon */
  61276. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  61277. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  61278. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  61279. 0x07556b71, 0xff9370db, /* mediumpurple */
  61280. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  61281. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  61282. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  61283. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  61284. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  61285. 0x168eb32a, 0xff191970, /* midnightblue */
  61286. 0x4306b960, 0xfff5fffa, /* mintcream */
  61287. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  61288. 0xe97218a6, 0xffffdead, /* navajowhite */
  61289. 0x00337bb6, 0xff000080, /* navy */
  61290. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  61291. 0x064ee1db, 0xff808000, /* olive */
  61292. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  61293. 0xc3de262e, 0xffffa500, /* orange */
  61294. 0x58bebba3, 0xffff4500, /* orangered */
  61295. 0xc3def8a3, 0xffda70d6, /* orchid */
  61296. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  61297. 0x3d9dd619, 0xff98fb98, /* palegreen */
  61298. 0x74022737, 0xffafeeee, /* paleturquoise */
  61299. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  61300. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  61301. 0x93e1b776, 0xffffdab9, /* peachpuff */
  61302. 0x003472f8, 0xffcd853f, /* peru */
  61303. 0x00348176, 0xffffc0cb, /* pink */
  61304. 0x00348d94, 0xffdda0dd, /* plum */
  61305. 0xd036be93, 0xffb0e0e6, /* powderblue */
  61306. 0xc5c507bc, 0xff800080, /* purple */
  61307. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  61308. 0xbd9413e1, 0xff4169e1, /* royalblue */
  61309. 0xf456044f, 0xff8b4513, /* saddlebrown */
  61310. 0xc9c6f66e, 0xfffa8072, /* salmon */
  61311. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  61312. 0x34636c14, 0xff2e8b57, /* seagreen */
  61313. 0x3507fb41, 0xfffff5ee, /* seashell */
  61314. 0xca348772, 0xffa0522d, /* sienna */
  61315. 0xca37d30d, 0xffc0c0c0, /* silver */
  61316. 0x80da74fb, 0xff87ceeb, /* skyblue */
  61317. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  61318. 0x44ab37f8, 0xff708090, /* slategrey */
  61319. 0x0035f183, 0xfffffafa, /* snow */
  61320. 0xd5440d16, 0xff00ff7f, /* springgreen */
  61321. 0x3e1524a5, 0xff4682b4, /* steelblue */
  61322. 0x0001bfa1, 0xffd2b48c, /* tan */
  61323. 0x0036425c, 0xff008080, /* teal */
  61324. 0xafc8858f, 0xffd8bfd8, /* thistle */
  61325. 0xcc41600a, 0xffff6347, /* tomato */
  61326. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  61327. 0xcf57947f, 0xffee82ee, /* violet */
  61328. 0x06bdbae7, 0xfff5deb3, /* wheat */
  61329. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  61330. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  61331. };
  61332. const int hash = colourName.trim().toLowerCase().hashCode();
  61333. for (int i = 0; i < numElementsInArray (presets); i += 2)
  61334. if (presets [i] == hash)
  61335. return Colour (presets [i + 1]);
  61336. return defaultColour;
  61337. }
  61338. END_JUCE_NAMESPACE
  61339. /********* End of inlined file: juce_Colours.cpp *********/
  61340. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  61341. BEGIN_JUCE_NAMESPACE
  61342. EdgeTable::EdgeTable (const int top_,
  61343. const int height_,
  61344. const OversamplingLevel oversampling_,
  61345. const int expectedEdgesPerLine) throw()
  61346. : top (top_),
  61347. height (height_),
  61348. maxEdgesPerLine (expectedEdgesPerLine),
  61349. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  61350. oversampling (oversampling_)
  61351. {
  61352. table = (int*) juce_calloc ((height << (int)oversampling_)
  61353. * lineStrideElements * sizeof (int));
  61354. }
  61355. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  61356. : table (0)
  61357. {
  61358. operator= (other);
  61359. }
  61360. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  61361. {
  61362. juce_free (table);
  61363. top = other.top;
  61364. height = other.height;
  61365. maxEdgesPerLine = other.maxEdgesPerLine;
  61366. lineStrideElements = other.lineStrideElements;
  61367. oversampling = other.oversampling;
  61368. const int tableSize = (height << (int)oversampling)
  61369. * lineStrideElements * sizeof (int);
  61370. table = (int*) juce_malloc (tableSize);
  61371. memcpy (table, other.table, tableSize);
  61372. return *this;
  61373. }
  61374. EdgeTable::~EdgeTable() throw()
  61375. {
  61376. juce_free (table);
  61377. }
  61378. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  61379. {
  61380. if (newNumEdgesPerLine != maxEdgesPerLine)
  61381. {
  61382. maxEdgesPerLine = newNumEdgesPerLine;
  61383. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  61384. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  61385. * newLineStrideElements * sizeof (int));
  61386. for (int i = 0; i < (height << (int) oversampling); ++i)
  61387. {
  61388. const int* srcLine = table + lineStrideElements * i;
  61389. int* dstLine = newTable + newLineStrideElements * i;
  61390. int num = *srcLine++;
  61391. *dstLine++ = num;
  61392. num <<= 1;
  61393. while (--num >= 0)
  61394. *dstLine++ = *srcLine++;
  61395. }
  61396. juce_free (table);
  61397. table = newTable;
  61398. lineStrideElements = newLineStrideElements;
  61399. }
  61400. }
  61401. void EdgeTable::optimiseTable() throw()
  61402. {
  61403. int maxLineElements = 0;
  61404. for (int i = height; --i >= 0;)
  61405. maxLineElements = jmax (maxLineElements,
  61406. table [i * lineStrideElements]);
  61407. remapTableForNumEdges (maxLineElements);
  61408. }
  61409. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  61410. {
  61411. jassert (y >= 0 && y < (height << oversampling))
  61412. int* lineStart = table + lineStrideElements * y;
  61413. int n = lineStart[0];
  61414. if (n >= maxEdgesPerLine)
  61415. {
  61416. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  61417. jassert (n < maxEdgesPerLine);
  61418. lineStart = table + lineStrideElements * y;
  61419. }
  61420. n <<= 1;
  61421. int* const line = lineStart + 1;
  61422. while (n > 0)
  61423. {
  61424. const int cx = line [n - 2];
  61425. if (cx <= x)
  61426. break;
  61427. line [n] = cx;
  61428. line [n + 1] = line [n - 1];
  61429. n -= 2;
  61430. }
  61431. line [n] = x;
  61432. line [n + 1] = winding;
  61433. lineStart[0]++;
  61434. }
  61435. void EdgeTable::addPath (const Path& path,
  61436. const AffineTransform& transform) throw()
  61437. {
  61438. const int windingAmount = 256 / (1 << (int) oversampling);
  61439. const float timesOversampling = (float) (1 << (int) oversampling);
  61440. const int bottomLimit = (height << (int) oversampling);
  61441. PathFlatteningIterator iter (path, transform);
  61442. while (iter.next())
  61443. {
  61444. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  61445. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  61446. if (y1 != y2)
  61447. {
  61448. const double x1 = 256.0 * iter.x1;
  61449. const double x2 = 256.0 * iter.x2;
  61450. const double multiplier = (x2 - x1) / (y2 - y1);
  61451. const int oldY1 = y1;
  61452. int winding;
  61453. if (y1 > y2)
  61454. {
  61455. swapVariables (y1, y2);
  61456. winding = windingAmount;
  61457. }
  61458. else
  61459. {
  61460. winding = -windingAmount;
  61461. }
  61462. jassert (y1 < y2);
  61463. if (y1 < 0)
  61464. y1 = 0;
  61465. if (y2 > bottomLimit)
  61466. y2 = bottomLimit;
  61467. while (y1 < y2)
  61468. {
  61469. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  61470. y1,
  61471. winding);
  61472. ++y1;
  61473. }
  61474. }
  61475. }
  61476. if (! path.isUsingNonZeroWinding())
  61477. {
  61478. // if it's an alternate-winding path, we need to go through and
  61479. // make sure all the windings are alternating.
  61480. int* lineStart = table;
  61481. for (int i = height << (int) oversampling; --i >= 0;)
  61482. {
  61483. int* line = lineStart;
  61484. lineStart += lineStrideElements;
  61485. int num = *line;
  61486. while (--num >= 0)
  61487. {
  61488. line += 2;
  61489. *line = abs (*line);
  61490. if (--num >= 0)
  61491. {
  61492. line += 2;
  61493. *line = -abs (*line);
  61494. }
  61495. }
  61496. }
  61497. }
  61498. }
  61499. END_JUCE_NAMESPACE
  61500. /********* End of inlined file: juce_EdgeTable.cpp *********/
  61501. /********* Start of inlined file: juce_Graphics.cpp *********/
  61502. BEGIN_JUCE_NAMESPACE
  61503. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  61504. #define MINIMUM_COORD -0x3fffffff
  61505. #define MAXIMUM_COORD 0x3fffffff
  61506. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61507. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61508. jassert ((int) x >= MINIMUM_COORD \
  61509. && (int) x <= MAXIMUM_COORD \
  61510. && (int) y >= MINIMUM_COORD \
  61511. && (int) y <= MAXIMUM_COORD \
  61512. && (int) w >= MINIMUM_COORD \
  61513. && (int) w <= MAXIMUM_COORD \
  61514. && (int) h >= MINIMUM_COORD \
  61515. && (int) h <= MAXIMUM_COORD);
  61516. LowLevelGraphicsContext::LowLevelGraphicsContext()
  61517. {
  61518. }
  61519. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  61520. {
  61521. }
  61522. Graphics::Graphics (Image& imageToDrawOnto) throw()
  61523. : context (imageToDrawOnto.createLowLevelContext()),
  61524. ownsContext (true),
  61525. state (new GraphicsState()),
  61526. saveStatePending (false)
  61527. {
  61528. }
  61529. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  61530. : context (internalContext),
  61531. ownsContext (false),
  61532. state (new GraphicsState()),
  61533. saveStatePending (false)
  61534. {
  61535. }
  61536. Graphics::~Graphics() throw()
  61537. {
  61538. delete state;
  61539. if (ownsContext)
  61540. delete context;
  61541. }
  61542. void Graphics::resetToDefaultState() throw()
  61543. {
  61544. setColour (Colours::black);
  61545. state->font.resetToDefaultState();
  61546. state->quality = defaultQuality;
  61547. }
  61548. bool Graphics::isVectorDevice() const throw()
  61549. {
  61550. return context->isVectorDevice();
  61551. }
  61552. bool Graphics::reduceClipRegion (const int x, const int y,
  61553. const int w, const int h) throw()
  61554. {
  61555. saveStateIfPending();
  61556. return context->reduceClipRegion (x, y, w, h);
  61557. }
  61558. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  61559. {
  61560. saveStateIfPending();
  61561. return context->reduceClipRegion (clipRegion);
  61562. }
  61563. void Graphics::excludeClipRegion (const int x, const int y,
  61564. const int w, const int h) throw()
  61565. {
  61566. saveStateIfPending();
  61567. context->excludeClipRegion (x, y, w, h);
  61568. }
  61569. bool Graphics::isClipEmpty() const throw()
  61570. {
  61571. return context->isClipEmpty();
  61572. }
  61573. const Rectangle Graphics::getClipBounds() const throw()
  61574. {
  61575. return context->getClipBounds();
  61576. }
  61577. void Graphics::saveState() throw()
  61578. {
  61579. saveStateIfPending();
  61580. saveStatePending = true;
  61581. }
  61582. void Graphics::restoreState() throw()
  61583. {
  61584. if (saveStatePending)
  61585. {
  61586. saveStatePending = false;
  61587. }
  61588. else
  61589. {
  61590. const int stackSize = stateStack.size();
  61591. if (stackSize > 0)
  61592. {
  61593. context->restoreState();
  61594. delete state;
  61595. state = stateStack.getUnchecked (stackSize - 1);
  61596. stateStack.removeLast (1, false);
  61597. }
  61598. else
  61599. {
  61600. // Trying to call restoreState() more times than you've called saveState() !
  61601. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  61602. jassertfalse
  61603. }
  61604. }
  61605. }
  61606. void Graphics::saveStateIfPending() throw()
  61607. {
  61608. if (saveStatePending)
  61609. {
  61610. saveStatePending = false;
  61611. context->saveState();
  61612. stateStack.add (new GraphicsState (*state));
  61613. }
  61614. }
  61615. void Graphics::setOrigin (const int newOriginX,
  61616. const int newOriginY) throw()
  61617. {
  61618. saveStateIfPending();
  61619. context->setOrigin (newOriginX, newOriginY);
  61620. }
  61621. bool Graphics::clipRegionIntersects (const int x, const int y,
  61622. const int w, const int h) const throw()
  61623. {
  61624. return context->clipRegionIntersects (x, y, w, h);
  61625. }
  61626. void Graphics::setColour (const Colour& newColour) throw()
  61627. {
  61628. saveStateIfPending();
  61629. state->colour = newColour;
  61630. deleteAndZero (state->brush);
  61631. }
  61632. const Colour& Graphics::getCurrentColour() const throw()
  61633. {
  61634. return state->colour;
  61635. }
  61636. void Graphics::setOpacity (const float newOpacity) throw()
  61637. {
  61638. saveStateIfPending();
  61639. state->colour = state->colour.withAlpha (newOpacity);
  61640. }
  61641. void Graphics::setBrush (const Brush* const newBrush) throw()
  61642. {
  61643. saveStateIfPending();
  61644. delete state->brush;
  61645. if (newBrush != 0)
  61646. state->brush = newBrush->createCopy();
  61647. else
  61648. state->brush = 0;
  61649. }
  61650. Graphics::GraphicsState::GraphicsState() throw()
  61651. : colour (Colours::black),
  61652. brush (0),
  61653. quality (defaultQuality)
  61654. {
  61655. }
  61656. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  61657. : colour (other.colour),
  61658. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  61659. font (other.font),
  61660. quality (other.quality)
  61661. {
  61662. }
  61663. Graphics::GraphicsState::~GraphicsState() throw()
  61664. {
  61665. delete brush;
  61666. }
  61667. void Graphics::setFont (const Font& newFont) throw()
  61668. {
  61669. saveStateIfPending();
  61670. state->font = newFont;
  61671. }
  61672. void Graphics::setFont (const float newFontHeight,
  61673. const int newFontStyleFlags) throw()
  61674. {
  61675. saveStateIfPending();
  61676. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  61677. }
  61678. const Font& Graphics::getCurrentFont() const throw()
  61679. {
  61680. return state->font;
  61681. }
  61682. void Graphics::drawSingleLineText (const String& text,
  61683. const int startX,
  61684. const int baselineY) const throw()
  61685. {
  61686. if (text.isNotEmpty()
  61687. && startX < context->getClipBounds().getRight())
  61688. {
  61689. GlyphArrangement arr;
  61690. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  61691. arr.draw (*this);
  61692. }
  61693. }
  61694. void Graphics::drawTextAsPath (const String& text,
  61695. const AffineTransform& transform) const throw()
  61696. {
  61697. if (text.isNotEmpty())
  61698. {
  61699. GlyphArrangement arr;
  61700. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  61701. arr.draw (*this, transform);
  61702. }
  61703. }
  61704. void Graphics::drawMultiLineText (const String& text,
  61705. const int startX,
  61706. const int baselineY,
  61707. const int maximumLineWidth) const throw()
  61708. {
  61709. if (text.isNotEmpty()
  61710. && startX < context->getClipBounds().getRight())
  61711. {
  61712. GlyphArrangement arr;
  61713. arr.addJustifiedText (state->font, text,
  61714. (float) startX, (float) baselineY, (float) maximumLineWidth,
  61715. Justification::left);
  61716. arr.draw (*this);
  61717. }
  61718. }
  61719. void Graphics::drawText (const String& text,
  61720. const int x,
  61721. const int y,
  61722. const int width,
  61723. const int height,
  61724. const Justification& justificationType,
  61725. const bool useEllipsesIfTooBig) const throw()
  61726. {
  61727. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  61728. {
  61729. GlyphArrangement arr;
  61730. arr.addCurtailedLineOfText (state->font, text,
  61731. 0.0f, 0.0f, (float)width,
  61732. useEllipsesIfTooBig);
  61733. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  61734. (float) x, (float) y,
  61735. (float) width, (float) height,
  61736. justificationType);
  61737. arr.draw (*this);
  61738. }
  61739. }
  61740. void Graphics::drawFittedText (const String& text,
  61741. const int x,
  61742. const int y,
  61743. const int width,
  61744. const int height,
  61745. const Justification& justification,
  61746. const int maximumNumberOfLines,
  61747. const float minimumHorizontalScale) const throw()
  61748. {
  61749. if (text.isNotEmpty()
  61750. && width > 0 && height > 0
  61751. && context->clipRegionIntersects (x, y, width, height))
  61752. {
  61753. GlyphArrangement arr;
  61754. arr.addFittedText (state->font, text,
  61755. (float) x, (float) y,
  61756. (float) width, (float) height,
  61757. justification,
  61758. maximumNumberOfLines,
  61759. minimumHorizontalScale);
  61760. arr.draw (*this);
  61761. }
  61762. }
  61763. void Graphics::fillRect (int x,
  61764. int y,
  61765. int width,
  61766. int height) const throw()
  61767. {
  61768. // passing in a silly number can cause maths problems in rendering!
  61769. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61770. SolidColourBrush colourBrush (state->colour);
  61771. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  61772. }
  61773. void Graphics::fillRect (const Rectangle& r) const throw()
  61774. {
  61775. fillRect (r.getX(),
  61776. r.getY(),
  61777. r.getWidth(),
  61778. r.getHeight());
  61779. }
  61780. void Graphics::fillRect (const float x,
  61781. const float y,
  61782. const float width,
  61783. const float height) const throw()
  61784. {
  61785. // passing in a silly number can cause maths problems in rendering!
  61786. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61787. Path p;
  61788. p.addRectangle (x, y, width, height);
  61789. fillPath (p);
  61790. }
  61791. void Graphics::setPixel (int x, int y) const throw()
  61792. {
  61793. if (context->clipRegionIntersects (x, y, 1, 1))
  61794. {
  61795. SolidColourBrush colourBrush (state->colour);
  61796. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  61797. }
  61798. }
  61799. void Graphics::fillAll() const throw()
  61800. {
  61801. fillRect (context->getClipBounds());
  61802. }
  61803. void Graphics::fillAll (const Colour& colourToUse) const throw()
  61804. {
  61805. if (! colourToUse.isTransparent())
  61806. {
  61807. const Rectangle clip (context->getClipBounds());
  61808. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  61809. colourToUse, false);
  61810. }
  61811. }
  61812. void Graphics::fillPath (const Path& path,
  61813. const AffineTransform& transform) const throw()
  61814. {
  61815. if ((! context->isClipEmpty()) && ! path.isEmpty())
  61816. {
  61817. SolidColourBrush colourBrush (state->colour);
  61818. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  61819. }
  61820. }
  61821. void Graphics::strokePath (const Path& path,
  61822. const PathStrokeType& strokeType,
  61823. const AffineTransform& transform) const throw()
  61824. {
  61825. if ((! state->colour.isTransparent()) || state->brush != 0)
  61826. {
  61827. Path stroke;
  61828. strokeType.createStrokedPath (stroke, path, transform);
  61829. fillPath (stroke);
  61830. }
  61831. }
  61832. void Graphics::drawRect (const int x,
  61833. const int y,
  61834. const int width,
  61835. const int height,
  61836. const int lineThickness) const throw()
  61837. {
  61838. // passing in a silly number can cause maths problems in rendering!
  61839. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61840. SolidColourBrush colourBrush (state->colour);
  61841. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  61842. b.paintRectangle (*context, x, y, width, lineThickness);
  61843. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  61844. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  61845. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  61846. }
  61847. void Graphics::drawRect (const float x,
  61848. const float y,
  61849. const float width,
  61850. const float height,
  61851. const float lineThickness) const throw()
  61852. {
  61853. // passing in a silly number can cause maths problems in rendering!
  61854. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61855. Path p;
  61856. p.addRectangle (x, y, width, lineThickness);
  61857. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  61858. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  61859. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  61860. fillPath (p);
  61861. }
  61862. void Graphics::drawRect (const Rectangle& r,
  61863. const int lineThickness) const throw()
  61864. {
  61865. drawRect (r.getX(), r.getY(),
  61866. r.getWidth(), r.getHeight(),
  61867. lineThickness);
  61868. }
  61869. void Graphics::drawBevel (const int x,
  61870. const int y,
  61871. const int width,
  61872. const int height,
  61873. const int bevelThickness,
  61874. const Colour& topLeftColour,
  61875. const Colour& bottomRightColour,
  61876. const bool useGradient,
  61877. const bool sharpEdgeOnOutside) const throw()
  61878. {
  61879. // passing in a silly number can cause maths problems in rendering!
  61880. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61881. if (clipRegionIntersects (x, y, width, height))
  61882. {
  61883. const float oldOpacity = state->colour.getFloatAlpha();
  61884. const float ramp = oldOpacity / bevelThickness;
  61885. for (int i = bevelThickness; --i >= 0;)
  61886. {
  61887. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  61888. : oldOpacity;
  61889. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  61890. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  61891. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  61892. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  61893. }
  61894. }
  61895. }
  61896. void Graphics::fillEllipse (const float x,
  61897. const float y,
  61898. const float width,
  61899. const float height) const throw()
  61900. {
  61901. // passing in a silly number can cause maths problems in rendering!
  61902. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61903. Path p;
  61904. p.addEllipse (x, y, width, height);
  61905. fillPath (p);
  61906. }
  61907. void Graphics::drawEllipse (const float x,
  61908. const float y,
  61909. const float width,
  61910. const float height,
  61911. const float lineThickness) const throw()
  61912. {
  61913. // passing in a silly number can cause maths problems in rendering!
  61914. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61915. Path p;
  61916. p.addEllipse (x, y, width, height);
  61917. strokePath (p, PathStrokeType (lineThickness));
  61918. }
  61919. void Graphics::fillRoundedRectangle (const float x,
  61920. const float y,
  61921. const float width,
  61922. const float height,
  61923. const float cornerSize) const throw()
  61924. {
  61925. // passing in a silly number can cause maths problems in rendering!
  61926. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61927. Path p;
  61928. p.addRoundedRectangle (x, y, width, height, cornerSize);
  61929. fillPath (p);
  61930. }
  61931. void Graphics::fillRoundedRectangle (const Rectangle& r,
  61932. const float cornerSize) const throw()
  61933. {
  61934. fillRoundedRectangle ((float) r.getX(),
  61935. (float) r.getY(),
  61936. (float) r.getWidth(),
  61937. (float) r.getHeight(),
  61938. cornerSize);
  61939. }
  61940. void Graphics::drawRoundedRectangle (const float x,
  61941. const float y,
  61942. const float width,
  61943. const float height,
  61944. const float cornerSize,
  61945. const float lineThickness) const throw()
  61946. {
  61947. // passing in a silly number can cause maths problems in rendering!
  61948. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61949. Path p;
  61950. p.addRoundedRectangle (x, y, width, height, cornerSize);
  61951. strokePath (p, PathStrokeType (lineThickness));
  61952. }
  61953. void Graphics::drawRoundedRectangle (const Rectangle& r,
  61954. const float cornerSize,
  61955. const float lineThickness) const throw()
  61956. {
  61957. drawRoundedRectangle ((float) r.getX(),
  61958. (float) r.getY(),
  61959. (float) r.getWidth(),
  61960. (float) r.getHeight(),
  61961. cornerSize, lineThickness);
  61962. }
  61963. void Graphics::drawArrow (const float startX,
  61964. const float startY,
  61965. const float endX,
  61966. const float endY,
  61967. const float lineThickness,
  61968. const float arrowheadWidth,
  61969. const float arrowheadLength) const throw()
  61970. {
  61971. Path p;
  61972. p.addArrow (startX, startY, endX, endY,
  61973. lineThickness, arrowheadWidth, arrowheadLength);
  61974. fillPath (p);
  61975. }
  61976. void Graphics::fillCheckerBoard (int x, int y,
  61977. int width, int height,
  61978. const int checkWidth,
  61979. const int checkHeight,
  61980. const Colour& colour1,
  61981. const Colour& colour2) const throw()
  61982. {
  61983. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  61984. if (checkWidth > 0 && checkHeight > 0)
  61985. {
  61986. if (colour1 == colour2)
  61987. {
  61988. context->fillRectWithColour (x, y, width, height, colour1, false);
  61989. }
  61990. else
  61991. {
  61992. const Rectangle clip (context->getClipBounds());
  61993. const int right = jmin (x + width, clip.getRight());
  61994. const int bottom = jmin (y + height, clip.getBottom());
  61995. int cy = 0;
  61996. while (y < bottom)
  61997. {
  61998. int cx = cy;
  61999. for (int xx = x; xx < right; xx += checkWidth)
  62000. context->fillRectWithColour (xx, y,
  62001. jmin (checkWidth, right - xx),
  62002. jmin (checkHeight, bottom - y),
  62003. ((cx++ & 1) == 0) ? colour1 : colour2,
  62004. false);
  62005. ++cy;
  62006. y += checkHeight;
  62007. }
  62008. }
  62009. }
  62010. }
  62011. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  62012. {
  62013. SolidColourBrush colourBrush (state->colour);
  62014. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  62015. }
  62016. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  62017. {
  62018. SolidColourBrush colourBrush (state->colour);
  62019. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  62020. }
  62021. void Graphics::drawLine (float x1, float y1,
  62022. float x2, float y2) const throw()
  62023. {
  62024. if (! context->isClipEmpty())
  62025. {
  62026. SolidColourBrush colourBrush (state->colour);
  62027. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  62028. }
  62029. }
  62030. void Graphics::drawLine (const float startX,
  62031. const float startY,
  62032. const float endX,
  62033. const float endY,
  62034. const float lineThickness) const throw()
  62035. {
  62036. Path p;
  62037. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  62038. fillPath (p);
  62039. }
  62040. void Graphics::drawLine (const Line& line) const throw()
  62041. {
  62042. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  62043. }
  62044. void Graphics::drawLine (const Line& line,
  62045. const float lineThickness) const throw()
  62046. {
  62047. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  62048. }
  62049. void Graphics::drawDashedLine (const float startX,
  62050. const float startY,
  62051. const float endX,
  62052. const float endY,
  62053. const float* const dashLengths,
  62054. const int numDashLengths,
  62055. const float lineThickness) const throw()
  62056. {
  62057. const double dx = endX - startX;
  62058. const double dy = endY - startY;
  62059. const double totalLen = juce_hypot (dx, dy);
  62060. if (totalLen >= 0.5)
  62061. {
  62062. const double onePixAlpha = 1.0 / totalLen;
  62063. double alpha = 0.0;
  62064. float x = startX;
  62065. float y = startY;
  62066. int n = 0;
  62067. while (alpha < 1.0f)
  62068. {
  62069. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  62070. n = n % numDashLengths;
  62071. const float oldX = x;
  62072. const float oldY = y;
  62073. x = (float) (startX + dx * alpha);
  62074. y = (float) (startY + dy * alpha);
  62075. if ((n & 1) != 0)
  62076. {
  62077. if (lineThickness != 1.0f)
  62078. drawLine (oldX, oldY, x, y, lineThickness);
  62079. else
  62080. drawLine (oldX, oldY, x, y);
  62081. }
  62082. }
  62083. }
  62084. }
  62085. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  62086. {
  62087. saveStateIfPending();
  62088. state->quality = newQuality;
  62089. }
  62090. void Graphics::drawImageAt (const Image* const imageToDraw,
  62091. const int topLeftX,
  62092. const int topLeftY,
  62093. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62094. {
  62095. if (imageToDraw != 0)
  62096. {
  62097. const int imageW = imageToDraw->getWidth();
  62098. const int imageH = imageToDraw->getHeight();
  62099. drawImage (imageToDraw,
  62100. topLeftX, topLeftY, imageW, imageH,
  62101. 0, 0, imageW, imageH,
  62102. fillAlphaChannelWithCurrentBrush);
  62103. }
  62104. }
  62105. void Graphics::drawImageWithin (const Image* const imageToDraw,
  62106. const int destX,
  62107. const int destY,
  62108. const int destW,
  62109. const int destH,
  62110. const RectanglePlacement& placementWithinTarget,
  62111. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62112. {
  62113. // passing in a silly number can cause maths problems in rendering!
  62114. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  62115. if (imageToDraw != 0)
  62116. {
  62117. const int imageW = imageToDraw->getWidth();
  62118. const int imageH = imageToDraw->getHeight();
  62119. if (imageW > 0 && imageH > 0)
  62120. {
  62121. double newX = 0.0, newY = 0.0;
  62122. double newW = imageW;
  62123. double newH = imageH;
  62124. placementWithinTarget.applyTo (newX, newY, newW, newH,
  62125. destX, destY, destW, destH);
  62126. if (newW > 0 && newH > 0)
  62127. {
  62128. drawImage (imageToDraw,
  62129. roundDoubleToInt (newX), roundDoubleToInt (newY),
  62130. roundDoubleToInt (newW), roundDoubleToInt (newH),
  62131. 0, 0, imageW, imageH,
  62132. fillAlphaChannelWithCurrentBrush);
  62133. }
  62134. }
  62135. }
  62136. }
  62137. void Graphics::drawImage (const Image* const imageToDraw,
  62138. int dx, int dy, int dw, int dh,
  62139. int sx, int sy, int sw, int sh,
  62140. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62141. {
  62142. // passing in a silly number can cause maths problems in rendering!
  62143. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  62144. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  62145. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  62146. return;
  62147. if (sw == dw && sh == dh)
  62148. {
  62149. if (sx < 0)
  62150. {
  62151. dx -= sx;
  62152. dw += sx;
  62153. sw += sx;
  62154. sx = 0;
  62155. }
  62156. if (sx + sw > imageToDraw->getWidth())
  62157. {
  62158. const int amount = sx + sw - imageToDraw->getWidth();
  62159. dw -= amount;
  62160. sw -= amount;
  62161. }
  62162. if (sy < 0)
  62163. {
  62164. dy -= sy;
  62165. dh += sy;
  62166. sh += sy;
  62167. sy = 0;
  62168. }
  62169. if (sy + sh > imageToDraw->getHeight())
  62170. {
  62171. const int amount = sy + sh - imageToDraw->getHeight();
  62172. dh -= amount;
  62173. sh -= amount;
  62174. }
  62175. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62176. return;
  62177. if (fillAlphaChannelWithCurrentBrush)
  62178. {
  62179. SolidColourBrush colourBrush (state->colour);
  62180. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62181. .paintAlphaChannel (*context, *imageToDraw,
  62182. dx - sx, dy - sy,
  62183. dx, dy,
  62184. dw, dh);
  62185. }
  62186. else
  62187. {
  62188. context->blendImage (*imageToDraw,
  62189. dx, dy, dw, dh, sx, sy,
  62190. state->colour.getFloatAlpha());
  62191. }
  62192. }
  62193. else
  62194. {
  62195. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62196. return;
  62197. if (fillAlphaChannelWithCurrentBrush)
  62198. {
  62199. if (imageToDraw->isRGB())
  62200. {
  62201. fillRect (dx, dy, dw, dh);
  62202. }
  62203. else
  62204. {
  62205. int tx = dx;
  62206. int ty = dy;
  62207. int tw = dw;
  62208. int th = dh;
  62209. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62210. {
  62211. Image temp (imageToDraw->getFormat(), tw, th, true);
  62212. Graphics g (temp);
  62213. g.setImageResamplingQuality (state->quality);
  62214. g.setOrigin (dx - tx, dy - ty);
  62215. g.drawImage (imageToDraw,
  62216. 0, 0, dw, dh,
  62217. sx, sy, sw, sh,
  62218. false);
  62219. SolidColourBrush colourBrush (state->colour);
  62220. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62221. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62222. }
  62223. }
  62224. }
  62225. else
  62226. {
  62227. context->blendImageRescaling (*imageToDraw,
  62228. dx, dy, dw, dh,
  62229. sx, sy, sw, sh,
  62230. state->colour.getFloatAlpha(),
  62231. state->quality);
  62232. }
  62233. }
  62234. }
  62235. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  62236. int sourceClipX,
  62237. int sourceClipY,
  62238. int sourceClipWidth,
  62239. int sourceClipHeight,
  62240. const AffineTransform& transform,
  62241. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62242. {
  62243. if (imageToDraw != 0
  62244. && (! context->isClipEmpty())
  62245. && ! transform.isSingularity())
  62246. {
  62247. if (transform.isIdentity())
  62248. {
  62249. drawImage (imageToDraw,
  62250. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62251. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62252. fillAlphaChannelWithCurrentBrush);
  62253. }
  62254. else if (fillAlphaChannelWithCurrentBrush)
  62255. {
  62256. Path p;
  62257. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  62258. (float) sourceClipWidth, (float) sourceClipHeight);
  62259. p.applyTransform (transform);
  62260. float dx, dy, dw, dh;
  62261. p.getBounds (dx, dy, dw, dh);
  62262. int tx = (int) dx;
  62263. int ty = (int) dy;
  62264. int tw = roundFloatToInt (dw) + 2;
  62265. int th = roundFloatToInt (dh) + 2;
  62266. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62267. {
  62268. Image temp (imageToDraw->getFormat(), tw, th, true);
  62269. Graphics g (temp);
  62270. g.setImageResamplingQuality (state->quality);
  62271. g.drawImageTransformed (imageToDraw,
  62272. sourceClipX,
  62273. sourceClipY,
  62274. sourceClipWidth,
  62275. sourceClipHeight,
  62276. transform.translated ((float) -tx, (float) -ty),
  62277. false);
  62278. SolidColourBrush colourBrush (state->colour);
  62279. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62280. }
  62281. }
  62282. else
  62283. {
  62284. context->blendImageWarping (*imageToDraw,
  62285. sourceClipX,
  62286. sourceClipY,
  62287. sourceClipWidth,
  62288. sourceClipHeight,
  62289. transform,
  62290. state->colour.getFloatAlpha(),
  62291. state->quality);
  62292. }
  62293. }
  62294. }
  62295. END_JUCE_NAMESPACE
  62296. /********* End of inlined file: juce_Graphics.cpp *********/
  62297. /********* Start of inlined file: juce_Justification.cpp *********/
  62298. BEGIN_JUCE_NAMESPACE
  62299. Justification::Justification (const Justification& other) throw()
  62300. : flags (other.flags)
  62301. {
  62302. }
  62303. const Justification& Justification::operator= (const Justification& other) throw()
  62304. {
  62305. flags = other.flags;
  62306. return *this;
  62307. }
  62308. int Justification::getOnlyVerticalFlags() const throw()
  62309. {
  62310. return flags & (top | bottom | verticallyCentred);
  62311. }
  62312. int Justification::getOnlyHorizontalFlags() const throw()
  62313. {
  62314. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  62315. }
  62316. void Justification::applyToRectangle (int& x, int& y,
  62317. const int w, const int h,
  62318. const int spaceX, const int spaceY,
  62319. const int spaceW, const int spaceH) const throw()
  62320. {
  62321. if ((flags & horizontallyCentred) != 0)
  62322. {
  62323. x = spaceX + ((spaceW - w) >> 1);
  62324. }
  62325. else if ((flags & right) != 0)
  62326. {
  62327. x = spaceX + spaceW - w;
  62328. }
  62329. else
  62330. {
  62331. x = spaceX;
  62332. }
  62333. if ((flags & verticallyCentred) != 0)
  62334. {
  62335. y = spaceY + ((spaceH - h) >> 1);
  62336. }
  62337. else if ((flags & bottom) != 0)
  62338. {
  62339. y = spaceY + spaceH - h;
  62340. }
  62341. else
  62342. {
  62343. y = spaceY;
  62344. }
  62345. }
  62346. END_JUCE_NAMESPACE
  62347. /********* End of inlined file: juce_Justification.cpp *********/
  62348. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62349. BEGIN_JUCE_NAMESPACE
  62350. #if JUCE_MSVC
  62351. #pragma warning (disable: 4996) // deprecated sprintf warning
  62352. #endif
  62353. // this will throw an assertion if you try to draw something that's not
  62354. // possible in postscript
  62355. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  62356. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  62357. #define notPossibleInPostscriptAssert jassertfalse
  62358. #else
  62359. #define notPossibleInPostscriptAssert
  62360. #endif
  62361. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  62362. const String& documentTitle,
  62363. const int totalWidth_,
  62364. const int totalHeight_)
  62365. : out (resultingPostScript),
  62366. totalWidth (totalWidth_),
  62367. totalHeight (totalHeight_),
  62368. xOffset (0),
  62369. yOffset (0),
  62370. needToClip (true)
  62371. {
  62372. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  62373. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  62374. out << "%!PS-Adobe-3.0 EPSF-3.0"
  62375. "\n%%BoundingBox: 0 0 600 824"
  62376. "\n%%Pages: 0"
  62377. "\n%%Creator: Raw Material Software JUCE"
  62378. "\n%%Title: " << documentTitle <<
  62379. "\n%%CreationDate: none"
  62380. "\n%%LanguageLevel: 2"
  62381. "\n%%EndComments"
  62382. "\n%%BeginProlog"
  62383. "\n%%BeginResource: JRes"
  62384. "\n/bd {bind def} bind def"
  62385. "\n/c {setrgbcolor} bd"
  62386. "\n/m {moveto} bd"
  62387. "\n/l {lineto} bd"
  62388. "\n/rl {rlineto} bd"
  62389. "\n/ct {curveto} bd"
  62390. "\n/cp {closepath} bd"
  62391. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  62392. "\n/doclip {initclip newpath} bd"
  62393. "\n/endclip {clip newpath} bd"
  62394. "\n%%EndResource"
  62395. "\n%%EndProlog"
  62396. "\n%%BeginSetup"
  62397. "\n%%EndSetup"
  62398. "\n%%Page: 1 1"
  62399. "\n%%BeginPageSetup"
  62400. "\n%%EndPageSetup\n\n"
  62401. << "40 800 translate\n"
  62402. << scale << ' ' << scale << " scale\n\n";
  62403. }
  62404. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  62405. {
  62406. delete clip;
  62407. }
  62408. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  62409. {
  62410. return true;
  62411. }
  62412. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  62413. {
  62414. if (x != 0 || y != 0)
  62415. {
  62416. xOffset += x;
  62417. yOffset += y;
  62418. needToClip = true;
  62419. }
  62420. }
  62421. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  62422. {
  62423. needToClip = true;
  62424. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62425. }
  62426. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62427. {
  62428. needToClip = true;
  62429. return clip->clipTo (clipRegion);
  62430. }
  62431. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  62432. {
  62433. needToClip = true;
  62434. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62435. }
  62436. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62437. {
  62438. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62439. }
  62440. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  62441. {
  62442. return clip->getBounds().translated (-xOffset, -yOffset);
  62443. }
  62444. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  62445. {
  62446. return clip->isEmpty();
  62447. }
  62448. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  62449. const int xOffset_, const int yOffset_)
  62450. : clip (clip_),
  62451. xOffset (xOffset_),
  62452. yOffset (yOffset_)
  62453. {
  62454. }
  62455. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  62456. {
  62457. delete clip;
  62458. }
  62459. void LowLevelGraphicsPostScriptRenderer::saveState()
  62460. {
  62461. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62462. }
  62463. void LowLevelGraphicsPostScriptRenderer::restoreState()
  62464. {
  62465. SavedState* const top = stateStack.getLast();
  62466. if (top != 0)
  62467. {
  62468. clip->swapWith (*top->clip);
  62469. xOffset = top->xOffset;
  62470. yOffset = top->yOffset;
  62471. stateStack.removeLast();
  62472. needToClip = true;
  62473. }
  62474. else
  62475. {
  62476. jassertfalse // trying to pop with an empty stack!
  62477. }
  62478. }
  62479. void LowLevelGraphicsPostScriptRenderer::writeClip()
  62480. {
  62481. if (needToClip)
  62482. {
  62483. needToClip = false;
  62484. out << "doclip ";
  62485. int itemsOnLine = 0;
  62486. for (RectangleList::Iterator i (*clip); i.next();)
  62487. {
  62488. if (++itemsOnLine == 6)
  62489. {
  62490. itemsOnLine = 0;
  62491. out << '\n';
  62492. }
  62493. const Rectangle& r = *i.getRectangle();
  62494. out << r.getX() << ' ' << -r.getY() << ' '
  62495. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  62496. }
  62497. out << "endclip\n";
  62498. }
  62499. }
  62500. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  62501. {
  62502. Colour c (Colours::white.overlaidWith (colour));
  62503. if (lastColour != c)
  62504. {
  62505. lastColour = c;
  62506. out << String (c.getFloatRed(), 3) << ' '
  62507. << String (c.getFloatGreen(), 3) << ' '
  62508. << String (c.getFloatBlue(), 3) << " c\n";
  62509. }
  62510. }
  62511. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  62512. {
  62513. out << String (x, 2) << ' '
  62514. << String (-y, 2) << ' ';
  62515. }
  62516. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  62517. {
  62518. out << "newpath ";
  62519. float lastX = 0.0f;
  62520. float lastY = 0.0f;
  62521. int itemsOnLine = 0;
  62522. Path::Iterator i (path);
  62523. while (i.next())
  62524. {
  62525. if (++itemsOnLine == 4)
  62526. {
  62527. itemsOnLine = 0;
  62528. out << '\n';
  62529. }
  62530. switch (i.elementType)
  62531. {
  62532. case Path::Iterator::startNewSubPath:
  62533. writeXY (i.x1, i.y1);
  62534. lastX = i.x1;
  62535. lastY = i.y1;
  62536. out << "m ";
  62537. break;
  62538. case Path::Iterator::lineTo:
  62539. writeXY (i.x1, i.y1);
  62540. lastX = i.x1;
  62541. lastY = i.y1;
  62542. out << "l ";
  62543. break;
  62544. case Path::Iterator::quadraticTo:
  62545. {
  62546. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  62547. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  62548. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  62549. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  62550. writeXY (cp1x, cp1y);
  62551. writeXY (cp2x, cp2y);
  62552. writeXY (i.x2, i.y2);
  62553. out << "ct ";
  62554. lastX = i.x2;
  62555. lastY = i.y2;
  62556. }
  62557. break;
  62558. case Path::Iterator::cubicTo:
  62559. writeXY (i.x1, i.y1);
  62560. writeXY (i.x2, i.y2);
  62561. writeXY (i.x3, i.y3);
  62562. out << "ct ";
  62563. lastX = i.x3;
  62564. lastY = i.y3;
  62565. break;
  62566. case Path::Iterator::closePath:
  62567. out << "cp ";
  62568. break;
  62569. default:
  62570. jassertfalse
  62571. break;
  62572. }
  62573. }
  62574. out << '\n';
  62575. }
  62576. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  62577. {
  62578. out << "[ "
  62579. << trans.mat00 << ' '
  62580. << trans.mat10 << ' '
  62581. << trans.mat01 << ' '
  62582. << trans.mat11 << ' '
  62583. << trans.mat02 << ' '
  62584. << trans.mat12 << " ] concat ";
  62585. }
  62586. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  62587. {
  62588. writeClip();
  62589. writeColour (colour);
  62590. x += xOffset;
  62591. y += yOffset;
  62592. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  62593. }
  62594. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62595. {
  62596. Path p;
  62597. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62598. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  62599. }
  62600. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62601. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  62602. {
  62603. writeClip();
  62604. Path p (path);
  62605. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62606. writePath (p);
  62607. writeColour (colour);
  62608. out << "fill\n";
  62609. }
  62610. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  62611. {
  62612. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  62613. // postscript can't do semi-transparent ones.
  62614. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62615. writeClip();
  62616. out << "gsave ";
  62617. {
  62618. Path p (path);
  62619. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62620. writePath (p);
  62621. out << "clip\n";
  62622. }
  62623. int numColours = 256;
  62624. PixelARGB* const colours = gradient.createLookupTable (numColours);
  62625. for (int i = numColours; --i >= 0;)
  62626. colours[i].unpremultiply();
  62627. const Rectangle bounds (clip->getBounds());
  62628. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  62629. // time-being, this just fills it with the average colour..
  62630. writeColour (Colour (colours [numColours / 2].getARGB()));
  62631. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  62632. juce_free (colours);
  62633. out << "grestore\n";
  62634. }
  62635. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62636. const Image& sourceImage,
  62637. int imageX, int imageY,
  62638. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  62639. {
  62640. writeClip();
  62641. out << "gsave ";
  62642. Path p (path);
  62643. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  62644. writePath (p);
  62645. out << "clip\n";
  62646. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  62647. out << "grestore\n";
  62648. }
  62649. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  62650. {
  62651. x += xOffset;
  62652. y += yOffset;
  62653. writeClip();
  62654. writeColour (colour);
  62655. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62656. }
  62657. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  62658. {
  62659. imageX += xOffset;
  62660. imageY += yOffset;
  62661. writeClip();
  62662. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62663. }
  62664. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  62665. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  62666. {
  62667. alphaImageX += xOffset;
  62668. alphaImageY += yOffset;
  62669. fillerImageX += xOffset;
  62670. fillerImageY += yOffset;
  62671. writeClip();
  62672. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62673. }
  62674. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  62675. int dx, int dy, int dw, int dh,
  62676. int sx, int sy, int sw, int sh,
  62677. float alpha,
  62678. const Graphics::ResamplingQuality quality)
  62679. {
  62680. if (sw > 0 && sh > 0)
  62681. {
  62682. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  62683. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  62684. if (sw == dw && sh == dh)
  62685. {
  62686. blendImage (sourceImage,
  62687. dx, dy, dw, dh,
  62688. sx, sy, alpha);
  62689. }
  62690. else
  62691. {
  62692. blendImageWarping (sourceImage,
  62693. sx, sy, sw, sh,
  62694. AffineTransform::scale (dw / (float) sw,
  62695. dh / (float) sh)
  62696. .translated ((float) (dx - sx),
  62697. (float) (dy - sy)),
  62698. alpha,
  62699. quality);
  62700. }
  62701. }
  62702. }
  62703. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62704. {
  62705. blendImageWarping (sourceImage,
  62706. sx, sy, dw, dh,
  62707. AffineTransform::translation ((float) dx, (float) dy),
  62708. opacity, Graphics::highResamplingQuality);
  62709. }
  62710. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  62711. const int sx, const int sy,
  62712. const int maxW, const int maxH) const
  62713. {
  62714. out << "{<\n";
  62715. const int w = jmin (maxW, im.getWidth());
  62716. const int h = jmin (maxH, im.getHeight());
  62717. int charsOnLine = 0;
  62718. int lineStride, pixelStride;
  62719. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  62720. Colour pixel;
  62721. for (int y = h; --y >= 0;)
  62722. {
  62723. for (int x = 0; x < w; ++x)
  62724. {
  62725. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  62726. if (x >= sx && y >= sy)
  62727. {
  62728. if (im.isARGB())
  62729. {
  62730. PixelARGB p (*(const PixelARGB*) pixelData);
  62731. p.unpremultiply();
  62732. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  62733. }
  62734. else if (im.isRGB())
  62735. {
  62736. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  62737. }
  62738. else
  62739. {
  62740. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  62741. }
  62742. }
  62743. else
  62744. {
  62745. pixel = Colours::transparentWhite;
  62746. }
  62747. char colourString [16];
  62748. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  62749. out << (const char*) colourString;
  62750. charsOnLine += 3;
  62751. if (charsOnLine > 100)
  62752. {
  62753. out << '\n';
  62754. charsOnLine = 0;
  62755. }
  62756. }
  62757. }
  62758. im.releasePixelDataReadOnly (data);
  62759. out << "\n>}\n";
  62760. }
  62761. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  62762. int srcClipX, int srcClipY,
  62763. int srcClipW, int srcClipH,
  62764. const AffineTransform& t,
  62765. float /*opacity*/,
  62766. const Graphics::ResamplingQuality /*quality*/)
  62767. {
  62768. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  62769. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  62770. writeClip();
  62771. out << "gsave ";
  62772. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  62773. .scaled (1.0f, -1.0f));
  62774. RectangleList imageClip;
  62775. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  62776. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  62777. out << "newpath ";
  62778. int itemsOnLine = 0;
  62779. for (RectangleList::Iterator i (imageClip); i.next();)
  62780. {
  62781. if (++itemsOnLine == 6)
  62782. {
  62783. out << '\n';
  62784. itemsOnLine = 0;
  62785. }
  62786. const Rectangle& r = *i.getRectangle();
  62787. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  62788. }
  62789. out << " clip newpath\n";
  62790. out << w << ' ' << h << " scale\n";
  62791. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  62792. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  62793. out << "false 3 colorimage grestore\n";
  62794. needToClip = true;
  62795. }
  62796. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62797. {
  62798. Path p;
  62799. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  62800. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  62801. }
  62802. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62803. {
  62804. drawLine (x, top, x, bottom, col);
  62805. }
  62806. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62807. {
  62808. drawLine (left, y, right, y, col);
  62809. }
  62810. END_JUCE_NAMESPACE
  62811. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62812. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  62813. BEGIN_JUCE_NAMESPACE
  62814. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  62815. #define JUCE_USE_SSE_INSTRUCTIONS 1
  62816. #endif
  62817. #if defined (JUCE_DEBUG) && JUCE_MSVC
  62818. #pragma warning (disable: 4714)
  62819. #endif
  62820. #define MINIMUM_COORD -0x3fffffff
  62821. #define MAXIMUM_COORD 0x3fffffff
  62822. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  62823. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  62824. jassert ((int) x >= MINIMUM_COORD \
  62825. && (int) x <= MAXIMUM_COORD \
  62826. && (int) y >= MINIMUM_COORD \
  62827. && (int) y <= MAXIMUM_COORD \
  62828. && (int) w >= 0 \
  62829. && (int) w < MAXIMUM_COORD \
  62830. && (int) h >= 0 \
  62831. && (int) h < MAXIMUM_COORD);
  62832. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62833. {
  62834. const PixelARGB blendColour (colour.getPixelARGB());
  62835. if (w < 32)
  62836. {
  62837. while (--h >= 0)
  62838. {
  62839. PixelRGB* dest = (PixelRGB*) pixels;
  62840. for (int i = w; --i >= 0;)
  62841. (dest++)->set (blendColour);
  62842. pixels += stride;
  62843. }
  62844. }
  62845. else
  62846. {
  62847. // for wider fills, it's worth using some optimisations..
  62848. const uint8 r = blendColour.getRed();
  62849. const uint8 g = blendColour.getGreen();
  62850. const uint8 b = blendColour.getBlue();
  62851. if (r == g && r == b) // if all the component values are the same, we can cheat..
  62852. {
  62853. while (--h >= 0)
  62854. {
  62855. memset (pixels, r, w * 3);
  62856. pixels += stride;
  62857. }
  62858. }
  62859. else
  62860. {
  62861. PixelRGB filler [4];
  62862. filler[0].set (blendColour);
  62863. filler[1].set (blendColour);
  62864. filler[2].set (blendColour);
  62865. filler[3].set (blendColour);
  62866. const int* const intFiller = (const int*) filler;
  62867. while (--h >= 0)
  62868. {
  62869. uint8* dest = (uint8*) pixels;
  62870. int i = w;
  62871. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  62872. {
  62873. ((PixelRGB*) dest)->set (blendColour);
  62874. dest += 3;
  62875. --i;
  62876. }
  62877. while (i >= 4)
  62878. {
  62879. ((int*) dest) [0] = intFiller[0];
  62880. ((int*) dest) [1] = intFiller[1];
  62881. ((int*) dest) [2] = intFiller[2];
  62882. dest += 12;
  62883. i -= 4;
  62884. }
  62885. while (--i >= 0)
  62886. {
  62887. ((PixelRGB*) dest)->set (blendColour);
  62888. dest += 3;
  62889. }
  62890. pixels += stride;
  62891. }
  62892. }
  62893. }
  62894. }
  62895. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62896. {
  62897. const PixelARGB blendColour (colour.getPixelARGB());
  62898. while (--h >= 0)
  62899. {
  62900. PixelARGB* const dest = (PixelARGB*) pixels;
  62901. for (int i = 0; i < w; ++i)
  62902. dest[i] = blendColour;
  62903. pixels += stride;
  62904. }
  62905. }
  62906. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62907. {
  62908. if (colour.isOpaque())
  62909. {
  62910. replaceRectRGB (pixels, w, h, stride, colour);
  62911. }
  62912. else
  62913. {
  62914. const PixelARGB blendColour (colour.getPixelARGB());
  62915. const int alpha = blendColour.getAlpha();
  62916. if (alpha <= 0)
  62917. return;
  62918. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  62919. if (SystemStats::hasSSE())
  62920. {
  62921. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  62922. | (int64) ((blendColour.getGreen() << 16)
  62923. | blendColour.getBlue());
  62924. const int invAlpha = 0xff - alpha;
  62925. int64 aaaa = (invAlpha << 16) | invAlpha;
  62926. aaaa = (aaaa << 16) | aaaa;
  62927. #ifndef JUCE_GCC
  62928. __asm
  62929. {
  62930. movq mm1, aaaa
  62931. movq mm2, rgb0
  62932. pxor mm7, mm7
  62933. }
  62934. while (--h >= 0)
  62935. {
  62936. __asm
  62937. {
  62938. mov edx, pixels
  62939. mov ebx, w
  62940. pixloop:
  62941. prefetchnta [edx]
  62942. mov ax, [edx + 1]
  62943. shl eax, 8
  62944. mov al, [edx]
  62945. movd mm0, eax
  62946. punpcklbw mm0, mm7
  62947. pmullw mm0, mm1
  62948. psrlw mm0, 8
  62949. paddw mm0, mm2
  62950. packuswb mm0, mm7
  62951. movd eax, mm0
  62952. mov [edx], al
  62953. inc edx
  62954. shr eax, 8
  62955. mov [edx], ax
  62956. add edx, 2
  62957. dec ebx
  62958. jg pixloop
  62959. }
  62960. pixels += stride;
  62961. }
  62962. __asm emms
  62963. #else
  62964. __asm__ __volatile__ (
  62965. "\tpush %%ebx \n"
  62966. "\tmovq %[aaaa], %%mm1 \n"
  62967. "\tmovq %[rgb0], %%mm2 \n"
  62968. "\tpxor %%mm7, %%mm7 \n"
  62969. ".lineLoop2: \n"
  62970. "\tmovl %%esi,%%edx \n"
  62971. "\tmovl %[w], %%ebx \n"
  62972. ".pixLoop2: \n"
  62973. "\tprefetchnta (%%edx) \n"
  62974. "\tmov (%%edx), %%ax \n"
  62975. "\tshl $8, %%eax \n"
  62976. "\tmov 2(%%edx), %%al \n"
  62977. "\tmovd %%eax, %%mm0 \n"
  62978. "\tpunpcklbw %%mm7, %%mm0 \n"
  62979. "\tpmullw %%mm1, %%mm0 \n"
  62980. "\tpsrlw $8, %%mm0 \n"
  62981. "\tpaddw %%mm2, %%mm0 \n"
  62982. "\tpackuswb %%mm7, %%mm0 \n"
  62983. "\tmovd %%mm0, %%eax \n"
  62984. "\tmovb %%al, (%%edx) \n"
  62985. "\tinc %%edx \n"
  62986. "\tshr $8, %%eax \n"
  62987. "\tmovw %%ax, (%%edx) \n"
  62988. "\tadd $2, %%edx \n"
  62989. "\tdec %%ebx \n"
  62990. "\tjg .pixLoop2 \n"
  62991. "\tadd %%edi, %%esi \n"
  62992. "\tdec %%ecx \n"
  62993. "\tjg .lineLoop2 \n"
  62994. "\tpop %%ebx \n"
  62995. "\temms \n"
  62996. : /* No output registers */
  62997. : [aaaa] "m" (aaaa), /* Input registers */
  62998. [rgb0] "m" (rgb0),
  62999. [w] "m" (w),
  63000. "c" (h),
  63001. [stride] "D" (stride),
  63002. [pixels] "S" (pixels)
  63003. : "cc", "eax", "edx", "memory" /* Clobber list */
  63004. );
  63005. #endif
  63006. }
  63007. else
  63008. #endif
  63009. {
  63010. while (--h >= 0)
  63011. {
  63012. PixelRGB* dest = (PixelRGB*) pixels;
  63013. for (int i = w; --i >= 0;)
  63014. (dest++)->blend (blendColour);
  63015. pixels += stride;
  63016. }
  63017. }
  63018. }
  63019. }
  63020. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63021. {
  63022. if (colour.isOpaque())
  63023. {
  63024. replaceRectARGB (pixels, w, h, stride, colour);
  63025. }
  63026. else
  63027. {
  63028. const PixelARGB blendColour (colour.getPixelARGB());
  63029. const int alpha = blendColour.getAlpha();
  63030. if (alpha <= 0)
  63031. return;
  63032. while (--h >= 0)
  63033. {
  63034. PixelARGB* dest = (PixelARGB*) pixels;
  63035. for (int i = w; --i >= 0;)
  63036. (dest++)->blend (blendColour);
  63037. pixels += stride;
  63038. }
  63039. }
  63040. }
  63041. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  63042. const uint8* alphaValues, const int w, int h,
  63043. const int pixelStride, const int lineStride,
  63044. const Colour& colour) throw()
  63045. {
  63046. const PixelARGB srcPix (colour.getPixelARGB());
  63047. while (--h >= 0)
  63048. {
  63049. PixelARGB* dest = (PixelARGB*) destPixel;
  63050. const uint8* src = alphaValues;
  63051. int i = w;
  63052. while (--i >= 0)
  63053. {
  63054. unsigned int srcAlpha = *src;
  63055. src += pixelStride;
  63056. if (srcAlpha > 0)
  63057. dest->blend (srcPix, srcAlpha);
  63058. ++dest;
  63059. }
  63060. alphaValues += lineStride;
  63061. destPixel += imageStride;
  63062. }
  63063. }
  63064. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  63065. const uint8* alphaValues, int const width, int height,
  63066. const int pixelStride, const int lineStride,
  63067. const Colour& colour) throw()
  63068. {
  63069. const PixelARGB srcPix (colour.getPixelARGB());
  63070. while (--height >= 0)
  63071. {
  63072. PixelRGB* dest = (PixelRGB*) destPixel;
  63073. const uint8* src = alphaValues;
  63074. int i = width;
  63075. while (--i >= 0)
  63076. {
  63077. unsigned int srcAlpha = *src;
  63078. src += pixelStride;
  63079. if (srcAlpha > 0)
  63080. dest->blend (srcPix, srcAlpha);
  63081. ++dest;
  63082. }
  63083. alphaValues += lineStride;
  63084. destPixel += imageStride;
  63085. }
  63086. }
  63087. template <class PixelType>
  63088. class SolidColourEdgeTableRenderer
  63089. {
  63090. uint8* const data;
  63091. const int stride;
  63092. PixelType* linePixels;
  63093. PixelARGB sourceColour;
  63094. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  63095. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  63096. public:
  63097. SolidColourEdgeTableRenderer (uint8* const data_,
  63098. const int stride_,
  63099. const Colour& colour) throw()
  63100. : data (data_),
  63101. stride (stride_),
  63102. sourceColour (colour.getPixelARGB())
  63103. {
  63104. }
  63105. forcedinline void setEdgeTableYPos (const int y) throw()
  63106. {
  63107. linePixels = (PixelType*) (data + stride * y);
  63108. }
  63109. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63110. {
  63111. linePixels[x].blend (sourceColour, alphaLevel);
  63112. }
  63113. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63114. {
  63115. PixelARGB p (sourceColour);
  63116. p.multiplyAlpha (alphaLevel);
  63117. PixelType* dest = linePixels + x;
  63118. if (p.getAlpha() < 0xff)
  63119. {
  63120. do
  63121. {
  63122. dest->blend (p);
  63123. ++dest;
  63124. } while (--width > 0);
  63125. }
  63126. else
  63127. {
  63128. do
  63129. {
  63130. dest->set (p);
  63131. ++dest;
  63132. } while (--width > 0);
  63133. }
  63134. }
  63135. };
  63136. class AlphaBitmapRenderer
  63137. {
  63138. uint8* data;
  63139. int stride;
  63140. uint8* lineStart;
  63141. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  63142. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  63143. public:
  63144. AlphaBitmapRenderer (uint8* const data_,
  63145. const int stride_) throw()
  63146. : data (data_),
  63147. stride (stride_)
  63148. {
  63149. }
  63150. forcedinline void setEdgeTableYPos (const int y) throw()
  63151. {
  63152. lineStart = data + (stride * y);
  63153. }
  63154. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63155. {
  63156. lineStart [x] = (uint8) alphaLevel;
  63157. }
  63158. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63159. {
  63160. uint8* d = lineStart + x;
  63161. while (--width >= 0)
  63162. *d++ = (uint8) alphaLevel;
  63163. }
  63164. };
  63165. static const int numScaleBits = 12;
  63166. class LinearGradientPixelGenerator
  63167. {
  63168. const PixelARGB* const lookupTable;
  63169. const int numEntries;
  63170. PixelARGB linePix;
  63171. int start, scale;
  63172. double grad, yTerm;
  63173. bool vertical, horizontal;
  63174. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  63175. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  63176. public:
  63177. LinearGradientPixelGenerator (const ColourGradient& gradient,
  63178. const PixelARGB* const lookupTable_, const int numEntries_)
  63179. : lookupTable (lookupTable_),
  63180. numEntries (numEntries_)
  63181. {
  63182. jassert (numEntries_ >= 0);
  63183. float x1 = gradient.x1;
  63184. float y1 = gradient.y1;
  63185. float x2 = gradient.x2;
  63186. float y2 = gradient.y2;
  63187. if (! gradient.transform.isIdentity())
  63188. {
  63189. Line l (x2, y2, x1, y1);
  63190. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  63191. float x3 = p3.getX();
  63192. float y3 = p3.getY();
  63193. gradient.transform.transformPoint (x1, y1);
  63194. gradient.transform.transformPoint (x2, y2);
  63195. gradient.transform.transformPoint (x3, y3);
  63196. Line l2 (x2, y2, x3, y3);
  63197. float prop = l2.findNearestPointTo (x1, y1);
  63198. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  63199. x2 = newP2.getX();
  63200. y2 = newP2.getY();
  63201. }
  63202. vertical = fabs (x1 - x2) < 0.001f;
  63203. horizontal = fabs (y1 - y2) < 0.001f;
  63204. if (vertical)
  63205. {
  63206. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  63207. start = roundDoubleToInt (y1 * scale);
  63208. }
  63209. else if (horizontal)
  63210. {
  63211. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  63212. start = roundDoubleToInt (x1 * scale);
  63213. }
  63214. else
  63215. {
  63216. grad = (y2 - y1) / (double) (x1 - x2);
  63217. yTerm = y1 - x1 / grad;
  63218. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  63219. grad *= scale;
  63220. }
  63221. }
  63222. forcedinline void setY (const int y) throw()
  63223. {
  63224. if (vertical)
  63225. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  63226. else if (! horizontal)
  63227. start = roundDoubleToInt ((y - yTerm) * grad);
  63228. }
  63229. forcedinline const PixelARGB getPixel (const int x) const throw()
  63230. {
  63231. if (vertical)
  63232. return linePix;
  63233. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  63234. }
  63235. };
  63236. class RadialGradientPixelGenerator
  63237. {
  63238. protected:
  63239. const PixelARGB* const lookupTable;
  63240. const int numEntries;
  63241. const double gx1, gy1;
  63242. double maxDist, invScale;
  63243. double dy;
  63244. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  63245. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  63246. public:
  63247. RadialGradientPixelGenerator (const ColourGradient& gradient,
  63248. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63249. : lookupTable (lookupTable_),
  63250. numEntries (numEntries_),
  63251. gx1 (gradient.x1),
  63252. gy1 (gradient.y1)
  63253. {
  63254. jassert (numEntries_ >= 0);
  63255. const float dx = gradient.x1 - gradient.x2;
  63256. const float dy = gradient.y1 - gradient.y2;
  63257. maxDist = dx * dx + dy * dy;
  63258. invScale = (numEntries + 1) / sqrt (maxDist);
  63259. }
  63260. forcedinline void setY (const int y) throw()
  63261. {
  63262. dy = y - gy1;
  63263. dy *= dy;
  63264. }
  63265. forcedinline const PixelARGB getPixel (const int px) const throw()
  63266. {
  63267. double x = px - gx1;
  63268. x *= x;
  63269. x += dy;
  63270. if (x >= maxDist)
  63271. return lookupTable [numEntries];
  63272. else
  63273. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63274. }
  63275. };
  63276. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  63277. {
  63278. double tM10, tM00, lineYM01, lineYM11;
  63279. AffineTransform inverseTransform;
  63280. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  63281. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  63282. public:
  63283. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  63284. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63285. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  63286. inverseTransform (gradient.transform.inverted())
  63287. {
  63288. tM10 = inverseTransform.mat10;
  63289. tM00 = inverseTransform.mat00;
  63290. }
  63291. forcedinline void setY (const int y) throw()
  63292. {
  63293. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  63294. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  63295. }
  63296. forcedinline const PixelARGB getPixel (const int px) const throw()
  63297. {
  63298. double x = px;
  63299. const double y = tM10 * x + lineYM11;
  63300. x = tM00 * x + lineYM01;
  63301. x *= x;
  63302. x += y * y;
  63303. if (x >= maxDist)
  63304. return lookupTable [numEntries];
  63305. else
  63306. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63307. }
  63308. };
  63309. template <class PixelType, class GradientType>
  63310. class GradientEdgeTableRenderer : public GradientType
  63311. {
  63312. uint8* const data;
  63313. const int stride;
  63314. PixelType* linePixels;
  63315. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  63316. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  63317. public:
  63318. GradientEdgeTableRenderer (uint8* const data_,
  63319. const int stride_,
  63320. const ColourGradient& gradient,
  63321. const PixelARGB* const lookupTable, const int numEntries) throw()
  63322. : GradientType (gradient, lookupTable, numEntries - 1),
  63323. data (data_),
  63324. stride (stride_)
  63325. {
  63326. }
  63327. forcedinline void setEdgeTableYPos (const int y) throw()
  63328. {
  63329. linePixels = (PixelType*) (data + stride * y);
  63330. GradientType::setY (y);
  63331. }
  63332. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63333. {
  63334. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  63335. }
  63336. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  63337. {
  63338. PixelType* dest = linePixels + x;
  63339. if (alphaLevel < 0xff)
  63340. {
  63341. do
  63342. {
  63343. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  63344. } while (--width > 0);
  63345. }
  63346. else
  63347. {
  63348. do
  63349. {
  63350. (dest++)->blend (GradientType::getPixel (x++));
  63351. } while (--width > 0);
  63352. }
  63353. }
  63354. };
  63355. template <class DestPixelType, class SrcPixelType>
  63356. class ImageFillEdgeTableRenderer
  63357. {
  63358. uint8* const destImageData;
  63359. const uint8* srcImageData;
  63360. int stride, srcStride, extraAlpha;
  63361. DestPixelType* linePixels;
  63362. SrcPixelType* sourceLineStart;
  63363. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  63364. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  63365. public:
  63366. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  63367. const int stride_,
  63368. const uint8* srcImageData_,
  63369. const int srcStride_,
  63370. int extraAlpha_,
  63371. SrcPixelType*) throw() // dummy param to avoid compiler error
  63372. : destImageData (destImageData_),
  63373. srcImageData (srcImageData_),
  63374. stride (stride_),
  63375. srcStride (srcStride_),
  63376. extraAlpha (extraAlpha_)
  63377. {
  63378. }
  63379. forcedinline void setEdgeTableYPos (int y) throw()
  63380. {
  63381. linePixels = (DestPixelType*) (destImageData + stride * y);
  63382. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  63383. }
  63384. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  63385. {
  63386. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63387. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  63388. }
  63389. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  63390. {
  63391. DestPixelType* dest = linePixels + x;
  63392. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63393. if (alphaLevel < 0xfe)
  63394. {
  63395. do
  63396. {
  63397. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  63398. } while (--width > 0);
  63399. }
  63400. else
  63401. {
  63402. do
  63403. {
  63404. dest++ ->blend (sourceLineStart [x++]);
  63405. } while (--width > 0);
  63406. }
  63407. }
  63408. };
  63409. static void blendRowOfPixels (PixelARGB* dst,
  63410. const PixelRGB* src,
  63411. int width) throw()
  63412. {
  63413. while (--width >= 0)
  63414. (dst++)->set (*src++);
  63415. }
  63416. static void blendRowOfPixels (PixelRGB* dst,
  63417. const PixelRGB* src,
  63418. int width) throw()
  63419. {
  63420. memcpy (dst, src, 3 * width);
  63421. }
  63422. static void blendRowOfPixels (PixelRGB* dst,
  63423. const PixelARGB* src,
  63424. int width) throw()
  63425. {
  63426. while (--width >= 0)
  63427. (dst++)->blend (*src++);
  63428. }
  63429. static void blendRowOfPixels (PixelARGB* dst,
  63430. const PixelARGB* src,
  63431. int width) throw()
  63432. {
  63433. while (--width >= 0)
  63434. (dst++)->blend (*src++);
  63435. }
  63436. static void blendRowOfPixels (PixelARGB* dst,
  63437. const PixelRGB* src,
  63438. int width,
  63439. const uint8 alpha) throw()
  63440. {
  63441. while (--width >= 0)
  63442. (dst++)->blend (*src++, alpha);
  63443. }
  63444. static void blendRowOfPixels (PixelRGB* dst,
  63445. const PixelRGB* src,
  63446. int width,
  63447. const uint8 alpha) throw()
  63448. {
  63449. uint8* d = (uint8*) dst;
  63450. const uint8* s = (const uint8*) src;
  63451. const int inverseAlpha = 0xff - alpha;
  63452. while (--width >= 0)
  63453. {
  63454. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  63455. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  63456. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  63457. d += 3;
  63458. s += 3;
  63459. }
  63460. }
  63461. static void blendRowOfPixels (PixelRGB* dst,
  63462. const PixelARGB* src,
  63463. int width,
  63464. const uint8 alpha) throw()
  63465. {
  63466. while (--width >= 0)
  63467. (dst++)->blend (*src++, alpha);
  63468. }
  63469. static void blendRowOfPixels (PixelARGB* dst,
  63470. const PixelARGB* src,
  63471. int width,
  63472. const uint8 alpha) throw()
  63473. {
  63474. while (--width >= 0)
  63475. (dst++)->blend (*src++, alpha);
  63476. }
  63477. template <class DestPixelType, class SrcPixelType>
  63478. static void overlayImage (DestPixelType* dest,
  63479. const int destStride,
  63480. const SrcPixelType* src,
  63481. const int srcStride,
  63482. const int width,
  63483. int height,
  63484. const uint8 alpha) throw()
  63485. {
  63486. if (alpha < 0xff)
  63487. {
  63488. while (--height >= 0)
  63489. {
  63490. blendRowOfPixels (dest, src, width, alpha);
  63491. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63492. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63493. }
  63494. }
  63495. else
  63496. {
  63497. while (--height >= 0)
  63498. {
  63499. blendRowOfPixels (dest, src, width);
  63500. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63501. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63502. }
  63503. }
  63504. }
  63505. template <class DestPixelType, class SrcPixelType>
  63506. static void transformedImageRender (Image& destImage,
  63507. const Image& sourceImage,
  63508. const int destClipX, const int destClipY,
  63509. const int destClipW, const int destClipH,
  63510. const int srcClipX, const int srcClipY,
  63511. const int srcClipWidth, const int srcClipHeight,
  63512. double srcX, double srcY,
  63513. const double lineDX, const double lineDY,
  63514. const double pixelDX, const double pixelDY,
  63515. const uint8 alpha,
  63516. const Graphics::ResamplingQuality quality,
  63517. DestPixelType*,
  63518. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  63519. // parameters of the templated classes to
  63520. // make it use the correct instance of this function..
  63521. {
  63522. int destStride, destPixelStride;
  63523. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  63524. int srcStride, srcPixelStride;
  63525. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  63526. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  63527. {
  63528. if (alpha == 255)
  63529. {
  63530. for (int y = 0; y < destClipH; ++y)
  63531. {
  63532. double sx = srcX;
  63533. double sy = srcY;
  63534. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63535. for (int x = destClipW; --x >= 0;)
  63536. {
  63537. const int ix = ((int) sx) - srcClipX;
  63538. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63539. {
  63540. const int iy = ((int) sy) - srcClipY;
  63541. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63542. {
  63543. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63544. dest->set (*src);
  63545. }
  63546. }
  63547. ++dest;
  63548. sx += pixelDX;
  63549. sy += pixelDY;
  63550. }
  63551. srcX += lineDX;
  63552. srcY += lineDY;
  63553. }
  63554. }
  63555. else
  63556. {
  63557. for (int y = 0; y < destClipH; ++y)
  63558. {
  63559. double sx = srcX;
  63560. double sy = srcY;
  63561. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63562. for (int x = destClipW; --x >= 0;)
  63563. {
  63564. const int ix = ((int) sx) - srcClipX;
  63565. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63566. {
  63567. const int iy = ((int) sy) - srcClipY;
  63568. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63569. {
  63570. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63571. dest->blend (*src, alpha);
  63572. }
  63573. }
  63574. ++dest;
  63575. sx += pixelDX;
  63576. sy += pixelDY;
  63577. }
  63578. srcX += lineDX;
  63579. srcY += lineDY;
  63580. }
  63581. }
  63582. }
  63583. else
  63584. {
  63585. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  63586. for (int y = 0; y < destClipH; ++y)
  63587. {
  63588. double sx = srcX - (srcClipWidth == destClipW ? 0.0 : 0.5);
  63589. double sy = srcY - (srcClipHeight == destClipH ? 0.0 : 0.5);
  63590. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63591. for (int x = 0; x < destClipW; ++x)
  63592. {
  63593. const double fx = floor (sx);
  63594. const double fy = floor (sy);
  63595. const int ix = roundDoubleToInt (fx) - srcClipX;
  63596. const int iy = roundDoubleToInt (fy) - srcClipY;
  63597. if (ix < srcClipWidth && iy < srcClipHeight)
  63598. {
  63599. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  63600. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63601. if (iy >= 0)
  63602. {
  63603. if (ix >= 0)
  63604. p1.set (src[0]);
  63605. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63606. p2.set (src[1]);
  63607. }
  63608. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  63609. {
  63610. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63611. if (ix >= 0)
  63612. p3.set (src[0]);
  63613. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63614. p4.set (src[1]);
  63615. }
  63616. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  63617. p1.tween (p2, dx);
  63618. p3.tween (p4, dx);
  63619. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  63620. if (p1.getAlpha() > 0)
  63621. dest->blend (p1, alpha);
  63622. }
  63623. ++dest;
  63624. sx += pixelDX;
  63625. sy += pixelDY;
  63626. }
  63627. srcX += lineDX;
  63628. srcY += lineDY;
  63629. }
  63630. }
  63631. destImage.releasePixelDataReadWrite (destPixels);
  63632. sourceImage.releasePixelDataReadOnly (srcPixels);
  63633. }
  63634. template <class SrcPixelType, class DestPixelType>
  63635. static void renderAlphaMap (DestPixelType* destPixels,
  63636. int destStride,
  63637. SrcPixelType* srcPixels,
  63638. int srcStride,
  63639. const uint8* alphaValues,
  63640. const int lineStride, const int pixelStride,
  63641. int width, int height,
  63642. const int extraAlpha) throw()
  63643. {
  63644. while (--height >= 0)
  63645. {
  63646. SrcPixelType* srcPix = srcPixels;
  63647. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  63648. DestPixelType* destPix = destPixels;
  63649. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  63650. const uint8* alpha = alphaValues;
  63651. alphaValues += lineStride;
  63652. if (extraAlpha < 0x100)
  63653. {
  63654. for (int i = width; --i >= 0;)
  63655. {
  63656. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  63657. alpha += pixelStride;
  63658. }
  63659. }
  63660. else
  63661. {
  63662. for (int i = width; --i >= 0;)
  63663. {
  63664. destPix++ ->blend (*srcPix++, *alpha);
  63665. alpha += pixelStride;
  63666. }
  63667. }
  63668. }
  63669. }
  63670. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  63671. : image (image_),
  63672. xOffset (0),
  63673. yOffset (0),
  63674. stateStack (20)
  63675. {
  63676. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  63677. }
  63678. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  63679. {
  63680. delete clip;
  63681. }
  63682. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  63683. {
  63684. return false;
  63685. }
  63686. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  63687. {
  63688. xOffset += x;
  63689. yOffset += y;
  63690. }
  63691. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  63692. {
  63693. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  63694. }
  63695. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  63696. {
  63697. RectangleList temp (clipRegion);
  63698. temp.offsetAll (xOffset, yOffset);
  63699. return clip->clipTo (temp);
  63700. }
  63701. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  63702. {
  63703. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  63704. }
  63705. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  63706. {
  63707. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  63708. }
  63709. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  63710. {
  63711. return clip->getBounds().translated (-xOffset, -yOffset);
  63712. }
  63713. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  63714. {
  63715. return clip->isEmpty();
  63716. }
  63717. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  63718. const int xOffset_, const int yOffset_)
  63719. : clip (clip_),
  63720. xOffset (xOffset_),
  63721. yOffset (yOffset_)
  63722. {
  63723. }
  63724. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  63725. {
  63726. delete clip;
  63727. }
  63728. void LowLevelGraphicsSoftwareRenderer::saveState()
  63729. {
  63730. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  63731. }
  63732. void LowLevelGraphicsSoftwareRenderer::restoreState()
  63733. {
  63734. SavedState* const top = stateStack.getLast();
  63735. if (top != 0)
  63736. {
  63737. clip->swapWith (*top->clip);
  63738. xOffset = top->xOffset;
  63739. yOffset = top->yOffset;
  63740. stateStack.removeLast();
  63741. }
  63742. else
  63743. {
  63744. jassertfalse // trying to pop with an empty stack!
  63745. }
  63746. }
  63747. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63748. {
  63749. x += xOffset;
  63750. y += yOffset;
  63751. for (RectangleList::Iterator i (*clip); i.next();)
  63752. {
  63753. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  63754. }
  63755. }
  63756. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  63757. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63758. {
  63759. if (clipRect.intersectRectangle (x, y, w, h))
  63760. {
  63761. int stride, pixelStride;
  63762. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63763. if (image.getFormat() == Image::RGB)
  63764. {
  63765. if (replaceExistingContents)
  63766. replaceRectRGB (pixels, w, h, stride, colour);
  63767. else
  63768. blendRectRGB (pixels, w, h, stride, colour);
  63769. }
  63770. else if (image.getFormat() == Image::ARGB)
  63771. {
  63772. if (replaceExistingContents)
  63773. replaceRectARGB (pixels, w, h, stride, colour);
  63774. else
  63775. blendRectARGB (pixels, w, h, stride, colour);
  63776. }
  63777. else
  63778. {
  63779. jassertfalse // not done!
  63780. }
  63781. image.releasePixelDataReadWrite (pixels);
  63782. }
  63783. }
  63784. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  63785. {
  63786. Path p;
  63787. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  63788. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  63789. }
  63790. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  63791. const Path& path, const AffineTransform& transform,
  63792. int& x, int& y, int& w, int& h) const
  63793. {
  63794. float tx, ty, tw, th;
  63795. path.getBoundsTransformed (transform, tx, ty, tw, th);
  63796. x = roundDoubleToInt (tx) - 1;
  63797. y = roundDoubleToInt (ty) - 1;
  63798. w = roundDoubleToInt (tw) + 2;
  63799. h = roundDoubleToInt (th) + 2;
  63800. // seems like this operation is using some crazy out-of-range numbers..
  63801. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  63802. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  63803. }
  63804. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  63805. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63806. {
  63807. for (RectangleList::Iterator i (*clip); i.next();)
  63808. {
  63809. const Rectangle& r = *i.getRectangle();
  63810. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  63811. }
  63812. }
  63813. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63814. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63815. {
  63816. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63817. int cx, cy, cw, ch;
  63818. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63819. {
  63820. EdgeTable edgeTable (0, ch, quality);
  63821. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63822. int stride, pixelStride;
  63823. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63824. if (image.getFormat() == Image::RGB)
  63825. {
  63826. jassert (pixelStride == 3);
  63827. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  63828. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63829. }
  63830. else if (image.getFormat() == Image::ARGB)
  63831. {
  63832. jassert (pixelStride == 4);
  63833. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  63834. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63835. }
  63836. else if (image.getFormat() == Image::SingleChannel)
  63837. {
  63838. jassert (pixelStride == 1);
  63839. AlphaBitmapRenderer renderer (pixels, stride);
  63840. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63841. }
  63842. image.releasePixelDataReadWrite (pixels);
  63843. }
  63844. }
  63845. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63846. {
  63847. for (RectangleList::Iterator i (*clip); i.next();)
  63848. {
  63849. const Rectangle& r = *i.getRectangle();
  63850. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63851. path, t, gradient, quality);
  63852. }
  63853. }
  63854. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63855. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63856. {
  63857. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63858. int cx, cy, cw, ch;
  63859. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63860. {
  63861. int stride, pixelStride;
  63862. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63863. ColourGradient g2 (gradient);
  63864. const bool isIdentity = g2.transform.isIdentity();
  63865. if (isIdentity)
  63866. {
  63867. g2.x1 += xOffset - cx;
  63868. g2.x2 += xOffset - cx;
  63869. g2.y1 += yOffset - cy;
  63870. g2.y2 += yOffset - cy;
  63871. }
  63872. else
  63873. {
  63874. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  63875. (float) (yOffset - cy));
  63876. }
  63877. int numLookupEntries;
  63878. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  63879. jassert (numLookupEntries > 0);
  63880. EdgeTable edgeTable (0, ch, quality);
  63881. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63882. if (image.getFormat() == Image::RGB)
  63883. {
  63884. jassert (pixelStride == 3);
  63885. if (g2.isRadial)
  63886. {
  63887. if (isIdentity)
  63888. {
  63889. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63890. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63891. }
  63892. else
  63893. {
  63894. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63895. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63896. }
  63897. }
  63898. else
  63899. {
  63900. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63901. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63902. }
  63903. }
  63904. else if (image.getFormat() == Image::ARGB)
  63905. {
  63906. jassert (pixelStride == 4);
  63907. if (g2.isRadial)
  63908. {
  63909. if (isIdentity)
  63910. {
  63911. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63912. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63913. }
  63914. else
  63915. {
  63916. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63917. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63918. }
  63919. }
  63920. else
  63921. {
  63922. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63923. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63924. }
  63925. }
  63926. else if (image.getFormat() == Image::SingleChannel)
  63927. {
  63928. jassertfalse // not done!
  63929. }
  63930. juce_free (lookupTable);
  63931. image.releasePixelDataReadWrite (pixels);
  63932. }
  63933. }
  63934. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  63935. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  63936. {
  63937. imageX += xOffset;
  63938. imageY += yOffset;
  63939. for (RectangleList::Iterator i (*clip); i.next();)
  63940. {
  63941. const Rectangle& r = *i.getRectangle();
  63942. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63943. path, transform, sourceImage, imageX, imageY, opacity, quality);
  63944. }
  63945. }
  63946. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  63947. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  63948. {
  63949. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  63950. {
  63951. EdgeTable edgeTable (0, h, quality);
  63952. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  63953. int stride, pixelStride;
  63954. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63955. int srcStride, srcPixelStride;
  63956. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  63957. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  63958. if (image.getFormat() == Image::RGB)
  63959. {
  63960. if (sourceImage.getFormat() == Image::RGB)
  63961. {
  63962. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  63963. srcPix, srcStride,
  63964. alpha, (PixelRGB*) 0);
  63965. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63966. }
  63967. else if (sourceImage.getFormat() == Image::ARGB)
  63968. {
  63969. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  63970. srcPix, srcStride,
  63971. alpha, (PixelARGB*) 0);
  63972. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63973. }
  63974. else
  63975. {
  63976. jassertfalse // not done!
  63977. }
  63978. }
  63979. else if (image.getFormat() == Image::ARGB)
  63980. {
  63981. if (sourceImage.getFormat() == Image::RGB)
  63982. {
  63983. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  63984. srcPix, srcStride,
  63985. alpha, (PixelRGB*) 0);
  63986. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63987. }
  63988. else if (sourceImage.getFormat() == Image::ARGB)
  63989. {
  63990. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  63991. srcPix, srcStride,
  63992. alpha, (PixelARGB*) 0);
  63993. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63994. }
  63995. else
  63996. {
  63997. jassertfalse // not done!
  63998. }
  63999. }
  64000. else
  64001. {
  64002. jassertfalse // not done!
  64003. }
  64004. sourceImage.releasePixelDataReadOnly (srcPix);
  64005. image.releasePixelDataReadWrite (pixels);
  64006. }
  64007. }
  64008. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  64009. {
  64010. x += xOffset;
  64011. y += yOffset;
  64012. for (RectangleList::Iterator i (*clip); i.next();)
  64013. {
  64014. const Rectangle& r = *i.getRectangle();
  64015. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64016. clipImage, x, y, colour);
  64017. }
  64018. }
  64019. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  64020. {
  64021. int w = clipImage.getWidth();
  64022. int h = clipImage.getHeight();
  64023. int sx = 0;
  64024. int sy = 0;
  64025. if (x < clipX)
  64026. {
  64027. sx = clipX - x;
  64028. w -= clipX - x;
  64029. x = clipX;
  64030. }
  64031. if (y < clipY)
  64032. {
  64033. sy = clipY - y;
  64034. h -= clipY - y;
  64035. y = clipY;
  64036. }
  64037. if (x + w > clipX + clipW)
  64038. w = clipX + clipW - x;
  64039. if (y + h > clipY + clipH)
  64040. h = clipY + clipH - y;
  64041. if (w > 0 && h > 0)
  64042. {
  64043. int stride, alphaStride, pixelStride;
  64044. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  64045. const uint8* const alphaValues
  64046. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  64047. #if JUCE_BIG_ENDIAN
  64048. const uint8* const alphas = alphaValues;
  64049. #else
  64050. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  64051. #endif
  64052. if (image.getFormat() == Image::RGB)
  64053. {
  64054. blendAlphaMapRGB (pixels, stride,
  64055. alphas, w, h,
  64056. pixelStride, alphaStride,
  64057. colour);
  64058. }
  64059. else if (image.getFormat() == Image::ARGB)
  64060. {
  64061. blendAlphaMapARGB (pixels, stride,
  64062. alphas, w, h,
  64063. pixelStride, alphaStride,
  64064. colour);
  64065. }
  64066. else
  64067. {
  64068. jassertfalse // not done!
  64069. }
  64070. clipImage.releasePixelDataReadOnly (alphaValues);
  64071. image.releasePixelDataReadWrite (pixels);
  64072. }
  64073. }
  64074. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  64075. {
  64076. imageX += xOffset;
  64077. imageY += yOffset;
  64078. for (RectangleList::Iterator i (*clip); i.next();)
  64079. {
  64080. const Rectangle& r = *i.getRectangle();
  64081. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64082. alphaChannelImage, imageX, imageY, gradient);
  64083. }
  64084. }
  64085. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  64086. const Image& alphaChannelImage,
  64087. int imageX, int imageY, const ColourGradient& gradient)
  64088. {
  64089. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  64090. {
  64091. ColourGradient g2 (gradient);
  64092. g2.x1 += xOffset - x;
  64093. g2.x2 += xOffset - x;
  64094. g2.y1 += yOffset - y;
  64095. g2.y2 += yOffset - y;
  64096. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  64097. LowLevelGraphicsSoftwareRenderer tempG (temp);
  64098. tempG.fillRectWithGradient (0, 0, w, h, g2);
  64099. clippedFillAlphaChannelWithImage (x, y, w, h,
  64100. alphaChannelImage, imageX, imageY,
  64101. temp, x, y, 1.0f);
  64102. }
  64103. }
  64104. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  64105. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64106. {
  64107. alphaImageX += xOffset;
  64108. alphaImageY += yOffset;
  64109. fillerImageX += xOffset;
  64110. fillerImageY += yOffset;
  64111. for (RectangleList::Iterator i (*clip); i.next();)
  64112. {
  64113. const Rectangle& r = *i.getRectangle();
  64114. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64115. alphaImage, alphaImageX, alphaImageY,
  64116. fillerImage, fillerImageX, fillerImageY, opacity);
  64117. }
  64118. }
  64119. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  64120. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64121. {
  64122. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  64123. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  64124. {
  64125. int dstStride, dstPixStride;
  64126. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  64127. int srcStride, srcPixStride;
  64128. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  64129. int maskStride, maskPixStride;
  64130. const uint8* const alpha
  64131. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  64132. #if JUCE_BIG_ENDIAN
  64133. const uint8* const alphaValues = alpha;
  64134. #else
  64135. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  64136. #endif
  64137. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  64138. if (image.getFormat() == Image::RGB)
  64139. {
  64140. if (fillerImage.getFormat() == Image::RGB)
  64141. {
  64142. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64143. }
  64144. else if (fillerImage.getFormat() == Image::ARGB)
  64145. {
  64146. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64147. }
  64148. else
  64149. {
  64150. jassertfalse // not done!
  64151. }
  64152. }
  64153. else if (image.getFormat() == Image::ARGB)
  64154. {
  64155. if (fillerImage.getFormat() == Image::RGB)
  64156. {
  64157. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64158. }
  64159. else if (fillerImage.getFormat() == Image::ARGB)
  64160. {
  64161. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64162. }
  64163. else
  64164. {
  64165. jassertfalse // not done!
  64166. }
  64167. }
  64168. else
  64169. {
  64170. jassertfalse // not done!
  64171. }
  64172. alphaImage.releasePixelDataReadOnly (alphaValues);
  64173. fillerImage.releasePixelDataReadOnly (srcPix);
  64174. image.releasePixelDataReadWrite (dstPix);
  64175. }
  64176. }
  64177. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64178. {
  64179. dx += xOffset;
  64180. dy += yOffset;
  64181. for (RectangleList::Iterator i (*clip); i.next();)
  64182. {
  64183. const Rectangle& r = *i.getRectangle();
  64184. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64185. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  64186. }
  64187. }
  64188. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  64189. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64190. {
  64191. if (dx < clipX)
  64192. {
  64193. sx += clipX - dx;
  64194. dw -= clipX - dx;
  64195. dx = clipX;
  64196. }
  64197. if (dy < clipY)
  64198. {
  64199. sy += clipY - dy;
  64200. dh -= clipY - dy;
  64201. dy = clipY;
  64202. }
  64203. if (dx + dw > clipX + clipW)
  64204. dw = clipX + clipW - dx;
  64205. if (dy + dh > clipY + clipH)
  64206. dh = clipY + clipH - dy;
  64207. if (dw <= 0 || dh <= 0)
  64208. return;
  64209. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64210. if (alpha == 0)
  64211. return;
  64212. int dstStride, dstPixelStride;
  64213. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  64214. int srcStride, srcPixelStride;
  64215. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  64216. if (image.getFormat() == Image::ARGB)
  64217. {
  64218. if (sourceImage.getFormat() == Image::ARGB)
  64219. {
  64220. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64221. (PixelARGB*) srcPixels, srcStride,
  64222. dw, dh, alpha);
  64223. }
  64224. else if (sourceImage.getFormat() == Image::RGB)
  64225. {
  64226. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64227. (PixelRGB*) srcPixels, srcStride,
  64228. dw, dh, alpha);
  64229. }
  64230. else
  64231. {
  64232. jassertfalse
  64233. }
  64234. }
  64235. else if (image.getFormat() == Image::RGB)
  64236. {
  64237. if (sourceImage.getFormat() == Image::ARGB)
  64238. {
  64239. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64240. (PixelARGB*) srcPixels, srcStride,
  64241. dw, dh, alpha);
  64242. }
  64243. else if (sourceImage.getFormat() == Image::RGB)
  64244. {
  64245. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64246. (PixelRGB*) srcPixels, srcStride,
  64247. dw, dh, alpha);
  64248. }
  64249. else
  64250. {
  64251. jassertfalse
  64252. }
  64253. }
  64254. else
  64255. {
  64256. jassertfalse
  64257. }
  64258. image.releasePixelDataReadWrite (dstPixels);
  64259. sourceImage.releasePixelDataReadOnly (srcPixels);
  64260. }
  64261. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  64262. int dx, int dy, int dw, int dh,
  64263. int sx, int sy, int sw, int sh,
  64264. float alpha,
  64265. const Graphics::ResamplingQuality quality)
  64266. {
  64267. if (sw > 0 && sh > 0)
  64268. {
  64269. if (sw == dw && sh == dh)
  64270. {
  64271. blendImage (sourceImage,
  64272. dx, dy, dw, dh,
  64273. sx, sy, alpha);
  64274. }
  64275. else
  64276. {
  64277. blendImageWarping (sourceImage,
  64278. sx, sy, sw, sh,
  64279. AffineTransform::translation ((float) -sx,
  64280. (float) -sy)
  64281. .scaled (dw / (float) sw,
  64282. dh / (float) sh)
  64283. .translated ((float) dx,
  64284. (float) dy),
  64285. alpha,
  64286. quality);
  64287. }
  64288. }
  64289. }
  64290. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  64291. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64292. const AffineTransform& t,
  64293. float opacity,
  64294. const Graphics::ResamplingQuality quality)
  64295. {
  64296. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64297. for (RectangleList::Iterator i (*clip); i.next();)
  64298. {
  64299. const Rectangle& r = *i.getRectangle();
  64300. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64301. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  64302. transform, opacity, quality);
  64303. }
  64304. }
  64305. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  64306. const Image& sourceImage,
  64307. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64308. const AffineTransform& transform,
  64309. float opacity,
  64310. const Graphics::ResamplingQuality quality)
  64311. {
  64312. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  64313. {
  64314. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  64315. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  64316. if (srcClipW <= 0 || srcClipH <= 0)
  64317. return;
  64318. jassert (srcClipX >= 0 && srcClipY >= 0);
  64319. Path imageBounds;
  64320. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  64321. imageBounds.applyTransform (transform);
  64322. float imX, imY, imW, imH;
  64323. imageBounds.getBounds (imX, imY, imW, imH);
  64324. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  64325. (int) floorf (imX),
  64326. (int) floorf (imY),
  64327. 1 + roundDoubleToInt (imW),
  64328. 1 + roundDoubleToInt (imH)))
  64329. {
  64330. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64331. float srcX1 = (float) destClipX;
  64332. float srcY1 = (float) destClipY;
  64333. float srcX2 = (float) (destClipX + destClipW);
  64334. float srcY2 = srcY1;
  64335. float srcX3 = srcX1;
  64336. float srcY3 = (float) (destClipY + destClipH);
  64337. AffineTransform inverse (transform.inverted());
  64338. inverse.transformPoint (srcX1, srcY1);
  64339. inverse.transformPoint (srcX2, srcY2);
  64340. inverse.transformPoint (srcX3, srcY3);
  64341. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  64342. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  64343. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  64344. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  64345. if (image.getFormat() == Image::ARGB)
  64346. {
  64347. if (sourceImage.getFormat() == Image::ARGB)
  64348. {
  64349. transformedImageRender (image, sourceImage,
  64350. destClipX, destClipY, destClipW, destClipH,
  64351. srcClipX, srcClipY, srcClipW, srcClipH,
  64352. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64353. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  64354. }
  64355. else if (sourceImage.getFormat() == Image::RGB)
  64356. {
  64357. transformedImageRender (image, sourceImage,
  64358. destClipX, destClipY, destClipW, destClipH,
  64359. srcClipX, srcClipY, srcClipW, srcClipH,
  64360. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64361. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  64362. }
  64363. else
  64364. {
  64365. jassertfalse
  64366. }
  64367. }
  64368. else if (image.getFormat() == Image::RGB)
  64369. {
  64370. if (sourceImage.getFormat() == Image::ARGB)
  64371. {
  64372. transformedImageRender (image, sourceImage,
  64373. destClipX, destClipY, destClipW, destClipH,
  64374. srcClipX, srcClipY, srcClipW, srcClipH,
  64375. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64376. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  64377. }
  64378. else if (sourceImage.getFormat() == Image::RGB)
  64379. {
  64380. transformedImageRender (image, sourceImage,
  64381. destClipX, destClipY, destClipW, destClipH,
  64382. srcClipX, srcClipY, srcClipW, srcClipH,
  64383. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64384. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  64385. }
  64386. else
  64387. {
  64388. jassertfalse
  64389. }
  64390. }
  64391. else
  64392. {
  64393. jassertfalse
  64394. }
  64395. }
  64396. }
  64397. }
  64398. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  64399. {
  64400. x1 += xOffset;
  64401. y1 += yOffset;
  64402. x2 += xOffset;
  64403. y2 += yOffset;
  64404. for (RectangleList::Iterator i (*clip); i.next();)
  64405. {
  64406. const Rectangle& r = *i.getRectangle();
  64407. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64408. x1, y1, x2, y2, colour);
  64409. }
  64410. }
  64411. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  64412. {
  64413. if (clipW > 0 && clipH > 0)
  64414. {
  64415. if (x1 == x2)
  64416. {
  64417. if (y2 < y1)
  64418. swapVariables (y1, y2);
  64419. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  64420. }
  64421. else if (y1 == y2)
  64422. {
  64423. if (x2 < x1)
  64424. swapVariables (x1, x2);
  64425. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  64426. }
  64427. else
  64428. {
  64429. double gradient = (y2 - y1) / (x2 - x1);
  64430. if (fabs (gradient) > 1.0)
  64431. {
  64432. gradient = 1.0 / gradient;
  64433. int y = roundDoubleToInt (y1);
  64434. const int startY = y;
  64435. int endY = roundDoubleToInt (y2);
  64436. if (y > endY)
  64437. swapVariables (y, endY);
  64438. while (y < endY)
  64439. {
  64440. const double x = x1 + gradient * (y - startY);
  64441. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  64442. ++y;
  64443. }
  64444. }
  64445. else
  64446. {
  64447. int x = roundDoubleToInt (x1);
  64448. const int startX = x;
  64449. int endX = roundDoubleToInt (x2);
  64450. if (x > endX)
  64451. swapVariables (x, endX);
  64452. while (x < endX)
  64453. {
  64454. const double y = y1 + gradient * (x - startX);
  64455. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  64456. ++x;
  64457. }
  64458. }
  64459. }
  64460. }
  64461. }
  64462. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  64463. {
  64464. for (RectangleList::Iterator i (*clip); i.next();)
  64465. {
  64466. const Rectangle& r = *i.getRectangle();
  64467. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64468. x + xOffset, top + yOffset, bottom + yOffset, col);
  64469. }
  64470. }
  64471. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  64472. const int x, double top, double bottom, const Colour& col)
  64473. {
  64474. jassert (top <= bottom);
  64475. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  64476. && top < clipY + clipH
  64477. && bottom > clipY
  64478. && clipW > 0)
  64479. {
  64480. if (top < clipY)
  64481. top = clipY;
  64482. if (bottom > clipY + clipH)
  64483. bottom = clipY + clipH;
  64484. if (bottom > top)
  64485. drawVertical (x, top, bottom, col);
  64486. }
  64487. }
  64488. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  64489. {
  64490. for (RectangleList::Iterator i (*clip); i.next();)
  64491. {
  64492. const Rectangle& r = *i.getRectangle();
  64493. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64494. y + yOffset, left + xOffset, right + xOffset, col);
  64495. }
  64496. }
  64497. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  64498. const int y, double left, double right, const Colour& col)
  64499. {
  64500. jassert (left <= right);
  64501. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  64502. && left < clipX + clipW
  64503. && right > clipX
  64504. && clipW > 0)
  64505. {
  64506. if (left < clipX)
  64507. left = clipX;
  64508. if (right > clipX + clipW)
  64509. right = clipX + clipW;
  64510. if (right > left)
  64511. drawHorizontal (y, left, right, col);
  64512. }
  64513. }
  64514. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  64515. const double top,
  64516. const double bottom,
  64517. const Colour& col)
  64518. {
  64519. int wholeStart = (int) top;
  64520. const int wholeEnd = (int) bottom;
  64521. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64522. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64523. if (totalPixels <= 0)
  64524. return;
  64525. int lineStride, dstPixelStride;
  64526. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  64527. uint8* dest = dstPixels;
  64528. PixelARGB colour (col.getPixelARGB());
  64529. if (wholeEnd == wholeStart)
  64530. {
  64531. if (image.getFormat() == Image::ARGB)
  64532. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64533. else if (image.getFormat() == Image::RGB)
  64534. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64535. else
  64536. {
  64537. jassertfalse
  64538. }
  64539. }
  64540. else
  64541. {
  64542. if (image.getFormat() == Image::ARGB)
  64543. {
  64544. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64545. ++wholeStart;
  64546. dest += lineStride;
  64547. if (colour.getAlpha() == 0xff)
  64548. {
  64549. while (wholeEnd > wholeStart)
  64550. {
  64551. ((PixelARGB*) dest)->set (colour);
  64552. ++wholeStart;
  64553. dest += lineStride;
  64554. }
  64555. }
  64556. else
  64557. {
  64558. while (wholeEnd > wholeStart)
  64559. {
  64560. ((PixelARGB*) dest)->blend (colour);
  64561. ++wholeStart;
  64562. dest += lineStride;
  64563. }
  64564. }
  64565. if (lastAlpha > 0)
  64566. {
  64567. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64568. }
  64569. }
  64570. else if (image.getFormat() == Image::RGB)
  64571. {
  64572. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64573. ++wholeStart;
  64574. dest += lineStride;
  64575. if (colour.getAlpha() == 0xff)
  64576. {
  64577. while (wholeEnd > wholeStart)
  64578. {
  64579. ((PixelRGB*) dest)->set (colour);
  64580. ++wholeStart;
  64581. dest += lineStride;
  64582. }
  64583. }
  64584. else
  64585. {
  64586. while (wholeEnd > wholeStart)
  64587. {
  64588. ((PixelRGB*) dest)->blend (colour);
  64589. ++wholeStart;
  64590. dest += lineStride;
  64591. }
  64592. }
  64593. if (lastAlpha > 0)
  64594. {
  64595. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64596. }
  64597. }
  64598. else
  64599. {
  64600. jassertfalse
  64601. }
  64602. }
  64603. image.releasePixelDataReadWrite (dstPixels);
  64604. }
  64605. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  64606. const double top,
  64607. const double bottom,
  64608. const Colour& col)
  64609. {
  64610. int wholeStart = (int) top;
  64611. const int wholeEnd = (int) bottom;
  64612. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64613. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64614. if (totalPixels <= 0)
  64615. return;
  64616. int lineStride, dstPixelStride;
  64617. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  64618. uint8* dest = dstPixels;
  64619. PixelARGB colour (col.getPixelARGB());
  64620. if (wholeEnd == wholeStart)
  64621. {
  64622. if (image.getFormat() == Image::ARGB)
  64623. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64624. else if (image.getFormat() == Image::RGB)
  64625. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64626. else
  64627. {
  64628. jassertfalse
  64629. }
  64630. }
  64631. else
  64632. {
  64633. if (image.getFormat() == Image::ARGB)
  64634. {
  64635. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64636. dest += dstPixelStride;
  64637. ++wholeStart;
  64638. if (colour.getAlpha() == 0xff)
  64639. {
  64640. while (wholeEnd > wholeStart)
  64641. {
  64642. ((PixelARGB*) dest)->set (colour);
  64643. dest += dstPixelStride;
  64644. ++wholeStart;
  64645. }
  64646. }
  64647. else
  64648. {
  64649. while (wholeEnd > wholeStart)
  64650. {
  64651. ((PixelARGB*) dest)->blend (colour);
  64652. dest += dstPixelStride;
  64653. ++wholeStart;
  64654. }
  64655. }
  64656. if (lastAlpha > 0)
  64657. {
  64658. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64659. }
  64660. }
  64661. else if (image.getFormat() == Image::RGB)
  64662. {
  64663. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64664. dest += dstPixelStride;
  64665. ++wholeStart;
  64666. if (colour.getAlpha() == 0xff)
  64667. {
  64668. while (wholeEnd > wholeStart)
  64669. {
  64670. ((PixelRGB*) dest)->set (colour);
  64671. dest += dstPixelStride;
  64672. ++wholeStart;
  64673. }
  64674. }
  64675. else
  64676. {
  64677. while (wholeEnd > wholeStart)
  64678. {
  64679. ((PixelRGB*) dest)->blend (colour);
  64680. dest += dstPixelStride;
  64681. ++wholeStart;
  64682. }
  64683. }
  64684. if (lastAlpha > 0)
  64685. {
  64686. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64687. }
  64688. }
  64689. else
  64690. {
  64691. jassertfalse
  64692. }
  64693. }
  64694. image.releasePixelDataReadWrite (dstPixels);
  64695. }
  64696. END_JUCE_NAMESPACE
  64697. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  64698. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  64699. BEGIN_JUCE_NAMESPACE
  64700. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  64701. : flags (other.flags)
  64702. {
  64703. }
  64704. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  64705. {
  64706. flags = other.flags;
  64707. return *this;
  64708. }
  64709. void RectanglePlacement::applyTo (double& x, double& y,
  64710. double& w, double& h,
  64711. const double dx, const double dy,
  64712. const double dw, const double dh) const throw()
  64713. {
  64714. if (w == 0 || h == 0)
  64715. return;
  64716. if ((flags & stretchToFit) != 0)
  64717. {
  64718. x = dx;
  64719. y = dy;
  64720. w = dw;
  64721. h = dh;
  64722. }
  64723. else
  64724. {
  64725. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  64726. : jmin (dw / w, dh / h);
  64727. if ((flags & onlyReduceInSize) != 0)
  64728. scale = jmin (scale, 1.0);
  64729. if ((flags & onlyIncreaseInSize) != 0)
  64730. scale = jmax (scale, 1.0);
  64731. w *= scale;
  64732. h *= scale;
  64733. if ((flags & xLeft) != 0)
  64734. x = dx;
  64735. else if ((flags & xRight) != 0)
  64736. x = dx + dw - w;
  64737. else
  64738. x = dx + (dw - w) * 0.5;
  64739. if ((flags & yTop) != 0)
  64740. y = dy;
  64741. else if ((flags & yBottom) != 0)
  64742. y = dy + dh - h;
  64743. else
  64744. y = dy + (dh - h) * 0.5;
  64745. }
  64746. }
  64747. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  64748. float w, float h,
  64749. const float dx, const float dy,
  64750. const float dw, const float dh) const throw()
  64751. {
  64752. if (w == 0 || h == 0)
  64753. return AffineTransform::identity;
  64754. const float scaleX = dw / w;
  64755. const float scaleY = dh / h;
  64756. if ((flags & stretchToFit) != 0)
  64757. return AffineTransform::translation (-x, -y)
  64758. .scaled (scaleX, scaleY)
  64759. .translated (dx, dy);
  64760. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  64761. : jmin (scaleX, scaleY);
  64762. if ((flags & onlyReduceInSize) != 0)
  64763. scale = jmin (scale, 1.0f);
  64764. if ((flags & onlyIncreaseInSize) != 0)
  64765. scale = jmax (scale, 1.0f);
  64766. w *= scale;
  64767. h *= scale;
  64768. float newX = dx;
  64769. if ((flags & xRight) != 0)
  64770. newX += dw - w; // right
  64771. else if ((flags & xLeft) == 0)
  64772. newX += (dw - w) / 2.0f; // centre
  64773. float newY = dy;
  64774. if ((flags & yBottom) != 0)
  64775. newY += dh - h; // bottom
  64776. else if ((flags & yTop) == 0)
  64777. newY += (dh - h) / 2.0f; // centre
  64778. return AffineTransform::translation (-x, -y)
  64779. .scaled (scale, scale)
  64780. .translated (newX, newY);
  64781. }
  64782. END_JUCE_NAMESPACE
  64783. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  64784. /********* Start of inlined file: juce_Drawable.cpp *********/
  64785. BEGIN_JUCE_NAMESPACE
  64786. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  64787. const AffineTransform& transform_,
  64788. const float opacity_) throw()
  64789. : g (g_),
  64790. transform (transform_),
  64791. opacity (opacity_)
  64792. {
  64793. }
  64794. Drawable::Drawable()
  64795. {
  64796. }
  64797. Drawable::~Drawable()
  64798. {
  64799. }
  64800. void Drawable::draw (Graphics& g,
  64801. const AffineTransform& transform) const
  64802. {
  64803. const RenderingContext context (g, transform, g.getCurrentColour().getFloatAlpha());
  64804. render (context);
  64805. }
  64806. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  64807. {
  64808. draw (g, AffineTransform::translation (x, y));
  64809. }
  64810. void Drawable::drawWithin (Graphics& g,
  64811. const int destX,
  64812. const int destY,
  64813. const int destW,
  64814. const int destH,
  64815. const RectanglePlacement& placement) const
  64816. {
  64817. if (destW > 0 && destH > 0)
  64818. {
  64819. float x, y, w, h;
  64820. getBounds (x, y, w, h);
  64821. draw (g, placement.getTransformToFit (x, y, w, h,
  64822. (float) destX, (float) destY,
  64823. (float) destW, (float) destH));
  64824. }
  64825. }
  64826. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  64827. {
  64828. Drawable* result = 0;
  64829. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  64830. if (image != 0)
  64831. {
  64832. DrawableImage* const di = new DrawableImage();
  64833. di->setImage (image, true);
  64834. result = di;
  64835. }
  64836. else
  64837. {
  64838. const String asString (String::createStringFromData (data, numBytes));
  64839. XmlDocument doc (asString);
  64840. XmlElement* const outer = doc.getDocumentElement (true);
  64841. if (outer != 0 && outer->hasTagName (T("svg")))
  64842. {
  64843. XmlElement* const svg = doc.getDocumentElement();
  64844. if (svg != 0)
  64845. {
  64846. result = Drawable::createFromSVG (*svg);
  64847. delete svg;
  64848. }
  64849. }
  64850. delete outer;
  64851. }
  64852. return result;
  64853. }
  64854. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  64855. {
  64856. MemoryBlock mb;
  64857. dataSource.readIntoMemoryBlock (mb);
  64858. return createFromImageData (mb.getData(), mb.getSize());
  64859. }
  64860. Drawable* Drawable::createFromImageFile (const File& file)
  64861. {
  64862. FileInputStream* fin = file.createInputStream();
  64863. if (fin == 0)
  64864. return 0;
  64865. Drawable* d = createFromImageDataStream (*fin);
  64866. delete fin;
  64867. return d;
  64868. }
  64869. END_JUCE_NAMESPACE
  64870. /********* End of inlined file: juce_Drawable.cpp *********/
  64871. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  64872. BEGIN_JUCE_NAMESPACE
  64873. DrawableComposite::DrawableComposite()
  64874. {
  64875. }
  64876. DrawableComposite::~DrawableComposite()
  64877. {
  64878. }
  64879. void DrawableComposite::insertDrawable (Drawable* drawable,
  64880. const AffineTransform& transform,
  64881. const int index)
  64882. {
  64883. if (drawable != 0)
  64884. {
  64885. if (! drawables.contains (drawable))
  64886. {
  64887. drawables.insert (index, drawable);
  64888. if (transform.isIdentity())
  64889. transforms.insert (index, 0);
  64890. else
  64891. transforms.insert (index, new AffineTransform (transform));
  64892. }
  64893. else
  64894. {
  64895. jassertfalse // trying to add a drawable that's already in here!
  64896. }
  64897. }
  64898. }
  64899. void DrawableComposite::insertDrawable (const Drawable& drawable,
  64900. const AffineTransform& transform,
  64901. const int index)
  64902. {
  64903. insertDrawable (drawable.createCopy(), transform, index);
  64904. }
  64905. void DrawableComposite::removeDrawable (const int index)
  64906. {
  64907. drawables.remove (index);
  64908. transforms.remove (index);
  64909. }
  64910. void DrawableComposite::bringToFront (const int index)
  64911. {
  64912. if (index >= 0 && index < drawables.size() - 1)
  64913. {
  64914. drawables.move (index, -1);
  64915. transforms.move (index, -1);
  64916. }
  64917. }
  64918. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  64919. {
  64920. if (drawables.size() > 0 && context.opacity > 0)
  64921. {
  64922. if (context.opacity >= 1.0f || drawables.size() == 1)
  64923. {
  64924. Drawable::RenderingContext contextCopy (context);
  64925. for (int i = 0; i < drawables.size(); ++i)
  64926. {
  64927. const AffineTransform* const t = transforms.getUnchecked(i);
  64928. contextCopy.transform = (t == 0) ? context.transform
  64929. : t->followedBy (context.transform);
  64930. drawables.getUnchecked(i)->render (contextCopy);
  64931. }
  64932. }
  64933. else
  64934. {
  64935. // To correctly render a whole composite layer with an overall transparency,
  64936. // we need to render everything opaquely into a temp buffer, then blend that
  64937. // with the target opacity...
  64938. const Rectangle clipBounds (context.g.getClipBounds());
  64939. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  64940. {
  64941. Graphics tempG (tempImage);
  64942. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  64943. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  64944. render (tempContext);
  64945. }
  64946. context.g.setOpacity (context.opacity);
  64947. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  64948. }
  64949. }
  64950. }
  64951. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  64952. {
  64953. Path totalPath;
  64954. for (int i = 0; i < drawables.size(); ++i)
  64955. {
  64956. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  64957. if (width > 0.0f && height > 0.0f)
  64958. {
  64959. Path outline;
  64960. outline.addRectangle (x, y, width, height);
  64961. const AffineTransform* const t = transforms.getUnchecked(i);
  64962. if (t == 0)
  64963. totalPath.addPath (outline);
  64964. else
  64965. totalPath.addPath (outline, *t);
  64966. }
  64967. }
  64968. totalPath.getBounds (x, y, width, height);
  64969. }
  64970. bool DrawableComposite::hitTest (float x, float y) const
  64971. {
  64972. for (int i = 0; i < drawables.size(); ++i)
  64973. {
  64974. float tx = x;
  64975. float ty = y;
  64976. const AffineTransform* const t = transforms.getUnchecked(i);
  64977. if (t != 0)
  64978. t->inverted().transformPoint (tx, ty);
  64979. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  64980. return true;
  64981. }
  64982. return false;
  64983. }
  64984. Drawable* DrawableComposite::createCopy() const
  64985. {
  64986. DrawableComposite* const dc = new DrawableComposite();
  64987. for (int i = 0; i < drawables.size(); ++i)
  64988. {
  64989. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  64990. const AffineTransform* const t = transforms.getUnchecked(i);
  64991. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  64992. }
  64993. return dc;
  64994. }
  64995. END_JUCE_NAMESPACE
  64996. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  64997. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  64998. BEGIN_JUCE_NAMESPACE
  64999. DrawableImage::DrawableImage()
  65000. : image (0),
  65001. canDeleteImage (false),
  65002. opacity (1.0f),
  65003. overlayColour (0x00000000)
  65004. {
  65005. }
  65006. DrawableImage::~DrawableImage()
  65007. {
  65008. clearImage();
  65009. }
  65010. void DrawableImage::clearImage()
  65011. {
  65012. if (canDeleteImage && image != 0)
  65013. {
  65014. if (ImageCache::isImageInCache (image))
  65015. ImageCache::release (image);
  65016. else
  65017. delete image;
  65018. }
  65019. image = 0;
  65020. }
  65021. void DrawableImage::setImage (const Image& imageToCopy)
  65022. {
  65023. clearImage();
  65024. image = new Image (imageToCopy);
  65025. canDeleteImage = true;
  65026. }
  65027. void DrawableImage::setImage (Image* imageToUse,
  65028. const bool releaseWhenNotNeeded)
  65029. {
  65030. clearImage();
  65031. image = imageToUse;
  65032. canDeleteImage = releaseWhenNotNeeded;
  65033. }
  65034. void DrawableImage::setOpacity (const float newOpacity)
  65035. {
  65036. opacity = newOpacity;
  65037. }
  65038. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  65039. {
  65040. overlayColour = newOverlayColour;
  65041. }
  65042. void DrawableImage::render (const Drawable::RenderingContext& context) const
  65043. {
  65044. if (image != 0)
  65045. {
  65046. if (opacity > 0.0f && ! overlayColour.isOpaque())
  65047. {
  65048. context.g.setOpacity (context.opacity * opacity);
  65049. context.g.drawImageTransformed (image,
  65050. 0, 0, image->getWidth(), image->getHeight(),
  65051. context.transform, false);
  65052. }
  65053. if (! overlayColour.isTransparent())
  65054. {
  65055. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  65056. context.g.drawImageTransformed (image,
  65057. 0, 0, image->getWidth(), image->getHeight(),
  65058. context.transform, true);
  65059. }
  65060. }
  65061. }
  65062. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  65063. {
  65064. x = 0.0f;
  65065. y = 0.0f;
  65066. width = 0.0f;
  65067. height = 0.0f;
  65068. if (image != 0)
  65069. {
  65070. width = (float) image->getWidth();
  65071. height = (float) image->getHeight();
  65072. }
  65073. }
  65074. bool DrawableImage::hitTest (float x, float y) const
  65075. {
  65076. return image != 0
  65077. && x >= 0.0f
  65078. && y >= 0.0f
  65079. && x < image->getWidth()
  65080. && y < image->getHeight()
  65081. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  65082. }
  65083. Drawable* DrawableImage::createCopy() const
  65084. {
  65085. DrawableImage* const di = new DrawableImage();
  65086. di->opacity = opacity;
  65087. di->overlayColour = overlayColour;
  65088. if (image != 0)
  65089. {
  65090. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  65091. {
  65092. di->setImage (*image);
  65093. }
  65094. else
  65095. {
  65096. ImageCache::incReferenceCount (image);
  65097. di->setImage (image, true);
  65098. }
  65099. }
  65100. return di;
  65101. }
  65102. END_JUCE_NAMESPACE
  65103. /********* End of inlined file: juce_DrawableImage.cpp *********/
  65104. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  65105. BEGIN_JUCE_NAMESPACE
  65106. DrawablePath::DrawablePath()
  65107. : fillBrush (new SolidColourBrush (Colours::black)),
  65108. strokeBrush (0),
  65109. strokeType (0.0f)
  65110. {
  65111. }
  65112. DrawablePath::~DrawablePath()
  65113. {
  65114. delete fillBrush;
  65115. delete strokeBrush;
  65116. }
  65117. void DrawablePath::setPath (const Path& newPath)
  65118. {
  65119. path = newPath;
  65120. updateOutline();
  65121. }
  65122. void DrawablePath::setSolidFill (const Colour& newColour)
  65123. {
  65124. delete fillBrush;
  65125. fillBrush = new SolidColourBrush (newColour);
  65126. }
  65127. void DrawablePath::setFillBrush (const Brush& newBrush)
  65128. {
  65129. delete fillBrush;
  65130. fillBrush = newBrush.createCopy();
  65131. }
  65132. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  65133. {
  65134. strokeType = PathStrokeType (thickness);
  65135. delete strokeBrush;
  65136. strokeBrush = new SolidColourBrush (colour);
  65137. updateOutline();
  65138. }
  65139. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  65140. {
  65141. strokeType = strokeType_;
  65142. delete strokeBrush;
  65143. strokeBrush = newStrokeBrush.createCopy();
  65144. updateOutline();
  65145. }
  65146. void DrawablePath::render (const Drawable::RenderingContext& context) const
  65147. {
  65148. {
  65149. Brush* const tempBrush = fillBrush->createCopy();
  65150. tempBrush->applyTransform (context.transform);
  65151. tempBrush->multiplyOpacity (context.opacity);
  65152. context.g.setBrush (tempBrush);
  65153. context.g.fillPath (path, context.transform);
  65154. delete tempBrush;
  65155. }
  65156. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  65157. {
  65158. Brush* const tempBrush = strokeBrush->createCopy();
  65159. tempBrush->applyTransform (context.transform);
  65160. tempBrush->multiplyOpacity (context.opacity);
  65161. context.g.setBrush (tempBrush);
  65162. context.g.fillPath (outline, context.transform);
  65163. delete tempBrush;
  65164. }
  65165. }
  65166. void DrawablePath::updateOutline()
  65167. {
  65168. outline.clear();
  65169. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  65170. }
  65171. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  65172. {
  65173. if (strokeType.getStrokeThickness() > 0.0f)
  65174. outline.getBounds (x, y, width, height);
  65175. else
  65176. path.getBounds (x, y, width, height);
  65177. }
  65178. bool DrawablePath::hitTest (float x, float y) const
  65179. {
  65180. return path.contains (x, y)
  65181. || outline.contains (x, y);
  65182. }
  65183. Drawable* DrawablePath::createCopy() const
  65184. {
  65185. DrawablePath* const dp = new DrawablePath();
  65186. dp->path = path;
  65187. dp->setFillBrush (*fillBrush);
  65188. if (strokeBrush != 0)
  65189. dp->setOutline (strokeType, *strokeBrush);
  65190. return dp;
  65191. }
  65192. END_JUCE_NAMESPACE
  65193. /********* End of inlined file: juce_DrawablePath.cpp *********/
  65194. /********* Start of inlined file: juce_DrawableText.cpp *********/
  65195. BEGIN_JUCE_NAMESPACE
  65196. DrawableText::DrawableText()
  65197. : colour (Colours::white)
  65198. {
  65199. }
  65200. DrawableText::~DrawableText()
  65201. {
  65202. }
  65203. void DrawableText::setText (const GlyphArrangement& newText)
  65204. {
  65205. text = newText;
  65206. }
  65207. void DrawableText::setText (const String& newText, const Font& fontToUse)
  65208. {
  65209. text.clear();
  65210. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  65211. }
  65212. void DrawableText::setColour (const Colour& newColour)
  65213. {
  65214. colour = newColour;
  65215. }
  65216. void DrawableText::render (const Drawable::RenderingContext& context) const
  65217. {
  65218. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  65219. text.draw (context.g, context.transform);
  65220. }
  65221. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  65222. {
  65223. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  65224. width -= x;
  65225. height -= y;
  65226. }
  65227. bool DrawableText::hitTest (float x, float y) const
  65228. {
  65229. return text.findGlyphIndexAt (x, y) >= 0;
  65230. }
  65231. Drawable* DrawableText::createCopy() const
  65232. {
  65233. DrawableText* const dt = new DrawableText();
  65234. dt->text = text;
  65235. dt->colour = colour;
  65236. return dt;
  65237. }
  65238. END_JUCE_NAMESPACE
  65239. /********* End of inlined file: juce_DrawableText.cpp *********/
  65240. /********* Start of inlined file: juce_SVGParser.cpp *********/
  65241. BEGIN_JUCE_NAMESPACE
  65242. class SVGState
  65243. {
  65244. public:
  65245. SVGState (const XmlElement* const topLevel)
  65246. : topLevelXml (topLevel),
  65247. x (0), y (0),
  65248. width (512), height (512),
  65249. viewBoxW (0), viewBoxH (0)
  65250. {
  65251. }
  65252. ~SVGState()
  65253. {
  65254. }
  65255. Drawable* parseSVGElement (const XmlElement& xml)
  65256. {
  65257. if (! xml.hasTagName (T("svg")))
  65258. return 0;
  65259. DrawableComposite* const drawable = new DrawableComposite();
  65260. drawable->setName (xml.getStringAttribute (T("id")));
  65261. SVGState newState (*this);
  65262. if (xml.hasAttribute (T("transform")))
  65263. newState.addTransform (xml);
  65264. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  65265. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  65266. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  65267. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  65268. if (xml.hasAttribute (T("viewBox")))
  65269. {
  65270. const String viewParams (xml.getStringAttribute (T("viewBox")));
  65271. int i = 0;
  65272. float vx, vy, vw, vh;
  65273. if (parseCoords (viewParams, vx, vy, i, true)
  65274. && parseCoords (viewParams, vw, vh, i, true)
  65275. && vw > 0
  65276. && vh > 0)
  65277. {
  65278. newState.viewBoxW = vw;
  65279. newState.viewBoxH = vh;
  65280. int placementFlags = 0;
  65281. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  65282. if (aspect.containsIgnoreCase (T("none")))
  65283. {
  65284. placementFlags = RectanglePlacement::stretchToFit;
  65285. }
  65286. else
  65287. {
  65288. if (aspect.containsIgnoreCase (T("slice")))
  65289. placementFlags |= RectanglePlacement::fillDestination;
  65290. if (aspect.containsIgnoreCase (T("xMin")))
  65291. placementFlags |= RectanglePlacement::xLeft;
  65292. else if (aspect.containsIgnoreCase (T("xMax")))
  65293. placementFlags |= RectanglePlacement::xRight;
  65294. else
  65295. placementFlags |= RectanglePlacement::xMid;
  65296. if (aspect.containsIgnoreCase (T("yMin")))
  65297. placementFlags |= RectanglePlacement::yTop;
  65298. else if (aspect.containsIgnoreCase (T("yMax")))
  65299. placementFlags |= RectanglePlacement::yBottom;
  65300. else
  65301. placementFlags |= RectanglePlacement::yMid;
  65302. }
  65303. const RectanglePlacement placement (placementFlags);
  65304. newState.transform
  65305. = placement.getTransformToFit (vx, vy, vw, vh,
  65306. 0.0f, 0.0f, newState.width, newState.height)
  65307. .followedBy (newState.transform);
  65308. }
  65309. }
  65310. else
  65311. {
  65312. if (viewBoxW == 0)
  65313. newState.viewBoxW = newState.width;
  65314. if (viewBoxH == 0)
  65315. newState.viewBoxH = newState.height;
  65316. }
  65317. newState.parseSubElements (xml, drawable);
  65318. return drawable;
  65319. }
  65320. private:
  65321. const XmlElement* const topLevelXml;
  65322. float x, y, width, height, viewBoxW, viewBoxH;
  65323. AffineTransform transform;
  65324. String cssStyleText;
  65325. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  65326. {
  65327. forEachXmlChildElement (xml, e)
  65328. {
  65329. Drawable* d = 0;
  65330. if (e->hasTagName (T("g")))
  65331. d = parseGroupElement (*e);
  65332. else if (e->hasTagName (T("svg")))
  65333. d = parseSVGElement (*e);
  65334. else if (e->hasTagName (T("path")))
  65335. d = parsePath (*e);
  65336. else if (e->hasTagName (T("rect")))
  65337. d = parseRect (*e);
  65338. else if (e->hasTagName (T("circle")))
  65339. d = parseCircle (*e);
  65340. else if (e->hasTagName (T("ellipse")))
  65341. d = parseEllipse (*e);
  65342. else if (e->hasTagName (T("line")))
  65343. d = parseLine (*e);
  65344. else if (e->hasTagName (T("polyline")))
  65345. d = parsePolygon (*e, true);
  65346. else if (e->hasTagName (T("polygon")))
  65347. d = parsePolygon (*e, false);
  65348. else if (e->hasTagName (T("text")))
  65349. d = parseText (*e);
  65350. else if (e->hasTagName (T("switch")))
  65351. d = parseSwitch (*e);
  65352. else if (e->hasTagName (T("style")))
  65353. parseCSSStyle (*e);
  65354. parentDrawable->insertDrawable (d);
  65355. }
  65356. }
  65357. DrawableComposite* parseSwitch (const XmlElement& xml)
  65358. {
  65359. const XmlElement* const group = xml.getChildByName (T("g"));
  65360. if (group != 0)
  65361. return parseGroupElement (*group);
  65362. return 0;
  65363. }
  65364. DrawableComposite* parseGroupElement (const XmlElement& xml)
  65365. {
  65366. DrawableComposite* const drawable = new DrawableComposite();
  65367. drawable->setName (xml.getStringAttribute (T("id")));
  65368. if (xml.hasAttribute (T("transform")))
  65369. {
  65370. SVGState newState (*this);
  65371. newState.addTransform (xml);
  65372. newState.parseSubElements (xml, drawable);
  65373. }
  65374. else
  65375. {
  65376. parseSubElements (xml, drawable);
  65377. }
  65378. return drawable;
  65379. }
  65380. Drawable* parsePath (const XmlElement& xml) const
  65381. {
  65382. const String d (xml.getStringAttribute (T("d")).trimStart());
  65383. Path path;
  65384. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  65385. path.setUsingNonZeroWinding (false);
  65386. int index = 0;
  65387. float lastX = 0, lastY = 0;
  65388. float lastX2 = 0, lastY2 = 0;
  65389. tchar lastCommandChar = 0;
  65390. bool carryOn = true;
  65391. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  65392. for (;;)
  65393. {
  65394. float x, y, x2, y2, x3, y3;
  65395. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  65396. if (validCommandChars.containsChar (d[index]))
  65397. lastCommandChar = d [index++];
  65398. switch (lastCommandChar)
  65399. {
  65400. case T('M'):
  65401. case T('m'):
  65402. case T('L'):
  65403. case T('l'):
  65404. if (parseCoords (d, x, y, index, false))
  65405. {
  65406. if (isRelative)
  65407. {
  65408. x += lastX;
  65409. y += lastY;
  65410. }
  65411. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  65412. path.startNewSubPath (x, y);
  65413. else
  65414. path.lineTo (x, y);
  65415. lastX2 = lastX;
  65416. lastY2 = lastY;
  65417. lastX = x;
  65418. lastY = y;
  65419. }
  65420. else
  65421. {
  65422. ++index;
  65423. }
  65424. break;
  65425. case T('H'):
  65426. case T('h'):
  65427. if (parseCoord (d, x, index, false, true))
  65428. {
  65429. if (isRelative)
  65430. x += lastX;
  65431. path.lineTo (x, lastY);
  65432. lastX2 = lastX;
  65433. lastX = x;
  65434. }
  65435. else
  65436. {
  65437. ++index;
  65438. }
  65439. break;
  65440. case T('V'):
  65441. case T('v'):
  65442. if (parseCoord (d, y, index, false, false))
  65443. {
  65444. if (isRelative)
  65445. y += lastY;
  65446. path.lineTo (lastX, y);
  65447. lastY2 = lastY;
  65448. lastY = y;
  65449. }
  65450. else
  65451. {
  65452. ++index;
  65453. }
  65454. break;
  65455. case T('C'):
  65456. case T('c'):
  65457. if (parseCoords (d, x, y, index, false)
  65458. && parseCoords (d, x2, y2, index, false)
  65459. && parseCoords (d, x3, y3, index, false))
  65460. {
  65461. if (isRelative)
  65462. {
  65463. x += lastX;
  65464. y += lastY;
  65465. x2 += lastX;
  65466. y2 += lastY;
  65467. x3 += lastX;
  65468. y3 += lastY;
  65469. }
  65470. path.cubicTo (x, y, x2, y2, x3, y3);
  65471. lastX2 = x2;
  65472. lastY2 = y2;
  65473. lastX = x3;
  65474. lastY = y3;
  65475. }
  65476. else
  65477. {
  65478. ++index;
  65479. }
  65480. break;
  65481. case T('S'):
  65482. case T('s'):
  65483. if (parseCoords (d, x, y, index, false)
  65484. && parseCoords (d, x3, y3, index, false))
  65485. {
  65486. if (isRelative)
  65487. {
  65488. x += lastX;
  65489. y += lastY;
  65490. x3 += lastX;
  65491. y3 += lastY;
  65492. }
  65493. x2 = lastX + (lastX - lastX2);
  65494. y2 = lastY + (lastY - lastY2);
  65495. path.cubicTo (x2, y2, x, y, x3, y3);
  65496. lastX2 = x;
  65497. lastY2 = y;
  65498. lastX = x3;
  65499. lastY = y3;
  65500. }
  65501. else
  65502. {
  65503. ++index;
  65504. }
  65505. break;
  65506. case T('Q'):
  65507. case T('q'):
  65508. if (parseCoords (d, x, y, index, false)
  65509. && parseCoords (d, x2, y2, index, false))
  65510. {
  65511. if (isRelative)
  65512. {
  65513. x += lastX;
  65514. y += lastY;
  65515. x2 += lastX;
  65516. y2 += lastY;
  65517. }
  65518. path.quadraticTo (x, y, x2, y2);
  65519. lastX2 = x;
  65520. lastY2 = y;
  65521. lastX = x2;
  65522. lastY = y2;
  65523. }
  65524. else
  65525. {
  65526. ++index;
  65527. }
  65528. break;
  65529. case T('T'):
  65530. case T('t'):
  65531. if (parseCoords (d, x, y, index, false))
  65532. {
  65533. if (isRelative)
  65534. {
  65535. x += lastX;
  65536. y += lastY;
  65537. }
  65538. x2 = lastX + (lastX - lastX2);
  65539. y2 = lastY + (lastY - lastY2);
  65540. path.quadraticTo (x2, y2, x, y);
  65541. lastX2 = x2;
  65542. lastY2 = y2;
  65543. lastX = x;
  65544. lastY = y;
  65545. }
  65546. else
  65547. {
  65548. ++index;
  65549. }
  65550. break;
  65551. case T('A'):
  65552. case T('a'):
  65553. if (parseCoords (d, x, y, index, false))
  65554. {
  65555. String num;
  65556. if (parseNextNumber (d, num, index, false))
  65557. {
  65558. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  65559. if (parseNextNumber (d, num, index, false))
  65560. {
  65561. const bool largeArc = num.getIntValue() != 0;
  65562. if (parseNextNumber (d, num, index, false))
  65563. {
  65564. const bool sweep = num.getIntValue() != 0;
  65565. if (parseCoords (d, x2, y2, index, false))
  65566. {
  65567. if (isRelative)
  65568. {
  65569. x2 += lastX;
  65570. y2 += lastY;
  65571. }
  65572. if (lastX != x2 || lastY != y2)
  65573. {
  65574. double centreX, centreY, startAngle, deltaAngle;
  65575. double rx = x, ry = y;
  65576. endpointToCentreParameters (lastX, lastY, x2, y2,
  65577. angle, largeArc, sweep,
  65578. rx, ry, centreX, centreY,
  65579. startAngle, deltaAngle);
  65580. path.addCentredArc ((float) centreX, (float) centreY,
  65581. (float) rx, (float) ry,
  65582. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  65583. false);
  65584. path.lineTo (x2, y2);
  65585. }
  65586. lastX2 = lastX;
  65587. lastY2 = lastY;
  65588. lastX = x2;
  65589. lastY = y2;
  65590. }
  65591. }
  65592. }
  65593. }
  65594. }
  65595. else
  65596. {
  65597. ++index;
  65598. }
  65599. break;
  65600. case T('Z'):
  65601. case T('z'):
  65602. path.closeSubPath();
  65603. while (CharacterFunctions::isWhitespace (d [index]))
  65604. ++index;
  65605. break;
  65606. default:
  65607. carryOn = false;
  65608. break;
  65609. }
  65610. if (! carryOn)
  65611. break;
  65612. }
  65613. return parseShape (xml, path);
  65614. }
  65615. Drawable* parseRect (const XmlElement& xml) const
  65616. {
  65617. Path rect;
  65618. const bool hasRX = xml.hasAttribute (T("rx"));
  65619. const bool hasRY = xml.hasAttribute (T("ry"));
  65620. if (hasRX || hasRY)
  65621. {
  65622. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  65623. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  65624. if (! hasRX)
  65625. rx = ry;
  65626. else if (! hasRY)
  65627. ry = rx;
  65628. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  65629. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  65630. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  65631. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  65632. rx, ry);
  65633. }
  65634. else
  65635. {
  65636. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  65637. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  65638. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  65639. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  65640. }
  65641. return parseShape (xml, rect);
  65642. }
  65643. Drawable* parseCircle (const XmlElement& xml) const
  65644. {
  65645. Path circle;
  65646. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  65647. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  65648. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  65649. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  65650. return parseShape (xml, circle);
  65651. }
  65652. Drawable* parseEllipse (const XmlElement& xml) const
  65653. {
  65654. Path ellipse;
  65655. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  65656. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  65657. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  65658. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  65659. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  65660. return parseShape (xml, ellipse);
  65661. }
  65662. Drawable* parseLine (const XmlElement& xml) const
  65663. {
  65664. Path line;
  65665. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  65666. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  65667. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  65668. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  65669. line.startNewSubPath (x1, y1);
  65670. line.lineTo (x2, y2);
  65671. return parseShape (xml, line);
  65672. }
  65673. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  65674. {
  65675. const String points (xml.getStringAttribute (T("points")));
  65676. Path path;
  65677. int index = 0;
  65678. float x, y;
  65679. if (parseCoords (points, x, y, index, true))
  65680. {
  65681. float firstX = x;
  65682. float firstY = y;
  65683. float lastX = 0, lastY = 0;
  65684. path.startNewSubPath (x, y);
  65685. while (parseCoords (points, x, y, index, true))
  65686. {
  65687. lastX = x;
  65688. lastY = y;
  65689. path.lineTo (x, y);
  65690. }
  65691. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  65692. path.closeSubPath();
  65693. }
  65694. return parseShape (xml, path);
  65695. }
  65696. Drawable* parseShape (const XmlElement& xml, Path& path,
  65697. const bool parseTransform = true) const
  65698. {
  65699. if (parseTransform && xml.hasAttribute (T("transform")))
  65700. {
  65701. SVGState newState (*this);
  65702. newState.addTransform (xml);
  65703. return newState.parseShape (xml, path, false);
  65704. }
  65705. DrawablePath* dp = new DrawablePath();
  65706. dp->setName (xml.getStringAttribute (T("id")));
  65707. dp->setSolidFill (Colours::transparentBlack);
  65708. path.applyTransform (transform);
  65709. dp->setPath (path);
  65710. Path::Iterator iter (path);
  65711. bool containsClosedSubPath = false;
  65712. while (iter.next())
  65713. {
  65714. if (iter.elementType == Path::Iterator::closePath)
  65715. {
  65716. containsClosedSubPath = true;
  65717. break;
  65718. }
  65719. }
  65720. Brush* const fillBrush
  65721. = getBrushForFill (path,
  65722. getStyleAttribute (&xml, T("fill")),
  65723. getStyleAttribute (&xml, T("fill-opacity")),
  65724. getStyleAttribute (&xml, T("opacity")),
  65725. containsClosedSubPath ? Colours::black
  65726. : Colours::transparentBlack);
  65727. if (fillBrush != 0)
  65728. {
  65729. if (! fillBrush->isInvisible())
  65730. {
  65731. fillBrush->applyTransform (transform);
  65732. dp->setFillBrush (*fillBrush);
  65733. }
  65734. delete fillBrush;
  65735. }
  65736. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  65737. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  65738. {
  65739. Brush* const strokeBrush
  65740. = getBrushForFill (path, strokeType,
  65741. getStyleAttribute (&xml, T("stroke-opacity")),
  65742. getStyleAttribute (&xml, T("opacity")),
  65743. Colours::transparentBlack);
  65744. if (strokeBrush != 0)
  65745. {
  65746. const PathStrokeType stroke (getStrokeFor (&xml));
  65747. if (! strokeBrush->isInvisible())
  65748. {
  65749. strokeBrush->applyTransform (transform);
  65750. dp->setOutline (stroke, *strokeBrush);
  65751. }
  65752. delete strokeBrush;
  65753. }
  65754. }
  65755. return dp;
  65756. }
  65757. const XmlElement* findLinkedElement (const XmlElement* e) const
  65758. {
  65759. const String id (e->getStringAttribute (T("xlink:href")));
  65760. if (! id.startsWithChar (T('#')))
  65761. return 0;
  65762. return findElementForId (topLevelXml, id.substring (1));
  65763. }
  65764. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  65765. {
  65766. if (fillXml == 0)
  65767. return;
  65768. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  65769. {
  65770. int index = 0;
  65771. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  65772. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  65773. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  65774. double offset = e->getDoubleAttribute (T("offset"));
  65775. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  65776. offset *= 0.01;
  65777. cg.addColour (jlimit (0.0, 1.0, offset), col);
  65778. }
  65779. }
  65780. Brush* getBrushForFill (const Path& path,
  65781. const String& fill,
  65782. const String& fillOpacity,
  65783. const String& overallOpacity,
  65784. const Colour& defaultColour) const
  65785. {
  65786. float opacity = 1.0f;
  65787. if (overallOpacity.isNotEmpty())
  65788. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  65789. if (fillOpacity.isNotEmpty())
  65790. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  65791. if (fill.startsWithIgnoreCase (T("url")))
  65792. {
  65793. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  65794. .upToLastOccurrenceOf (T(")"), false, false).trim());
  65795. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  65796. if (fillXml != 0
  65797. && (fillXml->hasTagName (T("linearGradient"))
  65798. || fillXml->hasTagName (T("radialGradient"))))
  65799. {
  65800. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  65801. ColourGradient cg;
  65802. addGradientStopsIn (cg, inheritedFrom);
  65803. addGradientStopsIn (cg, fillXml);
  65804. if (cg.getNumColours() > 0)
  65805. {
  65806. cg.addColour (0.0, cg.getColour (0));
  65807. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  65808. }
  65809. else
  65810. {
  65811. cg.addColour (0.0, Colours::black);
  65812. cg.addColour (1.0, Colours::black);
  65813. }
  65814. if (overallOpacity.isNotEmpty())
  65815. cg.multiplyOpacity (overallOpacity.getFloatValue());
  65816. jassert (cg.getNumColours() > 0);
  65817. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  65818. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  65819. float width = viewBoxW;
  65820. float height = viewBoxH;
  65821. float dx = 0.0;
  65822. float dy = 0.0;
  65823. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  65824. if (! userSpace)
  65825. path.getBounds (dx, dy, width, height);
  65826. if (cg.isRadial)
  65827. {
  65828. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  65829. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  65830. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  65831. cg.x2 = cg.x1 + radius;
  65832. cg.y2 = cg.y1;
  65833. //xxx (the fx, fy focal point isn't handled properly here..)
  65834. }
  65835. else
  65836. {
  65837. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  65838. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  65839. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  65840. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  65841. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  65842. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  65843. }
  65844. return new GradientBrush (cg);
  65845. }
  65846. }
  65847. if (fill.equalsIgnoreCase (T("none")))
  65848. return new SolidColourBrush (Colours::transparentBlack);
  65849. int i = 0;
  65850. Colour colour (parseColour (fill, i, defaultColour));
  65851. colour = colour.withMultipliedAlpha (opacity);
  65852. return new SolidColourBrush (colour);
  65853. }
  65854. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  65855. {
  65856. const String width (getStyleAttribute (xml, T("stroke-width")));
  65857. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  65858. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  65859. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  65860. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  65861. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  65862. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  65863. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  65864. if (join.equalsIgnoreCase (T("round")))
  65865. joinStyle = PathStrokeType::curved;
  65866. else if (join.equalsIgnoreCase (T("bevel")))
  65867. joinStyle = PathStrokeType::beveled;
  65868. if (cap.equalsIgnoreCase (T("round")))
  65869. capStyle = PathStrokeType::rounded;
  65870. else if (cap.equalsIgnoreCase (T("square")))
  65871. capStyle = PathStrokeType::square;
  65872. float ox = 0.0f, oy = 0.0f;
  65873. transform.transformPoint (ox, oy);
  65874. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  65875. transform.transformPoint (x, y);
  65876. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  65877. joinStyle, capStyle);
  65878. }
  65879. Drawable* parseText (const XmlElement& xml)
  65880. {
  65881. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  65882. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  65883. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  65884. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  65885. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  65886. //xxx not done text yet!
  65887. forEachXmlChildElement (xml, e)
  65888. {
  65889. if (e->isTextElement())
  65890. {
  65891. const String text (e->getText());
  65892. Path path;
  65893. Drawable* s = parseShape (*e, path);
  65894. delete s;
  65895. }
  65896. else if (e->hasTagName (T("tspan")))
  65897. {
  65898. Drawable* s = parseText (*e);
  65899. delete s;
  65900. }
  65901. }
  65902. return 0;
  65903. }
  65904. void addTransform (const XmlElement& xml)
  65905. {
  65906. transform = parseTransform (xml.getStringAttribute (T("transform")))
  65907. .followedBy (transform);
  65908. }
  65909. bool parseCoord (const String& s, float& value, int& index,
  65910. const bool allowUnits, const bool isX) const
  65911. {
  65912. String number;
  65913. if (! parseNextNumber (s, number, index, allowUnits))
  65914. {
  65915. value = 0;
  65916. return false;
  65917. }
  65918. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  65919. return true;
  65920. }
  65921. bool parseCoords (const String& s, float& x, float& y,
  65922. int& index, const bool allowUnits) const
  65923. {
  65924. return parseCoord (s, x, index, allowUnits, true)
  65925. && parseCoord (s, y, index, allowUnits, false);
  65926. }
  65927. float getCoordLength (const String& s, const float sizeForProportions) const
  65928. {
  65929. float n = s.getFloatValue();
  65930. const int len = s.length();
  65931. if (len > 2)
  65932. {
  65933. const float dpi = 96.0f;
  65934. const tchar n1 = s [len - 2];
  65935. const tchar n2 = s [len - 1];
  65936. if (n1 == T('i') && n2 == T('n'))
  65937. n *= dpi;
  65938. else if (n1 == T('m') && n2 == T('m'))
  65939. n *= dpi / 25.4f;
  65940. else if (n1 == T('c') && n2 == T('m'))
  65941. n *= dpi / 2.54f;
  65942. else if (n1 == T('p') && n2 == T('c'))
  65943. n *= 15.0f;
  65944. else if (n2 == T('%'))
  65945. n *= 0.01f * sizeForProportions;
  65946. }
  65947. return n;
  65948. }
  65949. void getCoordList (Array <float>& coords, const String& list,
  65950. const bool allowUnits, const bool isX) const
  65951. {
  65952. int index = 0;
  65953. float value;
  65954. while (parseCoord (list, value, index, allowUnits, isX))
  65955. coords.add (value);
  65956. }
  65957. void parseCSSStyle (const XmlElement& xml)
  65958. {
  65959. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  65960. }
  65961. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  65962. const String& defaultValue = String::empty) const
  65963. {
  65964. if (xml->hasAttribute (attributeName))
  65965. return xml->getStringAttribute (attributeName, defaultValue);
  65966. const String styleAtt (xml->getStringAttribute (T("style")));
  65967. if (styleAtt.isNotEmpty())
  65968. {
  65969. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  65970. if (value.isNotEmpty())
  65971. return value;
  65972. }
  65973. else if (xml->hasAttribute (T("class")))
  65974. {
  65975. const String className (T(".") + xml->getStringAttribute (T("class")));
  65976. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  65977. if (index < 0)
  65978. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  65979. if (index >= 0)
  65980. {
  65981. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  65982. if (openBracket > index)
  65983. {
  65984. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  65985. if (closeBracket > openBracket)
  65986. {
  65987. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  65988. if (value.isNotEmpty())
  65989. return value;
  65990. }
  65991. }
  65992. }
  65993. }
  65994. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  65995. if (xml != 0)
  65996. return getStyleAttribute (xml, attributeName, defaultValue);
  65997. return defaultValue;
  65998. }
  65999. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  66000. {
  66001. if (xml->hasAttribute (attributeName))
  66002. return xml->getStringAttribute (attributeName);
  66003. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66004. if (xml != 0)
  66005. return getInheritedAttribute (xml, attributeName);
  66006. return String::empty;
  66007. }
  66008. static bool isIdentifierChar (const tchar c)
  66009. {
  66010. return CharacterFunctions::isLetter (c) || c == T('-');
  66011. }
  66012. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  66013. {
  66014. int i = 0;
  66015. for (;;)
  66016. {
  66017. i = list.indexOf (i, attributeName);
  66018. if (i < 0)
  66019. break;
  66020. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  66021. && ! isIdentifierChar (list [i + attributeName.length()]))
  66022. {
  66023. i = list.indexOfChar (i, T(':'));
  66024. if (i < 0)
  66025. break;
  66026. int end = list.indexOfChar (i, T(';'));
  66027. if (end < 0)
  66028. end = 0x7ffff;
  66029. return list.substring (i + 1, end).trim();
  66030. }
  66031. ++i;
  66032. }
  66033. return defaultValue;
  66034. }
  66035. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  66036. {
  66037. const tchar* const s = (const tchar*) source;
  66038. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66039. ++index;
  66040. int start = index;
  66041. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  66042. ++index;
  66043. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  66044. ++index;
  66045. if ((s[index] == T('e') || s[index] == T('E'))
  66046. && (CharacterFunctions::isDigit (s[index + 1])
  66047. || s[index + 1] == T('-')
  66048. || s[index + 1] == T('+')))
  66049. {
  66050. index += 2;
  66051. while (CharacterFunctions::isDigit (s[index]))
  66052. ++index;
  66053. }
  66054. if (allowUnits)
  66055. {
  66056. while (CharacterFunctions::isLetter (s[index]))
  66057. ++index;
  66058. }
  66059. if (index == start)
  66060. return false;
  66061. value = String (s + start, index - start);
  66062. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66063. ++index;
  66064. return true;
  66065. }
  66066. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  66067. {
  66068. if (s [index] == T('#'))
  66069. {
  66070. uint32 hex [6];
  66071. zeromem (hex, sizeof (hex));
  66072. int numChars = 0;
  66073. for (int i = 6; --i >= 0;)
  66074. {
  66075. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  66076. if (hexValue >= 0)
  66077. hex [numChars++] = hexValue;
  66078. else
  66079. break;
  66080. }
  66081. if (numChars <= 3)
  66082. return Colour ((uint8) (hex [0] * 0x11),
  66083. (uint8) (hex [1] * 0x11),
  66084. (uint8) (hex [2] * 0x11));
  66085. else
  66086. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  66087. (uint8) ((hex [2] << 4) + hex [3]),
  66088. (uint8) ((hex [4] << 4) + hex [5]));
  66089. }
  66090. else if (s [index] == T('r')
  66091. && s [index + 1] == T('g')
  66092. && s [index + 2] == T('b'))
  66093. {
  66094. const int openBracket = s.indexOfChar (index, T('('));
  66095. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  66096. if (openBracket >= 3 && closeBracket > openBracket)
  66097. {
  66098. index = closeBracket;
  66099. StringArray tokens;
  66100. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  66101. tokens.trim();
  66102. tokens.removeEmptyStrings();
  66103. if (tokens[0].containsChar (T('%')))
  66104. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  66105. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  66106. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  66107. else
  66108. return Colour ((uint8) tokens[0].getIntValue(),
  66109. (uint8) tokens[1].getIntValue(),
  66110. (uint8) tokens[2].getIntValue());
  66111. }
  66112. }
  66113. return Colours::findColourForName (s, defaultColour);
  66114. }
  66115. static const AffineTransform parseTransform (String t)
  66116. {
  66117. AffineTransform result;
  66118. while (t.isNotEmpty())
  66119. {
  66120. StringArray tokens;
  66121. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  66122. .upToFirstOccurrenceOf (T(")"), false, false),
  66123. T(", "), 0);
  66124. tokens.removeEmptyStrings (true);
  66125. float numbers [6];
  66126. for (int i = 0; i < 6; ++i)
  66127. numbers[i] = tokens[i].getFloatValue();
  66128. AffineTransform trans;
  66129. if (t.startsWithIgnoreCase (T("matrix")))
  66130. {
  66131. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  66132. numbers[1], numbers[3], numbers[5]);
  66133. }
  66134. else if (t.startsWithIgnoreCase (T("translate")))
  66135. {
  66136. trans = trans.translated (numbers[0], numbers[1]);
  66137. }
  66138. else if (t.startsWithIgnoreCase (T("scale")))
  66139. {
  66140. if (tokens.size() == 1)
  66141. trans = trans.scaled (numbers[0], numbers[0]);
  66142. else
  66143. trans = trans.scaled (numbers[0], numbers[1]);
  66144. }
  66145. else if (t.startsWithIgnoreCase (T("rotate")))
  66146. {
  66147. if (tokens.size() != 3)
  66148. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  66149. else
  66150. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  66151. numbers[1], numbers[2]);
  66152. }
  66153. else if (t.startsWithIgnoreCase (T("skewX")))
  66154. {
  66155. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  66156. 0.0f, 1.0f, 0.0f);
  66157. }
  66158. else if (t.startsWithIgnoreCase (T("skewY")))
  66159. {
  66160. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  66161. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  66162. }
  66163. result = trans.followedBy (result);
  66164. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  66165. }
  66166. return result;
  66167. }
  66168. static void endpointToCentreParameters (const double x1, const double y1,
  66169. const double x2, const double y2,
  66170. const double angle,
  66171. const bool largeArc, const bool sweep,
  66172. double& rx, double& ry,
  66173. double& centreX, double& centreY,
  66174. double& startAngle, double& deltaAngle)
  66175. {
  66176. const double midX = (x1 - x2) * 0.5;
  66177. const double midY = (y1 - y2) * 0.5;
  66178. const double cosAngle = cos (angle);
  66179. const double sinAngle = sin (angle);
  66180. const double xp = cosAngle * midX + sinAngle * midY;
  66181. const double yp = cosAngle * midY - sinAngle * midX;
  66182. const double xp2 = xp * xp;
  66183. const double yp2 = yp * yp;
  66184. double rx2 = rx * rx;
  66185. double ry2 = ry * ry;
  66186. const double s = (xp2 / rx2) + (yp2 / ry2);
  66187. double c;
  66188. if (s <= 1.0)
  66189. {
  66190. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  66191. / (( rx2 * yp2) + (ry2 * xp2))));
  66192. if (largeArc == sweep)
  66193. c = -c;
  66194. }
  66195. else
  66196. {
  66197. const double s2 = sqrt (s);
  66198. rx *= s2;
  66199. ry *= s2;
  66200. rx2 = rx * rx;
  66201. ry2 = ry * ry;
  66202. c = 0;
  66203. }
  66204. const double cpx = ((rx * yp) / ry) * c;
  66205. const double cpy = ((-ry * xp) / rx) * c;
  66206. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  66207. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  66208. const double ux = (xp - cpx) / rx;
  66209. const double uy = (yp - cpy) / ry;
  66210. const double vx = (-xp - cpx) / rx;
  66211. const double vy = (-yp - cpy) / ry;
  66212. const double length = juce_hypot (ux, uy);
  66213. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  66214. if (uy < 0)
  66215. startAngle = -startAngle;
  66216. startAngle += double_Pi * 0.5;
  66217. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  66218. / (length * juce_hypot (vx, vy))));
  66219. if ((ux * vy) - (uy * vx) < 0)
  66220. deltaAngle = -deltaAngle;
  66221. if (sweep)
  66222. {
  66223. if (deltaAngle < 0)
  66224. deltaAngle += double_Pi * 2.0;
  66225. }
  66226. else
  66227. {
  66228. if (deltaAngle > 0)
  66229. deltaAngle -= double_Pi * 2.0;
  66230. }
  66231. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  66232. }
  66233. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  66234. {
  66235. forEachXmlChildElement (*parent, e)
  66236. {
  66237. if (e->compareAttribute (T("id"), id))
  66238. return e;
  66239. const XmlElement* const found = findElementForId (e, id);
  66240. if (found != 0)
  66241. return found;
  66242. }
  66243. return 0;
  66244. }
  66245. const SVGState& operator= (const SVGState&);
  66246. };
  66247. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  66248. {
  66249. SVGState state (&svgDocument);
  66250. return state.parseSVGElement (svgDocument);
  66251. }
  66252. END_JUCE_NAMESPACE
  66253. /********* End of inlined file: juce_SVGParser.cpp *********/
  66254. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  66255. BEGIN_JUCE_NAMESPACE
  66256. #if JUCE_MSVC
  66257. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  66258. #endif
  66259. DropShadowEffect::DropShadowEffect()
  66260. : offsetX (0),
  66261. offsetY (0),
  66262. radius (4),
  66263. opacity (0.6f)
  66264. {
  66265. }
  66266. DropShadowEffect::~DropShadowEffect()
  66267. {
  66268. }
  66269. void DropShadowEffect::setShadowProperties (const float newRadius,
  66270. const float newOpacity,
  66271. const int newShadowOffsetX,
  66272. const int newShadowOffsetY)
  66273. {
  66274. radius = jmax (1.1f, newRadius);
  66275. offsetX = newShadowOffsetX;
  66276. offsetY = newShadowOffsetY;
  66277. opacity = newOpacity;
  66278. }
  66279. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  66280. {
  66281. const int w = image.getWidth();
  66282. const int h = image.getHeight();
  66283. int lineStride, pixelStride;
  66284. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  66285. Image shadowImage (Image::SingleChannel, w, h, false);
  66286. int destStride, destPixelStride;
  66287. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  66288. const int filter = roundFloatToInt (63.0f / radius);
  66289. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  66290. for (int x = w; --x >= 0;)
  66291. {
  66292. int shadowAlpha = 0;
  66293. const PixelARGB* src = srcPixels + x;
  66294. uint8* shadowPix = shadowChannel + x;
  66295. for (int y = h; --y >= 0;)
  66296. {
  66297. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  66298. *shadowPix = (uint8) shadowAlpha;
  66299. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  66300. shadowPix += destStride;
  66301. }
  66302. }
  66303. for (int y = h; --y >= 0;)
  66304. {
  66305. int shadowAlpha = 0;
  66306. uint8* shadowPix = shadowChannel + y * destStride;
  66307. for (int x = w; --x >= 0;)
  66308. {
  66309. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  66310. *shadowPix++ = (uint8) shadowAlpha;
  66311. }
  66312. }
  66313. image.releasePixelDataReadOnly (srcPixels);
  66314. shadowImage.releasePixelDataReadWrite (shadowChannel);
  66315. g.setColour (Colours::black.withAlpha (opacity));
  66316. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  66317. g.setOpacity (1.0f);
  66318. g.drawImageAt (&image, 0, 0);
  66319. }
  66320. END_JUCE_NAMESPACE
  66321. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  66322. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  66323. BEGIN_JUCE_NAMESPACE
  66324. GlowEffect::GlowEffect()
  66325. : radius (2.0f),
  66326. colour (Colours::white)
  66327. {
  66328. }
  66329. GlowEffect::~GlowEffect()
  66330. {
  66331. }
  66332. void GlowEffect::setGlowProperties (const float newRadius,
  66333. const Colour& newColour)
  66334. {
  66335. radius = newRadius;
  66336. colour = newColour;
  66337. }
  66338. void GlowEffect::applyEffect (Image& image, Graphics& g)
  66339. {
  66340. const int w = image.getWidth();
  66341. const int h = image.getHeight();
  66342. Image temp (image.getFormat(), w, h, true);
  66343. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  66344. blurKernel.createGaussianBlur (radius);
  66345. blurKernel.rescaleAllValues (radius);
  66346. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  66347. g.setColour (colour);
  66348. g.drawImageAt (&temp, 0, 0, true);
  66349. g.setOpacity (1.0f);
  66350. g.drawImageAt (&image, 0, 0, false);
  66351. }
  66352. END_JUCE_NAMESPACE
  66353. /********* End of inlined file: juce_GlowEffect.cpp *********/
  66354. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  66355. BEGIN_JUCE_NAMESPACE
  66356. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  66357. : opacity (opacity_)
  66358. {
  66359. }
  66360. ReduceOpacityEffect::~ReduceOpacityEffect()
  66361. {
  66362. }
  66363. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  66364. {
  66365. opacity = jlimit (0.0f, 1.0f, newOpacity);
  66366. }
  66367. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  66368. {
  66369. g.setOpacity (opacity);
  66370. g.drawImageAt (&image, 0, 0);
  66371. }
  66372. END_JUCE_NAMESPACE
  66373. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  66374. /********* Start of inlined file: juce_Font.cpp *********/
  66375. BEGIN_JUCE_NAMESPACE
  66376. static const float minFontHeight = 0.1f;
  66377. static const float maxFontHeight = 10000.0f;
  66378. static const float defaultFontHeight = 14.0f;
  66379. Font::Font() throw()
  66380. : typefaceName (Typeface::defaultTypefaceNameSans),
  66381. height (defaultFontHeight),
  66382. horizontalScale (1.0f),
  66383. kerning (0),
  66384. ascent (0),
  66385. styleFlags (Font::plain)
  66386. {
  66387. }
  66388. void Font::resetToDefaultState() throw()
  66389. {
  66390. typefaceName = Typeface::defaultTypefaceNameSans;
  66391. height = defaultFontHeight;
  66392. horizontalScale = 1.0f;
  66393. kerning = 0;
  66394. ascent = 0;
  66395. styleFlags = Font::plain;
  66396. typeface = 0;
  66397. }
  66398. Font::Font (const float fontHeight,
  66399. const int styleFlags_) throw()
  66400. : typefaceName (Typeface::defaultTypefaceNameSans),
  66401. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  66402. horizontalScale (1.0f),
  66403. kerning (0),
  66404. ascent (0),
  66405. styleFlags (styleFlags_)
  66406. {
  66407. }
  66408. Font::Font (const String& typefaceName_,
  66409. const float fontHeight,
  66410. const int styleFlags_) throw()
  66411. : typefaceName (typefaceName_),
  66412. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  66413. horizontalScale (1.0f),
  66414. kerning (0),
  66415. ascent (0),
  66416. styleFlags (styleFlags_)
  66417. {
  66418. }
  66419. Font::Font (const Font& other) throw()
  66420. : typefaceName (other.typefaceName),
  66421. height (other.height),
  66422. horizontalScale (other.horizontalScale),
  66423. kerning (other.kerning),
  66424. ascent (other.ascent),
  66425. styleFlags (other.styleFlags),
  66426. typeface (other.typeface)
  66427. {
  66428. }
  66429. const Font& Font::operator= (const Font& other) throw()
  66430. {
  66431. if (this != &other)
  66432. {
  66433. typefaceName = other.typefaceName;
  66434. height = other.height;
  66435. styleFlags = other.styleFlags;
  66436. horizontalScale = other.horizontalScale;
  66437. kerning = other.kerning;
  66438. ascent = other.ascent;
  66439. typeface = other.typeface;
  66440. }
  66441. return *this;
  66442. }
  66443. Font::~Font() throw()
  66444. {
  66445. }
  66446. Font::Font (const Typeface& face) throw()
  66447. : height (11.0f),
  66448. horizontalScale (1.0f),
  66449. kerning (0),
  66450. ascent (0),
  66451. styleFlags (plain)
  66452. {
  66453. typefaceName = face.getName();
  66454. setBold (face.isBold());
  66455. setItalic (face.isItalic());
  66456. typeface = new Typeface (face);
  66457. }
  66458. bool Font::operator== (const Font& other) const throw()
  66459. {
  66460. return height == other.height
  66461. && horizontalScale == other.horizontalScale
  66462. && kerning == other.kerning
  66463. && styleFlags == other.styleFlags
  66464. && typefaceName == other.typefaceName;
  66465. }
  66466. bool Font::operator!= (const Font& other) const throw()
  66467. {
  66468. return ! operator== (other);
  66469. }
  66470. void Font::setTypefaceName (const String& faceName) throw()
  66471. {
  66472. typefaceName = faceName;
  66473. typeface = 0;
  66474. ascent = 0;
  66475. }
  66476. static String fallbackFont;
  66477. const String Font::getFallbackFontName() throw()
  66478. {
  66479. return fallbackFont;
  66480. }
  66481. void Font::setFallbackFontName (const String& name) throw()
  66482. {
  66483. fallbackFont = name;
  66484. }
  66485. void Font::setHeight (float newHeight) throw()
  66486. {
  66487. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  66488. }
  66489. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  66490. {
  66491. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  66492. horizontalScale *= (height / newHeight);
  66493. height = newHeight;
  66494. }
  66495. void Font::setStyleFlags (const int newFlags) throw()
  66496. {
  66497. if (styleFlags != newFlags)
  66498. {
  66499. styleFlags = newFlags;
  66500. typeface = 0;
  66501. ascent = 0;
  66502. }
  66503. }
  66504. void Font::setSizeAndStyle (const float newHeight,
  66505. const int newStyleFlags,
  66506. const float newHorizontalScale,
  66507. const float newKerningAmount) throw()
  66508. {
  66509. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  66510. horizontalScale = newHorizontalScale;
  66511. kerning = newKerningAmount;
  66512. setStyleFlags (newStyleFlags);
  66513. }
  66514. void Font::setHorizontalScale (const float scaleFactor) throw()
  66515. {
  66516. horizontalScale = scaleFactor;
  66517. }
  66518. void Font::setExtraKerningFactor (const float extraKerning) throw()
  66519. {
  66520. kerning = extraKerning;
  66521. }
  66522. void Font::setBold (const bool shouldBeBold) throw()
  66523. {
  66524. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  66525. : (styleFlags & ~bold));
  66526. }
  66527. bool Font::isBold() const throw()
  66528. {
  66529. return (styleFlags & bold) != 0;
  66530. }
  66531. void Font::setItalic (const bool shouldBeItalic) throw()
  66532. {
  66533. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  66534. : (styleFlags & ~italic));
  66535. }
  66536. bool Font::isItalic() const throw()
  66537. {
  66538. return (styleFlags & italic) != 0;
  66539. }
  66540. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  66541. {
  66542. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  66543. : (styleFlags & ~underlined));
  66544. }
  66545. bool Font::isUnderlined() const throw()
  66546. {
  66547. return (styleFlags & underlined) != 0;
  66548. }
  66549. float Font::getAscent() const throw()
  66550. {
  66551. if (ascent == 0)
  66552. ascent = getTypeface()->getAscent();
  66553. return height * ascent;
  66554. }
  66555. float Font::getDescent() const throw()
  66556. {
  66557. return height - getAscent();
  66558. }
  66559. int Font::getStringWidth (const String& text) const throw()
  66560. {
  66561. return roundFloatToInt (getStringWidthFloat (text));
  66562. }
  66563. float Font::getStringWidthFloat (const String& text) const throw()
  66564. {
  66565. float x = 0.0f;
  66566. if (text.isNotEmpty())
  66567. {
  66568. Typeface* const typeface = getTypeface();
  66569. const juce_wchar* t = (const juce_wchar*) text;
  66570. do
  66571. {
  66572. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  66573. if (glyph != 0)
  66574. x += kerning + glyph->getHorizontalSpacing (*t);
  66575. }
  66576. while (*t != 0);
  66577. x *= height;
  66578. x *= horizontalScale;
  66579. }
  66580. return x;
  66581. }
  66582. Typeface* Font::getTypeface() const throw()
  66583. {
  66584. if (typeface == 0)
  66585. typeface = Typeface::getTypefaceFor (*this);
  66586. return typeface;
  66587. }
  66588. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  66589. {
  66590. const StringArray names (findAllTypefaceNames());
  66591. for (int i = 0; i < names.size(); ++i)
  66592. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  66593. }
  66594. END_JUCE_NAMESPACE
  66595. /********* End of inlined file: juce_Font.cpp *********/
  66596. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  66597. BEGIN_JUCE_NAMESPACE
  66598. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  66599. class FontGlyphAlphaMap
  66600. {
  66601. public:
  66602. bool draw (const Graphics& g, float x, const float y) const throw()
  66603. {
  66604. if (bitmap1 == 0)
  66605. return false;
  66606. x += xOrigin;
  66607. const float xFloor = floorf (x);
  66608. const int intX = (int) xFloor;
  66609. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  66610. intX, (int) floorf (y + yOrigin), true);
  66611. return true;
  66612. }
  66613. juce_UseDebuggingNewOperator
  66614. private:
  66615. Image* bitmap1;
  66616. Image* bitmap2;
  66617. float xOrigin, yOrigin;
  66618. int lastAccessCount;
  66619. Typeface::Ptr typeface;
  66620. float height, horizontalScale;
  66621. juce_wchar character;
  66622. friend class GlyphCache;
  66623. FontGlyphAlphaMap() throw()
  66624. : bitmap1 (0),
  66625. bitmap2 (0),
  66626. lastAccessCount (0),
  66627. height (0),
  66628. horizontalScale (0),
  66629. character (0)
  66630. {
  66631. }
  66632. ~FontGlyphAlphaMap() throw()
  66633. {
  66634. delete bitmap1;
  66635. delete bitmap2;
  66636. }
  66637. class AlphaBitmapRenderer
  66638. {
  66639. uint8* const data;
  66640. const int stride;
  66641. uint8* lineStart;
  66642. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  66643. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  66644. public:
  66645. AlphaBitmapRenderer (uint8* const data_,
  66646. const int stride_) throw()
  66647. : data (data_),
  66648. stride (stride_)
  66649. {
  66650. }
  66651. forcedinline void setEdgeTableYPos (const int y) throw()
  66652. {
  66653. lineStart = data + (stride * y);
  66654. }
  66655. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66656. {
  66657. lineStart [x] = (uint8) alphaLevel;
  66658. }
  66659. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  66660. {
  66661. uint8* d = lineStart + x;
  66662. while (--width >= 0)
  66663. *d++ = (uint8) alphaLevel;
  66664. }
  66665. };
  66666. Image* createAlphaMapFromPath (const Path& path,
  66667. float& topLeftX, float& topLeftY,
  66668. float xScale, float yScale,
  66669. const float subPixelOffsetX) throw()
  66670. {
  66671. Image* im = 0;
  66672. float px, py, pw, ph;
  66673. path.getBounds (px, py, pw, ph);
  66674. topLeftX = floorf (px * xScale);
  66675. topLeftY = floorf (py * yScale);
  66676. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  66677. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  66678. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  66679. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  66680. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  66681. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  66682. int stride, pixelStride;
  66683. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  66684. jassert (pixelStride == 1);
  66685. AlphaBitmapRenderer renderer (pixels, stride);
  66686. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  66687. im->releasePixelDataReadWrite (pixels);
  66688. return im;
  66689. }
  66690. void generate (Typeface* const face,
  66691. const juce_wchar character_,
  66692. const float fontHeight,
  66693. const float fontHorizontalScale) throw()
  66694. {
  66695. character = character_;
  66696. typeface = face;
  66697. height = fontHeight;
  66698. horizontalScale = fontHorizontalScale;
  66699. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  66700. deleteAndZero (bitmap1);
  66701. deleteAndZero (bitmap2);
  66702. const float fontHScale = fontHeight * fontHorizontalScale;
  66703. if (glyphPath != 0 && ! glyphPath->isEmpty())
  66704. {
  66705. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  66706. if (fontHScale < 24.0f)
  66707. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  66708. }
  66709. else
  66710. {
  66711. xOrigin = yOrigin = 0;
  66712. }
  66713. }
  66714. };
  66715. static const int defaultNumGlyphsToCache = 120;
  66716. class GlyphCache;
  66717. static GlyphCache* cacheInstance = 0;
  66718. class GlyphCache : private DeletedAtShutdown
  66719. {
  66720. public:
  66721. static GlyphCache* getInstance() throw()
  66722. {
  66723. if (cacheInstance == 0)
  66724. cacheInstance = new GlyphCache();
  66725. return cacheInstance;
  66726. }
  66727. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  66728. const float fontHeight,
  66729. const float fontHorizontalScale,
  66730. const juce_wchar character) throw()
  66731. {
  66732. ++accessCounter;
  66733. int oldestCounter = INT_MAX;
  66734. int oldestIndex = 0;
  66735. for (int i = numGlyphs; --i >= 0;)
  66736. {
  66737. FontGlyphAlphaMap& g = glyphs[i];
  66738. if (g.character == character
  66739. && g.height == fontHeight
  66740. && g.typeface->hashCode() == typeface->hashCode()
  66741. && g.horizontalScale == fontHorizontalScale)
  66742. {
  66743. g.lastAccessCount = accessCounter;
  66744. ++hits;
  66745. return g;
  66746. }
  66747. if (oldestCounter > g.lastAccessCount)
  66748. {
  66749. oldestCounter = g.lastAccessCount;
  66750. oldestIndex = i;
  66751. }
  66752. }
  66753. ++misses;
  66754. if (hits + misses > (numGlyphs << 4))
  66755. {
  66756. if (misses * 2 > hits)
  66757. setCacheSize (numGlyphs + 32);
  66758. hits = 0;
  66759. misses = 0;
  66760. oldestIndex = 0;
  66761. }
  66762. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  66763. oldest.lastAccessCount = accessCounter;
  66764. oldest.generate (typeface,
  66765. character,
  66766. fontHeight,
  66767. fontHorizontalScale);
  66768. return oldest;
  66769. }
  66770. void setCacheSize (const int num) throw()
  66771. {
  66772. if (numGlyphs != num)
  66773. {
  66774. numGlyphs = num;
  66775. if (glyphs != 0)
  66776. delete[] glyphs;
  66777. glyphs = new FontGlyphAlphaMap [numGlyphs];
  66778. hits = 0;
  66779. misses = 0;
  66780. }
  66781. }
  66782. juce_UseDebuggingNewOperator
  66783. private:
  66784. FontGlyphAlphaMap* glyphs;
  66785. int numGlyphs, accessCounter;
  66786. int hits, misses;
  66787. GlyphCache() throw()
  66788. : glyphs (0),
  66789. numGlyphs (0),
  66790. accessCounter (0)
  66791. {
  66792. setCacheSize (defaultNumGlyphsToCache);
  66793. }
  66794. ~GlyphCache() throw()
  66795. {
  66796. delete[] glyphs;
  66797. jassert (cacheInstance == this);
  66798. cacheInstance = 0;
  66799. }
  66800. GlyphCache (const GlyphCache&);
  66801. const GlyphCache& operator= (const GlyphCache&);
  66802. };
  66803. PositionedGlyph::PositionedGlyph() throw()
  66804. {
  66805. }
  66806. void PositionedGlyph::draw (const Graphics& g) const throw()
  66807. {
  66808. if (! glyphInfo->isWhitespace())
  66809. {
  66810. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  66811. {
  66812. const FontGlyphAlphaMap& alphaMap
  66813. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  66814. fontHeight,
  66815. fontHorizontalScale,
  66816. getCharacter());
  66817. alphaMap.draw (g, x, y);
  66818. }
  66819. else
  66820. {
  66821. // that's a bit of a dodgy size, isn't it??
  66822. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  66823. draw (g, AffineTransform::identity);
  66824. }
  66825. }
  66826. }
  66827. void PositionedGlyph::draw (const Graphics& g,
  66828. const AffineTransform& transform) const throw()
  66829. {
  66830. if (! glyphInfo->isWhitespace())
  66831. {
  66832. g.fillPath (glyphInfo->getPath(),
  66833. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  66834. .translated (x, y)
  66835. .followedBy (transform));
  66836. }
  66837. }
  66838. void PositionedGlyph::createPath (Path& path) const throw()
  66839. {
  66840. if (! glyphInfo->isWhitespace())
  66841. {
  66842. path.addPath (glyphInfo->getPath(),
  66843. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  66844. .translated (x, y));
  66845. }
  66846. }
  66847. bool PositionedGlyph::hitTest (float px, float py) const throw()
  66848. {
  66849. if (px >= getLeft() && px < getRight()
  66850. && py >= getTop() && py < getBottom()
  66851. && fontHeight > 0.0f
  66852. && ! glyphInfo->isWhitespace())
  66853. {
  66854. AffineTransform::translation (-x, -y)
  66855. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  66856. .transformPoint (px, py);
  66857. return glyphInfo->getPath().contains (px, py);
  66858. }
  66859. return false;
  66860. }
  66861. void PositionedGlyph::moveBy (const float deltaX,
  66862. const float deltaY) throw()
  66863. {
  66864. x += deltaX;
  66865. y += deltaY;
  66866. }
  66867. GlyphArrangement::GlyphArrangement() throw()
  66868. : numGlyphs (0),
  66869. numAllocated (0),
  66870. glyphs (0)
  66871. {
  66872. }
  66873. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  66874. : numGlyphs (0),
  66875. numAllocated (0),
  66876. glyphs (0)
  66877. {
  66878. addGlyphArrangement (other);
  66879. }
  66880. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  66881. {
  66882. if (this != &other)
  66883. {
  66884. clear();
  66885. addGlyphArrangement (other);
  66886. }
  66887. return *this;
  66888. }
  66889. GlyphArrangement::~GlyphArrangement() throw()
  66890. {
  66891. clear();
  66892. juce_free (glyphs);
  66893. }
  66894. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  66895. {
  66896. if (numAllocated <= minGlyphs)
  66897. {
  66898. numAllocated = minGlyphs + 2;
  66899. if (glyphs == 0)
  66900. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  66901. else
  66902. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  66903. }
  66904. }
  66905. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  66906. {
  66907. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  66908. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  66909. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  66910. }
  66911. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  66912. {
  66913. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  66914. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  66915. }
  66916. void GlyphArrangement::clear() throw()
  66917. {
  66918. for (int i = numGlyphs; --i >= 0;)
  66919. decGlyphRefCount (i);
  66920. numGlyphs = 0;
  66921. }
  66922. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  66923. {
  66924. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  66925. return glyphs [index];
  66926. }
  66927. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  66928. {
  66929. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  66930. memcpy (glyphs + numGlyphs, other.glyphs,
  66931. other.numGlyphs * sizeof (PositionedGlyph));
  66932. for (int i = other.numGlyphs; --i >= 0;)
  66933. incGlyphRefCount (numGlyphs++);
  66934. }
  66935. void GlyphArrangement::removeLast() throw()
  66936. {
  66937. if (numGlyphs > 0)
  66938. decGlyphRefCount (--numGlyphs);
  66939. }
  66940. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  66941. {
  66942. jassert (startIndex >= 0);
  66943. if (startIndex < 0)
  66944. startIndex = 0;
  66945. if (num < 0 || startIndex + num >= numGlyphs)
  66946. {
  66947. while (numGlyphs > startIndex)
  66948. removeLast();
  66949. }
  66950. else if (num > 0)
  66951. {
  66952. int i;
  66953. for (i = startIndex; i < startIndex + num; ++i)
  66954. decGlyphRefCount (i);
  66955. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  66956. {
  66957. glyphs [startIndex] = glyphs [startIndex + num];
  66958. ++startIndex;
  66959. }
  66960. numGlyphs -= num;
  66961. }
  66962. }
  66963. void GlyphArrangement::addLineOfText (const Font& font,
  66964. const String& text,
  66965. const float xOffset,
  66966. const float yOffset) throw()
  66967. {
  66968. addCurtailedLineOfText (font, text,
  66969. xOffset, yOffset,
  66970. 1.0e10f, false);
  66971. }
  66972. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  66973. const String& text,
  66974. float xOffset,
  66975. const float yOffset,
  66976. const float maxWidthPixels,
  66977. const bool useEllipsis) throw()
  66978. {
  66979. const int textLen = text.length();
  66980. if (textLen > 0)
  66981. {
  66982. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  66983. Typeface* const typeface = font.getTypeface();
  66984. const float fontHeight = font.getHeight();
  66985. const float ascent = font.getAscent();
  66986. const float fontHorizontalScale = font.getHorizontalScale();
  66987. const float heightTimesScale = fontHorizontalScale * fontHeight;
  66988. const float kerningFactor = font.getExtraKerningFactor();
  66989. const float startX = xOffset;
  66990. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  66991. for (int i = 0; i < textLen; ++i)
  66992. {
  66993. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  66994. if (glyph != 0)
  66995. {
  66996. jassert (numAllocated > numGlyphs);
  66997. ensureNumGlyphsAllocated (numGlyphs);
  66998. PositionedGlyph& pg = glyphs [numGlyphs];
  66999. pg.glyphInfo = glyph;
  67000. pg.x = xOffset;
  67001. pg.y = yOffset;
  67002. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  67003. pg.fontHeight = fontHeight;
  67004. pg.fontAscent = ascent;
  67005. pg.fontHorizontalScale = fontHorizontalScale;
  67006. pg.isUnderlined = font.isUnderlined();
  67007. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  67008. if (xOffset - startX > maxWidthPixels + 1.0f)
  67009. {
  67010. // curtail the string if it's too wide..
  67011. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  67012. appendEllipsis (font, startX + maxWidthPixels);
  67013. break;
  67014. }
  67015. else
  67016. {
  67017. if (glyph->getTypeface() != 0)
  67018. glyph->getTypeface()->incReferenceCount();
  67019. ++numGlyphs;
  67020. }
  67021. }
  67022. }
  67023. }
  67024. }
  67025. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  67026. {
  67027. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  67028. if (dotGlyph != 0)
  67029. {
  67030. if (numGlyphs > 0)
  67031. {
  67032. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  67033. const float fontHeight = glyph.fontHeight;
  67034. const float fontHorizontalScale = glyph.fontHorizontalScale;
  67035. const float fontAscent = glyph.fontAscent;
  67036. const float dx = fontHeight * fontHorizontalScale
  67037. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  67038. float xOffset = 0.0f, yOffset = 0.0f;
  67039. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  67040. {
  67041. removeLast();
  67042. jassert (numAllocated > numGlyphs);
  67043. PositionedGlyph& pg = glyphs [numGlyphs];
  67044. xOffset = pg.x;
  67045. yOffset = pg.y;
  67046. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  67047. break;
  67048. }
  67049. for (int i = 3; --i >= 0;)
  67050. {
  67051. jassert (numAllocated > numGlyphs);
  67052. ensureNumGlyphsAllocated (numGlyphs);
  67053. PositionedGlyph& pg = glyphs [numGlyphs];
  67054. pg.glyphInfo = dotGlyph;
  67055. pg.x = xOffset;
  67056. pg.y = yOffset;
  67057. pg.w = dx;
  67058. pg.fontHeight = fontHeight;
  67059. pg.fontAscent = fontAscent;
  67060. pg.fontHorizontalScale = fontHorizontalScale;
  67061. pg.isUnderlined = font.isUnderlined();
  67062. xOffset += dx;
  67063. if (dotGlyph->getTypeface() != 0)
  67064. dotGlyph->getTypeface()->incReferenceCount();
  67065. ++numGlyphs;
  67066. }
  67067. }
  67068. }
  67069. }
  67070. void GlyphArrangement::addJustifiedText (const Font& font,
  67071. const String& text,
  67072. float x, float y,
  67073. const float maxLineWidth,
  67074. const Justification& horizontalLayout) throw()
  67075. {
  67076. int lineStartIndex = numGlyphs;
  67077. addLineOfText (font, text, x, y);
  67078. const float originalY = y;
  67079. while (lineStartIndex < numGlyphs)
  67080. {
  67081. int i = lineStartIndex;
  67082. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  67083. ++i;
  67084. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  67085. int lastWordBreakIndex = -1;
  67086. while (i < numGlyphs)
  67087. {
  67088. PositionedGlyph& pg = glyphs[i];
  67089. const juce_wchar c = pg.getCharacter();
  67090. if (c == T('\r') || c == T('\n'))
  67091. {
  67092. ++i;
  67093. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  67094. ++i;
  67095. break;
  67096. }
  67097. else if (pg.isWhitespace())
  67098. {
  67099. lastWordBreakIndex = i + 1;
  67100. }
  67101. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  67102. {
  67103. if (lastWordBreakIndex >= 0)
  67104. i = lastWordBreakIndex;
  67105. break;
  67106. }
  67107. ++i;
  67108. }
  67109. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  67110. float currentLineEndX = currentLineStartX;
  67111. for (int j = i; --j >= lineStartIndex;)
  67112. {
  67113. if (! glyphs[j].isWhitespace())
  67114. {
  67115. currentLineEndX = glyphs[j].getRight();
  67116. break;
  67117. }
  67118. }
  67119. float deltaX = 0.0f;
  67120. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  67121. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  67122. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  67123. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  67124. else if (horizontalLayout.testFlags (Justification::right))
  67125. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  67126. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  67127. x + deltaX - currentLineStartX, y - originalY);
  67128. lineStartIndex = i;
  67129. y += font.getHeight();
  67130. }
  67131. }
  67132. void GlyphArrangement::addFittedText (const Font& f,
  67133. const String& text,
  67134. float x, float y,
  67135. float width, float height,
  67136. const Justification& layout,
  67137. int maximumLines,
  67138. const float minimumHorizontalScale) throw()
  67139. {
  67140. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  67141. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  67142. if (text.containsAnyOf (T("\r\n")))
  67143. {
  67144. GlyphArrangement ga;
  67145. ga.addJustifiedText (f, text, x, y, width, layout);
  67146. float l, t, r, b;
  67147. ga.getBoundingBox (0, -1, l, t, r, b, false);
  67148. float dy = y - t;
  67149. if (layout.testFlags (Justification::verticallyCentred))
  67150. dy += (height - (b - t)) * 0.5f;
  67151. else if (layout.testFlags (Justification::bottom))
  67152. dy += height - (b - t);
  67153. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  67154. addGlyphArrangement (ga);
  67155. return;
  67156. }
  67157. int startIndex = numGlyphs;
  67158. addLineOfText (f, text.trim(), x, y);
  67159. if (numGlyphs > startIndex)
  67160. {
  67161. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67162. if (lineWidth <= 0)
  67163. return;
  67164. if (lineWidth * minimumHorizontalScale < width)
  67165. {
  67166. if (lineWidth > width)
  67167. {
  67168. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  67169. width / lineWidth);
  67170. }
  67171. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67172. x, y, width, height, layout);
  67173. }
  67174. else if (maximumLines <= 1)
  67175. {
  67176. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  67177. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  67178. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  67179. removeLast();
  67180. appendEllipsis (f, x + width);
  67181. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67182. x, y, width, height, layout);
  67183. }
  67184. else
  67185. {
  67186. Font font (f);
  67187. String txt (text.trim());
  67188. const int length = txt.length();
  67189. int numLines = 1;
  67190. const int originalStartIndex = startIndex;
  67191. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  67192. maximumLines = 1;
  67193. maximumLines = jmin (maximumLines, length);
  67194. while (numLines < maximumLines)
  67195. {
  67196. ++numLines;
  67197. const float newFontHeight = height / (float)numLines;
  67198. if (newFontHeight < 8.0f)
  67199. break;
  67200. if (newFontHeight < font.getHeight())
  67201. {
  67202. font.setHeight (newFontHeight);
  67203. while (numGlyphs > startIndex)
  67204. removeLast();
  67205. addLineOfText (font, txt, x, y);
  67206. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67207. }
  67208. if (numLines > lineWidth / width)
  67209. break;
  67210. }
  67211. if (numLines < 1)
  67212. numLines = 1;
  67213. float lineY = y;
  67214. float widthPerLine = lineWidth / numLines;
  67215. int lastLineStartIndex = 0;
  67216. for (int line = 0; line < numLines; ++line)
  67217. {
  67218. int i = startIndex;
  67219. lastLineStartIndex = i;
  67220. float lineStartX = glyphs[startIndex].getLeft();
  67221. while (i < numGlyphs)
  67222. {
  67223. lineWidth = (glyphs[i].getRight() - lineStartX);
  67224. if (lineWidth > widthPerLine)
  67225. {
  67226. // got to a point where the line's too long, so skip forward to find a
  67227. // good place to break it..
  67228. const int searchStartIndex = i;
  67229. while (i < numGlyphs)
  67230. {
  67231. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  67232. {
  67233. if (glyphs[i].isWhitespace()
  67234. || glyphs[i].getCharacter() == T('-'))
  67235. {
  67236. ++i;
  67237. break;
  67238. }
  67239. }
  67240. else
  67241. {
  67242. // can't find a suitable break, so try looking backwards..
  67243. i = searchStartIndex;
  67244. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  67245. {
  67246. if (glyphs[i - back].isWhitespace()
  67247. || glyphs[i - back].getCharacter() == T('-'))
  67248. {
  67249. i -= back - 1;
  67250. break;
  67251. }
  67252. }
  67253. break;
  67254. }
  67255. ++i;
  67256. }
  67257. break;
  67258. }
  67259. ++i;
  67260. }
  67261. int wsStart = i;
  67262. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  67263. --wsStart;
  67264. int wsEnd = i;
  67265. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  67266. ++wsEnd;
  67267. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  67268. i = jmax (wsStart, startIndex + 1);
  67269. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  67270. if (lineWidth > width)
  67271. {
  67272. stretchRangeOfGlyphs (startIndex, i - startIndex,
  67273. width / lineWidth);
  67274. }
  67275. justifyGlyphs (startIndex, i - startIndex,
  67276. x, lineY, width, font.getHeight(),
  67277. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67278. startIndex = i;
  67279. lineY += font.getHeight();
  67280. if (startIndex >= numGlyphs)
  67281. break;
  67282. }
  67283. if (startIndex < numGlyphs)
  67284. {
  67285. while (numGlyphs > startIndex)
  67286. removeLast();
  67287. if (startIndex - originalStartIndex > 4)
  67288. {
  67289. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  67290. appendEllipsis (font, lineStartX + width);
  67291. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  67292. if (lineWidth > width)
  67293. {
  67294. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67295. width / lineWidth);
  67296. }
  67297. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67298. x, lineY - font.getHeight(), width, font.getHeight(),
  67299. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67300. }
  67301. startIndex = numGlyphs;
  67302. }
  67303. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  67304. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  67305. }
  67306. }
  67307. }
  67308. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  67309. const float dx, const float dy) throw()
  67310. {
  67311. jassert (startIndex >= 0);
  67312. if (dx != 0.0f || dy != 0.0f)
  67313. {
  67314. if (num < 0 || startIndex + num > numGlyphs)
  67315. num = numGlyphs - startIndex;
  67316. while (--num >= 0)
  67317. {
  67318. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67319. glyphs [startIndex++].moveBy (dx, dy);
  67320. }
  67321. }
  67322. }
  67323. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  67324. const float horizontalScaleFactor) throw()
  67325. {
  67326. jassert (startIndex >= 0);
  67327. if (num < 0 || startIndex + num > numGlyphs)
  67328. num = numGlyphs - startIndex;
  67329. if (num > 0)
  67330. {
  67331. const float xAnchor = glyphs[startIndex].getLeft();
  67332. while (--num >= 0)
  67333. {
  67334. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67335. PositionedGlyph& pg = glyphs[startIndex++];
  67336. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  67337. pg.fontHorizontalScale *= horizontalScaleFactor;
  67338. pg.w *= horizontalScaleFactor;
  67339. }
  67340. }
  67341. }
  67342. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  67343. float& left,
  67344. float& top,
  67345. float& right,
  67346. float& bottom,
  67347. const bool includeWhitespace) const throw()
  67348. {
  67349. jassert (startIndex >= 0);
  67350. if (num < 0 || startIndex + num > numGlyphs)
  67351. num = numGlyphs - startIndex;
  67352. left = 0.0f;
  67353. top = 0.0f;
  67354. right = 0.0f;
  67355. bottom = 0.0f;
  67356. bool isFirst = true;
  67357. while (--num >= 0)
  67358. {
  67359. const PositionedGlyph& pg = glyphs [startIndex++];
  67360. if (includeWhitespace || ! pg.isWhitespace())
  67361. {
  67362. if (isFirst)
  67363. {
  67364. isFirst = false;
  67365. left = pg.getLeft();
  67366. top = pg.getTop();
  67367. right = pg.getRight();
  67368. bottom = pg.getBottom();
  67369. }
  67370. else
  67371. {
  67372. left = jmin (left, pg.getLeft());
  67373. top = jmin (top, pg.getTop());
  67374. right = jmax (right, pg.getRight());
  67375. bottom = jmax (bottom, pg.getBottom());
  67376. }
  67377. }
  67378. }
  67379. }
  67380. void GlyphArrangement::justifyGlyphs (const int startIndex,
  67381. const int num,
  67382. const float x, const float y,
  67383. const float width, const float height,
  67384. const Justification& justification) throw()
  67385. {
  67386. jassert (num >= 0 && startIndex >= 0);
  67387. if (numGlyphs > 0 && num > 0)
  67388. {
  67389. float left, top, right, bottom;
  67390. getBoundingBox (startIndex, num, left, top, right, bottom,
  67391. ! justification.testFlags (Justification::horizontallyJustified
  67392. | Justification::horizontallyCentred));
  67393. float deltaX = 0.0f;
  67394. if (justification.testFlags (Justification::horizontallyJustified))
  67395. deltaX = x - left;
  67396. else if (justification.testFlags (Justification::horizontallyCentred))
  67397. deltaX = x + (width - (right - left)) * 0.5f - left;
  67398. else if (justification.testFlags (Justification::right))
  67399. deltaX = (x + width) - right;
  67400. else
  67401. deltaX = x - left;
  67402. float deltaY = 0.0f;
  67403. if (justification.testFlags (Justification::top))
  67404. deltaY = y - top;
  67405. else if (justification.testFlags (Justification::bottom))
  67406. deltaY = (y + height) - bottom;
  67407. else
  67408. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  67409. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  67410. if (justification.testFlags (Justification::horizontallyJustified))
  67411. {
  67412. int lineStart = 0;
  67413. float baseY = glyphs [startIndex].getBaselineY();
  67414. int i;
  67415. for (i = 0; i < num; ++i)
  67416. {
  67417. const float glyphY = glyphs [startIndex + i].getBaselineY();
  67418. if (glyphY != baseY)
  67419. {
  67420. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  67421. lineStart = i;
  67422. baseY = glyphY;
  67423. }
  67424. }
  67425. if (i > lineStart)
  67426. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  67427. }
  67428. }
  67429. }
  67430. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  67431. {
  67432. if (start + num < numGlyphs
  67433. && glyphs [start + num - 1].getCharacter() != T('\r')
  67434. && glyphs [start + num - 1].getCharacter() != T('\n'))
  67435. {
  67436. int numSpaces = 0;
  67437. int spacesAtEnd = 0;
  67438. for (int i = 0; i < num; ++i)
  67439. {
  67440. if (glyphs [start + i].isWhitespace())
  67441. {
  67442. ++spacesAtEnd;
  67443. ++numSpaces;
  67444. }
  67445. else
  67446. {
  67447. spacesAtEnd = 0;
  67448. }
  67449. }
  67450. numSpaces -= spacesAtEnd;
  67451. if (numSpaces > 0)
  67452. {
  67453. const float startX = glyphs [start].getLeft();
  67454. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  67455. const float extraPaddingBetweenWords
  67456. = (targetWidth - (endX - startX)) / (float) numSpaces;
  67457. float deltaX = 0.0f;
  67458. for (int i = 0; i < num; ++i)
  67459. {
  67460. glyphs [start + i].moveBy (deltaX, 0.0);
  67461. if (glyphs [start + i].isWhitespace())
  67462. deltaX += extraPaddingBetweenWords;
  67463. }
  67464. }
  67465. }
  67466. }
  67467. void GlyphArrangement::draw (const Graphics& g) const throw()
  67468. {
  67469. for (int i = 0; i < numGlyphs; ++i)
  67470. {
  67471. glyphs[i].draw (g);
  67472. if (glyphs[i].isUnderlined)
  67473. {
  67474. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  67475. juce_wchar nextChar = 0;
  67476. if (i < numGlyphs - 1
  67477. && glyphs[i + 1].y == glyphs[i].y)
  67478. {
  67479. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  67480. }
  67481. g.fillRect (glyphs[i].x,
  67482. glyphs[i].y + lineThickness * 2.0f,
  67483. glyphs[i].fontHeight
  67484. * glyphs[i].fontHorizontalScale
  67485. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  67486. lineThickness);
  67487. }
  67488. }
  67489. }
  67490. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  67491. {
  67492. for (int i = 0; i < numGlyphs; ++i)
  67493. {
  67494. glyphs[i].draw (g, transform);
  67495. if (glyphs[i].isUnderlined)
  67496. {
  67497. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  67498. juce_wchar nextChar = 0;
  67499. if (i < numGlyphs - 1
  67500. && glyphs[i + 1].y == glyphs[i].y)
  67501. {
  67502. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  67503. }
  67504. Path p;
  67505. p.addLineSegment (glyphs[i].x,
  67506. glyphs[i].y + lineThickness * 2.5f,
  67507. glyphs[i].x + glyphs[i].fontHeight
  67508. * glyphs[i].fontHorizontalScale
  67509. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  67510. glyphs[i].y + lineThickness * 2.5f,
  67511. lineThickness);
  67512. g.fillPath (p, transform);
  67513. }
  67514. }
  67515. }
  67516. void GlyphArrangement::createPath (Path& path) const throw()
  67517. {
  67518. for (int i = 0; i < numGlyphs; ++i)
  67519. glyphs[i].createPath (path);
  67520. }
  67521. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  67522. {
  67523. for (int i = 0; i < numGlyphs; ++i)
  67524. if (glyphs[i].hitTest (x, y))
  67525. return i;
  67526. return -1;
  67527. }
  67528. END_JUCE_NAMESPACE
  67529. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  67530. /********* Start of inlined file: juce_TextLayout.cpp *********/
  67531. BEGIN_JUCE_NAMESPACE
  67532. class TextLayoutToken
  67533. {
  67534. public:
  67535. String text;
  67536. Font font;
  67537. int x, y, w, h;
  67538. int line, lineHeight;
  67539. bool isWhitespace, isNewLine;
  67540. TextLayoutToken (const String& t,
  67541. const Font& f,
  67542. const bool isWhitespace_) throw()
  67543. : text (t),
  67544. font (f),
  67545. x(0),
  67546. y(0),
  67547. isWhitespace (isWhitespace_)
  67548. {
  67549. w = font.getStringWidth (t);
  67550. h = roundFloatToInt (f.getHeight());
  67551. isNewLine = t.containsAnyOf (T("\r\n"));
  67552. }
  67553. TextLayoutToken (const TextLayoutToken& other) throw()
  67554. : text (other.text),
  67555. font (other.font),
  67556. x (other.x),
  67557. y (other.y),
  67558. w (other.w),
  67559. h (other.h),
  67560. line (other.line),
  67561. lineHeight (other.lineHeight),
  67562. isWhitespace (other.isWhitespace),
  67563. isNewLine (other.isNewLine)
  67564. {
  67565. }
  67566. ~TextLayoutToken() throw()
  67567. {
  67568. }
  67569. void draw (Graphics& g,
  67570. const int xOffset,
  67571. const int yOffset) throw()
  67572. {
  67573. if (! isWhitespace)
  67574. {
  67575. g.setFont (font);
  67576. g.drawSingleLineText (text.trimEnd(),
  67577. xOffset + x,
  67578. yOffset + y + (lineHeight - h)
  67579. + roundFloatToInt (font.getAscent()));
  67580. }
  67581. }
  67582. juce_UseDebuggingNewOperator
  67583. };
  67584. TextLayout::TextLayout() throw()
  67585. : tokens (64),
  67586. totalLines (0)
  67587. {
  67588. }
  67589. TextLayout::TextLayout (const String& text,
  67590. const Font& font) throw()
  67591. : tokens (64),
  67592. totalLines (0)
  67593. {
  67594. appendText (text, font);
  67595. }
  67596. TextLayout::TextLayout (const TextLayout& other) throw()
  67597. : tokens (64),
  67598. totalLines (0)
  67599. {
  67600. *this = other;
  67601. }
  67602. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  67603. {
  67604. if (this != &other)
  67605. {
  67606. clear();
  67607. totalLines = other.totalLines;
  67608. for (int i = 0; i < other.tokens.size(); ++i)
  67609. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  67610. }
  67611. return *this;
  67612. }
  67613. TextLayout::~TextLayout() throw()
  67614. {
  67615. clear();
  67616. }
  67617. void TextLayout::clear() throw()
  67618. {
  67619. for (int i = tokens.size(); --i >= 0;)
  67620. {
  67621. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  67622. delete t;
  67623. }
  67624. tokens.clear();
  67625. totalLines = 0;
  67626. }
  67627. void TextLayout::appendText (const String& text,
  67628. const Font& font) throw()
  67629. {
  67630. const tchar* t = text;
  67631. String currentString;
  67632. int lastCharType = 0;
  67633. for (;;)
  67634. {
  67635. const tchar c = *t++;
  67636. if (c == 0)
  67637. break;
  67638. int charType;
  67639. if (c == T('\r') || c == T('\n'))
  67640. {
  67641. charType = 0;
  67642. }
  67643. else if (CharacterFunctions::isWhitespace (c))
  67644. {
  67645. charType = 2;
  67646. }
  67647. else
  67648. {
  67649. charType = 1;
  67650. }
  67651. if (charType == 0 || charType != lastCharType)
  67652. {
  67653. if (currentString.isNotEmpty())
  67654. {
  67655. tokens.add (new TextLayoutToken (currentString, font,
  67656. lastCharType == 2 || lastCharType == 0));
  67657. }
  67658. currentString = String::charToString (c);
  67659. if (c == T('\r') && *t == T('\n'))
  67660. currentString += *t++;
  67661. }
  67662. else
  67663. {
  67664. currentString += c;
  67665. }
  67666. lastCharType = charType;
  67667. }
  67668. if (currentString.isNotEmpty())
  67669. tokens.add (new TextLayoutToken (currentString,
  67670. font,
  67671. lastCharType == 2));
  67672. }
  67673. void TextLayout::setText (const String& text, const Font& font) throw()
  67674. {
  67675. clear();
  67676. appendText (text, font);
  67677. }
  67678. void TextLayout::layout (int maxWidth,
  67679. const Justification& justification,
  67680. const bool attemptToBalanceLineLengths) throw()
  67681. {
  67682. if (attemptToBalanceLineLengths)
  67683. {
  67684. const int originalW = maxWidth;
  67685. int bestWidth = maxWidth;
  67686. float bestLineProportion = 0.0f;
  67687. while (maxWidth > originalW / 2)
  67688. {
  67689. layout (maxWidth, justification, false);
  67690. if (getNumLines() <= 1)
  67691. return;
  67692. const int lastLineW = getLineWidth (getNumLines() - 1);
  67693. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  67694. const float prop = lastLineW / (float) lastButOneLineW;
  67695. if (prop > 0.9f)
  67696. return;
  67697. if (prop > bestLineProportion)
  67698. {
  67699. bestLineProportion = prop;
  67700. bestWidth = maxWidth;
  67701. }
  67702. maxWidth -= 10;
  67703. }
  67704. layout (bestWidth, justification, false);
  67705. }
  67706. else
  67707. {
  67708. int x = 0;
  67709. int y = 0;
  67710. int h = 0;
  67711. totalLines = 0;
  67712. int i;
  67713. for (i = 0; i < tokens.size(); ++i)
  67714. {
  67715. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  67716. t->x = x;
  67717. t->y = y;
  67718. t->line = totalLines;
  67719. x += t->w;
  67720. h = jmax (h, t->h);
  67721. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  67722. if (nextTok == 0)
  67723. break;
  67724. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  67725. {
  67726. // finished a line, so go back and update the heights of the things on it
  67727. for (int j = i; j >= 0; --j)
  67728. {
  67729. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  67730. if (tok->line == totalLines)
  67731. tok->lineHeight = h;
  67732. else
  67733. break;
  67734. }
  67735. x = 0;
  67736. y += h;
  67737. h = 0;
  67738. ++totalLines;
  67739. }
  67740. }
  67741. // finished a line, so go back and update the heights of the things on it
  67742. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  67743. {
  67744. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  67745. if (t->line == totalLines)
  67746. t->lineHeight = h;
  67747. else
  67748. break;
  67749. }
  67750. ++totalLines;
  67751. if (! justification.testFlags (Justification::left))
  67752. {
  67753. int totalW = getWidth();
  67754. for (i = totalLines; --i >= 0;)
  67755. {
  67756. const int lineW = getLineWidth (i);
  67757. int dx = 0;
  67758. if (justification.testFlags (Justification::horizontallyCentred))
  67759. dx = (totalW - lineW) / 2;
  67760. else if (justification.testFlags (Justification::right))
  67761. dx = totalW - lineW;
  67762. for (int j = tokens.size(); --j >= 0;)
  67763. {
  67764. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  67765. if (t->line == i)
  67766. t->x += dx;
  67767. }
  67768. }
  67769. }
  67770. }
  67771. }
  67772. int TextLayout::getLineWidth (const int lineNumber) const throw()
  67773. {
  67774. int maxW = 0;
  67775. for (int i = tokens.size(); --i >= 0;)
  67776. {
  67777. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  67778. if (t->line == lineNumber && ! t->isWhitespace)
  67779. maxW = jmax (maxW, t->x + t->w);
  67780. }
  67781. return maxW;
  67782. }
  67783. int TextLayout::getWidth() const throw()
  67784. {
  67785. int maxW = 0;
  67786. for (int i = tokens.size(); --i >= 0;)
  67787. {
  67788. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  67789. if (! t->isWhitespace)
  67790. maxW = jmax (maxW, t->x + t->w);
  67791. }
  67792. return maxW;
  67793. }
  67794. int TextLayout::getHeight() const throw()
  67795. {
  67796. int maxH = 0;
  67797. for (int i = tokens.size(); --i >= 0;)
  67798. {
  67799. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  67800. if (! t->isWhitespace)
  67801. maxH = jmax (maxH, t->y + t->h);
  67802. }
  67803. return maxH;
  67804. }
  67805. void TextLayout::draw (Graphics& g,
  67806. const int xOffset,
  67807. const int yOffset) const throw()
  67808. {
  67809. for (int i = tokens.size(); --i >= 0;)
  67810. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  67811. }
  67812. void TextLayout::drawWithin (Graphics& g,
  67813. int x, int y, int w, int h,
  67814. const Justification& justification) const throw()
  67815. {
  67816. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  67817. x, y, w, h);
  67818. draw (g, x, y);
  67819. }
  67820. END_JUCE_NAMESPACE
  67821. /********* End of inlined file: juce_TextLayout.cpp *********/
  67822. /********* Start of inlined file: juce_Typeface.cpp *********/
  67823. BEGIN_JUCE_NAMESPACE
  67824. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  67825. const Path& shape,
  67826. const float horizontalSeparation,
  67827. Typeface* const typeface_) throw()
  67828. : character (character_),
  67829. path (shape),
  67830. width (horizontalSeparation),
  67831. typeface (typeface_)
  67832. {
  67833. }
  67834. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  67835. {
  67836. }
  67837. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  67838. {
  67839. if (subsequentCharacter != 0)
  67840. {
  67841. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  67842. const int numPairs = getNumKerningPairs();
  67843. for (int i = 0; i < numPairs; ++i)
  67844. if (pairs [i].character2 == subsequentCharacter)
  67845. return width + pairs [i].kerningAmount;
  67846. }
  67847. return width;
  67848. }
  67849. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  67850. const float extraKerningAmount) throw()
  67851. {
  67852. const int numPairs = getNumKerningPairs();
  67853. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  67854. KerningPair& p = getKerningPair (numPairs);
  67855. p.character2 = subsequentCharacter;
  67856. p.kerningAmount = extraKerningAmount;
  67857. }
  67858. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  67859. {
  67860. return ((KerningPair*) kerningPairs.getData()) [index];
  67861. }
  67862. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  67863. {
  67864. return kerningPairs.getSize() / sizeof (KerningPair);
  67865. }
  67866. const tchar* Typeface::defaultTypefaceNameSans = T("<Sans-Serif>");
  67867. const tchar* Typeface::defaultTypefaceNameSerif = T("<Serif>");
  67868. const tchar* Typeface::defaultTypefaceNameMono = T("<Monospaced>");
  67869. Typeface::Typeface() throw()
  67870. : hash (0),
  67871. isFullyPopulated (false)
  67872. {
  67873. zeromem (lookupTable, sizeof (lookupTable));
  67874. }
  67875. Typeface::Typeface (const Typeface& other)
  67876. : typefaceName (other.typefaceName),
  67877. ascent (other.ascent),
  67878. bold (other.bold),
  67879. italic (other.italic),
  67880. isFullyPopulated (other.isFullyPopulated),
  67881. defaultCharacter (other.defaultCharacter)
  67882. {
  67883. zeromem (lookupTable, sizeof (lookupTable));
  67884. for (int i = 0; i < other.glyphs.size(); ++i)
  67885. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  67886. updateHashCode();
  67887. }
  67888. Typeface::Typeface (const String& faceName,
  67889. const bool bold,
  67890. const bool italic)
  67891. : isFullyPopulated (false)
  67892. {
  67893. zeromem (lookupTable, sizeof (lookupTable));
  67894. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  67895. updateHashCode();
  67896. }
  67897. Typeface::~Typeface()
  67898. {
  67899. clear();
  67900. }
  67901. const Typeface& Typeface::operator= (const Typeface& other) throw()
  67902. {
  67903. if (this != &other)
  67904. {
  67905. clear();
  67906. typefaceName = other.typefaceName;
  67907. ascent = other.ascent;
  67908. bold = other.bold;
  67909. italic = other.italic;
  67910. isFullyPopulated = other.isFullyPopulated;
  67911. defaultCharacter = other.defaultCharacter;
  67912. for (int i = 0; i < other.glyphs.size(); ++i)
  67913. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  67914. updateHashCode();
  67915. }
  67916. return *this;
  67917. }
  67918. void Typeface::updateHashCode() throw()
  67919. {
  67920. hash = typefaceName.hashCode();
  67921. if (bold)
  67922. hash ^= 0xffff;
  67923. if (italic)
  67924. hash ^= 0xffff0000;
  67925. }
  67926. void Typeface::clear() throw()
  67927. {
  67928. zeromem (lookupTable, sizeof (lookupTable));
  67929. typefaceName = String::empty;
  67930. bold = false;
  67931. italic = false;
  67932. for (int i = glyphs.size(); --i >= 0;)
  67933. {
  67934. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  67935. delete g;
  67936. }
  67937. glyphs.clear();
  67938. updateHashCode();
  67939. }
  67940. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  67941. {
  67942. zeromem (lookupTable, sizeof (lookupTable));
  67943. isFullyPopulated = true;
  67944. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  67945. BufferedInputStream in (&gzin, 32768, false);
  67946. typefaceName = in.readString();
  67947. bold = in.readBool();
  67948. italic = in.readBool();
  67949. ascent = in.readFloat();
  67950. defaultCharacter = (juce_wchar) in.readShort();
  67951. int i, numChars = in.readInt();
  67952. for (i = 0; i < numChars; ++i)
  67953. {
  67954. const juce_wchar c = (juce_wchar) in.readShort();
  67955. const float width = in.readFloat();
  67956. Path p;
  67957. p.loadPathFromStream (in);
  67958. addGlyph (c, p, width);
  67959. }
  67960. const int numKerningPairs = in.readInt();
  67961. for (i = 0; i < numKerningPairs; ++i)
  67962. {
  67963. const juce_wchar char1 = (juce_wchar) in.readShort();
  67964. const juce_wchar char2 = (juce_wchar) in.readShort();
  67965. addKerningPair (char1, char2, in.readFloat());
  67966. }
  67967. updateHashCode();
  67968. }
  67969. void Typeface::serialise (OutputStream& outputStream)
  67970. {
  67971. GZIPCompressorOutputStream out (&outputStream);
  67972. out.writeString (typefaceName);
  67973. out.writeBool (bold);
  67974. out.writeBool (italic);
  67975. out.writeFloat (ascent);
  67976. out.writeShort ((short) (unsigned short) defaultCharacter);
  67977. out.writeInt (glyphs.size());
  67978. int i, numKerningPairs = 0;
  67979. for (i = 0; i < glyphs.size(); ++i)
  67980. {
  67981. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  67982. out.writeShort ((short) (unsigned short) g.character);
  67983. out.writeFloat (g.width);
  67984. g.path.writePathToStream (out);
  67985. numKerningPairs += g.getNumKerningPairs();
  67986. }
  67987. out.writeInt (numKerningPairs);
  67988. for (i = 0; i < glyphs.size(); ++i)
  67989. {
  67990. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  67991. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  67992. {
  67993. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  67994. out.writeShort ((short) (unsigned short) g.character);
  67995. out.writeShort ((short) (unsigned short) p.character2);
  67996. out.writeFloat (p.kerningAmount);
  67997. }
  67998. }
  67999. }
  68000. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  68001. {
  68002. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  68003. if (g != 0)
  68004. return &(g->path);
  68005. else
  68006. return 0;
  68007. }
  68008. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  68009. {
  68010. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  68011. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68012. for (int i = 0; i < glyphs.size(); ++i)
  68013. {
  68014. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68015. if (g->character == character)
  68016. return g;
  68017. }
  68018. if ((! isFullyPopulated)
  68019. && findAndAddSystemGlyph (character))
  68020. {
  68021. for (int i = 0; i < glyphs.size(); ++i)
  68022. {
  68023. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68024. if (g->character == character)
  68025. return g;
  68026. }
  68027. }
  68028. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  68029. {
  68030. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  68031. if (spaceGlyph != 0)
  68032. {
  68033. // Add a copy of the empty glyph, mapped onto this character
  68034. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  68035. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68036. }
  68037. return spaceGlyph;
  68038. }
  68039. else if (character != defaultCharacter)
  68040. {
  68041. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  68042. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  68043. if (fallbackTypeface != 0 && fallbackTypeface != this)
  68044. return fallbackTypeface->getGlyph (character);
  68045. return getGlyph (defaultCharacter);
  68046. }
  68047. return 0;
  68048. }
  68049. void Typeface::addGlyph (const juce_wchar character,
  68050. const Path& path,
  68051. const float horizontalSpacing) throw()
  68052. {
  68053. #ifdef JUCE_DEBUG
  68054. for (int i = 0; i < glyphs.size(); ++i)
  68055. {
  68056. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68057. if (g->character == character)
  68058. jassertfalse;
  68059. }
  68060. #endif
  68061. if (((unsigned int) character) < 128)
  68062. lookupTable [character] = (short) glyphs.size();
  68063. glyphs.add (new TypefaceGlyphInfo (character,
  68064. path,
  68065. horizontalSpacing,
  68066. this));
  68067. }
  68068. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  68069. {
  68070. if (glyphInfoToCopy != 0)
  68071. {
  68072. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  68073. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  68074. TypefaceGlyphInfo* const newOne
  68075. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  68076. glyphInfoToCopy->path,
  68077. glyphInfoToCopy->width,
  68078. this);
  68079. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  68080. glyphs.add (newOne);
  68081. }
  68082. }
  68083. void Typeface::addKerningPair (const juce_wchar char1,
  68084. const juce_wchar char2,
  68085. const float extraAmount) throw()
  68086. {
  68087. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  68088. if (g != 0)
  68089. g->addKerningPair (char2, extraAmount);
  68090. }
  68091. void Typeface::setName (const String& name) throw()
  68092. {
  68093. typefaceName = name;
  68094. updateHashCode();
  68095. }
  68096. void Typeface::setAscent (const float newAscent) throw()
  68097. {
  68098. ascent = newAscent;
  68099. }
  68100. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  68101. {
  68102. defaultCharacter = newDefaultCharacter;
  68103. }
  68104. void Typeface::setBold (const bool shouldBeBold) throw()
  68105. {
  68106. bold = shouldBeBold;
  68107. updateHashCode();
  68108. }
  68109. void Typeface::setItalic (const bool shouldBeItalic) throw()
  68110. {
  68111. italic = shouldBeItalic;
  68112. updateHashCode();
  68113. }
  68114. class TypefaceCache;
  68115. static TypefaceCache* typefaceCacheInstance = 0;
  68116. void clearUpDefaultFontNames() throw(); // in juce_LookAndFeel.cpp
  68117. class TypefaceCache : private DeletedAtShutdown
  68118. {
  68119. private:
  68120. struct CachedFace
  68121. {
  68122. CachedFace() throw()
  68123. : lastUsageCount (0),
  68124. flags (0)
  68125. {
  68126. }
  68127. String typefaceName;
  68128. int lastUsageCount;
  68129. int flags;
  68130. Typeface::Ptr typeFace;
  68131. };
  68132. int counter;
  68133. OwnedArray <CachedFace> faces;
  68134. TypefaceCache (const TypefaceCache&);
  68135. const TypefaceCache& operator= (const TypefaceCache&);
  68136. public:
  68137. TypefaceCache (int numToCache = 10)
  68138. : counter (1),
  68139. faces (2)
  68140. {
  68141. while (--numToCache >= 0)
  68142. {
  68143. CachedFace* const face = new CachedFace();
  68144. face->typeFace = new Typeface();
  68145. faces.add (face);
  68146. }
  68147. }
  68148. ~TypefaceCache()
  68149. {
  68150. faces.clear();
  68151. jassert (typefaceCacheInstance == this);
  68152. typefaceCacheInstance = 0;
  68153. clearUpDefaultFontNames();
  68154. }
  68155. static TypefaceCache* getInstance() throw()
  68156. {
  68157. if (typefaceCacheInstance == 0)
  68158. typefaceCacheInstance = new TypefaceCache();
  68159. return typefaceCacheInstance;
  68160. }
  68161. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  68162. {
  68163. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  68164. int i;
  68165. for (i = faces.size(); --i >= 0;)
  68166. {
  68167. CachedFace* const face = faces.getUnchecked(i);
  68168. if (face->flags == flags
  68169. && face->typefaceName == font.getTypefaceName())
  68170. {
  68171. face->lastUsageCount = ++counter;
  68172. return face->typeFace;
  68173. }
  68174. }
  68175. int replaceIndex = 0;
  68176. int bestLastUsageCount = INT_MAX;
  68177. for (i = faces.size(); --i >= 0;)
  68178. {
  68179. const int lu = faces.getUnchecked(i)->lastUsageCount;
  68180. if (bestLastUsageCount > lu)
  68181. {
  68182. bestLastUsageCount = lu;
  68183. replaceIndex = i;
  68184. }
  68185. }
  68186. CachedFace* const face = faces.getUnchecked (replaceIndex);
  68187. face->typefaceName = font.getTypefaceName();
  68188. face->flags = flags;
  68189. face->lastUsageCount = ++counter;
  68190. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  68191. return face->typeFace;
  68192. }
  68193. };
  68194. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  68195. {
  68196. return TypefaceCache::getInstance()->findTypefaceFor (font);
  68197. }
  68198. END_JUCE_NAMESPACE
  68199. /********* End of inlined file: juce_Typeface.cpp *********/
  68200. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  68201. BEGIN_JUCE_NAMESPACE
  68202. AffineTransform::AffineTransform() throw()
  68203. : mat00 (1.0f),
  68204. mat01 (0),
  68205. mat02 (0),
  68206. mat10 (0),
  68207. mat11 (1.0f),
  68208. mat12 (0)
  68209. {
  68210. }
  68211. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  68212. : mat00 (other.mat00),
  68213. mat01 (other.mat01),
  68214. mat02 (other.mat02),
  68215. mat10 (other.mat10),
  68216. mat11 (other.mat11),
  68217. mat12 (other.mat12)
  68218. {
  68219. }
  68220. AffineTransform::AffineTransform (const float mat00_,
  68221. const float mat01_,
  68222. const float mat02_,
  68223. const float mat10_,
  68224. const float mat11_,
  68225. const float mat12_) throw()
  68226. : mat00 (mat00_),
  68227. mat01 (mat01_),
  68228. mat02 (mat02_),
  68229. mat10 (mat10_),
  68230. mat11 (mat11_),
  68231. mat12 (mat12_)
  68232. {
  68233. }
  68234. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  68235. {
  68236. mat00 = other.mat00;
  68237. mat01 = other.mat01;
  68238. mat02 = other.mat02;
  68239. mat10 = other.mat10;
  68240. mat11 = other.mat11;
  68241. mat12 = other.mat12;
  68242. return *this;
  68243. }
  68244. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  68245. {
  68246. return mat00 == other.mat00
  68247. && mat01 == other.mat01
  68248. && mat02 == other.mat02
  68249. && mat10 == other.mat10
  68250. && mat11 == other.mat11
  68251. && mat12 == other.mat12;
  68252. }
  68253. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  68254. {
  68255. return ! operator== (other);
  68256. }
  68257. bool AffineTransform::isIdentity() const throw()
  68258. {
  68259. return (mat01 == 0)
  68260. && (mat02 == 0)
  68261. && (mat10 == 0)
  68262. && (mat12 == 0)
  68263. && (mat00 == 1.0f)
  68264. && (mat11 == 1.0f);
  68265. }
  68266. const AffineTransform AffineTransform::identity;
  68267. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  68268. {
  68269. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  68270. other.mat00 * mat01 + other.mat01 * mat11,
  68271. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  68272. other.mat10 * mat00 + other.mat11 * mat10,
  68273. other.mat10 * mat01 + other.mat11 * mat11,
  68274. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  68275. }
  68276. const AffineTransform AffineTransform::followedBy (const float omat00,
  68277. const float omat01,
  68278. const float omat02,
  68279. const float omat10,
  68280. const float omat11,
  68281. const float omat12) const throw()
  68282. {
  68283. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  68284. omat00 * mat01 + omat01 * mat11,
  68285. omat00 * mat02 + omat01 * mat12 + omat02,
  68286. omat10 * mat00 + omat11 * mat10,
  68287. omat10 * mat01 + omat11 * mat11,
  68288. omat10 * mat02 + omat11 * mat12 + omat12);
  68289. }
  68290. const AffineTransform AffineTransform::translated (const float dx,
  68291. const float dy) const throw()
  68292. {
  68293. return followedBy (1.0f, 0, dx,
  68294. 0, 1.0f, dy);
  68295. }
  68296. const AffineTransform AffineTransform::translation (const float dx,
  68297. const float dy) throw()
  68298. {
  68299. return AffineTransform (1.0f, 0, dx,
  68300. 0, 1.0f, dy);
  68301. }
  68302. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  68303. {
  68304. const float cosRad = cosf (rad);
  68305. const float sinRad = sinf (rad);
  68306. return followedBy (cosRad, -sinRad, 0,
  68307. sinRad, cosRad, 0);
  68308. }
  68309. const AffineTransform AffineTransform::rotation (const float rad) throw()
  68310. {
  68311. const float cosRad = cosf (rad);
  68312. const float sinRad = sinf (rad);
  68313. return AffineTransform (cosRad, -sinRad, 0,
  68314. sinRad, cosRad, 0);
  68315. }
  68316. const AffineTransform AffineTransform::rotated (const float angle,
  68317. const float pivotX,
  68318. const float pivotY) const throw()
  68319. {
  68320. return translated (-pivotX, -pivotY)
  68321. .rotated (angle)
  68322. .translated (pivotX, pivotY);
  68323. }
  68324. const AffineTransform AffineTransform::rotation (const float angle,
  68325. const float pivotX,
  68326. const float pivotY) throw()
  68327. {
  68328. return translation (-pivotX, -pivotY)
  68329. .rotated (angle)
  68330. .translated (pivotX, pivotY);
  68331. }
  68332. const AffineTransform AffineTransform::scaled (const float factorX,
  68333. const float factorY) const throw()
  68334. {
  68335. return followedBy (factorX, 0, 0,
  68336. 0, factorY, 0);
  68337. }
  68338. const AffineTransform AffineTransform::scale (const float factorX,
  68339. const float factorY) throw()
  68340. {
  68341. return AffineTransform (factorX, 0, 0,
  68342. 0, factorY, 0);
  68343. }
  68344. const AffineTransform AffineTransform::sheared (const float shearX,
  68345. const float shearY) const throw()
  68346. {
  68347. return followedBy (1.0f, shearX, 0,
  68348. shearY, 1.0f, 0);
  68349. }
  68350. const AffineTransform AffineTransform::inverted() const throw()
  68351. {
  68352. double determinant = (mat00 * mat11 - mat10 * mat01);
  68353. if (determinant != 0.0)
  68354. {
  68355. determinant = 1.0 / determinant;
  68356. const float dst00 = (float) (mat11 * determinant);
  68357. const float dst10 = (float) (-mat10 * determinant);
  68358. const float dst01 = (float) (-mat01 * determinant);
  68359. const float dst11 = (float) (mat00 * determinant);
  68360. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  68361. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  68362. }
  68363. else
  68364. {
  68365. // singularity..
  68366. return *this;
  68367. }
  68368. }
  68369. bool AffineTransform::isSingularity() const throw()
  68370. {
  68371. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  68372. }
  68373. void AffineTransform::transformPoint (float& x,
  68374. float& y) const throw()
  68375. {
  68376. const float oldX = x;
  68377. x = mat00 * oldX + mat01 * y + mat02;
  68378. y = mat10 * oldX + mat11 * y + mat12;
  68379. }
  68380. void AffineTransform::transformPoint (double& x,
  68381. double& y) const throw()
  68382. {
  68383. const double oldX = x;
  68384. x = mat00 * oldX + mat01 * y + mat02;
  68385. y = mat10 * oldX + mat11 * y + mat12;
  68386. }
  68387. END_JUCE_NAMESPACE
  68388. /********* End of inlined file: juce_AffineTransform.cpp *********/
  68389. /********* Start of inlined file: juce_BorderSize.cpp *********/
  68390. BEGIN_JUCE_NAMESPACE
  68391. BorderSize::BorderSize() throw()
  68392. : top (0),
  68393. left (0),
  68394. bottom (0),
  68395. right (0)
  68396. {
  68397. }
  68398. BorderSize::BorderSize (const BorderSize& other) throw()
  68399. : top (other.top),
  68400. left (other.left),
  68401. bottom (other.bottom),
  68402. right (other.right)
  68403. {
  68404. }
  68405. BorderSize::BorderSize (const int topGap,
  68406. const int leftGap,
  68407. const int bottomGap,
  68408. const int rightGap) throw()
  68409. : top (topGap),
  68410. left (leftGap),
  68411. bottom (bottomGap),
  68412. right (rightGap)
  68413. {
  68414. }
  68415. BorderSize::BorderSize (const int allGaps) throw()
  68416. : top (allGaps),
  68417. left (allGaps),
  68418. bottom (allGaps),
  68419. right (allGaps)
  68420. {
  68421. }
  68422. BorderSize::~BorderSize() throw()
  68423. {
  68424. }
  68425. void BorderSize::setTop (const int newTopGap) throw()
  68426. {
  68427. top = newTopGap;
  68428. }
  68429. void BorderSize::setLeft (const int newLeftGap) throw()
  68430. {
  68431. left = newLeftGap;
  68432. }
  68433. void BorderSize::setBottom (const int newBottomGap) throw()
  68434. {
  68435. bottom = newBottomGap;
  68436. }
  68437. void BorderSize::setRight (const int newRightGap) throw()
  68438. {
  68439. right = newRightGap;
  68440. }
  68441. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  68442. {
  68443. return Rectangle (r.getX() + left,
  68444. r.getY() + top,
  68445. r.getWidth() - (left + right),
  68446. r.getHeight() - (top + bottom));
  68447. }
  68448. void BorderSize::subtractFrom (Rectangle& r) const throw()
  68449. {
  68450. r.setBounds (r.getX() + left,
  68451. r.getY() + top,
  68452. r.getWidth() - (left + right),
  68453. r.getHeight() - (top + bottom));
  68454. }
  68455. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  68456. {
  68457. return Rectangle (r.getX() - left,
  68458. r.getY() - top,
  68459. r.getWidth() + (left + right),
  68460. r.getHeight() + (top + bottom));
  68461. }
  68462. void BorderSize::addTo (Rectangle& r) const throw()
  68463. {
  68464. r.setBounds (r.getX() - left,
  68465. r.getY() - top,
  68466. r.getWidth() + (left + right),
  68467. r.getHeight() + (top + bottom));
  68468. }
  68469. bool BorderSize::operator== (const BorderSize& other) const throw()
  68470. {
  68471. return top == other.top
  68472. && left == other.left
  68473. && bottom == other.bottom
  68474. && right == other.right;
  68475. }
  68476. bool BorderSize::operator!= (const BorderSize& other) const throw()
  68477. {
  68478. return ! operator== (other);
  68479. }
  68480. END_JUCE_NAMESPACE
  68481. /********* End of inlined file: juce_BorderSize.cpp *********/
  68482. /********* Start of inlined file: juce_Line.cpp *********/
  68483. BEGIN_JUCE_NAMESPACE
  68484. static bool juce_lineIntersection (const float x1, const float y1,
  68485. const float x2, const float y2,
  68486. const float x3, const float y3,
  68487. const float x4, const float y4,
  68488. float& intersectionX,
  68489. float& intersectionY) throw()
  68490. {
  68491. if (x2 != x3 || y2 != y3)
  68492. {
  68493. const float dx1 = x2 - x1;
  68494. const float dy1 = y2 - y1;
  68495. const float dx2 = x4 - x3;
  68496. const float dy2 = y4 - y3;
  68497. const float divisor = dx1 * dy2 - dx2 * dy1;
  68498. if (divisor == 0)
  68499. {
  68500. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  68501. {
  68502. if (dy1 == 0 && dy2 != 0)
  68503. {
  68504. const float along = (y1 - y3) / dy2;
  68505. intersectionX = x3 + along * dx2;
  68506. intersectionY = y1;
  68507. return along >= 0 && along <= 1.0f;
  68508. }
  68509. else if (dy2 == 0 && dy1 != 0)
  68510. {
  68511. const float along = (y3 - y1) / dy1;
  68512. intersectionX = x1 + along * dx1;
  68513. intersectionY = y3;
  68514. return along >= 0 && along <= 1.0f;
  68515. }
  68516. else if (dx1 == 0 && dx2 != 0)
  68517. {
  68518. const float along = (x1 - x3) / dx2;
  68519. intersectionX = x1;
  68520. intersectionY = y3 + along * dy2;
  68521. return along >= 0 && along <= 1.0f;
  68522. }
  68523. else if (dx2 == 0 && dx1 != 0)
  68524. {
  68525. const float along = (x3 - x1) / dx1;
  68526. intersectionX = x3;
  68527. intersectionY = y1 + along * dy1;
  68528. return along >= 0 && along <= 1.0f;
  68529. }
  68530. }
  68531. intersectionX = 0.5f * (x2 + x3);
  68532. intersectionY = 0.5f * (y2 + y3);
  68533. return false;
  68534. }
  68535. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  68536. intersectionX = x1 + along1 * dx1;
  68537. intersectionY = y1 + along1 * dy1;
  68538. if (along1 < 0 || along1 > 1.0f)
  68539. return false;
  68540. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  68541. return along2 >= 0 && along2 <= 1.0f;
  68542. }
  68543. intersectionX = x2;
  68544. intersectionY = y2;
  68545. return true;
  68546. }
  68547. Line::Line() throw()
  68548. : startX (0.0f),
  68549. startY (0.0f),
  68550. endX (0.0f),
  68551. endY (0.0f)
  68552. {
  68553. }
  68554. Line::Line (const Line& other) throw()
  68555. : startX (other.startX),
  68556. startY (other.startY),
  68557. endX (other.endX),
  68558. endY (other.endY)
  68559. {
  68560. }
  68561. Line::Line (const float startX_, const float startY_,
  68562. const float endX_, const float endY_) throw()
  68563. : startX (startX_),
  68564. startY (startY_),
  68565. endX (endX_),
  68566. endY (endY_)
  68567. {
  68568. }
  68569. Line::Line (const Point& start,
  68570. const Point& end) throw()
  68571. : startX (start.getX()),
  68572. startY (start.getY()),
  68573. endX (end.getX()),
  68574. endY (end.getY())
  68575. {
  68576. }
  68577. const Line& Line::operator= (const Line& other) throw()
  68578. {
  68579. startX = other.startX;
  68580. startY = other.startY;
  68581. endX = other.endX;
  68582. endY = other.endY;
  68583. return *this;
  68584. }
  68585. Line::~Line() throw()
  68586. {
  68587. }
  68588. const Point Line::getStart() const throw()
  68589. {
  68590. return Point (startX, startY);
  68591. }
  68592. const Point Line::getEnd() const throw()
  68593. {
  68594. return Point (endX, endY);
  68595. }
  68596. void Line::setStart (const float newStartX,
  68597. const float newStartY) throw()
  68598. {
  68599. startX = newStartX;
  68600. startY = newStartY;
  68601. }
  68602. void Line::setStart (const Point& newStart) throw()
  68603. {
  68604. startX = newStart.getX();
  68605. startY = newStart.getY();
  68606. }
  68607. void Line::setEnd (const float newEndX,
  68608. const float newEndY) throw()
  68609. {
  68610. endX = newEndX;
  68611. endY = newEndY;
  68612. }
  68613. void Line::setEnd (const Point& newEnd) throw()
  68614. {
  68615. endX = newEnd.getX();
  68616. endY = newEnd.getY();
  68617. }
  68618. bool Line::operator== (const Line& other) const throw()
  68619. {
  68620. return startX == other.startX
  68621. && startY == other.startY
  68622. && endX == other.endX
  68623. && endY == other.endY;
  68624. }
  68625. bool Line::operator!= (const Line& other) const throw()
  68626. {
  68627. return startX != other.startX
  68628. || startY != other.startY
  68629. || endX != other.endX
  68630. || endY != other.endY;
  68631. }
  68632. void Line::applyTransform (const AffineTransform& transform) throw()
  68633. {
  68634. transform.transformPoint (startX, startY);
  68635. transform.transformPoint (endX, endY);
  68636. }
  68637. float Line::getLength() const throw()
  68638. {
  68639. return (float) juce_hypot (startX - endX,
  68640. startY - endY);
  68641. }
  68642. float Line::getAngle() const throw()
  68643. {
  68644. return atan2f (endX - startX,
  68645. endY - startY);
  68646. }
  68647. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  68648. {
  68649. const float alpha = distanceFromStart / getLength();
  68650. return Point (startX + (endX - startX) * alpha,
  68651. startY + (endY - startY) * alpha);
  68652. }
  68653. const Point Line::getPointAlongLine (const float offsetX,
  68654. const float offsetY) const throw()
  68655. {
  68656. const float dx = endX - startX;
  68657. const float dy = endY - startY;
  68658. const double length = juce_hypot (dx, dy);
  68659. if (length == 0)
  68660. return Point (startX, startY);
  68661. else
  68662. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  68663. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  68664. }
  68665. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  68666. {
  68667. return Point (startX + (endX - startX) * alpha,
  68668. startY + (endY - startY) * alpha);
  68669. }
  68670. float Line::getDistanceFromLine (const float x,
  68671. const float y) const throw()
  68672. {
  68673. const double dx = endX - startX;
  68674. const double dy = endY - startY;
  68675. const double length = dx * dx + dy * dy;
  68676. if (length > 0)
  68677. {
  68678. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  68679. if (prop >= 0.0f && prop < 1.0f)
  68680. {
  68681. return (float) juce_hypot (x - (startX + prop * dx),
  68682. y - (startY + prop * dy));
  68683. }
  68684. }
  68685. return (float) jmin (juce_hypot (x - startX, y - startY),
  68686. juce_hypot (x - endX, y - endY));
  68687. }
  68688. float Line::findNearestPointTo (const float x,
  68689. const float y) const throw()
  68690. {
  68691. const double dx = endX - startX;
  68692. const double dy = endY - startY;
  68693. const double length = dx * dx + dy * dy;
  68694. if (length <= 0.0)
  68695. return 0.0f;
  68696. return jlimit (0.0f, 1.0f,
  68697. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  68698. }
  68699. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  68700. {
  68701. const float length = getLength();
  68702. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  68703. getEnd());
  68704. }
  68705. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  68706. {
  68707. const float length = getLength();
  68708. return Line (getStart(),
  68709. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  68710. }
  68711. bool Line::clipToPath (const Path& path,
  68712. const bool keepSectionOutsidePath) throw()
  68713. {
  68714. const bool startInside = path.contains (startX, startY);
  68715. const bool endInside = path.contains (endX, endY);
  68716. if (startInside == endInside)
  68717. {
  68718. if (keepSectionOutsidePath != startInside)
  68719. {
  68720. // entirely outside the path
  68721. return false;
  68722. }
  68723. else
  68724. {
  68725. // entirely inside the path
  68726. startX = 0.0f;
  68727. startY = 0.0f;
  68728. endX = 0.0f;
  68729. endY = 0.0f;
  68730. return true;
  68731. }
  68732. }
  68733. else
  68734. {
  68735. bool changed = false;
  68736. PathFlatteningIterator iter (path, AffineTransform::identity);
  68737. while (iter.next())
  68738. {
  68739. float ix, iy;
  68740. if (intersects (Line (iter.x1, iter.y1,
  68741. iter.x2, iter.y2),
  68742. ix, iy))
  68743. {
  68744. if ((startInside && keepSectionOutsidePath)
  68745. || (endInside && ! keepSectionOutsidePath))
  68746. {
  68747. setStart (ix, iy);
  68748. }
  68749. else
  68750. {
  68751. setEnd (ix, iy);
  68752. }
  68753. changed = true;
  68754. }
  68755. }
  68756. return changed;
  68757. }
  68758. }
  68759. bool Line::intersects (const Line& line,
  68760. float& intersectionX,
  68761. float& intersectionY) const throw()
  68762. {
  68763. return juce_lineIntersection (startX, startY,
  68764. endX, endY,
  68765. line.startX, line.startY,
  68766. line.endX, line.endY,
  68767. intersectionX,
  68768. intersectionY);
  68769. }
  68770. bool Line::isVertical() const throw()
  68771. {
  68772. return startX == endX;
  68773. }
  68774. bool Line::isHorizontal() const throw()
  68775. {
  68776. return startY == endY;
  68777. }
  68778. bool Line::isPointAbove (const float x, const float y) const throw()
  68779. {
  68780. return startX != endX
  68781. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  68782. }
  68783. END_JUCE_NAMESPACE
  68784. /********* End of inlined file: juce_Line.cpp *********/
  68785. /********* Start of inlined file: juce_Path.cpp *********/
  68786. BEGIN_JUCE_NAMESPACE
  68787. // tests that some co-ords aren't NaNs
  68788. #define CHECK_COORDS_ARE_VALID(x, y) \
  68789. jassert (x == x && y == y);
  68790. const float Path::lineMarker = 100001.0f;
  68791. const float Path::moveMarker = 100002.0f;
  68792. const float Path::quadMarker = 100003.0f;
  68793. const float Path::cubicMarker = 100004.0f;
  68794. const float Path::closeSubPathMarker = 100005.0f;
  68795. static const int defaultGranularity = 32;
  68796. Path::Path() throw()
  68797. : ArrayAllocationBase <float> (defaultGranularity),
  68798. numElements (0),
  68799. pathXMin (0),
  68800. pathXMax (0),
  68801. pathYMin (0),
  68802. pathYMax (0),
  68803. useNonZeroWinding (true)
  68804. {
  68805. }
  68806. Path::~Path() throw()
  68807. {
  68808. }
  68809. Path::Path (const Path& other) throw()
  68810. : ArrayAllocationBase <float> (defaultGranularity),
  68811. numElements (other.numElements),
  68812. pathXMin (other.pathXMin),
  68813. pathXMax (other.pathXMax),
  68814. pathYMin (other.pathYMin),
  68815. pathYMax (other.pathYMax),
  68816. useNonZeroWinding (other.useNonZeroWinding)
  68817. {
  68818. if (numElements > 0)
  68819. {
  68820. setAllocatedSize (numElements);
  68821. memcpy (elements, other.elements, numElements * sizeof (float));
  68822. }
  68823. }
  68824. const Path& Path::operator= (const Path& other) throw()
  68825. {
  68826. if (this != &other)
  68827. {
  68828. ensureAllocatedSize (other.numElements);
  68829. numElements = other.numElements;
  68830. pathXMin = other.pathXMin;
  68831. pathXMax = other.pathXMax;
  68832. pathYMin = other.pathYMin;
  68833. pathYMax = other.pathYMax;
  68834. useNonZeroWinding = other.useNonZeroWinding;
  68835. if (numElements > 0)
  68836. memcpy (elements, other.elements, numElements * sizeof (float));
  68837. }
  68838. return *this;
  68839. }
  68840. void Path::clear() throw()
  68841. {
  68842. numElements = 0;
  68843. pathXMin = 0;
  68844. pathYMin = 0;
  68845. pathYMax = 0;
  68846. pathXMax = 0;
  68847. }
  68848. void Path::swapWithPath (Path& other)
  68849. {
  68850. swapVariables <int> (this->numAllocated, other.numAllocated);
  68851. swapVariables <float*> (this->elements, other.elements);
  68852. swapVariables <int> (this->numElements, other.numElements);
  68853. swapVariables <float> (this->pathXMin, other.pathXMin);
  68854. swapVariables <float> (this->pathXMax, other.pathXMax);
  68855. swapVariables <float> (this->pathYMin, other.pathYMin);
  68856. swapVariables <float> (this->pathYMax, other.pathYMax);
  68857. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  68858. }
  68859. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  68860. {
  68861. useNonZeroWinding = isNonZero;
  68862. }
  68863. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  68864. const bool preserveProportions) throw()
  68865. {
  68866. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  68867. }
  68868. bool Path::isEmpty() const throw()
  68869. {
  68870. int i = 0;
  68871. while (i < numElements)
  68872. {
  68873. const float type = elements [i++];
  68874. if (type == moveMarker)
  68875. {
  68876. i += 2;
  68877. }
  68878. else if (type == lineMarker
  68879. || type == quadMarker
  68880. || type == cubicMarker)
  68881. {
  68882. return false;
  68883. }
  68884. }
  68885. return true;
  68886. }
  68887. void Path::getBounds (float& x, float& y,
  68888. float& w, float& h) const throw()
  68889. {
  68890. x = pathXMin;
  68891. y = pathYMin;
  68892. w = pathXMax - pathXMin;
  68893. h = pathYMax - pathYMin;
  68894. }
  68895. void Path::getBoundsTransformed (const AffineTransform& transform,
  68896. float& x, float& y,
  68897. float& w, float& h) const throw()
  68898. {
  68899. float x1 = pathXMin;
  68900. float y1 = pathYMin;
  68901. transform.transformPoint (x1, y1);
  68902. float x2 = pathXMax;
  68903. float y2 = pathYMin;
  68904. transform.transformPoint (x2, y2);
  68905. float x3 = pathXMin;
  68906. float y3 = pathYMax;
  68907. transform.transformPoint (x3, y3);
  68908. float x4 = pathXMax;
  68909. float y4 = pathYMax;
  68910. transform.transformPoint (x4, y4);
  68911. x = jmin (x1, x2, x3, x4);
  68912. y = jmin (y1, y2, y3, y4);
  68913. w = jmax (x1, x2, x3, x4) - x;
  68914. h = jmax (y1, y2, y3, y4) - y;
  68915. }
  68916. void Path::startNewSubPath (const float x,
  68917. const float y) throw()
  68918. {
  68919. CHECK_COORDS_ARE_VALID (x, y);
  68920. if (numElements == 0)
  68921. {
  68922. pathXMin = pathXMax = x;
  68923. pathYMin = pathYMax = y;
  68924. }
  68925. else
  68926. {
  68927. pathXMin = jmin (pathXMin, x);
  68928. pathXMax = jmax (pathXMax, x);
  68929. pathYMin = jmin (pathYMin, y);
  68930. pathYMax = jmax (pathYMax, y);
  68931. }
  68932. ensureAllocatedSize (numElements + 3);
  68933. elements [numElements++] = moveMarker;
  68934. elements [numElements++] = x;
  68935. elements [numElements++] = y;
  68936. }
  68937. void Path::lineTo (const float x, const float y) throw()
  68938. {
  68939. CHECK_COORDS_ARE_VALID (x, y);
  68940. if (numElements == 0)
  68941. startNewSubPath (0, 0);
  68942. ensureAllocatedSize (numElements + 3);
  68943. elements [numElements++] = lineMarker;
  68944. elements [numElements++] = x;
  68945. elements [numElements++] = y;
  68946. pathXMin = jmin (pathXMin, x);
  68947. pathXMax = jmax (pathXMax, x);
  68948. pathYMin = jmin (pathYMin, y);
  68949. pathYMax = jmax (pathYMax, y);
  68950. }
  68951. void Path::quadraticTo (const float x1, const float y1,
  68952. const float x2, const float y2) throw()
  68953. {
  68954. CHECK_COORDS_ARE_VALID (x1, y1);
  68955. CHECK_COORDS_ARE_VALID (x2, y2);
  68956. if (numElements == 0)
  68957. startNewSubPath (0, 0);
  68958. ensureAllocatedSize (numElements + 5);
  68959. elements [numElements++] = quadMarker;
  68960. elements [numElements++] = x1;
  68961. elements [numElements++] = y1;
  68962. elements [numElements++] = x2;
  68963. elements [numElements++] = y2;
  68964. pathXMin = jmin (pathXMin, x1, x2);
  68965. pathXMax = jmax (pathXMax, x1, x2);
  68966. pathYMin = jmin (pathYMin, y1, y2);
  68967. pathYMax = jmax (pathYMax, y1, y2);
  68968. }
  68969. void Path::cubicTo (const float x1, const float y1,
  68970. const float x2, const float y2,
  68971. const float x3, const float y3) throw()
  68972. {
  68973. CHECK_COORDS_ARE_VALID (x1, y1);
  68974. CHECK_COORDS_ARE_VALID (x2, y2);
  68975. CHECK_COORDS_ARE_VALID (x3, y3);
  68976. if (numElements == 0)
  68977. startNewSubPath (0, 0);
  68978. ensureAllocatedSize (numElements + 7);
  68979. elements [numElements++] = cubicMarker;
  68980. elements [numElements++] = x1;
  68981. elements [numElements++] = y1;
  68982. elements [numElements++] = x2;
  68983. elements [numElements++] = y2;
  68984. elements [numElements++] = x3;
  68985. elements [numElements++] = y3;
  68986. pathXMin = jmin (pathXMin, x1, x2, x3);
  68987. pathXMax = jmax (pathXMax, x1, x2, x3);
  68988. pathYMin = jmin (pathYMin, y1, y2, y3);
  68989. pathYMax = jmax (pathYMax, y1, y2, y3);
  68990. }
  68991. void Path::closeSubPath() throw()
  68992. {
  68993. if (numElements > 0
  68994. && elements [numElements - 1] != closeSubPathMarker)
  68995. {
  68996. ensureAllocatedSize (numElements + 1);
  68997. elements [numElements++] = closeSubPathMarker;
  68998. }
  68999. }
  69000. const Point Path::getCurrentPosition() const
  69001. {
  69002. int i = numElements - 1;
  69003. if (i > 0 && elements[i] == closeSubPathMarker)
  69004. {
  69005. while (i >= 0)
  69006. {
  69007. if (elements[i] == moveMarker)
  69008. {
  69009. i += 2;
  69010. break;
  69011. }
  69012. --i;
  69013. }
  69014. }
  69015. if (i > 0)
  69016. return Point (elements [i - 1], elements [i]);
  69017. return Point (0.0f, 0.0f);
  69018. }
  69019. void Path::addRectangle (const float x, const float y,
  69020. const float w, const float h) throw()
  69021. {
  69022. startNewSubPath (x, y + h);
  69023. lineTo (x, y);
  69024. lineTo (x + w, y);
  69025. lineTo (x + w, y + h);
  69026. closeSubPath();
  69027. }
  69028. void Path::addRoundedRectangle (const float x, const float y,
  69029. const float w, const float h,
  69030. float csx,
  69031. float csy) throw()
  69032. {
  69033. csx = jmin (csx, w * 0.5f);
  69034. csy = jmin (csy, h * 0.5f);
  69035. const float cs45x = csx * 0.45f;
  69036. const float cs45y = csy * 0.45f;
  69037. const float x2 = x + w;
  69038. const float y2 = y + h;
  69039. startNewSubPath (x + csx, y);
  69040. lineTo (x2 - csx, y);
  69041. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  69042. lineTo (x2, y2 - csy);
  69043. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  69044. lineTo (x + csx, y2);
  69045. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  69046. lineTo (x, y + csy);
  69047. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  69048. closeSubPath();
  69049. }
  69050. void Path::addRoundedRectangle (const float x, const float y,
  69051. const float w, const float h,
  69052. float cs) throw()
  69053. {
  69054. addRoundedRectangle (x, y, w, h, cs, cs);
  69055. }
  69056. void Path::addTriangle (const float x1, const float y1,
  69057. const float x2, const float y2,
  69058. const float x3, const float y3) throw()
  69059. {
  69060. startNewSubPath (x1, y1);
  69061. lineTo (x2, y2);
  69062. lineTo (x3, y3);
  69063. closeSubPath();
  69064. }
  69065. void Path::addQuadrilateral (const float x1, const float y1,
  69066. const float x2, const float y2,
  69067. const float x3, const float y3,
  69068. const float x4, const float y4) throw()
  69069. {
  69070. startNewSubPath (x1, y1);
  69071. lineTo (x2, y2);
  69072. lineTo (x3, y3);
  69073. lineTo (x4, y4);
  69074. closeSubPath();
  69075. }
  69076. void Path::addEllipse (const float x, const float y,
  69077. const float w, const float h) throw()
  69078. {
  69079. const float hw = w * 0.5f;
  69080. const float hw55 = hw * 0.55f;
  69081. const float hh = h * 0.5f;
  69082. const float hh45 = hh * 0.55f;
  69083. const float cx = x + hw;
  69084. const float cy = y + hh;
  69085. startNewSubPath (cx, cy - hh);
  69086. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  69087. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  69088. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  69089. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  69090. closeSubPath();
  69091. }
  69092. void Path::addArc (const float x, const float y,
  69093. const float w, const float h,
  69094. const float fromRadians,
  69095. const float toRadians,
  69096. const bool startAsNewSubPath) throw()
  69097. {
  69098. const float radiusX = w / 2.0f;
  69099. const float radiusY = h / 2.0f;
  69100. addCentredArc (x + radiusX,
  69101. y + radiusY,
  69102. radiusX, radiusY,
  69103. 0.0f,
  69104. fromRadians, toRadians,
  69105. startAsNewSubPath);
  69106. }
  69107. static const float ellipseAngularIncrement = 0.05f;
  69108. void Path::addCentredArc (const float centreX, const float centreY,
  69109. const float radiusX, const float radiusY,
  69110. const float rotationOfEllipse,
  69111. const float fromRadians,
  69112. const float toRadians,
  69113. const bool startAsNewSubPath) throw()
  69114. {
  69115. if (radiusX > 0.0f && radiusY > 0.0f)
  69116. {
  69117. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  69118. float angle = fromRadians;
  69119. if (startAsNewSubPath)
  69120. {
  69121. float x = centreX + radiusX * sinf (angle);
  69122. float y = centreY - radiusY * cosf (angle);
  69123. if (rotationOfEllipse != 0)
  69124. rotation.transformPoint (x, y);
  69125. startNewSubPath (x, y);
  69126. }
  69127. if (fromRadians < toRadians)
  69128. {
  69129. if (startAsNewSubPath)
  69130. angle += ellipseAngularIncrement;
  69131. while (angle < toRadians)
  69132. {
  69133. float x = centreX + radiusX * sinf (angle);
  69134. float y = centreY - radiusY * cosf (angle);
  69135. if (rotationOfEllipse != 0)
  69136. rotation.transformPoint (x, y);
  69137. lineTo (x, y);
  69138. angle += ellipseAngularIncrement;
  69139. }
  69140. }
  69141. else
  69142. {
  69143. if (startAsNewSubPath)
  69144. angle -= ellipseAngularIncrement;
  69145. while (angle > toRadians)
  69146. {
  69147. float x = centreX + radiusX * sinf (angle);
  69148. float y = centreY - radiusY * cosf (angle);
  69149. if (rotationOfEllipse != 0)
  69150. rotation.transformPoint (x, y);
  69151. lineTo (x, y);
  69152. angle -= ellipseAngularIncrement;
  69153. }
  69154. }
  69155. float x = centreX + radiusX * sinf (toRadians);
  69156. float y = centreY - radiusY * cosf (toRadians);
  69157. if (rotationOfEllipse != 0)
  69158. rotation.transformPoint (x, y);
  69159. lineTo (x, y);
  69160. }
  69161. }
  69162. void Path::addPieSegment (const float x, const float y,
  69163. const float width, const float height,
  69164. const float fromRadians,
  69165. const float toRadians,
  69166. const float innerCircleProportionalSize)
  69167. {
  69168. float hw = width * 0.5f;
  69169. float hh = height * 0.5f;
  69170. const float centreX = x + hw;
  69171. const float centreY = y + hh;
  69172. startNewSubPath (centreX + hw * sinf (fromRadians),
  69173. centreY - hh * cosf (fromRadians));
  69174. addArc (x, y, width, height, fromRadians, toRadians);
  69175. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  69176. {
  69177. closeSubPath();
  69178. if (innerCircleProportionalSize > 0)
  69179. {
  69180. hw *= innerCircleProportionalSize;
  69181. hh *= innerCircleProportionalSize;
  69182. startNewSubPath (centreX + hw * sinf (toRadians),
  69183. centreY - hh * cosf (toRadians));
  69184. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69185. toRadians, fromRadians);
  69186. }
  69187. }
  69188. else
  69189. {
  69190. if (innerCircleProportionalSize > 0)
  69191. {
  69192. hw *= innerCircleProportionalSize;
  69193. hh *= innerCircleProportionalSize;
  69194. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69195. toRadians, fromRadians);
  69196. }
  69197. else
  69198. {
  69199. lineTo (centreX, centreY);
  69200. }
  69201. }
  69202. closeSubPath();
  69203. }
  69204. static void perpendicularOffset (const float x1, const float y1,
  69205. const float x2, const float y2,
  69206. const float offsetX, const float offsetY,
  69207. float& resultX, float& resultY) throw()
  69208. {
  69209. const float dx = x2 - x1;
  69210. const float dy = y2 - y1;
  69211. const float len = juce_hypotf (dx, dy);
  69212. if (len == 0)
  69213. {
  69214. resultX = x1;
  69215. resultY = y1;
  69216. }
  69217. else
  69218. {
  69219. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  69220. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  69221. }
  69222. }
  69223. void Path::addLineSegment (const float startX, const float startY,
  69224. const float endX, const float endY,
  69225. float lineThickness) throw()
  69226. {
  69227. lineThickness *= 0.5f;
  69228. float x, y;
  69229. perpendicularOffset (startX, startY, endX, endY,
  69230. 0, lineThickness, x, y);
  69231. startNewSubPath (x, y);
  69232. perpendicularOffset (startX, startY, endX, endY,
  69233. 0, -lineThickness, x, y);
  69234. lineTo (x, y);
  69235. perpendicularOffset (endX, endY, startX, startY,
  69236. 0, lineThickness, x, y);
  69237. lineTo (x, y);
  69238. perpendicularOffset (endX, endY, startX, startY,
  69239. 0, -lineThickness, x, y);
  69240. lineTo (x, y);
  69241. closeSubPath();
  69242. }
  69243. void Path::addArrow (const float startX, const float startY,
  69244. const float endX, const float endY,
  69245. float lineThickness,
  69246. float arrowheadWidth,
  69247. float arrowheadLength) throw()
  69248. {
  69249. lineThickness *= 0.5f;
  69250. arrowheadWidth *= 0.5f;
  69251. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  69252. startY - endY));
  69253. float x, y;
  69254. perpendicularOffset (startX, startY, endX, endY,
  69255. 0, lineThickness, x, y);
  69256. startNewSubPath (x, y);
  69257. perpendicularOffset (startX, startY, endX, endY,
  69258. 0, -lineThickness, x, y);
  69259. lineTo (x, y);
  69260. perpendicularOffset (endX, endY, startX, startY,
  69261. arrowheadLength, lineThickness, x, y);
  69262. lineTo (x, y);
  69263. perpendicularOffset (endX, endY, startX, startY,
  69264. arrowheadLength, arrowheadWidth, x, y);
  69265. lineTo (x, y);
  69266. perpendicularOffset (endX, endY, startX, startY,
  69267. 0, 0, x, y);
  69268. lineTo (x, y);
  69269. perpendicularOffset (endX, endY, startX, startY,
  69270. arrowheadLength, -arrowheadWidth, x, y);
  69271. lineTo (x, y);
  69272. perpendicularOffset (endX, endY, startX, startY,
  69273. arrowheadLength, -lineThickness, x, y);
  69274. lineTo (x, y);
  69275. closeSubPath();
  69276. }
  69277. void Path::addStar (const float centreX,
  69278. const float centreY,
  69279. const int numberOfPoints,
  69280. const float innerRadius,
  69281. const float outerRadius,
  69282. const float startAngle)
  69283. {
  69284. jassert (numberOfPoints > 1); // this would be silly.
  69285. if (numberOfPoints > 1)
  69286. {
  69287. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  69288. for (int i = 0; i < numberOfPoints; ++i)
  69289. {
  69290. float angle = startAngle + i * angleBetweenPoints;
  69291. const float x = centreX + outerRadius * sinf (angle);
  69292. const float y = centreY - outerRadius * cosf (angle);
  69293. if (i == 0)
  69294. startNewSubPath (x, y);
  69295. else
  69296. lineTo (x, y);
  69297. angle += angleBetweenPoints * 0.5f;
  69298. lineTo (centreX + innerRadius * sinf (angle),
  69299. centreY - innerRadius * cosf (angle));
  69300. }
  69301. closeSubPath();
  69302. }
  69303. }
  69304. void Path::addBubble (float x, float y,
  69305. float w, float h,
  69306. float cs,
  69307. float tipX,
  69308. float tipY,
  69309. int whichSide,
  69310. float arrowPos,
  69311. float arrowWidth)
  69312. {
  69313. if (w > 1.0f && h > 1.0f)
  69314. {
  69315. cs = jmin (cs, w * 0.5f, h * 0.5f);
  69316. const float cs2 = 2.0f * cs;
  69317. startNewSubPath (x + cs, y);
  69318. if (whichSide == 0)
  69319. {
  69320. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69321. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69322. lineTo (arrowX1, y);
  69323. lineTo (tipX, tipY);
  69324. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  69325. }
  69326. lineTo (x + w - cs, y);
  69327. if (cs > 0.0f)
  69328. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  69329. if (whichSide == 3)
  69330. {
  69331. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69332. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69333. lineTo (x + w, arrowY1);
  69334. lineTo (tipX, tipY);
  69335. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  69336. }
  69337. lineTo (x + w, y + h - cs);
  69338. if (cs > 0.0f)
  69339. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  69340. if (whichSide == 2)
  69341. {
  69342. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69343. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69344. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  69345. lineTo (tipX, tipY);
  69346. lineTo (arrowX1, y + h);
  69347. }
  69348. lineTo (x + cs, y + h);
  69349. if (cs > 0.0f)
  69350. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  69351. if (whichSide == 1)
  69352. {
  69353. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69354. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69355. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  69356. lineTo (tipX, tipY);
  69357. lineTo (x, arrowY1);
  69358. }
  69359. lineTo (x, y + cs);
  69360. if (cs > 0.0f)
  69361. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  69362. closeSubPath();
  69363. }
  69364. }
  69365. void Path::addPath (const Path& other) throw()
  69366. {
  69367. int i = 0;
  69368. while (i < other.numElements)
  69369. {
  69370. const float type = other.elements [i++];
  69371. if (type == moveMarker)
  69372. {
  69373. startNewSubPath (other.elements [i],
  69374. other.elements [i + 1]);
  69375. i += 2;
  69376. }
  69377. else if (type == lineMarker)
  69378. {
  69379. lineTo (other.elements [i],
  69380. other.elements [i + 1]);
  69381. i += 2;
  69382. }
  69383. else if (type == quadMarker)
  69384. {
  69385. quadraticTo (other.elements [i],
  69386. other.elements [i + 1],
  69387. other.elements [i + 2],
  69388. other.elements [i + 3]);
  69389. i += 4;
  69390. }
  69391. else if (type == cubicMarker)
  69392. {
  69393. cubicTo (other.elements [i],
  69394. other.elements [i + 1],
  69395. other.elements [i + 2],
  69396. other.elements [i + 3],
  69397. other.elements [i + 4],
  69398. other.elements [i + 5]);
  69399. i += 6;
  69400. }
  69401. else if (type == closeSubPathMarker)
  69402. {
  69403. closeSubPath();
  69404. }
  69405. else
  69406. {
  69407. // something's gone wrong with the element list!
  69408. jassertfalse
  69409. }
  69410. }
  69411. }
  69412. void Path::addPath (const Path& other,
  69413. const AffineTransform& transformToApply) throw()
  69414. {
  69415. int i = 0;
  69416. while (i < other.numElements)
  69417. {
  69418. const float type = other.elements [i++];
  69419. if (type == closeSubPathMarker)
  69420. {
  69421. closeSubPath();
  69422. }
  69423. else
  69424. {
  69425. float x = other.elements [i++];
  69426. float y = other.elements [i++];
  69427. transformToApply.transformPoint (x, y);
  69428. if (type == moveMarker)
  69429. {
  69430. startNewSubPath (x, y);
  69431. }
  69432. else if (type == lineMarker)
  69433. {
  69434. lineTo (x, y);
  69435. }
  69436. else if (type == quadMarker)
  69437. {
  69438. float x2 = other.elements [i++];
  69439. float y2 = other.elements [i++];
  69440. transformToApply.transformPoint (x2, y2);
  69441. quadraticTo (x, y, x2, y2);
  69442. }
  69443. else if (type == cubicMarker)
  69444. {
  69445. float x2 = other.elements [i++];
  69446. float y2 = other.elements [i++];
  69447. float x3 = other.elements [i++];
  69448. float y3 = other.elements [i++];
  69449. transformToApply.transformPoint (x2, y2);
  69450. transformToApply.transformPoint (x3, y3);
  69451. cubicTo (x, y, x2, y2, x3, y3);
  69452. }
  69453. else
  69454. {
  69455. // something's gone wrong with the element list!
  69456. jassertfalse
  69457. }
  69458. }
  69459. }
  69460. }
  69461. void Path::applyTransform (const AffineTransform& transform) throw()
  69462. {
  69463. int i = 0;
  69464. pathYMin = pathXMin = 0;
  69465. pathYMax = pathXMax = 0;
  69466. bool setMaxMin = false;
  69467. while (i < numElements)
  69468. {
  69469. const float type = elements [i++];
  69470. if (type == moveMarker)
  69471. {
  69472. transform.transformPoint (elements [i],
  69473. elements [i + 1]);
  69474. if (setMaxMin)
  69475. {
  69476. pathXMin = jmin (pathXMin, elements [i]);
  69477. pathXMax = jmax (pathXMax, elements [i]);
  69478. pathYMin = jmin (pathYMin, elements [i + 1]);
  69479. pathYMax = jmax (pathYMax, elements [i + 1]);
  69480. }
  69481. else
  69482. {
  69483. pathXMin = pathXMax = elements [i];
  69484. pathYMin = pathYMax = elements [i + 1];
  69485. setMaxMin = true;
  69486. }
  69487. i += 2;
  69488. }
  69489. else if (type == lineMarker)
  69490. {
  69491. transform.transformPoint (elements [i],
  69492. elements [i + 1]);
  69493. pathXMin = jmin (pathXMin, elements [i]);
  69494. pathXMax = jmax (pathXMax, elements [i]);
  69495. pathYMin = jmin (pathYMin, elements [i + 1]);
  69496. pathYMax = jmax (pathYMax, elements [i + 1]);
  69497. i += 2;
  69498. }
  69499. else if (type == quadMarker)
  69500. {
  69501. transform.transformPoint (elements [i],
  69502. elements [i + 1]);
  69503. transform.transformPoint (elements [i + 2],
  69504. elements [i + 3]);
  69505. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  69506. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  69507. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  69508. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  69509. i += 4;
  69510. }
  69511. else if (type == cubicMarker)
  69512. {
  69513. transform.transformPoint (elements [i],
  69514. elements [i + 1]);
  69515. transform.transformPoint (elements [i + 2],
  69516. elements [i + 3]);
  69517. transform.transformPoint (elements [i + 4],
  69518. elements [i + 5]);
  69519. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  69520. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  69521. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  69522. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  69523. i += 6;
  69524. }
  69525. }
  69526. }
  69527. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  69528. const float w, const float h,
  69529. const bool preserveProportions,
  69530. const Justification& justification) const throw()
  69531. {
  69532. float sx, sy, sw, sh;
  69533. getBounds (sx, sy, sw, sh);
  69534. if (preserveProportions)
  69535. {
  69536. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  69537. return AffineTransform::identity;
  69538. float newW, newH;
  69539. const float srcRatio = sh / sw;
  69540. if (srcRatio > h / w)
  69541. {
  69542. newW = h / srcRatio;
  69543. newH = h;
  69544. }
  69545. else
  69546. {
  69547. newW = w;
  69548. newH = w * srcRatio;
  69549. }
  69550. float newXCentre = x;
  69551. float newYCentre = y;
  69552. if (justification.testFlags (Justification::left))
  69553. newXCentre += newW * 0.5f;
  69554. else if (justification.testFlags (Justification::right))
  69555. newXCentre += w - newW * 0.5f;
  69556. else
  69557. newXCentre += w * 0.5f;
  69558. if (justification.testFlags (Justification::top))
  69559. newYCentre += newH * 0.5f;
  69560. else if (justification.testFlags (Justification::bottom))
  69561. newYCentre += h - newH * 0.5f;
  69562. else
  69563. newYCentre += h * 0.5f;
  69564. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  69565. .scaled (newW / sw, newH / sh)
  69566. .translated (newXCentre, newYCentre);
  69567. }
  69568. else
  69569. {
  69570. return AffineTransform::translation (-sx, -sy)
  69571. .scaled (w / sw, h / sh)
  69572. .translated (x, y);
  69573. }
  69574. }
  69575. bool Path::contains (const float x, const float y, const float tolerence) const throw()
  69576. {
  69577. if (x <= pathXMin || x >= pathXMax
  69578. || y <= pathYMin || y >= pathYMax)
  69579. return false;
  69580. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  69581. int positiveCrossings = 0;
  69582. int negativeCrossings = 0;
  69583. while (i.next())
  69584. {
  69585. if ((i.y1 <= y && i.y2 > y)
  69586. || (i.y2 <= y && i.y1 > y))
  69587. {
  69588. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  69589. if (intersectX <= x)
  69590. {
  69591. if (i.y1 < i.y2)
  69592. ++positiveCrossings;
  69593. else
  69594. ++negativeCrossings;
  69595. }
  69596. }
  69597. }
  69598. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  69599. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  69600. }
  69601. bool Path::intersectsLine (const float x1, const float y1,
  69602. const float x2, const float y2,
  69603. const float tolerence) throw()
  69604. {
  69605. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  69606. const Line line1 (x1, y1, x2, y2);
  69607. while (i.next())
  69608. {
  69609. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  69610. float ix, iy;
  69611. if (line1.intersects (line2, ix, iy))
  69612. return true;
  69613. }
  69614. return false;
  69615. }
  69616. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  69617. {
  69618. if (cornerRadius <= 0.01f)
  69619. return *this;
  69620. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  69621. int n = 0;
  69622. bool lastWasLine = false, firstWasLine = false;
  69623. Path p;
  69624. while (n < numElements)
  69625. {
  69626. const float type = elements [n++];
  69627. if (type == moveMarker)
  69628. {
  69629. indexOfPathStart = p.numElements;
  69630. indexOfPathStartThis = n - 1;
  69631. const float x = elements [n++];
  69632. const float y = elements [n++];
  69633. p.startNewSubPath (x, y);
  69634. lastWasLine = false;
  69635. firstWasLine = (elements [n] == lineMarker);
  69636. }
  69637. else if (type == lineMarker || type == closeSubPathMarker)
  69638. {
  69639. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  69640. if (type == lineMarker)
  69641. {
  69642. endX = elements [n++];
  69643. endY = elements [n++];
  69644. if (n > 8)
  69645. {
  69646. startX = elements [n - 8];
  69647. startY = elements [n - 7];
  69648. joinX = elements [n - 5];
  69649. joinY = elements [n - 4];
  69650. }
  69651. }
  69652. else
  69653. {
  69654. endX = elements [indexOfPathStartThis + 1];
  69655. endY = elements [indexOfPathStartThis + 2];
  69656. if (n > 6)
  69657. {
  69658. startX = elements [n - 6];
  69659. startY = elements [n - 5];
  69660. joinX = elements [n - 3];
  69661. joinY = elements [n - 2];
  69662. }
  69663. }
  69664. if (lastWasLine)
  69665. {
  69666. const double len1 = juce_hypot (startX - joinX,
  69667. startY - joinY);
  69668. if (len1 > 0)
  69669. {
  69670. const double propNeeded = jmin (0.5, cornerRadius / len1);
  69671. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  69672. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  69673. }
  69674. const double len2 = juce_hypot (endX - joinX,
  69675. endY - joinY);
  69676. if (len2 > 0)
  69677. {
  69678. const double propNeeded = jmin (0.5, cornerRadius / len2);
  69679. p.quadraticTo (joinX, joinY,
  69680. (float) (joinX + (endX - joinX) * propNeeded),
  69681. (float) (joinY + (endY - joinY) * propNeeded));
  69682. }
  69683. p.lineTo (endX, endY);
  69684. }
  69685. else if (type == lineMarker)
  69686. {
  69687. p.lineTo (endX, endY);
  69688. lastWasLine = true;
  69689. }
  69690. if (type == closeSubPathMarker)
  69691. {
  69692. if (firstWasLine)
  69693. {
  69694. startX = elements [n - 3];
  69695. startY = elements [n - 2];
  69696. joinX = endX;
  69697. joinY = endY;
  69698. endX = elements [indexOfPathStartThis + 4];
  69699. endY = elements [indexOfPathStartThis + 5];
  69700. const double len1 = juce_hypot (startX - joinX,
  69701. startY - joinY);
  69702. if (len1 > 0)
  69703. {
  69704. const double propNeeded = jmin (0.5, cornerRadius / len1);
  69705. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  69706. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  69707. }
  69708. const double len2 = juce_hypot (endX - joinX,
  69709. endY - joinY);
  69710. if (len2 > 0)
  69711. {
  69712. const double propNeeded = jmin (0.5, cornerRadius / len2);
  69713. endX = (float) (joinX + (endX - joinX) * propNeeded);
  69714. endY = (float) (joinY + (endY - joinY) * propNeeded);
  69715. p.quadraticTo (joinX, joinY, endX, endY);
  69716. p.elements [indexOfPathStart + 1] = endX;
  69717. p.elements [indexOfPathStart + 2] = endY;
  69718. }
  69719. }
  69720. p.closeSubPath();
  69721. }
  69722. }
  69723. else if (type == quadMarker)
  69724. {
  69725. lastWasLine = false;
  69726. const float x1 = elements [n++];
  69727. const float y1 = elements [n++];
  69728. const float x2 = elements [n++];
  69729. const float y2 = elements [n++];
  69730. p.quadraticTo (x1, y1, x2, y2);
  69731. }
  69732. else if (type == cubicMarker)
  69733. {
  69734. lastWasLine = false;
  69735. const float x1 = elements [n++];
  69736. const float y1 = elements [n++];
  69737. const float x2 = elements [n++];
  69738. const float y2 = elements [n++];
  69739. const float x3 = elements [n++];
  69740. const float y3 = elements [n++];
  69741. p.cubicTo (x1, y1, x2, y2, x3, y3);
  69742. }
  69743. }
  69744. return p;
  69745. }
  69746. void Path::loadPathFromStream (InputStream& source)
  69747. {
  69748. while (! source.isExhausted())
  69749. {
  69750. switch (source.readByte())
  69751. {
  69752. case 'm':
  69753. {
  69754. const float x = source.readFloat();
  69755. const float y = source.readFloat();
  69756. startNewSubPath (x, y);
  69757. break;
  69758. }
  69759. case 'l':
  69760. {
  69761. const float x = source.readFloat();
  69762. const float y = source.readFloat();
  69763. lineTo (x, y);
  69764. break;
  69765. }
  69766. case 'q':
  69767. {
  69768. const float x1 = source.readFloat();
  69769. const float y1 = source.readFloat();
  69770. const float x2 = source.readFloat();
  69771. const float y2 = source.readFloat();
  69772. quadraticTo (x1, y1, x2, y2);
  69773. break;
  69774. }
  69775. case 'b':
  69776. {
  69777. const float x1 = source.readFloat();
  69778. const float y1 = source.readFloat();
  69779. const float x2 = source.readFloat();
  69780. const float y2 = source.readFloat();
  69781. const float x3 = source.readFloat();
  69782. const float y3 = source.readFloat();
  69783. cubicTo (x1, y1, x2, y2, x3, y3);
  69784. break;
  69785. }
  69786. case 'c':
  69787. closeSubPath();
  69788. break;
  69789. case 'n':
  69790. useNonZeroWinding = true;
  69791. break;
  69792. case 'z':
  69793. useNonZeroWinding = false;
  69794. break;
  69795. case 'e':
  69796. return; // end of path marker
  69797. default:
  69798. jassertfalse // illegal char in the stream
  69799. break;
  69800. }
  69801. }
  69802. }
  69803. void Path::loadPathFromData (const unsigned char* const data,
  69804. const int numberOfBytes) throw()
  69805. {
  69806. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  69807. loadPathFromStream (in);
  69808. }
  69809. void Path::writePathToStream (OutputStream& dest) const
  69810. {
  69811. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  69812. int i = 0;
  69813. while (i < numElements)
  69814. {
  69815. const float type = elements [i++];
  69816. if (type == moveMarker)
  69817. {
  69818. dest.writeByte ('m');
  69819. dest.writeFloat (elements [i++]);
  69820. dest.writeFloat (elements [i++]);
  69821. }
  69822. else if (type == lineMarker)
  69823. {
  69824. dest.writeByte ('l');
  69825. dest.writeFloat (elements [i++]);
  69826. dest.writeFloat (elements [i++]);
  69827. }
  69828. else if (type == quadMarker)
  69829. {
  69830. dest.writeByte ('q');
  69831. dest.writeFloat (elements [i++]);
  69832. dest.writeFloat (elements [i++]);
  69833. dest.writeFloat (elements [i++]);
  69834. dest.writeFloat (elements [i++]);
  69835. }
  69836. else if (type == cubicMarker)
  69837. {
  69838. dest.writeByte ('b');
  69839. dest.writeFloat (elements [i++]);
  69840. dest.writeFloat (elements [i++]);
  69841. dest.writeFloat (elements [i++]);
  69842. dest.writeFloat (elements [i++]);
  69843. dest.writeFloat (elements [i++]);
  69844. dest.writeFloat (elements [i++]);
  69845. }
  69846. else if (type == closeSubPathMarker)
  69847. {
  69848. dest.writeByte ('c');
  69849. }
  69850. }
  69851. dest.writeByte ('e'); // marks the end-of-path
  69852. }
  69853. const String Path::toString() const
  69854. {
  69855. String s;
  69856. s.preallocateStorage (numElements * 4);
  69857. if (! useNonZeroWinding)
  69858. s << T("a ");
  69859. int i = 0;
  69860. float lastMarker = 0.0f;
  69861. while (i < numElements)
  69862. {
  69863. const float marker = elements [i++];
  69864. tchar markerChar = 0;
  69865. int numCoords = 0;
  69866. if (marker == moveMarker)
  69867. {
  69868. markerChar = T('m');
  69869. numCoords = 2;
  69870. }
  69871. else if (marker == lineMarker)
  69872. {
  69873. markerChar = T('l');
  69874. numCoords = 2;
  69875. }
  69876. else if (marker == quadMarker)
  69877. {
  69878. markerChar = T('q');
  69879. numCoords = 4;
  69880. }
  69881. else if (marker == cubicMarker)
  69882. {
  69883. markerChar = T('c');
  69884. numCoords = 6;
  69885. }
  69886. else
  69887. {
  69888. jassert (marker == closeSubPathMarker);
  69889. markerChar = T('z');
  69890. }
  69891. if (marker != lastMarker)
  69892. {
  69893. s << markerChar << T(' ');
  69894. lastMarker = marker;
  69895. }
  69896. while (--numCoords >= 0 && i < numElements)
  69897. {
  69898. String n (elements [i++], 3);
  69899. while (n.endsWithChar (T('0')))
  69900. n = n.dropLastCharacters (1);
  69901. if (n.endsWithChar (T('.')))
  69902. n = n.dropLastCharacters (1);
  69903. s << n << T(' ');
  69904. }
  69905. }
  69906. return s.trimEnd();
  69907. }
  69908. static const String nextToken (const tchar*& t)
  69909. {
  69910. while (*t == T(' '))
  69911. ++t;
  69912. const tchar* const start = t;
  69913. while (*t != 0 && *t != T(' '))
  69914. ++t;
  69915. const int length = (int) (t - start);
  69916. while (*t == T(' '))
  69917. ++t;
  69918. return String (start, length);
  69919. }
  69920. void Path::restoreFromString (const String& stringVersion)
  69921. {
  69922. clear();
  69923. setUsingNonZeroWinding (true);
  69924. const tchar* t = stringVersion;
  69925. tchar marker = T('m');
  69926. int numValues = 2;
  69927. float values [6];
  69928. while (*t != 0)
  69929. {
  69930. const String token (nextToken (t));
  69931. const tchar firstChar = token[0];
  69932. int startNum = 0;
  69933. if (firstChar == T('m') || firstChar == T('l'))
  69934. {
  69935. marker = firstChar;
  69936. numValues = 2;
  69937. }
  69938. else if (firstChar == T('q'))
  69939. {
  69940. marker = firstChar;
  69941. numValues = 4;
  69942. }
  69943. else if (firstChar == T('c'))
  69944. {
  69945. marker = firstChar;
  69946. numValues = 6;
  69947. }
  69948. else if (firstChar == T('z'))
  69949. {
  69950. marker = firstChar;
  69951. numValues = 0;
  69952. }
  69953. else if (firstChar == T('a'))
  69954. {
  69955. setUsingNonZeroWinding (false);
  69956. continue;
  69957. }
  69958. else
  69959. {
  69960. ++startNum;
  69961. values [0] = token.getFloatValue();
  69962. }
  69963. for (int i = startNum; i < numValues; ++i)
  69964. values [i] = nextToken (t).getFloatValue();
  69965. switch (marker)
  69966. {
  69967. case T('m'):
  69968. startNewSubPath (values[0], values[1]);
  69969. break;
  69970. case T('l'):
  69971. lineTo (values[0], values[1]);
  69972. break;
  69973. case T('q'):
  69974. quadraticTo (values[0], values[1],
  69975. values[2], values[3]);
  69976. break;
  69977. case T('c'):
  69978. cubicTo (values[0], values[1],
  69979. values[2], values[3],
  69980. values[4], values[5]);
  69981. break;
  69982. case T('z'):
  69983. closeSubPath();
  69984. break;
  69985. default:
  69986. jassertfalse // illegal string format?
  69987. break;
  69988. }
  69989. }
  69990. }
  69991. Path::Iterator::Iterator (const Path& path_)
  69992. : path (path_),
  69993. index (0)
  69994. {
  69995. }
  69996. Path::Iterator::~Iterator()
  69997. {
  69998. }
  69999. bool Path::Iterator::next()
  70000. {
  70001. const float* const elements = path.elements;
  70002. if (index < path.numElements)
  70003. {
  70004. const float type = elements [index++];
  70005. if (type == moveMarker)
  70006. {
  70007. elementType = startNewSubPath;
  70008. x1 = elements [index++];
  70009. y1 = elements [index++];
  70010. }
  70011. else if (type == lineMarker)
  70012. {
  70013. elementType = lineTo;
  70014. x1 = elements [index++];
  70015. y1 = elements [index++];
  70016. }
  70017. else if (type == quadMarker)
  70018. {
  70019. elementType = quadraticTo;
  70020. x1 = elements [index++];
  70021. y1 = elements [index++];
  70022. x2 = elements [index++];
  70023. y2 = elements [index++];
  70024. }
  70025. else if (type == cubicMarker)
  70026. {
  70027. elementType = cubicTo;
  70028. x1 = elements [index++];
  70029. y1 = elements [index++];
  70030. x2 = elements [index++];
  70031. y2 = elements [index++];
  70032. x3 = elements [index++];
  70033. y3 = elements [index++];
  70034. }
  70035. else if (type == closeSubPathMarker)
  70036. {
  70037. elementType = closePath;
  70038. }
  70039. return true;
  70040. }
  70041. return false;
  70042. }
  70043. END_JUCE_NAMESPACE
  70044. /********* End of inlined file: juce_Path.cpp *********/
  70045. /********* Start of inlined file: juce_PathIterator.cpp *********/
  70046. BEGIN_JUCE_NAMESPACE
  70047. #if JUCE_MSVC
  70048. #pragma optimize ("t", on)
  70049. #endif
  70050. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  70051. const AffineTransform& transform_,
  70052. float tolerence_) throw()
  70053. : x2 (0),
  70054. y2 (0),
  70055. closesSubPath (false),
  70056. subPathIndex (-1),
  70057. path (path_),
  70058. transform (transform_),
  70059. points (path_.elements),
  70060. tolerence (tolerence_ * tolerence_),
  70061. subPathCloseX (0),
  70062. subPathCloseY (0),
  70063. index (0),
  70064. stackSize (32)
  70065. {
  70066. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  70067. isIdentityTransform = transform.isIdentity();
  70068. stackPos = stackBase;
  70069. }
  70070. PathFlatteningIterator::~PathFlatteningIterator() throw()
  70071. {
  70072. juce_free (stackBase);
  70073. }
  70074. bool PathFlatteningIterator::next() throw()
  70075. {
  70076. x1 = x2;
  70077. y1 = y2;
  70078. float x3 = 0;
  70079. float y3 = 0;
  70080. float x4 = 0;
  70081. float y4 = 0;
  70082. float type;
  70083. for (;;)
  70084. {
  70085. if (stackPos == stackBase)
  70086. {
  70087. if (index >= path.numElements)
  70088. {
  70089. return false;
  70090. }
  70091. else
  70092. {
  70093. type = points [index++];
  70094. if (type != Path::closeSubPathMarker)
  70095. {
  70096. x2 = points [index++];
  70097. y2 = points [index++];
  70098. if (! isIdentityTransform)
  70099. transform.transformPoint (x2, y2);
  70100. if (type == Path::quadMarker)
  70101. {
  70102. x3 = points [index++];
  70103. y3 = points [index++];
  70104. if (! isIdentityTransform)
  70105. transform.transformPoint (x3, y3);
  70106. }
  70107. else if (type == Path::cubicMarker)
  70108. {
  70109. x3 = points [index++];
  70110. y3 = points [index++];
  70111. x4 = points [index++];
  70112. y4 = points [index++];
  70113. if (! isIdentityTransform)
  70114. {
  70115. transform.transformPoint (x3, y3);
  70116. transform.transformPoint (x4, y4);
  70117. }
  70118. }
  70119. }
  70120. }
  70121. }
  70122. else
  70123. {
  70124. type = *--stackPos;
  70125. if (type != Path::closeSubPathMarker)
  70126. {
  70127. x2 = *--stackPos;
  70128. y2 = *--stackPos;
  70129. if (type == Path::quadMarker)
  70130. {
  70131. x3 = *--stackPos;
  70132. y3 = *--stackPos;
  70133. }
  70134. else if (type == Path::cubicMarker)
  70135. {
  70136. x3 = *--stackPos;
  70137. y3 = *--stackPos;
  70138. x4 = *--stackPos;
  70139. y4 = *--stackPos;
  70140. }
  70141. }
  70142. }
  70143. if (type == Path::lineMarker)
  70144. {
  70145. ++subPathIndex;
  70146. closesSubPath = (stackPos == stackBase)
  70147. && (index < path.numElements)
  70148. && (points [index] == Path::closeSubPathMarker)
  70149. && x2 == subPathCloseX
  70150. && y2 == subPathCloseY;
  70151. return true;
  70152. }
  70153. else if (type == Path::quadMarker)
  70154. {
  70155. const int offset = (int) (stackPos - stackBase);
  70156. if (offset >= stackSize - 10)
  70157. {
  70158. stackSize <<= 1;
  70159. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70160. stackPos = stackBase + offset;
  70161. }
  70162. const float dx1 = x1 - x2;
  70163. const float dy1 = y1 - y2;
  70164. const float dx2 = x2 - x3;
  70165. const float dy2 = y2 - y3;
  70166. const float m1x = (x1 + x2) * 0.5f;
  70167. const float m1y = (y1 + y2) * 0.5f;
  70168. const float m2x = (x2 + x3) * 0.5f;
  70169. const float m2y = (y2 + y3) * 0.5f;
  70170. const float m3x = (m1x + m2x) * 0.5f;
  70171. const float m3y = (m1y + m2y) * 0.5f;
  70172. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  70173. {
  70174. *stackPos++ = y3;
  70175. *stackPos++ = x3;
  70176. *stackPos++ = m2y;
  70177. *stackPos++ = m2x;
  70178. *stackPos++ = Path::quadMarker;
  70179. *stackPos++ = m3y;
  70180. *stackPos++ = m3x;
  70181. *stackPos++ = m1y;
  70182. *stackPos++ = m1x;
  70183. *stackPos++ = Path::quadMarker;
  70184. }
  70185. else
  70186. {
  70187. *stackPos++ = y3;
  70188. *stackPos++ = x3;
  70189. *stackPos++ = Path::lineMarker;
  70190. *stackPos++ = m3y;
  70191. *stackPos++ = m3x;
  70192. *stackPos++ = Path::lineMarker;
  70193. }
  70194. jassert (stackPos < stackBase + stackSize);
  70195. }
  70196. else if (type == Path::cubicMarker)
  70197. {
  70198. const int offset = (int) (stackPos - stackBase);
  70199. if (offset >= stackSize - 16)
  70200. {
  70201. stackSize <<= 1;
  70202. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70203. stackPos = stackBase + offset;
  70204. }
  70205. const float dx1 = x1 - x2;
  70206. const float dy1 = y1 - y2;
  70207. const float dx2 = x2 - x3;
  70208. const float dy2 = y2 - y3;
  70209. const float dx3 = x3 - x4;
  70210. const float dy3 = y3 - y4;
  70211. const float m1x = (x1 + x2) * 0.5f;
  70212. const float m1y = (y1 + y2) * 0.5f;
  70213. const float m2x = (x3 + x2) * 0.5f;
  70214. const float m2y = (y3 + y2) * 0.5f;
  70215. const float m3x = (x3 + x4) * 0.5f;
  70216. const float m3y = (y3 + y4) * 0.5f;
  70217. const float m4x = (m1x + m2x) * 0.5f;
  70218. const float m4y = (m1y + m2y) * 0.5f;
  70219. const float m5x = (m3x + m2x) * 0.5f;
  70220. const float m5y = (m3y + m2y) * 0.5f;
  70221. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  70222. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  70223. {
  70224. *stackPos++ = y4;
  70225. *stackPos++ = x4;
  70226. *stackPos++ = m3y;
  70227. *stackPos++ = m3x;
  70228. *stackPos++ = m5y;
  70229. *stackPos++ = m5x;
  70230. *stackPos++ = Path::cubicMarker;
  70231. *stackPos++ = (m4y + m5y) * 0.5f;
  70232. *stackPos++ = (m4x + m5x) * 0.5f;
  70233. *stackPos++ = m4y;
  70234. *stackPos++ = m4x;
  70235. *stackPos++ = m1y;
  70236. *stackPos++ = m1x;
  70237. *stackPos++ = Path::cubicMarker;
  70238. }
  70239. else
  70240. {
  70241. *stackPos++ = y4;
  70242. *stackPos++ = x4;
  70243. *stackPos++ = Path::lineMarker;
  70244. *stackPos++ = m5y;
  70245. *stackPos++ = m5x;
  70246. *stackPos++ = Path::lineMarker;
  70247. *stackPos++ = m4y;
  70248. *stackPos++ = m4x;
  70249. *stackPos++ = Path::lineMarker;
  70250. }
  70251. }
  70252. else if (type == Path::closeSubPathMarker)
  70253. {
  70254. if (x2 != subPathCloseX || y2 != subPathCloseY)
  70255. {
  70256. x1 = x2;
  70257. y1 = y2;
  70258. x2 = subPathCloseX;
  70259. y2 = subPathCloseY;
  70260. closesSubPath = true;
  70261. return true;
  70262. }
  70263. }
  70264. else
  70265. {
  70266. jassert (type == Path::moveMarker);
  70267. subPathIndex = -1;
  70268. subPathCloseX = x1 = x2;
  70269. subPathCloseY = y1 = y2;
  70270. }
  70271. }
  70272. }
  70273. END_JUCE_NAMESPACE
  70274. /********* End of inlined file: juce_PathIterator.cpp *********/
  70275. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  70276. BEGIN_JUCE_NAMESPACE
  70277. PathStrokeType::PathStrokeType (const float strokeThickness,
  70278. const JointStyle jointStyle_,
  70279. const EndCapStyle endStyle_) throw()
  70280. : thickness (strokeThickness),
  70281. jointStyle (jointStyle_),
  70282. endStyle (endStyle_)
  70283. {
  70284. }
  70285. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  70286. : thickness (other.thickness),
  70287. jointStyle (other.jointStyle),
  70288. endStyle (other.endStyle)
  70289. {
  70290. }
  70291. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  70292. {
  70293. thickness = other.thickness;
  70294. jointStyle = other.jointStyle;
  70295. endStyle = other.endStyle;
  70296. return *this;
  70297. }
  70298. PathStrokeType::~PathStrokeType() throw()
  70299. {
  70300. }
  70301. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  70302. {
  70303. return thickness == other.thickness
  70304. && jointStyle == other.jointStyle
  70305. && endStyle == other.endStyle;
  70306. }
  70307. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  70308. {
  70309. return ! operator== (other);
  70310. }
  70311. static bool lineIntersection (const float x1, const float y1,
  70312. const float x2, const float y2,
  70313. const float x3, const float y3,
  70314. const float x4, const float y4,
  70315. float& intersectionX,
  70316. float& intersectionY,
  70317. float& distanceBeyondLine1EndSquared) throw()
  70318. {
  70319. if (x2 != x3 || y2 != y3)
  70320. {
  70321. const float dx1 = x2 - x1;
  70322. const float dy1 = y2 - y1;
  70323. const float dx2 = x4 - x3;
  70324. const float dy2 = y4 - y3;
  70325. const float divisor = dx1 * dy2 - dx2 * dy1;
  70326. if (divisor == 0)
  70327. {
  70328. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  70329. {
  70330. if (dy1 == 0 && dy2 != 0)
  70331. {
  70332. const float along = (y1 - y3) / dy2;
  70333. intersectionX = x3 + along * dx2;
  70334. intersectionY = y1;
  70335. distanceBeyondLine1EndSquared = intersectionX - x2;
  70336. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70337. if ((x2 > x1) == (intersectionX < x2))
  70338. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70339. return along >= 0 && along <= 1.0f;
  70340. }
  70341. else if (dy2 == 0 && dy1 != 0)
  70342. {
  70343. const float along = (y3 - y1) / dy1;
  70344. intersectionX = x1 + along * dx1;
  70345. intersectionY = y3;
  70346. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  70347. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70348. if (along < 1.0f)
  70349. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70350. return along >= 0 && along <= 1.0f;
  70351. }
  70352. else if (dx1 == 0 && dx2 != 0)
  70353. {
  70354. const float along = (x1 - x3) / dx2;
  70355. intersectionX = x1;
  70356. intersectionY = y3 + along * dy2;
  70357. distanceBeyondLine1EndSquared = intersectionY - y2;
  70358. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70359. if ((y2 > y1) == (intersectionY < y2))
  70360. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70361. return along >= 0 && along <= 1.0f;
  70362. }
  70363. else if (dx2 == 0 && dx1 != 0)
  70364. {
  70365. const float along = (x3 - x1) / dx1;
  70366. intersectionX = x3;
  70367. intersectionY = y1 + along * dy1;
  70368. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  70369. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70370. if (along < 1.0f)
  70371. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70372. return along >= 0 && along <= 1.0f;
  70373. }
  70374. }
  70375. intersectionX = 0.5f * (x2 + x3);
  70376. intersectionY = 0.5f * (y2 + y3);
  70377. distanceBeyondLine1EndSquared = 0.0f;
  70378. return false;
  70379. }
  70380. else
  70381. {
  70382. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  70383. intersectionX = x1 + along1 * dx1;
  70384. intersectionY = y1 + along1 * dy1;
  70385. if (along1 >= 0 && along1 <= 1.0f)
  70386. {
  70387. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  70388. if (along2 >= 0 && along2 <= divisor)
  70389. {
  70390. distanceBeyondLine1EndSquared = 0.0f;
  70391. return true;
  70392. }
  70393. }
  70394. distanceBeyondLine1EndSquared = along1 - 1.0f;
  70395. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70396. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  70397. if (along1 < 1.0f)
  70398. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70399. return false;
  70400. }
  70401. }
  70402. intersectionX = x2;
  70403. intersectionY = y2;
  70404. distanceBeyondLine1EndSquared = 0.0f;
  70405. return true;
  70406. }
  70407. // part of stroke drawing stuff
  70408. static void addEdgeAndJoint (Path& destPath,
  70409. const PathStrokeType::JointStyle style,
  70410. const float maxMiterExtensionSquared, const float width,
  70411. const float x1, const float y1,
  70412. const float x2, const float y2,
  70413. const float x3, const float y3,
  70414. const float x4, const float y4,
  70415. const float midX, const float midY) throw()
  70416. {
  70417. if (style == PathStrokeType::beveled
  70418. || (x3 == x4 && y3 == y4)
  70419. || (x1 == x2 && y1 == y2))
  70420. {
  70421. destPath.lineTo (x2, y2);
  70422. destPath.lineTo (x3, y3);
  70423. }
  70424. else
  70425. {
  70426. float jx, jy, distanceBeyondLine1EndSquared;
  70427. // if they intersect, use this point..
  70428. if (lineIntersection (x1, y1, x2, y2,
  70429. x3, y3, x4, y4,
  70430. jx, jy, distanceBeyondLine1EndSquared))
  70431. {
  70432. destPath.lineTo (jx, jy);
  70433. }
  70434. else
  70435. {
  70436. if (style == PathStrokeType::mitered)
  70437. {
  70438. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  70439. && distanceBeyondLine1EndSquared > 0.0f)
  70440. {
  70441. destPath.lineTo (jx, jy);
  70442. }
  70443. else
  70444. {
  70445. // the end sticks out too far, so just use a blunt joint
  70446. destPath.lineTo (x2, y2);
  70447. destPath.lineTo (x3, y3);
  70448. }
  70449. }
  70450. else
  70451. {
  70452. // curved joints
  70453. float angle = atan2f (x2 - midX, y2 - midY);
  70454. float angle2 = atan2f (x3 - midX, y3 - midY);
  70455. while (angle < angle2 - 0.01f)
  70456. angle2 -= float_Pi * 2.0f;
  70457. destPath.lineTo (x2, y2);
  70458. while (angle > angle2)
  70459. {
  70460. destPath.lineTo (midX + width * sinf (angle),
  70461. midY + width * cosf (angle));
  70462. angle -= 0.1f;
  70463. }
  70464. destPath.lineTo (x3, y3);
  70465. }
  70466. }
  70467. }
  70468. }
  70469. static inline void addLineEnd (Path& destPath,
  70470. const PathStrokeType::EndCapStyle style,
  70471. const float x1, const float y1,
  70472. const float x2, const float y2,
  70473. const float width) throw()
  70474. {
  70475. if (style == PathStrokeType::butt)
  70476. {
  70477. destPath.lineTo (x2, y2);
  70478. }
  70479. else
  70480. {
  70481. float offx1, offy1, offx2, offy2;
  70482. float dx = x2 - x1;
  70483. float dy = y2 - y1;
  70484. const float len = juce_hypotf (dx, dy);
  70485. if (len == 0)
  70486. {
  70487. offx1 = offx2 = x1;
  70488. offy1 = offy2 = y1;
  70489. }
  70490. else
  70491. {
  70492. const float offset = width / len;
  70493. dx *= offset;
  70494. dy *= offset;
  70495. offx1 = x1 + dy;
  70496. offy1 = y1 - dx;
  70497. offx2 = x2 + dy;
  70498. offy2 = y2 - dx;
  70499. }
  70500. if (style == PathStrokeType::square)
  70501. {
  70502. // sqaure ends
  70503. destPath.lineTo (offx1, offy1);
  70504. destPath.lineTo (offx2, offy2);
  70505. destPath.lineTo (x2, y2);
  70506. }
  70507. else
  70508. {
  70509. // rounded ends
  70510. const float midx = (offx1 + offx2) * 0.5f;
  70511. const float midy = (offy1 + offy2) * 0.5f;
  70512. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  70513. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  70514. midx, midy);
  70515. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  70516. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  70517. x2, y2);
  70518. }
  70519. }
  70520. }
  70521. struct LineSection
  70522. {
  70523. LineSection() throw() {}
  70524. LineSection (int) throw() {}
  70525. float x1, y1, x2, y2; // original line
  70526. float lx1, ly1, lx2, ly2; // the left-hand stroke
  70527. float rx1, ry1, rx2, ry2; // the right-hand stroke
  70528. };
  70529. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  70530. const bool isClosed,
  70531. const float width, const float maxMiterExtensionSquared,
  70532. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  70533. {
  70534. jassert (subPath.size() > 0);
  70535. const LineSection& firstLine = subPath.getReference (0);
  70536. float lastX1 = firstLine.lx1;
  70537. float lastY1 = firstLine.ly1;
  70538. float lastX2 = firstLine.lx2;
  70539. float lastY2 = firstLine.ly2;
  70540. if (isClosed)
  70541. {
  70542. destPath.startNewSubPath (lastX1, lastY1);
  70543. }
  70544. else
  70545. {
  70546. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  70547. addLineEnd (destPath, endStyle,
  70548. firstLine.rx2, firstLine.ry2,
  70549. lastX1, lastY1,
  70550. width);
  70551. }
  70552. int i;
  70553. for (i = 1; i < subPath.size(); ++i)
  70554. {
  70555. const LineSection& l = subPath.getReference (i);
  70556. addEdgeAndJoint (destPath, jointStyle,
  70557. maxMiterExtensionSquared, width,
  70558. lastX1, lastY1, lastX2, lastY2,
  70559. l.lx1, l.ly1, l.lx2, l.ly2,
  70560. l.x1, l.y1);
  70561. lastX1 = l.lx1;
  70562. lastY1 = l.ly1;
  70563. lastX2 = l.lx2;
  70564. lastY2 = l.ly2;
  70565. }
  70566. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  70567. if (isClosed)
  70568. {
  70569. const LineSection& l = subPath.getReference (0);
  70570. addEdgeAndJoint (destPath, jointStyle,
  70571. maxMiterExtensionSquared, width,
  70572. lastX1, lastY1, lastX2, lastY2,
  70573. l.lx1, l.ly1, l.lx2, l.ly2,
  70574. l.x1, l.y1);
  70575. destPath.closeSubPath();
  70576. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  70577. }
  70578. else
  70579. {
  70580. destPath.lineTo (lastX2, lastY2);
  70581. addLineEnd (destPath, endStyle,
  70582. lastX2, lastY2,
  70583. lastLine.rx1, lastLine.ry1,
  70584. width);
  70585. }
  70586. lastX1 = lastLine.rx1;
  70587. lastY1 = lastLine.ry1;
  70588. lastX2 = lastLine.rx2;
  70589. lastY2 = lastLine.ry2;
  70590. for (i = subPath.size() - 1; --i >= 0;)
  70591. {
  70592. const LineSection& l = subPath.getReference (i);
  70593. addEdgeAndJoint (destPath, jointStyle,
  70594. maxMiterExtensionSquared, width,
  70595. lastX1, lastY1, lastX2, lastY2,
  70596. l.rx1, l.ry1, l.rx2, l.ry2,
  70597. l.x2, l.y2);
  70598. lastX1 = l.rx1;
  70599. lastY1 = l.ry1;
  70600. lastX2 = l.rx2;
  70601. lastY2 = l.ry2;
  70602. }
  70603. if (isClosed)
  70604. {
  70605. addEdgeAndJoint (destPath, jointStyle,
  70606. maxMiterExtensionSquared, width,
  70607. lastX1, lastY1, lastX2, lastY2,
  70608. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  70609. lastLine.x2, lastLine.y2);
  70610. }
  70611. else
  70612. {
  70613. // do the last line
  70614. destPath.lineTo (lastX2, lastY2);
  70615. }
  70616. destPath.closeSubPath();
  70617. }
  70618. void PathStrokeType::createStrokedPath (Path& destPath,
  70619. const Path& source,
  70620. const AffineTransform& transform,
  70621. const float extraAccuracy) const throw()
  70622. {
  70623. if (thickness <= 0)
  70624. {
  70625. destPath.clear();
  70626. return;
  70627. }
  70628. const Path* sourcePath = &source;
  70629. Path temp;
  70630. if (sourcePath == &destPath)
  70631. {
  70632. destPath.swapWithPath (temp);
  70633. sourcePath = &temp;
  70634. }
  70635. else
  70636. {
  70637. destPath.clear();
  70638. }
  70639. destPath.setUsingNonZeroWinding (true);
  70640. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  70641. const float width = 0.5f * thickness;
  70642. // Iterate the path, creating a list of the
  70643. // left/right-hand lines along either side of it...
  70644. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  70645. Array <LineSection> subPath;
  70646. LineSection l;
  70647. l.x1 = 0;
  70648. l.y1 = 0;
  70649. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  70650. while (it.next())
  70651. {
  70652. if (it.subPathIndex == 0)
  70653. {
  70654. if (subPath.size() > 0)
  70655. {
  70656. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  70657. subPath.clearQuick();
  70658. }
  70659. l.x1 = it.x1;
  70660. l.y1 = it.y1;
  70661. }
  70662. l.x2 = it.x2;
  70663. l.y2 = it.y2;
  70664. float dx = l.x2 - l.x1;
  70665. float dy = l.y2 - l.y1;
  70666. const float hypotSquared = dx*dx + dy*dy;
  70667. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  70668. {
  70669. const float len = sqrtf (hypotSquared);
  70670. if (len == 0)
  70671. {
  70672. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  70673. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  70674. }
  70675. else
  70676. {
  70677. const float offset = width / len;
  70678. dx *= offset;
  70679. dy *= offset;
  70680. l.rx2 = l.x1 - dy;
  70681. l.ry2 = l.y1 + dx;
  70682. l.lx1 = l.x1 + dy;
  70683. l.ly1 = l.y1 - dx;
  70684. l.lx2 = l.x2 + dy;
  70685. l.ly2 = l.y2 - dx;
  70686. l.rx1 = l.x2 - dy;
  70687. l.ry1 = l.y2 + dx;
  70688. }
  70689. subPath.add (l);
  70690. if (it.closesSubPath)
  70691. {
  70692. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  70693. subPath.clearQuick();
  70694. }
  70695. else
  70696. {
  70697. l.x1 = it.x2;
  70698. l.y1 = it.y2;
  70699. }
  70700. }
  70701. }
  70702. if (subPath.size() > 0)
  70703. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  70704. }
  70705. void PathStrokeType::createDashedStroke (Path& destPath,
  70706. const Path& sourcePath,
  70707. const float* dashLengths,
  70708. int numDashLengths,
  70709. const AffineTransform& transform,
  70710. const float extraAccuracy) const throw()
  70711. {
  70712. if (thickness <= 0)
  70713. return;
  70714. // this should really be an even number..
  70715. jassert ((numDashLengths & 1) == 0);
  70716. Path newDestPath;
  70717. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  70718. bool first = true;
  70719. int dashNum = 0;
  70720. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  70721. float dx = 0.0f, dy = 0.0f;
  70722. for (;;)
  70723. {
  70724. const bool isSolid = ((dashNum & 1) == 0);
  70725. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  70726. jassert (dashLen > 0); // must be a positive increment!
  70727. if (dashLen <= 0)
  70728. break;
  70729. pos += dashLen;
  70730. while (pos > lineEndPos)
  70731. {
  70732. if (! it.next())
  70733. {
  70734. if (isSolid && ! first)
  70735. newDestPath.lineTo (it.x2, it.y2);
  70736. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  70737. return;
  70738. }
  70739. if (isSolid && ! first)
  70740. newDestPath.lineTo (it.x1, it.y1);
  70741. else
  70742. newDestPath.startNewSubPath (it.x1, it.y1);
  70743. dx = it.x2 - it.x1;
  70744. dy = it.y2 - it.y1;
  70745. lineLen = juce_hypotf (dx, dy);
  70746. lineEndPos += lineLen;
  70747. first = it.closesSubPath;
  70748. }
  70749. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  70750. if (isSolid)
  70751. newDestPath.lineTo (it.x1 + dx * alpha,
  70752. it.y1 + dy * alpha);
  70753. else
  70754. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  70755. it.y1 + dy * alpha);
  70756. }
  70757. }
  70758. END_JUCE_NAMESPACE
  70759. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  70760. /********* Start of inlined file: juce_Point.cpp *********/
  70761. BEGIN_JUCE_NAMESPACE
  70762. Point::Point() throw()
  70763. : x (0.0f),
  70764. y (0.0f)
  70765. {
  70766. }
  70767. Point::Point (const Point& other) throw()
  70768. : x (other.x),
  70769. y (other.y)
  70770. {
  70771. }
  70772. const Point& Point::operator= (const Point& other) throw()
  70773. {
  70774. x = other.x;
  70775. y = other.y;
  70776. return *this;
  70777. }
  70778. Point::Point (const float x_,
  70779. const float y_) throw()
  70780. : x (x_),
  70781. y (y_)
  70782. {
  70783. }
  70784. Point::~Point() throw()
  70785. {
  70786. }
  70787. void Point::setXY (const float x_,
  70788. const float y_) throw()
  70789. {
  70790. x = x_;
  70791. y = y_;
  70792. }
  70793. void Point::applyTransform (const AffineTransform& transform) throw()
  70794. {
  70795. transform.transformPoint (x, y);
  70796. }
  70797. END_JUCE_NAMESPACE
  70798. /********* End of inlined file: juce_Point.cpp *********/
  70799. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  70800. BEGIN_JUCE_NAMESPACE
  70801. PositionedRectangle::PositionedRectangle() throw()
  70802. : x (0.0),
  70803. y (0.0),
  70804. w (0.0),
  70805. h (0.0),
  70806. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  70807. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  70808. wMode (absoluteSize),
  70809. hMode (absoluteSize)
  70810. {
  70811. }
  70812. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  70813. : x (other.x),
  70814. y (other.y),
  70815. w (other.w),
  70816. h (other.h),
  70817. xMode (other.xMode),
  70818. yMode (other.yMode),
  70819. wMode (other.wMode),
  70820. hMode (other.hMode)
  70821. {
  70822. }
  70823. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  70824. {
  70825. if (this != &other)
  70826. {
  70827. x = other.x;
  70828. y = other.y;
  70829. w = other.w;
  70830. h = other.h;
  70831. xMode = other.xMode;
  70832. yMode = other.yMode;
  70833. wMode = other.wMode;
  70834. hMode = other.hMode;
  70835. }
  70836. return *this;
  70837. }
  70838. PositionedRectangle::~PositionedRectangle() throw()
  70839. {
  70840. }
  70841. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  70842. {
  70843. return x == other.x
  70844. && y == other.y
  70845. && w == other.w
  70846. && h == other.h
  70847. && xMode == other.xMode
  70848. && yMode == other.yMode
  70849. && wMode == other.wMode
  70850. && hMode == other.hMode;
  70851. }
  70852. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  70853. {
  70854. return ! operator== (other);
  70855. }
  70856. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  70857. {
  70858. StringArray tokens;
  70859. tokens.addTokens (stringVersion, false);
  70860. decodePosString (tokens [0], xMode, x);
  70861. decodePosString (tokens [1], yMode, y);
  70862. decodeSizeString (tokens [2], wMode, w);
  70863. decodeSizeString (tokens [3], hMode, h);
  70864. }
  70865. const String PositionedRectangle::toString() const throw()
  70866. {
  70867. String s;
  70868. s.preallocateStorage (12);
  70869. addPosDescription (s, xMode, x);
  70870. s << T(' ');
  70871. addPosDescription (s, yMode, y);
  70872. s << T(' ');
  70873. addSizeDescription (s, wMode, w);
  70874. s << T(' ');
  70875. addSizeDescription (s, hMode, h);
  70876. return s;
  70877. }
  70878. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  70879. {
  70880. jassert (! target.isEmpty());
  70881. double x_, y_, w_, h_;
  70882. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  70883. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  70884. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  70885. roundDoubleToInt (w_), roundDoubleToInt (h_));
  70886. }
  70887. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  70888. double& x_, double& y_,
  70889. double& w_, double& h_) const throw()
  70890. {
  70891. jassert (! target.isEmpty());
  70892. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  70893. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  70894. }
  70895. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  70896. {
  70897. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  70898. }
  70899. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  70900. const Rectangle& target) throw()
  70901. {
  70902. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  70903. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  70904. }
  70905. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  70906. const double newW, const double newH,
  70907. const Rectangle& target) throw()
  70908. {
  70909. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  70910. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  70911. }
  70912. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  70913. {
  70914. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  70915. updateFrom (comp.getBounds(), Rectangle());
  70916. else
  70917. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  70918. }
  70919. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  70920. {
  70921. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  70922. }
  70923. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  70924. {
  70925. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  70926. | absoluteFromParentBottomRight
  70927. | absoluteFromParentCentre
  70928. | proportionOfParentSize));
  70929. }
  70930. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  70931. {
  70932. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  70933. }
  70934. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  70935. {
  70936. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  70937. | absoluteFromParentBottomRight
  70938. | absoluteFromParentCentre
  70939. | proportionOfParentSize));
  70940. }
  70941. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  70942. {
  70943. return (SizeMode) wMode;
  70944. }
  70945. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  70946. {
  70947. return (SizeMode) hMode;
  70948. }
  70949. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  70950. const PositionMode xMode_,
  70951. const AnchorPoint yAnchor,
  70952. const PositionMode yMode_,
  70953. const SizeMode widthMode,
  70954. const SizeMode heightMode,
  70955. const Rectangle& target) throw()
  70956. {
  70957. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  70958. {
  70959. double tx, tw;
  70960. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  70961. xMode = (uint8) (xAnchor | xMode_);
  70962. wMode = (uint8) widthMode;
  70963. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  70964. }
  70965. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  70966. {
  70967. double ty, th;
  70968. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  70969. yMode = (uint8) (yAnchor | yMode_);
  70970. hMode = (uint8) heightMode;
  70971. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  70972. }
  70973. }
  70974. bool PositionedRectangle::isPositionAbsolute() const throw()
  70975. {
  70976. return xMode == absoluteFromParentTopLeft
  70977. && yMode == absoluteFromParentTopLeft
  70978. && wMode == absoluteSize
  70979. && hMode == absoluteSize;
  70980. }
  70981. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  70982. {
  70983. if ((mode & proportionOfParentSize) != 0)
  70984. {
  70985. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  70986. }
  70987. else
  70988. {
  70989. s << (roundDoubleToInt (value * 100.0) / 100.0);
  70990. if ((mode & absoluteFromParentBottomRight) != 0)
  70991. s << T('R');
  70992. else if ((mode & absoluteFromParentCentre) != 0)
  70993. s << T('C');
  70994. }
  70995. if ((mode & anchorAtRightOrBottom) != 0)
  70996. s << T('r');
  70997. else if ((mode & anchorAtCentre) != 0)
  70998. s << T('c');
  70999. }
  71000. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  71001. {
  71002. if (mode == proportionalSize)
  71003. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71004. else if (mode == parentSizeMinusAbsolute)
  71005. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  71006. else
  71007. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71008. }
  71009. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  71010. {
  71011. if (s.containsChar (T('r')))
  71012. mode = anchorAtRightOrBottom;
  71013. else if (s.containsChar (T('c')))
  71014. mode = anchorAtCentre;
  71015. else
  71016. mode = anchorAtLeftOrTop;
  71017. if (s.containsChar (T('%')))
  71018. {
  71019. mode |= proportionOfParentSize;
  71020. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  71021. }
  71022. else
  71023. {
  71024. if (s.containsChar (T('R')))
  71025. mode |= absoluteFromParentBottomRight;
  71026. else if (s.containsChar (T('C')))
  71027. mode |= absoluteFromParentCentre;
  71028. else
  71029. mode |= absoluteFromParentTopLeft;
  71030. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  71031. }
  71032. }
  71033. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  71034. {
  71035. if (s.containsChar (T('%')))
  71036. {
  71037. mode = proportionalSize;
  71038. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  71039. }
  71040. else if (s.containsChar (T('M')))
  71041. {
  71042. mode = parentSizeMinusAbsolute;
  71043. value = s.getDoubleValue();
  71044. }
  71045. else
  71046. {
  71047. mode = absoluteSize;
  71048. value = s.getDoubleValue();
  71049. }
  71050. }
  71051. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  71052. const double x_, const double w_,
  71053. const uint8 xMode_, const uint8 wMode_,
  71054. const int parentPos,
  71055. const int parentSize) const throw()
  71056. {
  71057. if (wMode_ == proportionalSize)
  71058. wOut = roundDoubleToInt (w_ * parentSize);
  71059. else if (wMode_ == parentSizeMinusAbsolute)
  71060. wOut = jmax (0, parentSize - roundDoubleToInt (w_));
  71061. else
  71062. wOut = roundDoubleToInt (w_);
  71063. if ((xMode_ & proportionOfParentSize) != 0)
  71064. xOut = parentPos + x_ * parentSize;
  71065. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71066. xOut = (parentPos + parentSize) - x_;
  71067. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71068. xOut = x_ + (parentPos + parentSize / 2);
  71069. else
  71070. xOut = x_ + parentPos;
  71071. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71072. xOut -= wOut;
  71073. else if ((xMode_ & anchorAtCentre) != 0)
  71074. xOut -= wOut / 2;
  71075. }
  71076. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  71077. double x_, const double w_,
  71078. const uint8 xMode_, const uint8 wMode_,
  71079. const int parentPos,
  71080. const int parentSize) const throw()
  71081. {
  71082. if (wMode_ == proportionalSize)
  71083. {
  71084. if (parentSize > 0)
  71085. wOut = w_ / parentSize;
  71086. }
  71087. else if (wMode_ == parentSizeMinusAbsolute)
  71088. wOut = parentSize - w_;
  71089. else
  71090. wOut = w_;
  71091. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71092. x_ += w_;
  71093. else if ((xMode_ & anchorAtCentre) != 0)
  71094. x_ += w_ / 2;
  71095. if ((xMode_ & proportionOfParentSize) != 0)
  71096. {
  71097. if (parentSize > 0)
  71098. xOut = (x_ - parentPos) / parentSize;
  71099. }
  71100. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71101. xOut = (parentPos + parentSize) - x_;
  71102. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71103. xOut = x_ - (parentPos + parentSize / 2);
  71104. else
  71105. xOut = x_ - parentPos;
  71106. }
  71107. END_JUCE_NAMESPACE
  71108. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  71109. /********* Start of inlined file: juce_Rectangle.cpp *********/
  71110. BEGIN_JUCE_NAMESPACE
  71111. Rectangle::Rectangle() throw()
  71112. : x (0),
  71113. y (0),
  71114. w (0),
  71115. h (0)
  71116. {
  71117. }
  71118. Rectangle::Rectangle (const int x_, const int y_,
  71119. const int w_, const int h_) throw()
  71120. : x (x_),
  71121. y (y_),
  71122. w (w_),
  71123. h (h_)
  71124. {
  71125. }
  71126. Rectangle::Rectangle (const int w_, const int h_) throw()
  71127. : x (0),
  71128. y (0),
  71129. w (w_),
  71130. h (h_)
  71131. {
  71132. }
  71133. Rectangle::Rectangle (const Rectangle& other) throw()
  71134. : x (other.x),
  71135. y (other.y),
  71136. w (other.w),
  71137. h (other.h)
  71138. {
  71139. }
  71140. Rectangle::~Rectangle() throw()
  71141. {
  71142. }
  71143. bool Rectangle::isEmpty() const throw()
  71144. {
  71145. return w <= 0 || h <= 0;
  71146. }
  71147. void Rectangle::setBounds (const int x_,
  71148. const int y_,
  71149. const int w_,
  71150. const int h_) throw()
  71151. {
  71152. x = x_;
  71153. y = y_;
  71154. w = w_;
  71155. h = h_;
  71156. }
  71157. void Rectangle::setPosition (const int x_,
  71158. const int y_) throw()
  71159. {
  71160. x = x_;
  71161. y = y_;
  71162. }
  71163. void Rectangle::setSize (const int w_,
  71164. const int h_) throw()
  71165. {
  71166. w = w_;
  71167. h = h_;
  71168. }
  71169. void Rectangle::setLeft (const int newLeft) throw()
  71170. {
  71171. w = jmax (0, x + w - newLeft);
  71172. x = newLeft;
  71173. }
  71174. void Rectangle::setTop (const int newTop) throw()
  71175. {
  71176. h = jmax (0, y + h - newTop);
  71177. y = newTop;
  71178. }
  71179. void Rectangle::setRight (const int newRight) throw()
  71180. {
  71181. x = jmin (x, newRight);
  71182. w = newRight - x;
  71183. }
  71184. void Rectangle::setBottom (const int newBottom) throw()
  71185. {
  71186. y = jmin (y, newBottom);
  71187. h = newBottom - y;
  71188. }
  71189. void Rectangle::translate (const int dx,
  71190. const int dy) throw()
  71191. {
  71192. x += dx;
  71193. y += dy;
  71194. }
  71195. const Rectangle Rectangle::translated (const int dx,
  71196. const int dy) const throw()
  71197. {
  71198. return Rectangle (x + dx, y + dy, w, h);
  71199. }
  71200. void Rectangle::expand (const int deltaX,
  71201. const int deltaY) throw()
  71202. {
  71203. const int nw = jmax (0, w + deltaX + deltaX);
  71204. const int nh = jmax (0, h + deltaY + deltaY);
  71205. setBounds (x - deltaX,
  71206. y - deltaY,
  71207. nw, nh);
  71208. }
  71209. const Rectangle Rectangle::expanded (const int deltaX,
  71210. const int deltaY) const throw()
  71211. {
  71212. const int nw = jmax (0, w + deltaX + deltaX);
  71213. const int nh = jmax (0, h + deltaY + deltaY);
  71214. return Rectangle (x - deltaX,
  71215. y - deltaY,
  71216. nw, nh);
  71217. }
  71218. void Rectangle::reduce (const int deltaX,
  71219. const int deltaY) throw()
  71220. {
  71221. expand (-deltaX, -deltaY);
  71222. }
  71223. const Rectangle Rectangle::reduced (const int deltaX,
  71224. const int deltaY) const throw()
  71225. {
  71226. return expanded (-deltaX, -deltaY);
  71227. }
  71228. bool Rectangle::operator== (const Rectangle& other) const throw()
  71229. {
  71230. return x == other.x
  71231. && y == other.y
  71232. && w == other.w
  71233. && h == other.h;
  71234. }
  71235. bool Rectangle::operator!= (const Rectangle& other) const throw()
  71236. {
  71237. return x != other.x
  71238. || y != other.y
  71239. || w != other.w
  71240. || h != other.h;
  71241. }
  71242. bool Rectangle::contains (const int px,
  71243. const int py) const throw()
  71244. {
  71245. return px >= x
  71246. && py >= y
  71247. && px < x + w
  71248. && py < y + h;
  71249. }
  71250. bool Rectangle::contains (const Rectangle& other) const throw()
  71251. {
  71252. return x <= other.x
  71253. && y <= other.y
  71254. && x + w >= other.x + other.w
  71255. && y + h >= other.y + other.h;
  71256. }
  71257. bool Rectangle::intersects (const Rectangle& other) const throw()
  71258. {
  71259. return x + w > other.x
  71260. && y + h > other.y
  71261. && x < other.x + other.w
  71262. && y < other.y + other.h
  71263. && w > 0
  71264. && h > 0;
  71265. }
  71266. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  71267. {
  71268. const int nx = jmax (x, other.x);
  71269. const int ny = jmax (y, other.y);
  71270. const int nw = jmin (x + w, other.x + other.w) - nx;
  71271. const int nh = jmin (y + h, other.y + other.h) - ny;
  71272. if (nw >= 0 && nh >= 0)
  71273. return Rectangle (nx, ny, nw, nh);
  71274. else
  71275. return Rectangle();
  71276. }
  71277. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  71278. {
  71279. const int maxX = jmax (x1, x);
  71280. w1 = jmin (x1 + w1, x + w) - maxX;
  71281. if (w1 > 0)
  71282. {
  71283. const int maxY = jmax (y1, y);
  71284. h1 = jmin (y1 + h1, y + h) - maxY;
  71285. if (h1 > 0)
  71286. {
  71287. x1 = maxX;
  71288. y1 = maxY;
  71289. return true;
  71290. }
  71291. }
  71292. return false;
  71293. }
  71294. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  71295. int x2, int y2, int w2, int h2) throw()
  71296. {
  71297. const int x = jmax (x1, x2);
  71298. w1 = jmin (x1 + w1, x2 + w2) - x;
  71299. if (w1 > 0)
  71300. {
  71301. const int y = jmax (y1, y2);
  71302. h1 = jmin (y1 + h1, y2 + h2) - y;
  71303. if (h1 > 0)
  71304. {
  71305. x1 = x;
  71306. y1 = y;
  71307. return true;
  71308. }
  71309. }
  71310. return false;
  71311. }
  71312. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  71313. {
  71314. const int newX = jmin (x, other.x);
  71315. const int newY = jmin (y, other.y);
  71316. return Rectangle (newX, newY,
  71317. jmax (x + w, other.x + other.w) - newX,
  71318. jmax (y + h, other.y + other.h) - newY);
  71319. }
  71320. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  71321. {
  71322. if (x == other.x && getRight() == other.getRight()
  71323. && (other.getBottom() >= y && other.y <= getBottom()))
  71324. {
  71325. const int newY = jmin (y, other.y);
  71326. h = jmax (getBottom(), other.getBottom()) - newY;
  71327. y = newY;
  71328. return true;
  71329. }
  71330. else if (y == other.y && getBottom() == other.getBottom()
  71331. && (other.getRight() >= x && other.x <= getRight()))
  71332. {
  71333. const int newX = jmin (x, other.x);
  71334. w = jmax (getRight(), other.getRight()) - newX;
  71335. x = newX;
  71336. return true;
  71337. }
  71338. return false;
  71339. }
  71340. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  71341. {
  71342. int inside = 0;
  71343. const int otherR = other.getRight();
  71344. if (x >= other.x && x < otherR)
  71345. inside = 1;
  71346. const int otherB = other.getBottom();
  71347. if (y >= other.y && y < otherB)
  71348. inside |= 2;
  71349. const int r = x + w;
  71350. if (r >= other.x && r < otherR)
  71351. inside |= 4;
  71352. const int b = y + h;
  71353. if (b >= other.y && b < otherB)
  71354. inside |= 8;
  71355. switch (inside)
  71356. {
  71357. case 1 + 2 + 8:
  71358. w = r - otherR;
  71359. x = otherR;
  71360. return true;
  71361. case 1 + 2 + 4:
  71362. h = b - otherB;
  71363. y = otherB;
  71364. return true;
  71365. case 2 + 4 + 8:
  71366. w = other.x - x;
  71367. return true;
  71368. case 1 + 4 + 8:
  71369. h = other.y - y;
  71370. return true;
  71371. }
  71372. return false;
  71373. }
  71374. const String Rectangle::toString() const throw()
  71375. {
  71376. String s;
  71377. s.preallocateStorage (16);
  71378. s << x << T(' ')
  71379. << y << T(' ')
  71380. << w << T(' ')
  71381. << h;
  71382. return s;
  71383. }
  71384. const Rectangle Rectangle::fromString (const String& stringVersion)
  71385. {
  71386. StringArray toks;
  71387. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  71388. return Rectangle (toks[0].trim().getIntValue(),
  71389. toks[1].trim().getIntValue(),
  71390. toks[2].trim().getIntValue(),
  71391. toks[3].trim().getIntValue());
  71392. }
  71393. END_JUCE_NAMESPACE
  71394. /********* End of inlined file: juce_Rectangle.cpp *********/
  71395. /********* Start of inlined file: juce_RectangleList.cpp *********/
  71396. BEGIN_JUCE_NAMESPACE
  71397. RectangleList::RectangleList() throw()
  71398. {
  71399. }
  71400. RectangleList::RectangleList (const Rectangle& rect) throw()
  71401. {
  71402. if (! rect.isEmpty())
  71403. rects.add (rect);
  71404. }
  71405. RectangleList::RectangleList (const RectangleList& other) throw()
  71406. : rects (other.rects)
  71407. {
  71408. }
  71409. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  71410. {
  71411. if (this != &other)
  71412. rects = other.rects;
  71413. return *this;
  71414. }
  71415. RectangleList::~RectangleList() throw()
  71416. {
  71417. }
  71418. void RectangleList::clear() throw()
  71419. {
  71420. rects.clearQuick();
  71421. }
  71422. const Rectangle RectangleList::getRectangle (const int index) const throw()
  71423. {
  71424. if (((unsigned int) index) < (unsigned int) rects.size())
  71425. return rects.getReference (index);
  71426. return Rectangle();
  71427. }
  71428. bool RectangleList::isEmpty() const throw()
  71429. {
  71430. return rects.size() == 0;
  71431. }
  71432. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  71433. : current (0),
  71434. owner (list),
  71435. index (list.rects.size())
  71436. {
  71437. }
  71438. RectangleList::Iterator::~Iterator() throw()
  71439. {
  71440. }
  71441. bool RectangleList::Iterator::next() throw()
  71442. {
  71443. if (--index >= 0)
  71444. {
  71445. current = & (owner.rects.getReference (index));
  71446. return true;
  71447. }
  71448. return false;
  71449. }
  71450. void RectangleList::add (const Rectangle& rect) throw()
  71451. {
  71452. if (! rect.isEmpty())
  71453. {
  71454. if (rects.size() == 0)
  71455. {
  71456. rects.add (rect);
  71457. }
  71458. else
  71459. {
  71460. bool anyOverlaps = false;
  71461. int i;
  71462. for (i = rects.size(); --i >= 0;)
  71463. {
  71464. Rectangle& ourRect = rects.getReference (i);
  71465. if (rect.intersects (ourRect))
  71466. {
  71467. if (rect.contains (ourRect))
  71468. rects.remove (i);
  71469. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  71470. anyOverlaps = true;
  71471. }
  71472. }
  71473. if (anyOverlaps && rects.size() > 0)
  71474. {
  71475. RectangleList r (rect);
  71476. for (i = rects.size(); --i >= 0;)
  71477. {
  71478. const Rectangle& ourRect = rects.getReference (i);
  71479. if (rect.intersects (ourRect))
  71480. {
  71481. r.subtract (ourRect);
  71482. if (r.rects.size() == 0)
  71483. return;
  71484. }
  71485. }
  71486. for (i = r.getNumRectangles(); --i >= 0;)
  71487. rects.add (r.rects.getReference (i));
  71488. }
  71489. else
  71490. {
  71491. rects.add (rect);
  71492. }
  71493. }
  71494. }
  71495. }
  71496. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  71497. {
  71498. rects.add (rect);
  71499. }
  71500. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  71501. {
  71502. if (rects.size() == 0)
  71503. {
  71504. if (w > 0 && h > 0)
  71505. rects.add (Rectangle (x, y, w, h));
  71506. }
  71507. else
  71508. {
  71509. add (Rectangle (x, y, w, h));
  71510. }
  71511. }
  71512. void RectangleList::add (const RectangleList& other) throw()
  71513. {
  71514. for (int i = 0; i < other.rects.size(); ++i)
  71515. add (other.rects.getReference (i));
  71516. }
  71517. void RectangleList::subtract (const Rectangle& rect) throw()
  71518. {
  71519. const int originalNumRects = rects.size();
  71520. if (originalNumRects > 0)
  71521. {
  71522. const int x1 = rect.x;
  71523. const int y1 = rect.y;
  71524. const int x2 = x1 + rect.w;
  71525. const int y2 = y1 + rect.h;
  71526. for (int i = getNumRectangles(); --i >= 0;)
  71527. {
  71528. Rectangle& r = rects.getReference (i);
  71529. const int rx1 = r.x;
  71530. const int ry1 = r.y;
  71531. const int rx2 = rx1 + r.w;
  71532. const int ry2 = ry1 + r.h;
  71533. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  71534. {
  71535. if (x1 > rx1 && x1 < rx2)
  71536. {
  71537. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  71538. {
  71539. r.w = x1 - rx1;
  71540. }
  71541. else
  71542. {
  71543. r.x = x1;
  71544. r.w = rx2 - x1;
  71545. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  71546. i += 2;
  71547. }
  71548. }
  71549. else if (x2 > rx1 && x2 < rx2)
  71550. {
  71551. r.x = x2;
  71552. r.w = rx2 - x2;
  71553. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  71554. {
  71555. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  71556. i += 2;
  71557. }
  71558. }
  71559. else if (y1 > ry1 && y1 < ry2)
  71560. {
  71561. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  71562. {
  71563. r.h = y1 - ry1;
  71564. }
  71565. else
  71566. {
  71567. r.y = y1;
  71568. r.h = ry2 - y1;
  71569. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  71570. i += 2;
  71571. }
  71572. }
  71573. else if (y2 > ry1 && y2 < ry2)
  71574. {
  71575. r.y = y2;
  71576. r.h = ry2 - y2;
  71577. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  71578. {
  71579. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  71580. i += 2;
  71581. }
  71582. }
  71583. else
  71584. {
  71585. rects.remove (i);
  71586. }
  71587. }
  71588. }
  71589. if (rects.size() > originalNumRects + 10)
  71590. consolidate();
  71591. }
  71592. }
  71593. void RectangleList::subtract (const RectangleList& otherList) throw()
  71594. {
  71595. for (int i = otherList.rects.size(); --i >= 0;)
  71596. subtract (otherList.rects.getReference (i));
  71597. }
  71598. bool RectangleList::clipTo (const Rectangle& rect) throw()
  71599. {
  71600. bool notEmpty = false;
  71601. if (rect.isEmpty())
  71602. {
  71603. clear();
  71604. }
  71605. else
  71606. {
  71607. for (int i = rects.size(); --i >= 0;)
  71608. {
  71609. Rectangle& r = rects.getReference (i);
  71610. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  71611. rects.remove (i);
  71612. else
  71613. notEmpty = true;
  71614. }
  71615. }
  71616. return notEmpty;
  71617. }
  71618. bool RectangleList::clipTo (const RectangleList& other) throw()
  71619. {
  71620. if (rects.size() == 0)
  71621. return false;
  71622. RectangleList result;
  71623. for (int j = 0; j < rects.size(); ++j)
  71624. {
  71625. const Rectangle& rect = rects.getReference (j);
  71626. for (int i = other.rects.size(); --i >= 0;)
  71627. {
  71628. Rectangle r (other.rects.getReference (i));
  71629. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  71630. result.rects.add (r);
  71631. }
  71632. }
  71633. swapWith (result);
  71634. return ! isEmpty();
  71635. }
  71636. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  71637. {
  71638. destRegion.clear();
  71639. if (! rect.isEmpty())
  71640. {
  71641. for (int i = rects.size(); --i >= 0;)
  71642. {
  71643. Rectangle r (rects.getReference (i));
  71644. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  71645. destRegion.rects.add (r);
  71646. }
  71647. }
  71648. return destRegion.rects.size() > 0;
  71649. }
  71650. void RectangleList::swapWith (RectangleList& otherList) throw()
  71651. {
  71652. rects.swapWithArray (otherList.rects);
  71653. }
  71654. void RectangleList::consolidate() throw()
  71655. {
  71656. int i;
  71657. for (i = 0; i < getNumRectangles() - 1; ++i)
  71658. {
  71659. Rectangle& r = rects.getReference (i);
  71660. const int rx1 = r.x;
  71661. const int ry1 = r.y;
  71662. const int rx2 = rx1 + r.w;
  71663. const int ry2 = ry1 + r.h;
  71664. for (int j = rects.size(); --j > i;)
  71665. {
  71666. Rectangle& r2 = rects.getReference (j);
  71667. const int jrx1 = r2.x;
  71668. const int jry1 = r2.y;
  71669. const int jrx2 = jrx1 + r2.w;
  71670. const int jry2 = jry1 + r2.h;
  71671. // if the vertical edges of any blocks are touching and their horizontals don't
  71672. // line up, split them horizontally..
  71673. if (jrx1 == rx2 || jrx2 == rx1)
  71674. {
  71675. if (jry1 > ry1 && jry1 < ry2)
  71676. {
  71677. r.h = jry1 - ry1;
  71678. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  71679. i = -1;
  71680. break;
  71681. }
  71682. if (jry2 > ry1 && jry2 < ry2)
  71683. {
  71684. r.h = jry2 - ry1;
  71685. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  71686. i = -1;
  71687. break;
  71688. }
  71689. else if (ry1 > jry1 && ry1 < jry2)
  71690. {
  71691. r2.h = ry1 - jry1;
  71692. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  71693. i = -1;
  71694. break;
  71695. }
  71696. else if (ry2 > jry1 && ry2 < jry2)
  71697. {
  71698. r2.h = ry2 - jry1;
  71699. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  71700. i = -1;
  71701. break;
  71702. }
  71703. }
  71704. }
  71705. }
  71706. for (i = 0; i < rects.size() - 1; ++i)
  71707. {
  71708. Rectangle& r = rects.getReference (i);
  71709. for (int j = rects.size(); --j > i;)
  71710. {
  71711. if (r.enlargeIfAdjacent (rects.getReference (j)))
  71712. {
  71713. rects.remove (j);
  71714. i = -1;
  71715. break;
  71716. }
  71717. }
  71718. }
  71719. }
  71720. bool RectangleList::containsPoint (const int x, const int y) const throw()
  71721. {
  71722. for (int i = getNumRectangles(); --i >= 0;)
  71723. if (rects.getReference (i).contains (x, y))
  71724. return true;
  71725. return false;
  71726. }
  71727. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  71728. {
  71729. if (rects.size() > 1)
  71730. {
  71731. RectangleList r (rectangleToCheck);
  71732. for (int i = rects.size(); --i >= 0;)
  71733. {
  71734. r.subtract (rects.getReference (i));
  71735. if (r.rects.size() == 0)
  71736. return true;
  71737. }
  71738. }
  71739. else if (rects.size() > 0)
  71740. {
  71741. return rects.getReference (0).contains (rectangleToCheck);
  71742. }
  71743. return false;
  71744. }
  71745. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  71746. {
  71747. for (int i = rects.size(); --i >= 0;)
  71748. if (rects.getReference (i).intersects (rectangleToCheck))
  71749. return true;
  71750. return false;
  71751. }
  71752. bool RectangleList::intersects (const RectangleList& other) const throw()
  71753. {
  71754. for (int i = rects.size(); --i >= 0;)
  71755. if (other.intersectsRectangle (rects.getReference (i)))
  71756. return true;
  71757. return false;
  71758. }
  71759. const Rectangle RectangleList::getBounds() const throw()
  71760. {
  71761. if (rects.size() <= 1)
  71762. {
  71763. if (rects.size() == 0)
  71764. return Rectangle();
  71765. else
  71766. return rects.getReference (0);
  71767. }
  71768. else
  71769. {
  71770. const Rectangle& r = rects.getReference (0);
  71771. int minX = r.x;
  71772. int minY = r.y;
  71773. int maxX = minX + r.w;
  71774. int maxY = minY + r.h;
  71775. for (int i = rects.size(); --i > 0;)
  71776. {
  71777. const Rectangle& r2 = rects.getReference (i);
  71778. minX = jmin (minX, r2.x);
  71779. minY = jmin (minY, r2.y);
  71780. maxX = jmax (maxX, r2.getRight());
  71781. maxY = jmax (maxY, r2.getBottom());
  71782. }
  71783. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  71784. }
  71785. }
  71786. void RectangleList::offsetAll (const int dx, const int dy) throw()
  71787. {
  71788. for (int i = rects.size(); --i >= 0;)
  71789. {
  71790. Rectangle& r = rects.getReference (i);
  71791. r.x += dx;
  71792. r.y += dy;
  71793. }
  71794. }
  71795. const Path RectangleList::toPath() const throw()
  71796. {
  71797. Path p;
  71798. for (int i = rects.size(); --i >= 0;)
  71799. {
  71800. const Rectangle& r = rects.getReference (i);
  71801. p.addRectangle ((float) r.x,
  71802. (float) r.y,
  71803. (float) r.w,
  71804. (float) r.h);
  71805. }
  71806. return p;
  71807. }
  71808. END_JUCE_NAMESPACE
  71809. /********* End of inlined file: juce_RectangleList.cpp *********/
  71810. /********* Start of inlined file: juce_Image.cpp *********/
  71811. BEGIN_JUCE_NAMESPACE
  71812. static const int fullAlphaThreshold = 253;
  71813. Image::Image (const PixelFormat format_,
  71814. const int imageWidth_,
  71815. const int imageHeight_)
  71816. : format (format_),
  71817. imageWidth (imageWidth_),
  71818. imageHeight (imageHeight_),
  71819. imageData (0)
  71820. {
  71821. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  71822. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  71823. // actual image will be at least 1x1.
  71824. }
  71825. Image::Image (const PixelFormat format_,
  71826. const int imageWidth_,
  71827. const int imageHeight_,
  71828. const bool clearImage)
  71829. : format (format_),
  71830. imageWidth (imageWidth_),
  71831. imageHeight (imageHeight_)
  71832. {
  71833. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  71834. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  71835. // actual image will be at least 1x1.
  71836. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  71837. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  71838. const int dataSize = lineStride * jmax (1, imageHeight_);
  71839. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  71840. : juce_malloc (dataSize));
  71841. }
  71842. Image::Image (const Image& other)
  71843. : format (other.format),
  71844. imageWidth (other.imageWidth),
  71845. imageHeight (other.imageHeight)
  71846. {
  71847. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  71848. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  71849. const int dataSize = lineStride * jmax (1, imageHeight);
  71850. imageData = (uint8*) juce_malloc (dataSize);
  71851. int ls, ps;
  71852. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  71853. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  71854. other.releasePixelDataReadOnly (srcData);
  71855. }
  71856. Image::~Image()
  71857. {
  71858. juce_free (imageData);
  71859. }
  71860. LowLevelGraphicsContext* Image::createLowLevelContext()
  71861. {
  71862. return new LowLevelGraphicsSoftwareRenderer (*this);
  71863. }
  71864. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  71865. {
  71866. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  71867. w = w;
  71868. h = h;
  71869. ls = lineStride;
  71870. ps = pixelStride;
  71871. return imageData + x * pixelStride + y * lineStride;
  71872. }
  71873. void Image::releasePixelDataReadWrite (void*)
  71874. {
  71875. }
  71876. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  71877. {
  71878. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  71879. w = w;
  71880. h = h;
  71881. ls = lineStride;
  71882. ps = pixelStride;
  71883. return imageData + x * pixelStride + y * lineStride;
  71884. }
  71885. void Image::releasePixelDataReadOnly (const void*) const
  71886. {
  71887. }
  71888. void Image::setPixelData (int x, int y, int w, int h,
  71889. const uint8* sourcePixelData, int sourceLineStride)
  71890. {
  71891. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  71892. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  71893. {
  71894. int ls, ps;
  71895. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  71896. for (int i = 0; i < h; ++i)
  71897. {
  71898. memcpy (dest + ls * i,
  71899. sourcePixelData + sourceLineStride * i,
  71900. w * pixelStride);
  71901. }
  71902. releasePixelDataReadWrite (dest);
  71903. }
  71904. }
  71905. void Image::clear (int dx, int dy, int dw, int dh,
  71906. const Colour& colourToClearTo)
  71907. {
  71908. const PixelARGB col (colourToClearTo.getPixelARGB());
  71909. int ls, ps;
  71910. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  71911. uint8* dest = dstData;
  71912. while (--dh >= 0)
  71913. {
  71914. uint8* line = dest;
  71915. dest += ls;
  71916. if (isARGB())
  71917. {
  71918. for (int x = dw; --x >= 0;)
  71919. {
  71920. ((PixelARGB*) line)->set (col);
  71921. line += ps;
  71922. }
  71923. }
  71924. else if (isRGB())
  71925. {
  71926. for (int x = dw; --x >= 0;)
  71927. {
  71928. ((PixelRGB*) line)->set (col);
  71929. line += ps;
  71930. }
  71931. }
  71932. else
  71933. {
  71934. for (int x = dw; --x >= 0;)
  71935. {
  71936. *line = col.getAlpha();
  71937. line += ps;
  71938. }
  71939. }
  71940. }
  71941. releasePixelDataReadWrite (dstData);
  71942. }
  71943. Image* Image::createCopy (int newWidth, int newHeight,
  71944. const Graphics::ResamplingQuality quality) const
  71945. {
  71946. if (newWidth < 0)
  71947. newWidth = imageWidth;
  71948. if (newHeight < 0)
  71949. newHeight = imageHeight;
  71950. Image* const newImage = new Image (format, newWidth, newHeight, true);
  71951. Graphics g (*newImage);
  71952. g.setImageResamplingQuality (quality);
  71953. g.drawImage (this,
  71954. 0, 0, newWidth, newHeight,
  71955. 0, 0, imageWidth, imageHeight,
  71956. false);
  71957. return newImage;
  71958. }
  71959. const Colour Image::getPixelAt (const int x, const int y) const
  71960. {
  71961. Colour c;
  71962. if (((unsigned int) x) < (unsigned int) imageWidth
  71963. && ((unsigned int) y) < (unsigned int) imageHeight)
  71964. {
  71965. int ls, ps;
  71966. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  71967. if (isARGB())
  71968. {
  71969. PixelARGB p (*(const PixelARGB*) pixels);
  71970. p.unpremultiply();
  71971. c = Colour (p.getARGB());
  71972. }
  71973. else if (isRGB())
  71974. c = Colour (((const PixelRGB*) pixels)->getARGB());
  71975. else
  71976. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  71977. releasePixelDataReadOnly (pixels);
  71978. }
  71979. return c;
  71980. }
  71981. void Image::setPixelAt (const int x, const int y,
  71982. const Colour& colour)
  71983. {
  71984. if (((unsigned int) x) < (unsigned int) imageWidth
  71985. && ((unsigned int) y) < (unsigned int) imageHeight)
  71986. {
  71987. int ls, ps;
  71988. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  71989. const PixelARGB col (colour.getPixelARGB());
  71990. if (isARGB())
  71991. ((PixelARGB*) pixels)->set (col);
  71992. else if (isRGB())
  71993. ((PixelRGB*) pixels)->set (col);
  71994. else
  71995. *pixels = col.getAlpha();
  71996. releasePixelDataReadWrite (pixels);
  71997. }
  71998. }
  71999. void Image::multiplyAlphaAt (const int x, const int y,
  72000. const float multiplier)
  72001. {
  72002. if (((unsigned int) x) < (unsigned int) imageWidth
  72003. && ((unsigned int) y) < (unsigned int) imageHeight
  72004. && hasAlphaChannel())
  72005. {
  72006. int ls, ps;
  72007. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72008. if (isARGB())
  72009. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  72010. else
  72011. *pixels = (uint8) (*pixels * multiplier);
  72012. releasePixelDataReadWrite (pixels);
  72013. }
  72014. }
  72015. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  72016. {
  72017. if (hasAlphaChannel())
  72018. {
  72019. int ls, ps;
  72020. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72021. if (isARGB())
  72022. {
  72023. for (int y = 0; y < imageHeight; ++y)
  72024. {
  72025. uint8* p = pixels + y * ls;
  72026. for (int x = 0; x < imageWidth; ++x)
  72027. {
  72028. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  72029. p += ps;
  72030. }
  72031. }
  72032. }
  72033. else
  72034. {
  72035. for (int y = 0; y < imageHeight; ++y)
  72036. {
  72037. uint8* p = pixels + y * ls;
  72038. for (int x = 0; x < imageWidth; ++x)
  72039. {
  72040. *p = (uint8) (*p * amountToMultiplyBy);
  72041. p += ps;
  72042. }
  72043. }
  72044. }
  72045. releasePixelDataReadWrite (pixels);
  72046. }
  72047. else
  72048. {
  72049. jassertfalse // can't do this without an alpha-channel!
  72050. }
  72051. }
  72052. void Image::desaturate()
  72053. {
  72054. if (isARGB() || isRGB())
  72055. {
  72056. int ls, ps;
  72057. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72058. if (isARGB())
  72059. {
  72060. for (int y = 0; y < imageHeight; ++y)
  72061. {
  72062. uint8* p = pixels + y * ls;
  72063. for (int x = 0; x < imageWidth; ++x)
  72064. {
  72065. ((PixelARGB*) p)->desaturate();
  72066. p += ps;
  72067. }
  72068. }
  72069. }
  72070. else
  72071. {
  72072. for (int y = 0; y < imageHeight; ++y)
  72073. {
  72074. uint8* p = pixels + y * ls;
  72075. for (int x = 0; x < imageWidth; ++x)
  72076. {
  72077. ((PixelRGB*) p)->desaturate();
  72078. p += ps;
  72079. }
  72080. }
  72081. }
  72082. releasePixelDataReadWrite (pixels);
  72083. }
  72084. }
  72085. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  72086. {
  72087. if (hasAlphaChannel())
  72088. {
  72089. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  72090. SparseSet <int> pixelsOnRow;
  72091. int ls, ps;
  72092. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72093. for (int y = 0; y < imageHeight; ++y)
  72094. {
  72095. pixelsOnRow.clear();
  72096. const uint8* lineData = pixels + ls * y;
  72097. if (isARGB())
  72098. {
  72099. for (int x = 0; x < imageWidth; ++x)
  72100. {
  72101. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  72102. pixelsOnRow.addRange (x, 1);
  72103. lineData += ps;
  72104. }
  72105. }
  72106. else
  72107. {
  72108. for (int x = 0; x < imageWidth; ++x)
  72109. {
  72110. if (*lineData >= threshold)
  72111. pixelsOnRow.addRange (x, 1);
  72112. lineData += ps;
  72113. }
  72114. }
  72115. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  72116. {
  72117. int x, w;
  72118. if (pixelsOnRow.getRange (i, x, w))
  72119. result.add (Rectangle (x, y, w, 1));
  72120. }
  72121. result.consolidate();
  72122. }
  72123. releasePixelDataReadOnly (pixels);
  72124. }
  72125. else
  72126. {
  72127. result.add (0, 0, imageWidth, imageHeight);
  72128. }
  72129. }
  72130. void Image::moveImageSection (int dx, int dy,
  72131. int sx, int sy,
  72132. int w, int h)
  72133. {
  72134. if (dx < 0)
  72135. {
  72136. w += dx;
  72137. sx -= dx;
  72138. dx = 0;
  72139. }
  72140. if (dy < 0)
  72141. {
  72142. h += dy;
  72143. sy -= dy;
  72144. dy = 0;
  72145. }
  72146. if (sx < 0)
  72147. {
  72148. w += sx;
  72149. dx -= sx;
  72150. sx = 0;
  72151. }
  72152. if (sy < 0)
  72153. {
  72154. h += sy;
  72155. dy -= sy;
  72156. sy = 0;
  72157. }
  72158. const int minX = jmin (dx, sx);
  72159. const int minY = jmin (dy, sy);
  72160. w = jmin (w, getWidth() - jmax (sx, dx));
  72161. h = jmin (h, getHeight() - jmax (sy, dy));
  72162. if (w > 0 && h > 0)
  72163. {
  72164. const int maxX = jmax (dx, sx) + w;
  72165. const int maxY = jmax (dy, sy) + h;
  72166. int ls, ps;
  72167. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  72168. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  72169. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  72170. const int lineSize = ps * w;
  72171. if (dy > sy)
  72172. {
  72173. while (--h >= 0)
  72174. {
  72175. const int offset = h * ls;
  72176. memmove (dst + offset, src + offset, lineSize);
  72177. }
  72178. }
  72179. else if (dst != src)
  72180. {
  72181. while (--h >= 0)
  72182. {
  72183. memmove (dst, src, lineSize);
  72184. dst += ls;
  72185. src += ls;
  72186. }
  72187. }
  72188. releasePixelDataReadWrite (pixels);
  72189. }
  72190. }
  72191. END_JUCE_NAMESPACE
  72192. /********* End of inlined file: juce_Image.cpp *********/
  72193. /********* Start of inlined file: juce_ImageCache.cpp *********/
  72194. BEGIN_JUCE_NAMESPACE
  72195. struct CachedImageInfo
  72196. {
  72197. Image* image;
  72198. int64 hashCode;
  72199. int refCount;
  72200. unsigned int releaseTime;
  72201. juce_UseDebuggingNewOperator
  72202. };
  72203. static ImageCache* instance = 0;
  72204. static int cacheTimeout = 5000;
  72205. ImageCache::ImageCache() throw()
  72206. : images (4)
  72207. {
  72208. }
  72209. ImageCache::~ImageCache()
  72210. {
  72211. const ScopedLock sl (lock);
  72212. for (int i = images.size(); --i >= 0;)
  72213. {
  72214. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  72215. delete ci->image;
  72216. delete ci;
  72217. }
  72218. images.clear();
  72219. jassert (instance == this);
  72220. instance = 0;
  72221. }
  72222. Image* ImageCache::getFromHashCode (const int64 hashCode)
  72223. {
  72224. if (instance != 0)
  72225. {
  72226. const ScopedLock sl (instance->lock);
  72227. for (int i = instance->images.size(); --i >= 0;)
  72228. {
  72229. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72230. if (ci->hashCode == hashCode)
  72231. {
  72232. atomicIncrement (ci->refCount);
  72233. return ci->image;
  72234. }
  72235. }
  72236. }
  72237. return 0;
  72238. }
  72239. void ImageCache::addImageToCache (Image* const image,
  72240. const int64 hashCode)
  72241. {
  72242. if (image != 0)
  72243. {
  72244. if (instance == 0)
  72245. instance = new ImageCache();
  72246. CachedImageInfo* const newC = new CachedImageInfo();
  72247. newC->hashCode = hashCode;
  72248. newC->image = image;
  72249. newC->refCount = 1;
  72250. newC->releaseTime = 0;
  72251. const ScopedLock sl (instance->lock);
  72252. instance->images.add (newC);
  72253. }
  72254. }
  72255. void ImageCache::release (Image* const imageToRelease)
  72256. {
  72257. if (imageToRelease != 0 && instance != 0)
  72258. {
  72259. const ScopedLock sl (instance->lock);
  72260. for (int i = instance->images.size(); --i >= 0;)
  72261. {
  72262. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72263. if (ci->image == imageToRelease)
  72264. {
  72265. if (--(ci->refCount) == 0)
  72266. ci->releaseTime = Time::getApproximateMillisecondCounter();
  72267. if (! instance->isTimerRunning())
  72268. instance->startTimer (999);
  72269. break;
  72270. }
  72271. }
  72272. }
  72273. }
  72274. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  72275. {
  72276. if (instance != 0)
  72277. {
  72278. const ScopedLock sl (instance->lock);
  72279. for (int i = instance->images.size(); --i >= 0;)
  72280. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  72281. return true;
  72282. }
  72283. return false;
  72284. }
  72285. void ImageCache::incReferenceCount (Image* const image)
  72286. {
  72287. if (instance != 0)
  72288. {
  72289. const ScopedLock sl (instance->lock);
  72290. for (int i = instance->images.size(); --i >= 0;)
  72291. {
  72292. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72293. if (ci->image == image)
  72294. {
  72295. ci->refCount++;
  72296. return;
  72297. }
  72298. }
  72299. }
  72300. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  72301. }
  72302. void ImageCache::timerCallback()
  72303. {
  72304. int numberStillNeedingReleasing = 0;
  72305. const unsigned int now = Time::getApproximateMillisecondCounter();
  72306. const ScopedLock sl (lock);
  72307. for (int i = images.size(); --i >= 0;)
  72308. {
  72309. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  72310. if (ci->refCount <= 0)
  72311. {
  72312. if (now > ci->releaseTime + cacheTimeout
  72313. || now < ci->releaseTime - 1000)
  72314. {
  72315. images.remove (i);
  72316. delete ci->image;
  72317. delete ci;
  72318. }
  72319. else
  72320. {
  72321. ++numberStillNeedingReleasing;
  72322. }
  72323. }
  72324. }
  72325. if (numberStillNeedingReleasing == 0)
  72326. stopTimer();
  72327. }
  72328. Image* ImageCache::getFromFile (const File& file)
  72329. {
  72330. const int64 hashCode = file.getFullPathName().hashCode64();
  72331. Image* image = getFromHashCode (hashCode);
  72332. if (image == 0)
  72333. {
  72334. image = ImageFileFormat::loadFrom (file);
  72335. addImageToCache (image, hashCode);
  72336. }
  72337. return image;
  72338. }
  72339. Image* ImageCache::getFromMemory (const void* imageData,
  72340. const int dataSize)
  72341. {
  72342. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  72343. Image* image = getFromHashCode (hashCode);
  72344. if (image == 0)
  72345. {
  72346. image = ImageFileFormat::loadFrom (imageData, dataSize);
  72347. addImageToCache (image, hashCode);
  72348. }
  72349. return image;
  72350. }
  72351. void ImageCache::setCacheTimeout (const int millisecs)
  72352. {
  72353. cacheTimeout = millisecs;
  72354. }
  72355. END_JUCE_NAMESPACE
  72356. /********* End of inlined file: juce_ImageCache.cpp *********/
  72357. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  72358. BEGIN_JUCE_NAMESPACE
  72359. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  72360. : size (size_)
  72361. {
  72362. values = new float* [size];
  72363. for (int i = size; --i >= 0;)
  72364. values[i] = new float [size];
  72365. clear();
  72366. }
  72367. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  72368. {
  72369. for (int i = size; --i >= 0;)
  72370. delete[] values[i];
  72371. delete[] values;
  72372. }
  72373. void ImageConvolutionKernel::setKernelValue (const int x,
  72374. const int y,
  72375. const float value) throw()
  72376. {
  72377. if (((unsigned int) x) < (unsigned int) size
  72378. && ((unsigned int) y) < (unsigned int) size)
  72379. {
  72380. values[x][y] = value;
  72381. }
  72382. else
  72383. {
  72384. jassertfalse
  72385. }
  72386. }
  72387. void ImageConvolutionKernel::clear() throw()
  72388. {
  72389. for (int y = size; --y >= 0;)
  72390. for (int x = size; --x >= 0;)
  72391. values[x][y] = 0;
  72392. }
  72393. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  72394. {
  72395. double currentTotal = 0.0;
  72396. for (int y = size; --y >= 0;)
  72397. for (int x = size; --x >= 0;)
  72398. currentTotal += values[x][y];
  72399. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  72400. }
  72401. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  72402. {
  72403. for (int y = size; --y >= 0;)
  72404. for (int x = size; --x >= 0;)
  72405. values[x][y] *= multiplier;
  72406. }
  72407. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  72408. {
  72409. const double radiusFactor = -1.0 / (radius * radius * 2);
  72410. const int centre = size >> 1;
  72411. for (int y = size; --y >= 0;)
  72412. {
  72413. for (int x = size; --x >= 0;)
  72414. {
  72415. const int cx = x - centre;
  72416. const int cy = y - centre;
  72417. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  72418. }
  72419. }
  72420. setOverallSum (1.0f);
  72421. }
  72422. void ImageConvolutionKernel::applyToImage (Image& destImage,
  72423. const Image* sourceImage,
  72424. int dx,
  72425. int dy,
  72426. int dw,
  72427. int dh) const
  72428. {
  72429. Image* imageCreated = 0;
  72430. if (sourceImage == 0)
  72431. {
  72432. sourceImage = imageCreated = destImage.createCopy();
  72433. }
  72434. else
  72435. {
  72436. jassert (sourceImage->getWidth() == destImage.getWidth()
  72437. && sourceImage->getHeight() == destImage.getHeight()
  72438. && sourceImage->getFormat() == destImage.getFormat());
  72439. if (sourceImage->getWidth() != destImage.getWidth()
  72440. || sourceImage->getHeight() != destImage.getHeight()
  72441. || sourceImage->getFormat() != destImage.getFormat())
  72442. return;
  72443. }
  72444. const int imageWidth = destImage.getWidth();
  72445. const int imageHeight = destImage.getHeight();
  72446. if (dx >= imageWidth || dy >= imageHeight)
  72447. return;
  72448. if (dx + dw > imageWidth)
  72449. dw = imageWidth - dx;
  72450. if (dy + dh > imageHeight)
  72451. dh = imageHeight - dy;
  72452. const int dx2 = dx + dw;
  72453. const int dy2 = dy + dh;
  72454. int lineStride, pixelStride;
  72455. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  72456. uint8* line = pixels;
  72457. int srcLineStride, srcPixelStride;
  72458. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  72459. if (pixelStride == 4)
  72460. {
  72461. for (int y = dy; y < dy2; ++y)
  72462. {
  72463. uint8* dest = line;
  72464. line += lineStride;
  72465. for (int x = dx; x < dx2; ++x)
  72466. {
  72467. float c1 = 0;
  72468. float c2 = 0;
  72469. float c3 = 0;
  72470. float c4 = 0;
  72471. for (int yy = 0; yy < size; ++yy)
  72472. {
  72473. const int sy = y + yy - (size >> 1);
  72474. if (sy >= imageHeight)
  72475. break;
  72476. if (sy >= 0)
  72477. {
  72478. int sx = x - (size >> 1);
  72479. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  72480. for (int xx = 0; xx < size; ++xx)
  72481. {
  72482. if (sx >= imageWidth)
  72483. break;
  72484. if (sx >= 0)
  72485. {
  72486. const float kernelMult = values[xx][yy];
  72487. c1 += kernelMult * *src++;
  72488. c2 += kernelMult * *src++;
  72489. c3 += kernelMult * *src++;
  72490. c4 += kernelMult * *src++;
  72491. }
  72492. else
  72493. {
  72494. src += 4;
  72495. }
  72496. ++sx;
  72497. }
  72498. }
  72499. }
  72500. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  72501. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  72502. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  72503. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  72504. }
  72505. }
  72506. }
  72507. else if (pixelStride == 3)
  72508. {
  72509. for (int y = dy; y < dy2; ++y)
  72510. {
  72511. uint8* dest = line;
  72512. line += lineStride;
  72513. for (int x = dx; x < dx2; ++x)
  72514. {
  72515. float c1 = 0;
  72516. float c2 = 0;
  72517. float c3 = 0;
  72518. for (int yy = 0; yy < size; ++yy)
  72519. {
  72520. const int sy = y + yy - (size >> 1);
  72521. if (sy >= imageHeight)
  72522. break;
  72523. if (sy >= 0)
  72524. {
  72525. int sx = x - (size >> 1);
  72526. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  72527. for (int xx = 0; xx < size; ++xx)
  72528. {
  72529. if (sx >= imageWidth)
  72530. break;
  72531. if (sx >= 0)
  72532. {
  72533. const float kernelMult = values[xx][yy];
  72534. c1 += kernelMult * *src++;
  72535. c2 += kernelMult * *src++;
  72536. c3 += kernelMult * *src++;
  72537. }
  72538. else
  72539. {
  72540. src += 3;
  72541. }
  72542. ++sx;
  72543. }
  72544. }
  72545. }
  72546. *dest++ = (uint8) roundFloatToInt (c1);
  72547. *dest++ = (uint8) roundFloatToInt (c2);
  72548. *dest++ = (uint8) roundFloatToInt (c3);
  72549. }
  72550. }
  72551. }
  72552. sourceImage->releasePixelDataReadOnly (srcPixels);
  72553. destImage.releasePixelDataReadWrite (pixels);
  72554. if (imageCreated != 0)
  72555. delete imageCreated;
  72556. }
  72557. END_JUCE_NAMESPACE
  72558. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  72559. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  72560. BEGIN_JUCE_NAMESPACE
  72561. /********* Start of inlined file: juce_GIFLoader.h *********/
  72562. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  72563. #define __JUCE_GIFLOADER_JUCEHEADER__
  72564. #ifndef DOXYGEN
  72565. static const int maxGifCode = 1 << 12;
  72566. /**
  72567. Used internally by ImageFileFormat - don't use this class directly in your
  72568. application.
  72569. @see ImageFileFormat
  72570. */
  72571. class GIFLoader
  72572. {
  72573. public:
  72574. GIFLoader (InputStream& in);
  72575. ~GIFLoader() throw();
  72576. Image* getImage() const throw() { return image; }
  72577. private:
  72578. Image* image;
  72579. InputStream& input;
  72580. uint8 buffer [300];
  72581. uint8 palette [256][4];
  72582. bool dataBlockIsZero, fresh, finished;
  72583. int currentBit, lastBit, lastByteIndex;
  72584. int codeSize, setCodeSize;
  72585. int maxCode, maxCodeSize;
  72586. int firstcode, oldcode;
  72587. int clearCode, end_code;
  72588. int table [2] [maxGifCode];
  72589. int stack [2 * maxGifCode];
  72590. int *sp;
  72591. bool getSizeFromHeader (int& width, int& height);
  72592. bool readPalette (const int numCols);
  72593. int readDataBlock (unsigned char* dest);
  72594. int processExtension (int type, int& transparent);
  72595. int readLZWByte (bool initialise, int input_code_size);
  72596. int getCode (int code_size, bool initialise);
  72597. bool readImage (int width, int height,
  72598. int interlace, int transparent);
  72599. GIFLoader (const GIFLoader&);
  72600. const GIFLoader& operator= (const GIFLoader&);
  72601. };
  72602. #endif // DOXYGEN
  72603. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  72604. /********* End of inlined file: juce_GIFLoader.h *********/
  72605. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  72606. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  72607. PNGImageFormat::PNGImageFormat() throw() {}
  72608. PNGImageFormat::~PNGImageFormat() throw() {}
  72609. const String PNGImageFormat::getFormatName()
  72610. {
  72611. return T("PNG");
  72612. }
  72613. bool PNGImageFormat::canUnderstand (InputStream& in)
  72614. {
  72615. const int bytesNeeded = 4;
  72616. char header [bytesNeeded];
  72617. return in.read (header, bytesNeeded) == bytesNeeded
  72618. && header[1] == 'P'
  72619. && header[2] == 'N'
  72620. && header[3] == 'G';
  72621. }
  72622. Image* PNGImageFormat::decodeImage (InputStream& in)
  72623. {
  72624. return juce_loadPNGImageFromStream (in);
  72625. }
  72626. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  72627. OutputStream& destStream)
  72628. {
  72629. return juce_writePNGImageToStream (sourceImage, destStream);
  72630. }
  72631. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  72632. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  72633. JPEGImageFormat::JPEGImageFormat() throw()
  72634. : quality (-1.0f)
  72635. {
  72636. }
  72637. JPEGImageFormat::~JPEGImageFormat() throw() {}
  72638. void JPEGImageFormat::setQuality (const float newQuality)
  72639. {
  72640. quality = newQuality;
  72641. }
  72642. const String JPEGImageFormat::getFormatName()
  72643. {
  72644. return T("JPEG");
  72645. }
  72646. bool JPEGImageFormat::canUnderstand (InputStream& in)
  72647. {
  72648. const int bytesNeeded = 10;
  72649. uint8 header [bytesNeeded];
  72650. if (in.read (header, bytesNeeded) == bytesNeeded)
  72651. {
  72652. return header[0] == 0xff
  72653. && header[1] == 0xd8
  72654. && header[2] == 0xff
  72655. && (header[3] == 0xe0 || header[3] == 0xe1);
  72656. }
  72657. return false;
  72658. }
  72659. Image* JPEGImageFormat::decodeImage (InputStream& in)
  72660. {
  72661. return juce_loadJPEGImageFromStream (in);
  72662. }
  72663. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  72664. OutputStream& destStream)
  72665. {
  72666. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  72667. }
  72668. class GIFImageFormat : public ImageFileFormat
  72669. {
  72670. public:
  72671. GIFImageFormat() throw() {}
  72672. ~GIFImageFormat() throw() {}
  72673. const String getFormatName()
  72674. {
  72675. return T("GIF");
  72676. }
  72677. bool canUnderstand (InputStream& in)
  72678. {
  72679. const int bytesNeeded = 4;
  72680. char header [bytesNeeded];
  72681. return (in.read (header, bytesNeeded) == bytesNeeded)
  72682. && header[0] == 'G'
  72683. && header[1] == 'I'
  72684. && header[2] == 'F';
  72685. }
  72686. Image* decodeImage (InputStream& in)
  72687. {
  72688. GIFLoader* const loader = new GIFLoader (in);
  72689. Image* const im = loader->getImage();
  72690. delete loader;
  72691. return im;
  72692. }
  72693. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  72694. {
  72695. return false;
  72696. }
  72697. };
  72698. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  72699. {
  72700. static PNGImageFormat png;
  72701. static JPEGImageFormat jpg;
  72702. static GIFImageFormat gif;
  72703. ImageFileFormat* formats[4];
  72704. int numFormats = 0;
  72705. formats [numFormats++] = &png;
  72706. formats [numFormats++] = &jpg;
  72707. formats [numFormats++] = &gif;
  72708. const int64 streamPos = input.getPosition();
  72709. for (int i = 0; i < numFormats; ++i)
  72710. {
  72711. const bool found = formats[i]->canUnderstand (input);
  72712. input.setPosition (streamPos);
  72713. if (found)
  72714. return formats[i];
  72715. }
  72716. return 0;
  72717. }
  72718. Image* ImageFileFormat::loadFrom (InputStream& input)
  72719. {
  72720. ImageFileFormat* const format = findImageFormatForStream (input);
  72721. if (format != 0)
  72722. return format->decodeImage (input);
  72723. return 0;
  72724. }
  72725. Image* ImageFileFormat::loadFrom (const File& file)
  72726. {
  72727. InputStream* const in = file.createInputStream();
  72728. if (in != 0)
  72729. {
  72730. BufferedInputStream b (in, 8192, true);
  72731. return loadFrom (b);
  72732. }
  72733. return 0;
  72734. }
  72735. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  72736. {
  72737. if (rawData != 0 && numBytes > 4)
  72738. {
  72739. MemoryInputStream stream (rawData, numBytes, false);
  72740. return loadFrom (stream);
  72741. }
  72742. return 0;
  72743. }
  72744. END_JUCE_NAMESPACE
  72745. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  72746. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  72747. BEGIN_JUCE_NAMESPACE
  72748. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  72749. {
  72750. return (b << 8) | a;
  72751. }
  72752. GIFLoader::GIFLoader (InputStream& in)
  72753. : image (0),
  72754. input (in),
  72755. dataBlockIsZero (false),
  72756. fresh (false),
  72757. finished (false)
  72758. {
  72759. currentBit = lastBit = lastByteIndex = 0;
  72760. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  72761. firstcode = oldcode = 0;
  72762. clearCode = end_code = 0;
  72763. int imageWidth, imageHeight;
  72764. int transparent = -1;
  72765. if (! getSizeFromHeader (imageWidth, imageHeight))
  72766. return;
  72767. if ((imageWidth <= 0) || (imageHeight <= 0))
  72768. return;
  72769. unsigned char buf [16];
  72770. if (in.read (buf, 3) != 3)
  72771. return;
  72772. int numColours = 2 << (buf[0] & 7);
  72773. if ((buf[0] & 0x80) != 0)
  72774. readPalette (numColours);
  72775. for (;;)
  72776. {
  72777. if (input.read (buf, 1) != 1)
  72778. break;
  72779. if (buf[0] == ';')
  72780. break;
  72781. if (buf[0] == '!')
  72782. {
  72783. if (input.read (buf, 1) != 1)
  72784. break;
  72785. if (processExtension (buf[0], transparent) < 0)
  72786. break;
  72787. continue;
  72788. }
  72789. if (buf[0] != ',')
  72790. continue;
  72791. if (input.read (buf, 9) != 9)
  72792. break;
  72793. imageWidth = makeWord (buf[4], buf[5]);
  72794. imageHeight = makeWord (buf[6], buf[7]);
  72795. numColours = 2 << (buf[8] & 7);
  72796. if ((buf[8] & 0x80) != 0)
  72797. if (! readPalette (numColours))
  72798. break;
  72799. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  72800. imageWidth, imageHeight, (transparent >= 0));
  72801. readImage (imageWidth, imageHeight,
  72802. (buf[8] & 0x40) != 0,
  72803. transparent);
  72804. break;
  72805. }
  72806. }
  72807. GIFLoader::~GIFLoader() throw()
  72808. {
  72809. }
  72810. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  72811. {
  72812. unsigned char b [8];
  72813. if (input.read (b, 6) == 6)
  72814. {
  72815. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  72816. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  72817. {
  72818. if (input.read (b, 4) == 4)
  72819. {
  72820. w = makeWord (b[0], b[1]);
  72821. h = makeWord (b[2], b[3]);
  72822. return true;
  72823. }
  72824. }
  72825. }
  72826. return false;
  72827. }
  72828. bool GIFLoader::readPalette (const int numCols)
  72829. {
  72830. unsigned char rgb[4];
  72831. for (int i = 0; i < numCols; ++i)
  72832. {
  72833. input.read (rgb, 3);
  72834. palette [i][0] = rgb[0];
  72835. palette [i][1] = rgb[1];
  72836. palette [i][2] = rgb[2];
  72837. palette [i][3] = 0xff;
  72838. }
  72839. return true;
  72840. }
  72841. int GIFLoader::readDataBlock (unsigned char* const dest)
  72842. {
  72843. unsigned char n;
  72844. if (input.read (&n, 1) == 1)
  72845. {
  72846. dataBlockIsZero = (n == 0);
  72847. if (dataBlockIsZero || (input.read (dest, n) == n))
  72848. return n;
  72849. }
  72850. return -1;
  72851. }
  72852. int GIFLoader::processExtension (const int type, int& transparent)
  72853. {
  72854. unsigned char b [300];
  72855. int n = 0;
  72856. if (type == 0xf9)
  72857. {
  72858. n = readDataBlock (b);
  72859. if (n < 0)
  72860. return 1;
  72861. if ((b[0] & 0x1) != 0)
  72862. transparent = b[3];
  72863. }
  72864. do
  72865. {
  72866. n = readDataBlock (b);
  72867. }
  72868. while (n > 0);
  72869. return n;
  72870. }
  72871. int GIFLoader::getCode (const int codeSize, const bool initialise)
  72872. {
  72873. if (initialise)
  72874. {
  72875. currentBit = 0;
  72876. lastBit = 0;
  72877. finished = false;
  72878. return 0;
  72879. }
  72880. if ((currentBit + codeSize) >= lastBit)
  72881. {
  72882. if (finished)
  72883. return -1;
  72884. buffer[0] = buffer [lastByteIndex - 2];
  72885. buffer[1] = buffer [lastByteIndex - 1];
  72886. const int n = readDataBlock (&buffer[2]);
  72887. if (n == 0)
  72888. finished = true;
  72889. lastByteIndex = 2 + n;
  72890. currentBit = (currentBit - lastBit) + 16;
  72891. lastBit = (2 + n) * 8 ;
  72892. }
  72893. int result = 0;
  72894. int i = currentBit;
  72895. for (int j = 0; j < codeSize; ++j)
  72896. {
  72897. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  72898. ++i;
  72899. }
  72900. currentBit += codeSize;
  72901. return result;
  72902. }
  72903. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  72904. {
  72905. int code, incode, i;
  72906. if (initialise)
  72907. {
  72908. setCodeSize = inputCodeSize;
  72909. codeSize = setCodeSize + 1;
  72910. clearCode = 1 << setCodeSize;
  72911. end_code = clearCode + 1;
  72912. maxCodeSize = 2 * clearCode;
  72913. maxCode = clearCode + 2;
  72914. getCode (0, true);
  72915. fresh = true;
  72916. for (i = 0; i < clearCode; ++i)
  72917. {
  72918. table[0][i] = 0;
  72919. table[1][i] = i;
  72920. }
  72921. for (; i < maxGifCode; ++i)
  72922. {
  72923. table[0][i] = 0;
  72924. table[1][i] = 0;
  72925. }
  72926. sp = stack;
  72927. return 0;
  72928. }
  72929. else if (fresh)
  72930. {
  72931. fresh = false;
  72932. do
  72933. {
  72934. firstcode = oldcode
  72935. = getCode (codeSize, false);
  72936. }
  72937. while (firstcode == clearCode);
  72938. return firstcode;
  72939. }
  72940. if (sp > stack)
  72941. return *--sp;
  72942. while ((code = getCode (codeSize, false)) >= 0)
  72943. {
  72944. if (code == clearCode)
  72945. {
  72946. for (i = 0; i < clearCode; ++i)
  72947. {
  72948. table[0][i] = 0;
  72949. table[1][i] = i;
  72950. }
  72951. for (; i < maxGifCode; ++i)
  72952. {
  72953. table[0][i] = 0;
  72954. table[1][i] = 0;
  72955. }
  72956. codeSize = setCodeSize + 1;
  72957. maxCodeSize = 2 * clearCode;
  72958. maxCode = clearCode + 2;
  72959. sp = stack;
  72960. firstcode = oldcode = getCode (codeSize, false);
  72961. return firstcode;
  72962. }
  72963. else if (code == end_code)
  72964. {
  72965. if (dataBlockIsZero)
  72966. return -2;
  72967. unsigned char buf [260];
  72968. int n;
  72969. while ((n = readDataBlock (buf)) > 0)
  72970. {}
  72971. if (n != 0)
  72972. return -2;
  72973. }
  72974. incode = code;
  72975. if (code >= maxCode)
  72976. {
  72977. *sp++ = firstcode;
  72978. code = oldcode;
  72979. }
  72980. while (code >= clearCode)
  72981. {
  72982. *sp++ = table[1][code];
  72983. if (code == table[0][code])
  72984. return -2;
  72985. code = table[0][code];
  72986. }
  72987. *sp++ = firstcode = table[1][code];
  72988. if ((code = maxCode) < maxGifCode)
  72989. {
  72990. table[0][code] = oldcode;
  72991. table[1][code] = firstcode;
  72992. ++maxCode;
  72993. if ((maxCode >= maxCodeSize)
  72994. && (maxCodeSize < maxGifCode))
  72995. {
  72996. maxCodeSize <<= 1;
  72997. ++codeSize;
  72998. }
  72999. }
  73000. oldcode = incode;
  73001. if (sp > stack)
  73002. return *--sp;
  73003. }
  73004. return code;
  73005. }
  73006. bool GIFLoader::readImage (const int width, const int height,
  73007. const int interlace, const int transparent)
  73008. {
  73009. unsigned char c;
  73010. if (input.read (&c, 1) != 1
  73011. || readLZWByte (true, c) < 0)
  73012. return false;
  73013. if (transparent >= 0)
  73014. {
  73015. palette [transparent][0] = 0;
  73016. palette [transparent][1] = 0;
  73017. palette [transparent][2] = 0;
  73018. palette [transparent][3] = 0;
  73019. }
  73020. int index;
  73021. int xpos = 0, ypos = 0, pass = 0;
  73022. int stride, pixelStride;
  73023. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  73024. uint8* p = pixels;
  73025. const bool hasAlpha = image->hasAlphaChannel();
  73026. while ((index = readLZWByte (false, c)) >= 0)
  73027. {
  73028. const uint8* const paletteEntry = palette [index];
  73029. if (hasAlpha)
  73030. {
  73031. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  73032. paletteEntry[0],
  73033. paletteEntry[1],
  73034. paletteEntry[2]);
  73035. ((PixelARGB*) p)->premultiply();
  73036. p += pixelStride;
  73037. }
  73038. else
  73039. {
  73040. ((PixelRGB*) p)->setARGB (0,
  73041. paletteEntry[0],
  73042. paletteEntry[1],
  73043. paletteEntry[2]);
  73044. p += pixelStride;
  73045. }
  73046. ++xpos;
  73047. if (xpos == width)
  73048. {
  73049. xpos = 0;
  73050. if (interlace)
  73051. {
  73052. switch (pass)
  73053. {
  73054. case 0:
  73055. case 1:
  73056. ypos += 8;
  73057. break;
  73058. case 2:
  73059. ypos += 4;
  73060. break;
  73061. case 3:
  73062. ypos += 2;
  73063. break;
  73064. }
  73065. while (ypos >= height)
  73066. {
  73067. ++pass;
  73068. switch (pass)
  73069. {
  73070. case 1:
  73071. ypos = 4;
  73072. break;
  73073. case 2:
  73074. ypos = 2;
  73075. break;
  73076. case 3:
  73077. ypos = 1;
  73078. break;
  73079. default:
  73080. return true;
  73081. }
  73082. }
  73083. }
  73084. else
  73085. {
  73086. ++ypos;
  73087. }
  73088. p = pixels + xpos * pixelStride + ypos * stride;
  73089. }
  73090. if (ypos >= height)
  73091. break;
  73092. }
  73093. image->releasePixelDataReadWrite (pixels);
  73094. return true;
  73095. }
  73096. END_JUCE_NAMESPACE
  73097. /********* End of inlined file: juce_GIFLoader.cpp *********/
  73098. #endif
  73099. //==============================================================================
  73100. // some files include lots of library code, so leave them to the end to avoid cluttering
  73101. // up the build for the clean files.
  73102. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  73103. namespace zlibNamespace
  73104. {
  73105. #if JUCE_INCLUDE_ZLIB_CODE
  73106. #undef OS_CODE
  73107. #undef fdopen
  73108. /********* Start of inlined file: zlib.h *********/
  73109. #ifndef ZLIB_H
  73110. #define ZLIB_H
  73111. /********* Start of inlined file: zconf.h *********/
  73112. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73113. #ifndef ZCONF_H
  73114. #define ZCONF_H
  73115. // *** Just a few hacks here to make it compile nicely with Juce..
  73116. #define Z_PREFIX 1
  73117. #undef __MACTYPES__
  73118. #ifdef _MSC_VER
  73119. #pragma warning (disable : 4131 4127 4244 4267)
  73120. #endif
  73121. /*
  73122. * If you *really* need a unique prefix for all types and library functions,
  73123. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  73124. */
  73125. #ifdef Z_PREFIX
  73126. # define deflateInit_ z_deflateInit_
  73127. # define deflate z_deflate
  73128. # define deflateEnd z_deflateEnd
  73129. # define inflateInit_ z_inflateInit_
  73130. # define inflate z_inflate
  73131. # define inflateEnd z_inflateEnd
  73132. # define deflateInit2_ z_deflateInit2_
  73133. # define deflateSetDictionary z_deflateSetDictionary
  73134. # define deflateCopy z_deflateCopy
  73135. # define deflateReset z_deflateReset
  73136. # define deflateParams z_deflateParams
  73137. # define deflateBound z_deflateBound
  73138. # define deflatePrime z_deflatePrime
  73139. # define inflateInit2_ z_inflateInit2_
  73140. # define inflateSetDictionary z_inflateSetDictionary
  73141. # define inflateSync z_inflateSync
  73142. # define inflateSyncPoint z_inflateSyncPoint
  73143. # define inflateCopy z_inflateCopy
  73144. # define inflateReset z_inflateReset
  73145. # define inflateBack z_inflateBack
  73146. # define inflateBackEnd z_inflateBackEnd
  73147. # define compress z_compress
  73148. # define compress2 z_compress2
  73149. # define compressBound z_compressBound
  73150. # define uncompress z_uncompress
  73151. # define adler32 z_adler32
  73152. # define crc32 z_crc32
  73153. # define get_crc_table z_get_crc_table
  73154. # define zError z_zError
  73155. # define alloc_func z_alloc_func
  73156. # define free_func z_free_func
  73157. # define in_func z_in_func
  73158. # define out_func z_out_func
  73159. # define Byte z_Byte
  73160. # define uInt z_uInt
  73161. # define uLong z_uLong
  73162. # define Bytef z_Bytef
  73163. # define charf z_charf
  73164. # define intf z_intf
  73165. # define uIntf z_uIntf
  73166. # define uLongf z_uLongf
  73167. # define voidpf z_voidpf
  73168. # define voidp z_voidp
  73169. #endif
  73170. #if defined(__MSDOS__) && !defined(MSDOS)
  73171. # define MSDOS
  73172. #endif
  73173. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  73174. # define OS2
  73175. #endif
  73176. #if defined(_WINDOWS) && !defined(WINDOWS)
  73177. # define WINDOWS
  73178. #endif
  73179. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  73180. # ifndef WIN32
  73181. # define WIN32
  73182. # endif
  73183. #endif
  73184. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  73185. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  73186. # ifndef SYS16BIT
  73187. # define SYS16BIT
  73188. # endif
  73189. # endif
  73190. #endif
  73191. /*
  73192. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  73193. * than 64k bytes at a time (needed on systems with 16-bit int).
  73194. */
  73195. #ifdef SYS16BIT
  73196. # define MAXSEG_64K
  73197. #endif
  73198. #ifdef MSDOS
  73199. # define UNALIGNED_OK
  73200. #endif
  73201. #ifdef __STDC_VERSION__
  73202. # ifndef STDC
  73203. # define STDC
  73204. # endif
  73205. # if __STDC_VERSION__ >= 199901L
  73206. # ifndef STDC99
  73207. # define STDC99
  73208. # endif
  73209. # endif
  73210. #endif
  73211. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  73212. # define STDC
  73213. #endif
  73214. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  73215. # define STDC
  73216. #endif
  73217. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  73218. # define STDC
  73219. #endif
  73220. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  73221. # define STDC
  73222. #endif
  73223. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  73224. # define STDC
  73225. #endif
  73226. #ifndef STDC
  73227. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  73228. # define const /* note: need a more gentle solution here */
  73229. # endif
  73230. #endif
  73231. /* Some Mac compilers merge all .h files incorrectly: */
  73232. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  73233. # define NO_DUMMY_DECL
  73234. #endif
  73235. /* Maximum value for memLevel in deflateInit2 */
  73236. #ifndef MAX_MEM_LEVEL
  73237. # ifdef MAXSEG_64K
  73238. # define MAX_MEM_LEVEL 8
  73239. # else
  73240. # define MAX_MEM_LEVEL 9
  73241. # endif
  73242. #endif
  73243. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  73244. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  73245. * created by gzip. (Files created by minigzip can still be extracted by
  73246. * gzip.)
  73247. */
  73248. #ifndef MAX_WBITS
  73249. # define MAX_WBITS 15 /* 32K LZ77 window */
  73250. #endif
  73251. /* The memory requirements for deflate are (in bytes):
  73252. (1 << (windowBits+2)) + (1 << (memLevel+9))
  73253. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  73254. plus a few kilobytes for small objects. For example, if you want to reduce
  73255. the default memory requirements from 256K to 128K, compile with
  73256. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  73257. Of course this will generally degrade compression (there's no free lunch).
  73258. The memory requirements for inflate are (in bytes) 1 << windowBits
  73259. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  73260. for small objects.
  73261. */
  73262. /* Type declarations */
  73263. #ifndef OF /* function prototypes */
  73264. # ifdef STDC
  73265. # define OF(args) args
  73266. # else
  73267. # define OF(args) ()
  73268. # endif
  73269. #endif
  73270. /* The following definitions for FAR are needed only for MSDOS mixed
  73271. * model programming (small or medium model with some far allocations).
  73272. * This was tested only with MSC; for other MSDOS compilers you may have
  73273. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  73274. * just define FAR to be empty.
  73275. */
  73276. #ifdef SYS16BIT
  73277. # if defined(M_I86SM) || defined(M_I86MM)
  73278. /* MSC small or medium model */
  73279. # define SMALL_MEDIUM
  73280. # ifdef _MSC_VER
  73281. # define FAR _far
  73282. # else
  73283. # define FAR far
  73284. # endif
  73285. # endif
  73286. # if (defined(__SMALL__) || defined(__MEDIUM__))
  73287. /* Turbo C small or medium model */
  73288. # define SMALL_MEDIUM
  73289. # ifdef __BORLANDC__
  73290. # define FAR _far
  73291. # else
  73292. # define FAR far
  73293. # endif
  73294. # endif
  73295. #endif
  73296. #if defined(WINDOWS) || defined(WIN32)
  73297. /* If building or using zlib as a DLL, define ZLIB_DLL.
  73298. * This is not mandatory, but it offers a little performance increase.
  73299. */
  73300. # ifdef ZLIB_DLL
  73301. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  73302. # ifdef ZLIB_INTERNAL
  73303. # define ZEXTERN extern __declspec(dllexport)
  73304. # else
  73305. # define ZEXTERN extern __declspec(dllimport)
  73306. # endif
  73307. # endif
  73308. # endif /* ZLIB_DLL */
  73309. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  73310. * define ZLIB_WINAPI.
  73311. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  73312. */
  73313. # ifdef ZLIB_WINAPI
  73314. # ifdef FAR
  73315. # undef FAR
  73316. # endif
  73317. # include <windows.h>
  73318. /* No need for _export, use ZLIB.DEF instead. */
  73319. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  73320. # define ZEXPORT WINAPI
  73321. # ifdef WIN32
  73322. # define ZEXPORTVA WINAPIV
  73323. # else
  73324. # define ZEXPORTVA FAR CDECL
  73325. # endif
  73326. # endif
  73327. #endif
  73328. #if defined (__BEOS__)
  73329. # ifdef ZLIB_DLL
  73330. # ifdef ZLIB_INTERNAL
  73331. # define ZEXPORT __declspec(dllexport)
  73332. # define ZEXPORTVA __declspec(dllexport)
  73333. # else
  73334. # define ZEXPORT __declspec(dllimport)
  73335. # define ZEXPORTVA __declspec(dllimport)
  73336. # endif
  73337. # endif
  73338. #endif
  73339. #ifndef ZEXTERN
  73340. # define ZEXTERN extern
  73341. #endif
  73342. #ifndef ZEXPORT
  73343. # define ZEXPORT
  73344. #endif
  73345. #ifndef ZEXPORTVA
  73346. # define ZEXPORTVA
  73347. #endif
  73348. #ifndef FAR
  73349. # define FAR
  73350. #endif
  73351. #if !defined(__MACTYPES__)
  73352. typedef unsigned char Byte; /* 8 bits */
  73353. #endif
  73354. typedef unsigned int uInt; /* 16 bits or more */
  73355. typedef unsigned long uLong; /* 32 bits or more */
  73356. #ifdef SMALL_MEDIUM
  73357. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  73358. # define Bytef Byte FAR
  73359. #else
  73360. typedef Byte FAR Bytef;
  73361. #endif
  73362. typedef char FAR charf;
  73363. typedef int FAR intf;
  73364. typedef uInt FAR uIntf;
  73365. typedef uLong FAR uLongf;
  73366. #ifdef STDC
  73367. typedef void const *voidpc;
  73368. typedef void FAR *voidpf;
  73369. typedef void *voidp;
  73370. #else
  73371. typedef Byte const *voidpc;
  73372. typedef Byte FAR *voidpf;
  73373. typedef Byte *voidp;
  73374. #endif
  73375. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  73376. # include <sys/types.h> /* for off_t */
  73377. # include <unistd.h> /* for SEEK_* and off_t */
  73378. # ifdef VMS
  73379. # include <unixio.h> /* for off_t */
  73380. # endif
  73381. # define z_off_t off_t
  73382. #endif
  73383. #ifndef SEEK_SET
  73384. # define SEEK_SET 0 /* Seek from beginning of file. */
  73385. # define SEEK_CUR 1 /* Seek from current position. */
  73386. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  73387. #endif
  73388. #ifndef z_off_t
  73389. # define z_off_t long
  73390. #endif
  73391. #if defined(__OS400__)
  73392. # define NO_vsnprintf
  73393. #endif
  73394. #if defined(__MVS__)
  73395. # define NO_vsnprintf
  73396. # ifdef FAR
  73397. # undef FAR
  73398. # endif
  73399. #endif
  73400. /* MVS linker does not support external names larger than 8 bytes */
  73401. #if defined(__MVS__)
  73402. # pragma map(deflateInit_,"DEIN")
  73403. # pragma map(deflateInit2_,"DEIN2")
  73404. # pragma map(deflateEnd,"DEEND")
  73405. # pragma map(deflateBound,"DEBND")
  73406. # pragma map(inflateInit_,"ININ")
  73407. # pragma map(inflateInit2_,"ININ2")
  73408. # pragma map(inflateEnd,"INEND")
  73409. # pragma map(inflateSync,"INSY")
  73410. # pragma map(inflateSetDictionary,"INSEDI")
  73411. # pragma map(compressBound,"CMBND")
  73412. # pragma map(inflate_table,"INTABL")
  73413. # pragma map(inflate_fast,"INFA")
  73414. # pragma map(inflate_copyright,"INCOPY")
  73415. #endif
  73416. #endif /* ZCONF_H */
  73417. /********* End of inlined file: zconf.h *********/
  73418. #ifdef __cplusplus
  73419. extern "C" {
  73420. #endif
  73421. #define ZLIB_VERSION "1.2.3"
  73422. #define ZLIB_VERNUM 0x1230
  73423. /*
  73424. The 'zlib' compression library provides in-memory compression and
  73425. decompression functions, including integrity checks of the uncompressed
  73426. data. This version of the library supports only one compression method
  73427. (deflation) but other algorithms will be added later and will have the same
  73428. stream interface.
  73429. Compression can be done in a single step if the buffers are large
  73430. enough (for example if an input file is mmap'ed), or can be done by
  73431. repeated calls of the compression function. In the latter case, the
  73432. application must provide more input and/or consume the output
  73433. (providing more output space) before each call.
  73434. The compressed data format used by default by the in-memory functions is
  73435. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  73436. around a deflate stream, which is itself documented in RFC 1951.
  73437. The library also supports reading and writing files in gzip (.gz) format
  73438. with an interface similar to that of stdio using the functions that start
  73439. with "gz". The gzip format is different from the zlib format. gzip is a
  73440. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  73441. This library can optionally read and write gzip streams in memory as well.
  73442. The zlib format was designed to be compact and fast for use in memory
  73443. and on communications channels. The gzip format was designed for single-
  73444. file compression on file systems, has a larger header than zlib to maintain
  73445. directory information, and uses a different, slower check method than zlib.
  73446. The library does not install any signal handler. The decoder checks
  73447. the consistency of the compressed data, so the library should never
  73448. crash even in case of corrupted input.
  73449. */
  73450. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  73451. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  73452. struct internal_state;
  73453. typedef struct z_stream_s {
  73454. Bytef *next_in; /* next input byte */
  73455. uInt avail_in; /* number of bytes available at next_in */
  73456. uLong total_in; /* total nb of input bytes read so far */
  73457. Bytef *next_out; /* next output byte should be put there */
  73458. uInt avail_out; /* remaining free space at next_out */
  73459. uLong total_out; /* total nb of bytes output so far */
  73460. char *msg; /* last error message, NULL if no error */
  73461. struct internal_state FAR *state; /* not visible by applications */
  73462. alloc_func zalloc; /* used to allocate the internal state */
  73463. free_func zfree; /* used to free the internal state */
  73464. voidpf opaque; /* private data object passed to zalloc and zfree */
  73465. int data_type; /* best guess about the data type: binary or text */
  73466. uLong adler; /* adler32 value of the uncompressed data */
  73467. uLong reserved; /* reserved for future use */
  73468. } z_stream;
  73469. typedef z_stream FAR *z_streamp;
  73470. /*
  73471. gzip header information passed to and from zlib routines. See RFC 1952
  73472. for more details on the meanings of these fields.
  73473. */
  73474. typedef struct gz_header_s {
  73475. int text; /* true if compressed data believed to be text */
  73476. uLong time; /* modification time */
  73477. int xflags; /* extra flags (not used when writing a gzip file) */
  73478. int os; /* operating system */
  73479. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  73480. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  73481. uInt extra_max; /* space at extra (only when reading header) */
  73482. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  73483. uInt name_max; /* space at name (only when reading header) */
  73484. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  73485. uInt comm_max; /* space at comment (only when reading header) */
  73486. int hcrc; /* true if there was or will be a header crc */
  73487. int done; /* true when done reading gzip header (not used
  73488. when writing a gzip file) */
  73489. } gz_header;
  73490. typedef gz_header FAR *gz_headerp;
  73491. /*
  73492. The application must update next_in and avail_in when avail_in has
  73493. dropped to zero. It must update next_out and avail_out when avail_out
  73494. has dropped to zero. The application must initialize zalloc, zfree and
  73495. opaque before calling the init function. All other fields are set by the
  73496. compression library and must not be updated by the application.
  73497. The opaque value provided by the application will be passed as the first
  73498. parameter for calls of zalloc and zfree. This can be useful for custom
  73499. memory management. The compression library attaches no meaning to the
  73500. opaque value.
  73501. zalloc must return Z_NULL if there is not enough memory for the object.
  73502. If zlib is used in a multi-threaded application, zalloc and zfree must be
  73503. thread safe.
  73504. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  73505. exactly 65536 bytes, but will not be required to allocate more than this
  73506. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  73507. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  73508. have their offset normalized to zero. The default allocation function
  73509. provided by this library ensures this (see zutil.c). To reduce memory
  73510. requirements and avoid any allocation of 64K objects, at the expense of
  73511. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  73512. The fields total_in and total_out can be used for statistics or
  73513. progress reports. After compression, total_in holds the total size of
  73514. the uncompressed data and may be saved for use in the decompressor
  73515. (particularly if the decompressor wants to decompress everything in
  73516. a single step).
  73517. */
  73518. /* constants */
  73519. #define Z_NO_FLUSH 0
  73520. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  73521. #define Z_SYNC_FLUSH 2
  73522. #define Z_FULL_FLUSH 3
  73523. #define Z_FINISH 4
  73524. #define Z_BLOCK 5
  73525. /* Allowed flush values; see deflate() and inflate() below for details */
  73526. #define Z_OK 0
  73527. #define Z_STREAM_END 1
  73528. #define Z_NEED_DICT 2
  73529. #define Z_ERRNO (-1)
  73530. #define Z_STREAM_ERROR (-2)
  73531. #define Z_DATA_ERROR (-3)
  73532. #define Z_MEM_ERROR (-4)
  73533. #define Z_BUF_ERROR (-5)
  73534. #define Z_VERSION_ERROR (-6)
  73535. /* Return codes for the compression/decompression functions. Negative
  73536. * values are errors, positive values are used for special but normal events.
  73537. */
  73538. #define Z_NO_COMPRESSION 0
  73539. #define Z_BEST_SPEED 1
  73540. #define Z_BEST_COMPRESSION 9
  73541. #define Z_DEFAULT_COMPRESSION (-1)
  73542. /* compression levels */
  73543. #define Z_FILTERED 1
  73544. #define Z_HUFFMAN_ONLY 2
  73545. #define Z_RLE 3
  73546. #define Z_FIXED 4
  73547. #define Z_DEFAULT_STRATEGY 0
  73548. /* compression strategy; see deflateInit2() below for details */
  73549. #define Z_BINARY 0
  73550. #define Z_TEXT 1
  73551. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  73552. #define Z_UNKNOWN 2
  73553. /* Possible values of the data_type field (though see inflate()) */
  73554. #define Z_DEFLATED 8
  73555. /* The deflate compression method (the only one supported in this version) */
  73556. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  73557. #define zlib_version zlibVersion()
  73558. /* for compatibility with versions < 1.0.2 */
  73559. /* basic functions */
  73560. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  73561. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  73562. If the first character differs, the library code actually used is
  73563. not compatible with the zlib.h header file used by the application.
  73564. This check is automatically made by deflateInit and inflateInit.
  73565. */
  73566. /*
  73567. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  73568. Initializes the internal stream state for compression. The fields
  73569. zalloc, zfree and opaque must be initialized before by the caller.
  73570. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  73571. use default allocation functions.
  73572. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  73573. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  73574. all (the input data is simply copied a block at a time).
  73575. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  73576. compression (currently equivalent to level 6).
  73577. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  73578. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  73579. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  73580. with the version assumed by the caller (ZLIB_VERSION).
  73581. msg is set to null if there is no error message. deflateInit does not
  73582. perform any compression: this will be done by deflate().
  73583. */
  73584. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  73585. /*
  73586. deflate compresses as much data as possible, and stops when the input
  73587. buffer becomes empty or the output buffer becomes full. It may introduce some
  73588. output latency (reading input without producing any output) except when
  73589. forced to flush.
  73590. The detailed semantics are as follows. deflate performs one or both of the
  73591. following actions:
  73592. - Compress more input starting at next_in and update next_in and avail_in
  73593. accordingly. If not all input can be processed (because there is not
  73594. enough room in the output buffer), next_in and avail_in are updated and
  73595. processing will resume at this point for the next call of deflate().
  73596. - Provide more output starting at next_out and update next_out and avail_out
  73597. accordingly. This action is forced if the parameter flush is non zero.
  73598. Forcing flush frequently degrades the compression ratio, so this parameter
  73599. should be set only when necessary (in interactive applications).
  73600. Some output may be provided even if flush is not set.
  73601. Before the call of deflate(), the application should ensure that at least
  73602. one of the actions is possible, by providing more input and/or consuming
  73603. more output, and updating avail_in or avail_out accordingly; avail_out
  73604. should never be zero before the call. The application can consume the
  73605. compressed output when it wants, for example when the output buffer is full
  73606. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  73607. and with zero avail_out, it must be called again after making room in the
  73608. output buffer because there might be more output pending.
  73609. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  73610. decide how much data to accumualte before producing output, in order to
  73611. maximize compression.
  73612. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  73613. flushed to the output buffer and the output is aligned on a byte boundary, so
  73614. that the decompressor can get all input data available so far. (In particular
  73615. avail_in is zero after the call if enough output space has been provided
  73616. before the call.) Flushing may degrade compression for some compression
  73617. algorithms and so it should be used only when necessary.
  73618. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  73619. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  73620. restart from this point if previous compressed data has been damaged or if
  73621. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  73622. compression.
  73623. If deflate returns with avail_out == 0, this function must be called again
  73624. with the same value of the flush parameter and more output space (updated
  73625. avail_out), until the flush is complete (deflate returns with non-zero
  73626. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  73627. avail_out is greater than six to avoid repeated flush markers due to
  73628. avail_out == 0 on return.
  73629. If the parameter flush is set to Z_FINISH, pending input is processed,
  73630. pending output is flushed and deflate returns with Z_STREAM_END if there
  73631. was enough output space; if deflate returns with Z_OK, this function must be
  73632. called again with Z_FINISH and more output space (updated avail_out) but no
  73633. more input data, until it returns with Z_STREAM_END or an error. After
  73634. deflate has returned Z_STREAM_END, the only possible operations on the
  73635. stream are deflateReset or deflateEnd.
  73636. Z_FINISH can be used immediately after deflateInit if all the compression
  73637. is to be done in a single step. In this case, avail_out must be at least
  73638. the value returned by deflateBound (see below). If deflate does not return
  73639. Z_STREAM_END, then it must be called again as described above.
  73640. deflate() sets strm->adler to the adler32 checksum of all input read
  73641. so far (that is, total_in bytes).
  73642. deflate() may update strm->data_type if it can make a good guess about
  73643. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  73644. binary. This field is only for information purposes and does not affect
  73645. the compression algorithm in any manner.
  73646. deflate() returns Z_OK if some progress has been made (more input
  73647. processed or more output produced), Z_STREAM_END if all input has been
  73648. consumed and all output has been produced (only when flush is set to
  73649. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  73650. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  73651. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  73652. fatal, and deflate() can be called again with more input and more output
  73653. space to continue compressing.
  73654. */
  73655. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  73656. /*
  73657. All dynamically allocated data structures for this stream are freed.
  73658. This function discards any unprocessed input and does not flush any
  73659. pending output.
  73660. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  73661. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  73662. prematurely (some input or output was discarded). In the error case,
  73663. msg may be set but then points to a static string (which must not be
  73664. deallocated).
  73665. */
  73666. /*
  73667. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  73668. Initializes the internal stream state for decompression. The fields
  73669. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  73670. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  73671. value depends on the compression method), inflateInit determines the
  73672. compression method from the zlib header and allocates all data structures
  73673. accordingly; otherwise the allocation will be deferred to the first call of
  73674. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  73675. use default allocation functions.
  73676. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73677. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  73678. version assumed by the caller. msg is set to null if there is no error
  73679. message. inflateInit does not perform any decompression apart from reading
  73680. the zlib header if present: this will be done by inflate(). (So next_in and
  73681. avail_in may be modified, but next_out and avail_out are unchanged.)
  73682. */
  73683. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  73684. /*
  73685. inflate decompresses as much data as possible, and stops when the input
  73686. buffer becomes empty or the output buffer becomes full. It may introduce
  73687. some output latency (reading input without producing any output) except when
  73688. forced to flush.
  73689. The detailed semantics are as follows. inflate performs one or both of the
  73690. following actions:
  73691. - Decompress more input starting at next_in and update next_in and avail_in
  73692. accordingly. If not all input can be processed (because there is not
  73693. enough room in the output buffer), next_in is updated and processing
  73694. will resume at this point for the next call of inflate().
  73695. - Provide more output starting at next_out and update next_out and avail_out
  73696. accordingly. inflate() provides as much output as possible, until there
  73697. is no more input data or no more space in the output buffer (see below
  73698. about the flush parameter).
  73699. Before the call of inflate(), the application should ensure that at least
  73700. one of the actions is possible, by providing more input and/or consuming
  73701. more output, and updating the next_* and avail_* values accordingly.
  73702. The application can consume the uncompressed output when it wants, for
  73703. example when the output buffer is full (avail_out == 0), or after each
  73704. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  73705. must be called again after making room in the output buffer because there
  73706. might be more output pending.
  73707. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  73708. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  73709. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  73710. if and when it gets to the next deflate block boundary. When decoding the
  73711. zlib or gzip format, this will cause inflate() to return immediately after
  73712. the header and before the first block. When doing a raw inflate, inflate()
  73713. will go ahead and process the first block, and will return when it gets to
  73714. the end of that block, or when it runs out of data.
  73715. The Z_BLOCK option assists in appending to or combining deflate streams.
  73716. Also to assist in this, on return inflate() will set strm->data_type to the
  73717. number of unused bits in the last byte taken from strm->next_in, plus 64
  73718. if inflate() is currently decoding the last block in the deflate stream,
  73719. plus 128 if inflate() returned immediately after decoding an end-of-block
  73720. code or decoding the complete header up to just before the first byte of the
  73721. deflate stream. The end-of-block will not be indicated until all of the
  73722. uncompressed data from that block has been written to strm->next_out. The
  73723. number of unused bits may in general be greater than seven, except when
  73724. bit 7 of data_type is set, in which case the number of unused bits will be
  73725. less than eight.
  73726. inflate() should normally be called until it returns Z_STREAM_END or an
  73727. error. However if all decompression is to be performed in a single step
  73728. (a single call of inflate), the parameter flush should be set to
  73729. Z_FINISH. In this case all pending input is processed and all pending
  73730. output is flushed; avail_out must be large enough to hold all the
  73731. uncompressed data. (The size of the uncompressed data may have been saved
  73732. by the compressor for this purpose.) The next operation on this stream must
  73733. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  73734. is never required, but can be used to inform inflate that a faster approach
  73735. may be used for the single inflate() call.
  73736. In this implementation, inflate() always flushes as much output as
  73737. possible to the output buffer, and always uses the faster approach on the
  73738. first call. So the only effect of the flush parameter in this implementation
  73739. is on the return value of inflate(), as noted below, or when it returns early
  73740. because Z_BLOCK is used.
  73741. If a preset dictionary is needed after this call (see inflateSetDictionary
  73742. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  73743. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  73744. strm->adler to the adler32 checksum of all output produced so far (that is,
  73745. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  73746. below. At the end of the stream, inflate() checks that its computed adler32
  73747. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  73748. only if the checksum is correct.
  73749. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  73750. deflate data. The header type is detected automatically. Any information
  73751. contained in the gzip header is not retained, so applications that need that
  73752. information should instead use raw inflate, see inflateInit2() below, or
  73753. inflateBack() and perform their own processing of the gzip header and
  73754. trailer.
  73755. inflate() returns Z_OK if some progress has been made (more input processed
  73756. or more output produced), Z_STREAM_END if the end of the compressed data has
  73757. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  73758. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  73759. corrupted (input stream not conforming to the zlib format or incorrect check
  73760. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  73761. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  73762. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  73763. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  73764. inflate() can be called again with more input and more output space to
  73765. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  73766. call inflateSync() to look for a good compression block if a partial recovery
  73767. of the data is desired.
  73768. */
  73769. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  73770. /*
  73771. All dynamically allocated data structures for this stream are freed.
  73772. This function discards any unprocessed input and does not flush any
  73773. pending output.
  73774. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  73775. was inconsistent. In the error case, msg may be set but then points to a
  73776. static string (which must not be deallocated).
  73777. */
  73778. /* Advanced functions */
  73779. /*
  73780. The following functions are needed only in some special applications.
  73781. */
  73782. /*
  73783. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  73784. int level,
  73785. int method,
  73786. int windowBits,
  73787. int memLevel,
  73788. int strategy));
  73789. This is another version of deflateInit with more compression options. The
  73790. fields next_in, zalloc, zfree and opaque must be initialized before by
  73791. the caller.
  73792. The method parameter is the compression method. It must be Z_DEFLATED in
  73793. this version of the library.
  73794. The windowBits parameter is the base two logarithm of the window size
  73795. (the size of the history buffer). It should be in the range 8..15 for this
  73796. version of the library. Larger values of this parameter result in better
  73797. compression at the expense of memory usage. The default value is 15 if
  73798. deflateInit is used instead.
  73799. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  73800. determines the window size. deflate() will then generate raw deflate data
  73801. with no zlib header or trailer, and will not compute an adler32 check value.
  73802. windowBits can also be greater than 15 for optional gzip encoding. Add
  73803. 16 to windowBits to write a simple gzip header and trailer around the
  73804. compressed data instead of a zlib wrapper. The gzip header will have no
  73805. file name, no extra data, no comment, no modification time (set to zero),
  73806. no header crc, and the operating system will be set to 255 (unknown). If a
  73807. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  73808. The memLevel parameter specifies how much memory should be allocated
  73809. for the internal compression state. memLevel=1 uses minimum memory but
  73810. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  73811. for optimal speed. The default value is 8. See zconf.h for total memory
  73812. usage as a function of windowBits and memLevel.
  73813. The strategy parameter is used to tune the compression algorithm. Use the
  73814. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  73815. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  73816. string match), or Z_RLE to limit match distances to one (run-length
  73817. encoding). Filtered data consists mostly of small values with a somewhat
  73818. random distribution. In this case, the compression algorithm is tuned to
  73819. compress them better. The effect of Z_FILTERED is to force more Huffman
  73820. coding and less string matching; it is somewhat intermediate between
  73821. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  73822. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  73823. parameter only affects the compression ratio but not the correctness of the
  73824. compressed output even if it is not set appropriately. Z_FIXED prevents the
  73825. use of dynamic Huffman codes, allowing for a simpler decoder for special
  73826. applications.
  73827. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73828. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  73829. method). msg is set to null if there is no error message. deflateInit2 does
  73830. not perform any compression: this will be done by deflate().
  73831. */
  73832. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  73833. const Bytef *dictionary,
  73834. uInt dictLength));
  73835. /*
  73836. Initializes the compression dictionary from the given byte sequence
  73837. without producing any compressed output. This function must be called
  73838. immediately after deflateInit, deflateInit2 or deflateReset, before any
  73839. call of deflate. The compressor and decompressor must use exactly the same
  73840. dictionary (see inflateSetDictionary).
  73841. The dictionary should consist of strings (byte sequences) that are likely
  73842. to be encountered later in the data to be compressed, with the most commonly
  73843. used strings preferably put towards the end of the dictionary. Using a
  73844. dictionary is most useful when the data to be compressed is short and can be
  73845. predicted with good accuracy; the data can then be compressed better than
  73846. with the default empty dictionary.
  73847. Depending on the size of the compression data structures selected by
  73848. deflateInit or deflateInit2, a part of the dictionary may in effect be
  73849. discarded, for example if the dictionary is larger than the window size in
  73850. deflate or deflate2. Thus the strings most likely to be useful should be
  73851. put at the end of the dictionary, not at the front. In addition, the
  73852. current implementation of deflate will use at most the window size minus
  73853. 262 bytes of the provided dictionary.
  73854. Upon return of this function, strm->adler is set to the adler32 value
  73855. of the dictionary; the decompressor may later use this value to determine
  73856. which dictionary has been used by the compressor. (The adler32 value
  73857. applies to the whole dictionary even if only a subset of the dictionary is
  73858. actually used by the compressor.) If a raw deflate was requested, then the
  73859. adler32 value is not computed and strm->adler is not set.
  73860. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  73861. parameter is invalid (such as NULL dictionary) or the stream state is
  73862. inconsistent (for example if deflate has already been called for this stream
  73863. or if the compression method is bsort). deflateSetDictionary does not
  73864. perform any compression: this will be done by deflate().
  73865. */
  73866. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  73867. z_streamp source));
  73868. /*
  73869. Sets the destination stream as a complete copy of the source stream.
  73870. This function can be useful when several compression strategies will be
  73871. tried, for example when there are several ways of pre-processing the input
  73872. data with a filter. The streams that will be discarded should then be freed
  73873. by calling deflateEnd. Note that deflateCopy duplicates the internal
  73874. compression state which can be quite large, so this strategy is slow and
  73875. can consume lots of memory.
  73876. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  73877. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  73878. (such as zalloc being NULL). msg is left unchanged in both source and
  73879. destination.
  73880. */
  73881. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  73882. /*
  73883. This function is equivalent to deflateEnd followed by deflateInit,
  73884. but does not free and reallocate all the internal compression state.
  73885. The stream will keep the same compression level and any other attributes
  73886. that may have been set by deflateInit2.
  73887. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  73888. stream state was inconsistent (such as zalloc or state being NULL).
  73889. */
  73890. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  73891. int level,
  73892. int strategy));
  73893. /*
  73894. Dynamically update the compression level and compression strategy. The
  73895. interpretation of level and strategy is as in deflateInit2. This can be
  73896. used to switch between compression and straight copy of the input data, or
  73897. to switch to a different kind of input data requiring a different
  73898. strategy. If the compression level is changed, the input available so far
  73899. is compressed with the old level (and may be flushed); the new level will
  73900. take effect only at the next call of deflate().
  73901. Before the call of deflateParams, the stream state must be set as for
  73902. a call of deflate(), since the currently available input may have to
  73903. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  73904. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  73905. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  73906. if strm->avail_out was zero.
  73907. */
  73908. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  73909. int good_length,
  73910. int max_lazy,
  73911. int nice_length,
  73912. int max_chain));
  73913. /*
  73914. Fine tune deflate's internal compression parameters. This should only be
  73915. used by someone who understands the algorithm used by zlib's deflate for
  73916. searching for the best matching string, and even then only by the most
  73917. fanatic optimizer trying to squeeze out the last compressed bit for their
  73918. specific input data. Read the deflate.c source code for the meaning of the
  73919. max_lazy, good_length, nice_length, and max_chain parameters.
  73920. deflateTune() can be called after deflateInit() or deflateInit2(), and
  73921. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  73922. */
  73923. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  73924. uLong sourceLen));
  73925. /*
  73926. deflateBound() returns an upper bound on the compressed size after
  73927. deflation of sourceLen bytes. It must be called after deflateInit()
  73928. or deflateInit2(). This would be used to allocate an output buffer
  73929. for deflation in a single pass, and so would be called before deflate().
  73930. */
  73931. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  73932. int bits,
  73933. int value));
  73934. /*
  73935. deflatePrime() inserts bits in the deflate output stream. The intent
  73936. is that this function is used to start off the deflate output with the
  73937. bits leftover from a previous deflate stream when appending to it. As such,
  73938. this function can only be used for raw deflate, and must be used before the
  73939. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  73940. less than or equal to 16, and that many of the least significant bits of
  73941. value will be inserted in the output.
  73942. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  73943. stream state was inconsistent.
  73944. */
  73945. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  73946. gz_headerp head));
  73947. /*
  73948. deflateSetHeader() provides gzip header information for when a gzip
  73949. stream is requested by deflateInit2(). deflateSetHeader() may be called
  73950. after deflateInit2() or deflateReset() and before the first call of
  73951. deflate(). The text, time, os, extra field, name, and comment information
  73952. in the provided gz_header structure are written to the gzip header (xflag is
  73953. ignored -- the extra flags are set according to the compression level). The
  73954. caller must assure that, if not Z_NULL, name and comment are terminated with
  73955. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  73956. available there. If hcrc is true, a gzip header crc is included. Note that
  73957. the current versions of the command-line version of gzip (up through version
  73958. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  73959. gzip file" and give up.
  73960. If deflateSetHeader is not used, the default gzip header has text false,
  73961. the time set to zero, and os set to 255, with no extra, name, or comment
  73962. fields. The gzip header is returned to the default state by deflateReset().
  73963. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  73964. stream state was inconsistent.
  73965. */
  73966. /*
  73967. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  73968. int windowBits));
  73969. This is another version of inflateInit with an extra parameter. The
  73970. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  73971. before by the caller.
  73972. The windowBits parameter is the base two logarithm of the maximum window
  73973. size (the size of the history buffer). It should be in the range 8..15 for
  73974. this version of the library. The default value is 15 if inflateInit is used
  73975. instead. windowBits must be greater than or equal to the windowBits value
  73976. provided to deflateInit2() while compressing, or it must be equal to 15 if
  73977. deflateInit2() was not used. If a compressed stream with a larger window
  73978. size is given as input, inflate() will return with the error code
  73979. Z_DATA_ERROR instead of trying to allocate a larger window.
  73980. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  73981. determines the window size. inflate() will then process raw deflate data,
  73982. not looking for a zlib or gzip header, not generating a check value, and not
  73983. looking for any check values for comparison at the end of the stream. This
  73984. is for use with other formats that use the deflate compressed data format
  73985. such as zip. Those formats provide their own check values. If a custom
  73986. format is developed using the raw deflate format for compressed data, it is
  73987. recommended that a check value such as an adler32 or a crc32 be applied to
  73988. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  73989. most applications, the zlib format should be used as is. Note that comments
  73990. above on the use in deflateInit2() applies to the magnitude of windowBits.
  73991. windowBits can also be greater than 15 for optional gzip decoding. Add
  73992. 32 to windowBits to enable zlib and gzip decoding with automatic header
  73993. detection, or add 16 to decode only the gzip format (the zlib format will
  73994. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  73995. a crc32 instead of an adler32.
  73996. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73997. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  73998. is set to null if there is no error message. inflateInit2 does not perform
  73999. any decompression apart from reading the zlib header if present: this will
  74000. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  74001. and avail_out are unchanged.)
  74002. */
  74003. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  74004. const Bytef *dictionary,
  74005. uInt dictLength));
  74006. /*
  74007. Initializes the decompression dictionary from the given uncompressed byte
  74008. sequence. This function must be called immediately after a call of inflate,
  74009. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  74010. can be determined from the adler32 value returned by that call of inflate.
  74011. The compressor and decompressor must use exactly the same dictionary (see
  74012. deflateSetDictionary). For raw inflate, this function can be called
  74013. immediately after inflateInit2() or inflateReset() and before any call of
  74014. inflate() to set the dictionary. The application must insure that the
  74015. dictionary that was used for compression is provided.
  74016. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  74017. parameter is invalid (such as NULL dictionary) or the stream state is
  74018. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  74019. expected one (incorrect adler32 value). inflateSetDictionary does not
  74020. perform any decompression: this will be done by subsequent calls of
  74021. inflate().
  74022. */
  74023. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  74024. /*
  74025. Skips invalid compressed data until a full flush point (see above the
  74026. description of deflate with Z_FULL_FLUSH) can be found, or until all
  74027. available input is skipped. No output is provided.
  74028. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  74029. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  74030. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  74031. case, the application may save the current current value of total_in which
  74032. indicates where valid compressed data was found. In the error case, the
  74033. application may repeatedly call inflateSync, providing more input each time,
  74034. until success or end of the input data.
  74035. */
  74036. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  74037. z_streamp source));
  74038. /*
  74039. Sets the destination stream as a complete copy of the source stream.
  74040. This function can be useful when randomly accessing a large stream. The
  74041. first pass through the stream can periodically record the inflate state,
  74042. allowing restarting inflate at those points when randomly accessing the
  74043. stream.
  74044. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74045. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74046. (such as zalloc being NULL). msg is left unchanged in both source and
  74047. destination.
  74048. */
  74049. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  74050. /*
  74051. This function is equivalent to inflateEnd followed by inflateInit,
  74052. but does not free and reallocate all the internal decompression state.
  74053. The stream will keep attributes that may have been set by inflateInit2.
  74054. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74055. stream state was inconsistent (such as zalloc or state being NULL).
  74056. */
  74057. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  74058. int bits,
  74059. int value));
  74060. /*
  74061. This function inserts bits in the inflate input stream. The intent is
  74062. that this function is used to start inflating at a bit position in the
  74063. middle of a byte. The provided bits will be used before any bytes are used
  74064. from next_in. This function should only be used with raw inflate, and
  74065. should be used before the first inflate() call after inflateInit2() or
  74066. inflateReset(). bits must be less than or equal to 16, and that many of the
  74067. least significant bits of value will be inserted in the input.
  74068. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74069. stream state was inconsistent.
  74070. */
  74071. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  74072. gz_headerp head));
  74073. /*
  74074. inflateGetHeader() requests that gzip header information be stored in the
  74075. provided gz_header structure. inflateGetHeader() may be called after
  74076. inflateInit2() or inflateReset(), and before the first call of inflate().
  74077. As inflate() processes the gzip stream, head->done is zero until the header
  74078. is completed, at which time head->done is set to one. If a zlib stream is
  74079. being decoded, then head->done is set to -1 to indicate that there will be
  74080. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  74081. force inflate() to return immediately after header processing is complete
  74082. and before any actual data is decompressed.
  74083. The text, time, xflags, and os fields are filled in with the gzip header
  74084. contents. hcrc is set to true if there is a header CRC. (The header CRC
  74085. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  74086. contains the maximum number of bytes to write to extra. Once done is true,
  74087. extra_len contains the actual extra field length, and extra contains the
  74088. extra field, or that field truncated if extra_max is less than extra_len.
  74089. If name is not Z_NULL, then up to name_max characters are written there,
  74090. terminated with a zero unless the length is greater than name_max. If
  74091. comment is not Z_NULL, then up to comm_max characters are written there,
  74092. terminated with a zero unless the length is greater than comm_max. When
  74093. any of extra, name, or comment are not Z_NULL and the respective field is
  74094. not present in the header, then that field is set to Z_NULL to signal its
  74095. absence. This allows the use of deflateSetHeader() with the returned
  74096. structure to duplicate the header. However if those fields are set to
  74097. allocated memory, then the application will need to save those pointers
  74098. elsewhere so that they can be eventually freed.
  74099. If inflateGetHeader is not used, then the header information is simply
  74100. discarded. The header is always checked for validity, including the header
  74101. CRC if present. inflateReset() will reset the process to discard the header
  74102. information. The application would need to call inflateGetHeader() again to
  74103. retrieve the header from the next gzip stream.
  74104. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74105. stream state was inconsistent.
  74106. */
  74107. /*
  74108. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  74109. unsigned char FAR *window));
  74110. Initialize the internal stream state for decompression using inflateBack()
  74111. calls. The fields zalloc, zfree and opaque in strm must be initialized
  74112. before the call. If zalloc and zfree are Z_NULL, then the default library-
  74113. derived memory allocation routines are used. windowBits is the base two
  74114. logarithm of the window size, in the range 8..15. window is a caller
  74115. supplied buffer of that size. Except for special applications where it is
  74116. assured that deflate was used with small window sizes, windowBits must be 15
  74117. and a 32K byte window must be supplied to be able to decompress general
  74118. deflate streams.
  74119. See inflateBack() for the usage of these routines.
  74120. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  74121. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  74122. be allocated, or Z_VERSION_ERROR if the version of the library does not
  74123. match the version of the header file.
  74124. */
  74125. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  74126. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  74127. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  74128. in_func in, void FAR *in_desc,
  74129. out_func out, void FAR *out_desc));
  74130. /*
  74131. inflateBack() does a raw inflate with a single call using a call-back
  74132. interface for input and output. This is more efficient than inflate() for
  74133. file i/o applications in that it avoids copying between the output and the
  74134. sliding window by simply making the window itself the output buffer. This
  74135. function trusts the application to not change the output buffer passed by
  74136. the output function, at least until inflateBack() returns.
  74137. inflateBackInit() must be called first to allocate the internal state
  74138. and to initialize the state with the user-provided window buffer.
  74139. inflateBack() may then be used multiple times to inflate a complete, raw
  74140. deflate stream with each call. inflateBackEnd() is then called to free
  74141. the allocated state.
  74142. A raw deflate stream is one with no zlib or gzip header or trailer.
  74143. This routine would normally be used in a utility that reads zip or gzip
  74144. files and writes out uncompressed files. The utility would decode the
  74145. header and process the trailer on its own, hence this routine expects
  74146. only the raw deflate stream to decompress. This is different from the
  74147. normal behavior of inflate(), which expects either a zlib or gzip header and
  74148. trailer around the deflate stream.
  74149. inflateBack() uses two subroutines supplied by the caller that are then
  74150. called by inflateBack() for input and output. inflateBack() calls those
  74151. routines until it reads a complete deflate stream and writes out all of the
  74152. uncompressed data, or until it encounters an error. The function's
  74153. parameters and return types are defined above in the in_func and out_func
  74154. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  74155. number of bytes of provided input, and a pointer to that input in buf. If
  74156. there is no input available, in() must return zero--buf is ignored in that
  74157. case--and inflateBack() will return a buffer error. inflateBack() will call
  74158. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  74159. should return zero on success, or non-zero on failure. If out() returns
  74160. non-zero, inflateBack() will return with an error. Neither in() nor out()
  74161. are permitted to change the contents of the window provided to
  74162. inflateBackInit(), which is also the buffer that out() uses to write from.
  74163. The length written by out() will be at most the window size. Any non-zero
  74164. amount of input may be provided by in().
  74165. For convenience, inflateBack() can be provided input on the first call by
  74166. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  74167. in() will be called. Therefore strm->next_in must be initialized before
  74168. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  74169. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  74170. must also be initialized, and then if strm->avail_in is not zero, input will
  74171. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  74172. The in_desc and out_desc parameters of inflateBack() is passed as the
  74173. first parameter of in() and out() respectively when they are called. These
  74174. descriptors can be optionally used to pass any information that the caller-
  74175. supplied in() and out() functions need to do their job.
  74176. On return, inflateBack() will set strm->next_in and strm->avail_in to
  74177. pass back any unused input that was provided by the last in() call. The
  74178. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  74179. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  74180. error in the deflate stream (in which case strm->msg is set to indicate the
  74181. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  74182. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  74183. distinguished using strm->next_in which will be Z_NULL only if in() returned
  74184. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  74185. out() returning non-zero. (in() will always be called before out(), so
  74186. strm->next_in is assured to be defined if out() returns non-zero.) Note
  74187. that inflateBack() cannot return Z_OK.
  74188. */
  74189. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  74190. /*
  74191. All memory allocated by inflateBackInit() is freed.
  74192. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  74193. state was inconsistent.
  74194. */
  74195. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  74196. /* Return flags indicating compile-time options.
  74197. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  74198. 1.0: size of uInt
  74199. 3.2: size of uLong
  74200. 5.4: size of voidpf (pointer)
  74201. 7.6: size of z_off_t
  74202. Compiler, assembler, and debug options:
  74203. 8: DEBUG
  74204. 9: ASMV or ASMINF -- use ASM code
  74205. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  74206. 11: 0 (reserved)
  74207. One-time table building (smaller code, but not thread-safe if true):
  74208. 12: BUILDFIXED -- build static block decoding tables when needed
  74209. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  74210. 14,15: 0 (reserved)
  74211. Library content (indicates missing functionality):
  74212. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  74213. deflate code when not needed)
  74214. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  74215. and decode gzip streams (to avoid linking crc code)
  74216. 18-19: 0 (reserved)
  74217. Operation variations (changes in library functionality):
  74218. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  74219. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  74220. 22,23: 0 (reserved)
  74221. The sprintf variant used by gzprintf (zero is best):
  74222. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  74223. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  74224. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  74225. Remainder:
  74226. 27-31: 0 (reserved)
  74227. */
  74228. /* utility functions */
  74229. /*
  74230. The following utility functions are implemented on top of the
  74231. basic stream-oriented functions. To simplify the interface, some
  74232. default options are assumed (compression level and memory usage,
  74233. standard memory allocation functions). The source code of these
  74234. utility functions can easily be modified if you need special options.
  74235. */
  74236. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  74237. const Bytef *source, uLong sourceLen));
  74238. /*
  74239. Compresses the source buffer into the destination buffer. sourceLen is
  74240. the byte length of the source buffer. Upon entry, destLen is the total
  74241. size of the destination buffer, which must be at least the value returned
  74242. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74243. compressed buffer.
  74244. This function can be used to compress a whole file at once if the
  74245. input file is mmap'ed.
  74246. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  74247. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74248. buffer.
  74249. */
  74250. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  74251. const Bytef *source, uLong sourceLen,
  74252. int level));
  74253. /*
  74254. Compresses the source buffer into the destination buffer. The level
  74255. parameter has the same meaning as in deflateInit. sourceLen is the byte
  74256. length of the source buffer. Upon entry, destLen is the total size of the
  74257. destination buffer, which must be at least the value returned by
  74258. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74259. compressed buffer.
  74260. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74261. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  74262. Z_STREAM_ERROR if the level parameter is invalid.
  74263. */
  74264. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  74265. /*
  74266. compressBound() returns an upper bound on the compressed size after
  74267. compress() or compress2() on sourceLen bytes. It would be used before
  74268. a compress() or compress2() call to allocate the destination buffer.
  74269. */
  74270. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  74271. const Bytef *source, uLong sourceLen));
  74272. /*
  74273. Decompresses the source buffer into the destination buffer. sourceLen is
  74274. the byte length of the source buffer. Upon entry, destLen is the total
  74275. size of the destination buffer, which must be large enough to hold the
  74276. entire uncompressed data. (The size of the uncompressed data must have
  74277. been saved previously by the compressor and transmitted to the decompressor
  74278. by some mechanism outside the scope of this compression library.)
  74279. Upon exit, destLen is the actual size of the compressed buffer.
  74280. This function can be used to decompress a whole file at once if the
  74281. input file is mmap'ed.
  74282. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  74283. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74284. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  74285. */
  74286. typedef voidp gzFile;
  74287. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  74288. /*
  74289. Opens a gzip (.gz) file for reading or writing. The mode parameter
  74290. is as in fopen ("rb" or "wb") but can also include a compression level
  74291. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  74292. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  74293. as in "wb1R". (See the description of deflateInit2 for more information
  74294. about the strategy parameter.)
  74295. gzopen can be used to read a file which is not in gzip format; in this
  74296. case gzread will directly read from the file without decompression.
  74297. gzopen returns NULL if the file could not be opened or if there was
  74298. insufficient memory to allocate the (de)compression state; errno
  74299. can be checked to distinguish the two cases (if errno is zero, the
  74300. zlib error is Z_MEM_ERROR). */
  74301. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  74302. /*
  74303. gzdopen() associates a gzFile with the file descriptor fd. File
  74304. descriptors are obtained from calls like open, dup, creat, pipe or
  74305. fileno (in the file has been previously opened with fopen).
  74306. The mode parameter is as in gzopen.
  74307. The next call of gzclose on the returned gzFile will also close the
  74308. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  74309. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  74310. gzdopen returns NULL if there was insufficient memory to allocate
  74311. the (de)compression state.
  74312. */
  74313. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  74314. /*
  74315. Dynamically update the compression level or strategy. See the description
  74316. of deflateInit2 for the meaning of these parameters.
  74317. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  74318. opened for writing.
  74319. */
  74320. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  74321. /*
  74322. Reads the given number of uncompressed bytes from the compressed file.
  74323. If the input file was not in gzip format, gzread copies the given number
  74324. of bytes into the buffer.
  74325. gzread returns the number of uncompressed bytes actually read (0 for
  74326. end of file, -1 for error). */
  74327. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  74328. voidpc buf, unsigned len));
  74329. /*
  74330. Writes the given number of uncompressed bytes into the compressed file.
  74331. gzwrite returns the number of uncompressed bytes actually written
  74332. (0 in case of error).
  74333. */
  74334. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  74335. /*
  74336. Converts, formats, and writes the args to the compressed file under
  74337. control of the format string, as in fprintf. gzprintf returns the number of
  74338. uncompressed bytes actually written (0 in case of error). The number of
  74339. uncompressed bytes written is limited to 4095. The caller should assure that
  74340. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  74341. return an error (0) with nothing written. In this case, there may also be a
  74342. buffer overflow with unpredictable consequences, which is possible only if
  74343. zlib was compiled with the insecure functions sprintf() or vsprintf()
  74344. because the secure snprintf() or vsnprintf() functions were not available.
  74345. */
  74346. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  74347. /*
  74348. Writes the given null-terminated string to the compressed file, excluding
  74349. the terminating null character.
  74350. gzputs returns the number of characters written, or -1 in case of error.
  74351. */
  74352. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  74353. /*
  74354. Reads bytes from the compressed file until len-1 characters are read, or
  74355. a newline character is read and transferred to buf, or an end-of-file
  74356. condition is encountered. The string is then terminated with a null
  74357. character.
  74358. gzgets returns buf, or Z_NULL in case of error.
  74359. */
  74360. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  74361. /*
  74362. Writes c, converted to an unsigned char, into the compressed file.
  74363. gzputc returns the value that was written, or -1 in case of error.
  74364. */
  74365. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  74366. /*
  74367. Reads one byte from the compressed file. gzgetc returns this byte
  74368. or -1 in case of end of file or error.
  74369. */
  74370. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  74371. /*
  74372. Push one character back onto the stream to be read again later.
  74373. Only one character of push-back is allowed. gzungetc() returns the
  74374. character pushed, or -1 on failure. gzungetc() will fail if a
  74375. character has been pushed but not read yet, or if c is -1. The pushed
  74376. character will be discarded if the stream is repositioned with gzseek()
  74377. or gzrewind().
  74378. */
  74379. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  74380. /*
  74381. Flushes all pending output into the compressed file. The parameter
  74382. flush is as in the deflate() function. The return value is the zlib
  74383. error number (see function gzerror below). gzflush returns Z_OK if
  74384. the flush parameter is Z_FINISH and all output could be flushed.
  74385. gzflush should be called only when strictly necessary because it can
  74386. degrade compression.
  74387. */
  74388. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  74389. z_off_t offset, int whence));
  74390. /*
  74391. Sets the starting position for the next gzread or gzwrite on the
  74392. given compressed file. The offset represents a number of bytes in the
  74393. uncompressed data stream. The whence parameter is defined as in lseek(2);
  74394. the value SEEK_END is not supported.
  74395. If the file is opened for reading, this function is emulated but can be
  74396. extremely slow. If the file is opened for writing, only forward seeks are
  74397. supported; gzseek then compresses a sequence of zeroes up to the new
  74398. starting position.
  74399. gzseek returns the resulting offset location as measured in bytes from
  74400. the beginning of the uncompressed stream, or -1 in case of error, in
  74401. particular if the file is opened for writing and the new starting position
  74402. would be before the current position.
  74403. */
  74404. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  74405. /*
  74406. Rewinds the given file. This function is supported only for reading.
  74407. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  74408. */
  74409. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  74410. /*
  74411. Returns the starting position for the next gzread or gzwrite on the
  74412. given compressed file. This position represents a number of bytes in the
  74413. uncompressed data stream.
  74414. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  74415. */
  74416. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  74417. /*
  74418. Returns 1 when EOF has previously been detected reading the given
  74419. input stream, otherwise zero.
  74420. */
  74421. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  74422. /*
  74423. Returns 1 if file is being read directly without decompression, otherwise
  74424. zero.
  74425. */
  74426. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  74427. /*
  74428. Flushes all pending output if necessary, closes the compressed file
  74429. and deallocates all the (de)compression state. The return value is the zlib
  74430. error number (see function gzerror below).
  74431. */
  74432. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  74433. /*
  74434. Returns the error message for the last error which occurred on the
  74435. given compressed file. errnum is set to zlib error number. If an
  74436. error occurred in the file system and not in the compression library,
  74437. errnum is set to Z_ERRNO and the application may consult errno
  74438. to get the exact error code.
  74439. */
  74440. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  74441. /*
  74442. Clears the error and end-of-file flags for file. This is analogous to the
  74443. clearerr() function in stdio. This is useful for continuing to read a gzip
  74444. file that is being written concurrently.
  74445. */
  74446. /* checksum functions */
  74447. /*
  74448. These functions are not related to compression but are exported
  74449. anyway because they might be useful in applications using the
  74450. compression library.
  74451. */
  74452. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  74453. /*
  74454. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  74455. return the updated checksum. If buf is NULL, this function returns
  74456. the required initial value for the checksum.
  74457. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  74458. much faster. Usage example:
  74459. uLong adler = adler32(0L, Z_NULL, 0);
  74460. while (read_buffer(buffer, length) != EOF) {
  74461. adler = adler32(adler, buffer, length);
  74462. }
  74463. if (adler != original_adler) error();
  74464. */
  74465. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  74466. z_off_t len2));
  74467. /*
  74468. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  74469. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  74470. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  74471. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  74472. */
  74473. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  74474. /*
  74475. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  74476. updated CRC-32. If buf is NULL, this function returns the required initial
  74477. value for the for the crc. Pre- and post-conditioning (one's complement) is
  74478. performed within this function so it shouldn't be done by the application.
  74479. Usage example:
  74480. uLong crc = crc32(0L, Z_NULL, 0);
  74481. while (read_buffer(buffer, length) != EOF) {
  74482. crc = crc32(crc, buffer, length);
  74483. }
  74484. if (crc != original_crc) error();
  74485. */
  74486. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  74487. /*
  74488. Combine two CRC-32 check values into one. For two sequences of bytes,
  74489. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  74490. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  74491. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  74492. len2.
  74493. */
  74494. /* various hacks, don't look :) */
  74495. /* deflateInit and inflateInit are macros to allow checking the zlib version
  74496. * and the compiler's view of z_stream:
  74497. */
  74498. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  74499. const char *version, int stream_size));
  74500. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  74501. const char *version, int stream_size));
  74502. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  74503. int windowBits, int memLevel,
  74504. int strategy, const char *version,
  74505. int stream_size));
  74506. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  74507. const char *version, int stream_size));
  74508. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  74509. unsigned char FAR *window,
  74510. const char *version,
  74511. int stream_size));
  74512. #define deflateInit(strm, level) \
  74513. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  74514. #define inflateInit(strm) \
  74515. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  74516. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  74517. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  74518. (strategy), ZLIB_VERSION, sizeof(z_stream))
  74519. #define inflateInit2(strm, windowBits) \
  74520. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  74521. #define inflateBackInit(strm, windowBits, window) \
  74522. inflateBackInit_((strm), (windowBits), (window), \
  74523. ZLIB_VERSION, sizeof(z_stream))
  74524. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  74525. struct internal_state {int dummy;}; /* hack for buggy compilers */
  74526. #endif
  74527. ZEXTERN const char * ZEXPORT zError OF((int));
  74528. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  74529. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  74530. #ifdef __cplusplus
  74531. }
  74532. #endif
  74533. #endif /* ZLIB_H */
  74534. /********* End of inlined file: zlib.h *********/
  74535. #undef OS_CODE
  74536. #else
  74537. #include <zlib.h>
  74538. #endif
  74539. }
  74540. BEGIN_JUCE_NAMESPACE
  74541. using namespace zlibNamespace;
  74542. // internal helper object that holds the zlib structures so they don't have to be
  74543. // included publicly.
  74544. class GZIPCompressorHelper
  74545. {
  74546. private:
  74547. z_stream* stream;
  74548. uint8* data;
  74549. int dataSize, compLevel, strategy;
  74550. bool setParams;
  74551. public:
  74552. bool finished, shouldFinish;
  74553. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  74554. : data (0),
  74555. dataSize (0),
  74556. compLevel (compressionLevel),
  74557. strategy (0),
  74558. setParams (true),
  74559. finished (false),
  74560. shouldFinish (false)
  74561. {
  74562. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  74563. if (deflateInit2 (stream,
  74564. compLevel,
  74565. Z_DEFLATED,
  74566. nowrap ? -MAX_WBITS : MAX_WBITS,
  74567. 8,
  74568. strategy) != Z_OK)
  74569. {
  74570. juce_free (stream);
  74571. stream = 0;
  74572. }
  74573. }
  74574. ~GZIPCompressorHelper()
  74575. {
  74576. if (stream != 0)
  74577. {
  74578. deflateEnd (stream);
  74579. juce_free (stream);
  74580. }
  74581. }
  74582. bool needsInput() const throw()
  74583. {
  74584. return dataSize <= 0;
  74585. }
  74586. void setInput (uint8* const newData, const int size) throw()
  74587. {
  74588. data = newData;
  74589. dataSize = size;
  74590. }
  74591. int doNextBlock (uint8* const dest, const int destSize) throw()
  74592. {
  74593. if (stream != 0)
  74594. {
  74595. stream->next_in = data;
  74596. stream->next_out = dest;
  74597. stream->avail_in = dataSize;
  74598. stream->avail_out = destSize;
  74599. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  74600. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  74601. setParams = false;
  74602. switch (result)
  74603. {
  74604. case Z_STREAM_END:
  74605. finished = true;
  74606. case Z_OK:
  74607. data += dataSize - stream->avail_in;
  74608. dataSize = stream->avail_in;
  74609. return destSize - stream->avail_out;
  74610. default:
  74611. break;
  74612. }
  74613. }
  74614. return 0;
  74615. }
  74616. };
  74617. const int gzipCompBufferSize = 32768;
  74618. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  74619. int compressionLevel,
  74620. const bool deleteDestStream_,
  74621. const bool noWrap)
  74622. : destStream (destStream_),
  74623. deleteDestStream (deleteDestStream_)
  74624. {
  74625. if (compressionLevel < 1 || compressionLevel > 9)
  74626. compressionLevel = -1;
  74627. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  74628. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  74629. }
  74630. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  74631. {
  74632. flush();
  74633. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  74634. delete h;
  74635. juce_free (buffer);
  74636. if (deleteDestStream)
  74637. delete destStream;
  74638. }
  74639. void GZIPCompressorOutputStream::flush()
  74640. {
  74641. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  74642. if (! h->finished)
  74643. {
  74644. h->shouldFinish = true;
  74645. while (! h->finished)
  74646. doNextBlock();
  74647. }
  74648. destStream->flush();
  74649. }
  74650. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  74651. {
  74652. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  74653. if (! h->finished)
  74654. {
  74655. h->setInput ((uint8*) destBuffer, howMany);
  74656. while (! h->needsInput())
  74657. {
  74658. if (! doNextBlock())
  74659. return false;
  74660. }
  74661. }
  74662. return true;
  74663. }
  74664. bool GZIPCompressorOutputStream::doNextBlock()
  74665. {
  74666. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  74667. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  74668. if (len > 0)
  74669. return destStream->write (buffer, len);
  74670. else
  74671. return true;
  74672. }
  74673. int64 GZIPCompressorOutputStream::getPosition()
  74674. {
  74675. return destStream->getPosition();
  74676. }
  74677. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  74678. {
  74679. jassertfalse // can't do it!
  74680. return false;
  74681. }
  74682. END_JUCE_NAMESPACE
  74683. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  74684. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  74685. #if JUCE_MSVC
  74686. #pragma warning (push)
  74687. #pragma warning (disable: 4309 4305)
  74688. #endif
  74689. namespace zlibNamespace
  74690. {
  74691. #if JUCE_INCLUDE_ZLIB_CODE
  74692. extern "C"
  74693. {
  74694. #undef OS_CODE
  74695. #undef fdopen
  74696. #define ZLIB_INTERNAL
  74697. #define NO_DUMMY_DECL
  74698. /********* Start of inlined file: adler32.c *********/
  74699. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74700. #define ZLIB_INTERNAL
  74701. #define BASE 65521UL /* largest prime smaller than 65536 */
  74702. #define NMAX 5552
  74703. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  74704. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  74705. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  74706. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  74707. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  74708. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  74709. /* use NO_DIVIDE if your processor does not do division in hardware */
  74710. #ifdef NO_DIVIDE
  74711. # define MOD(a) \
  74712. do { \
  74713. if (a >= (BASE << 16)) a -= (BASE << 16); \
  74714. if (a >= (BASE << 15)) a -= (BASE << 15); \
  74715. if (a >= (BASE << 14)) a -= (BASE << 14); \
  74716. if (a >= (BASE << 13)) a -= (BASE << 13); \
  74717. if (a >= (BASE << 12)) a -= (BASE << 12); \
  74718. if (a >= (BASE << 11)) a -= (BASE << 11); \
  74719. if (a >= (BASE << 10)) a -= (BASE << 10); \
  74720. if (a >= (BASE << 9)) a -= (BASE << 9); \
  74721. if (a >= (BASE << 8)) a -= (BASE << 8); \
  74722. if (a >= (BASE << 7)) a -= (BASE << 7); \
  74723. if (a >= (BASE << 6)) a -= (BASE << 6); \
  74724. if (a >= (BASE << 5)) a -= (BASE << 5); \
  74725. if (a >= (BASE << 4)) a -= (BASE << 4); \
  74726. if (a >= (BASE << 3)) a -= (BASE << 3); \
  74727. if (a >= (BASE << 2)) a -= (BASE << 2); \
  74728. if (a >= (BASE << 1)) a -= (BASE << 1); \
  74729. if (a >= BASE) a -= BASE; \
  74730. } while (0)
  74731. # define MOD4(a) \
  74732. do { \
  74733. if (a >= (BASE << 4)) a -= (BASE << 4); \
  74734. if (a >= (BASE << 3)) a -= (BASE << 3); \
  74735. if (a >= (BASE << 2)) a -= (BASE << 2); \
  74736. if (a >= (BASE << 1)) a -= (BASE << 1); \
  74737. if (a >= BASE) a -= BASE; \
  74738. } while (0)
  74739. #else
  74740. # define MOD(a) a %= BASE
  74741. # define MOD4(a) a %= BASE
  74742. #endif
  74743. /* ========================================================================= */
  74744. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  74745. {
  74746. unsigned long sum2;
  74747. unsigned n;
  74748. /* split Adler-32 into component sums */
  74749. sum2 = (adler >> 16) & 0xffff;
  74750. adler &= 0xffff;
  74751. /* in case user likes doing a byte at a time, keep it fast */
  74752. if (len == 1) {
  74753. adler += buf[0];
  74754. if (adler >= BASE)
  74755. adler -= BASE;
  74756. sum2 += adler;
  74757. if (sum2 >= BASE)
  74758. sum2 -= BASE;
  74759. return adler | (sum2 << 16);
  74760. }
  74761. /* initial Adler-32 value (deferred check for len == 1 speed) */
  74762. if (buf == Z_NULL)
  74763. return 1L;
  74764. /* in case short lengths are provided, keep it somewhat fast */
  74765. if (len < 16) {
  74766. while (len--) {
  74767. adler += *buf++;
  74768. sum2 += adler;
  74769. }
  74770. if (adler >= BASE)
  74771. adler -= BASE;
  74772. MOD4(sum2); /* only added so many BASE's */
  74773. return adler | (sum2 << 16);
  74774. }
  74775. /* do length NMAX blocks -- requires just one modulo operation */
  74776. while (len >= NMAX) {
  74777. len -= NMAX;
  74778. n = NMAX / 16; /* NMAX is divisible by 16 */
  74779. do {
  74780. DO16(buf); /* 16 sums unrolled */
  74781. buf += 16;
  74782. } while (--n);
  74783. MOD(adler);
  74784. MOD(sum2);
  74785. }
  74786. /* do remaining bytes (less than NMAX, still just one modulo) */
  74787. if (len) { /* avoid modulos if none remaining */
  74788. while (len >= 16) {
  74789. len -= 16;
  74790. DO16(buf);
  74791. buf += 16;
  74792. }
  74793. while (len--) {
  74794. adler += *buf++;
  74795. sum2 += adler;
  74796. }
  74797. MOD(adler);
  74798. MOD(sum2);
  74799. }
  74800. /* return recombined sums */
  74801. return adler | (sum2 << 16);
  74802. }
  74803. /* ========================================================================= */
  74804. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  74805. {
  74806. unsigned long sum1;
  74807. unsigned long sum2;
  74808. unsigned rem;
  74809. /* the derivation of this formula is left as an exercise for the reader */
  74810. rem = (unsigned)(len2 % BASE);
  74811. sum1 = adler1 & 0xffff;
  74812. sum2 = rem * sum1;
  74813. MOD(sum2);
  74814. sum1 += (adler2 & 0xffff) + BASE - 1;
  74815. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  74816. if (sum1 > BASE) sum1 -= BASE;
  74817. if (sum1 > BASE) sum1 -= BASE;
  74818. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  74819. if (sum2 > BASE) sum2 -= BASE;
  74820. return sum1 | (sum2 << 16);
  74821. }
  74822. /********* End of inlined file: adler32.c *********/
  74823. /********* Start of inlined file: compress.c *********/
  74824. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74825. #define ZLIB_INTERNAL
  74826. /* ===========================================================================
  74827. Compresses the source buffer into the destination buffer. The level
  74828. parameter has the same meaning as in deflateInit. sourceLen is the byte
  74829. length of the source buffer. Upon entry, destLen is the total size of the
  74830. destination buffer, which must be at least 0.1% larger than sourceLen plus
  74831. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  74832. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74833. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  74834. Z_STREAM_ERROR if the level parameter is invalid.
  74835. */
  74836. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  74837. uLong sourceLen, int level)
  74838. {
  74839. z_stream stream;
  74840. int err;
  74841. stream.next_in = (Bytef*)source;
  74842. stream.avail_in = (uInt)sourceLen;
  74843. #ifdef MAXSEG_64K
  74844. /* Check for source > 64K on 16-bit machine: */
  74845. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  74846. #endif
  74847. stream.next_out = dest;
  74848. stream.avail_out = (uInt)*destLen;
  74849. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  74850. stream.zalloc = (alloc_func)0;
  74851. stream.zfree = (free_func)0;
  74852. stream.opaque = (voidpf)0;
  74853. err = deflateInit(&stream, level);
  74854. if (err != Z_OK) return err;
  74855. err = deflate(&stream, Z_FINISH);
  74856. if (err != Z_STREAM_END) {
  74857. deflateEnd(&stream);
  74858. return err == Z_OK ? Z_BUF_ERROR : err;
  74859. }
  74860. *destLen = stream.total_out;
  74861. err = deflateEnd(&stream);
  74862. return err;
  74863. }
  74864. /* ===========================================================================
  74865. */
  74866. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  74867. {
  74868. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  74869. }
  74870. /* ===========================================================================
  74871. If the default memLevel or windowBits for deflateInit() is changed, then
  74872. this function needs to be updated.
  74873. */
  74874. uLong ZEXPORT compressBound (uLong sourceLen)
  74875. {
  74876. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  74877. }
  74878. /********* End of inlined file: compress.c *********/
  74879. #undef DO1
  74880. #undef DO8
  74881. /********* Start of inlined file: crc32.c *********/
  74882. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74883. /*
  74884. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  74885. protection on the static variables used to control the first-use generation
  74886. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  74887. first call get_crc_table() to initialize the tables before allowing more than
  74888. one thread to use crc32().
  74889. */
  74890. #ifdef MAKECRCH
  74891. # include <stdio.h>
  74892. # ifndef DYNAMIC_CRC_TABLE
  74893. # define DYNAMIC_CRC_TABLE
  74894. # endif /* !DYNAMIC_CRC_TABLE */
  74895. #endif /* MAKECRCH */
  74896. /********* Start of inlined file: zutil.h *********/
  74897. /* WARNING: this file should *not* be used by applications. It is
  74898. part of the implementation of the compression library and is
  74899. subject to change. Applications should only use zlib.h.
  74900. */
  74901. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74902. #ifndef ZUTIL_H
  74903. #define ZUTIL_H
  74904. #define ZLIB_INTERNAL
  74905. #ifdef STDC
  74906. # ifndef _WIN32_WCE
  74907. # include <stddef.h>
  74908. # endif
  74909. # include <string.h>
  74910. # include <stdlib.h>
  74911. #endif
  74912. #ifdef NO_ERRNO_H
  74913. # ifdef _WIN32_WCE
  74914. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  74915. * errno. We define it as a global variable to simplify porting.
  74916. * Its value is always 0 and should not be used. We rename it to
  74917. * avoid conflict with other libraries that use the same workaround.
  74918. */
  74919. # define errno z_errno
  74920. # endif
  74921. extern int errno;
  74922. #else
  74923. # ifndef _WIN32_WCE
  74924. # include <errno.h>
  74925. # endif
  74926. #endif
  74927. #ifndef local
  74928. # define local static
  74929. #endif
  74930. /* compile with -Dlocal if your debugger can't find static symbols */
  74931. typedef unsigned char uch;
  74932. typedef uch FAR uchf;
  74933. typedef unsigned short ush;
  74934. typedef ush FAR ushf;
  74935. typedef unsigned long ulg;
  74936. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  74937. /* (size given to avoid silly warnings with Visual C++) */
  74938. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  74939. #define ERR_RETURN(strm,err) \
  74940. return (strm->msg = (char*)ERR_MSG(err), (err))
  74941. /* To be used only when the state is known to be valid */
  74942. /* common constants */
  74943. #ifndef DEF_WBITS
  74944. # define DEF_WBITS MAX_WBITS
  74945. #endif
  74946. /* default windowBits for decompression. MAX_WBITS is for compression only */
  74947. #if MAX_MEM_LEVEL >= 8
  74948. # define DEF_MEM_LEVEL 8
  74949. #else
  74950. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  74951. #endif
  74952. /* default memLevel */
  74953. #define STORED_BLOCK 0
  74954. #define STATIC_TREES 1
  74955. #define DYN_TREES 2
  74956. /* The three kinds of block type */
  74957. #define MIN_MATCH 3
  74958. #define MAX_MATCH 258
  74959. /* The minimum and maximum match lengths */
  74960. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  74961. /* target dependencies */
  74962. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  74963. # define OS_CODE 0x00
  74964. # if defined(__TURBOC__) || defined(__BORLANDC__)
  74965. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  74966. /* Allow compilation with ANSI keywords only enabled */
  74967. void _Cdecl farfree( void *block );
  74968. void *_Cdecl farmalloc( unsigned long nbytes );
  74969. # else
  74970. # include <alloc.h>
  74971. # endif
  74972. # else /* MSC or DJGPP */
  74973. # include <malloc.h>
  74974. # endif
  74975. #endif
  74976. #ifdef AMIGA
  74977. # define OS_CODE 0x01
  74978. #endif
  74979. #if defined(VAXC) || defined(VMS)
  74980. # define OS_CODE 0x02
  74981. # define F_OPEN(name, mode) \
  74982. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  74983. #endif
  74984. #if defined(ATARI) || defined(atarist)
  74985. # define OS_CODE 0x05
  74986. #endif
  74987. #ifdef OS2
  74988. # define OS_CODE 0x06
  74989. # ifdef M_I86
  74990. #include <malloc.h>
  74991. # endif
  74992. #endif
  74993. #if defined(MACOS) || TARGET_OS_MAC
  74994. # define OS_CODE 0x07
  74995. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  74996. # include <unix.h> /* for fdopen */
  74997. # else
  74998. # ifndef fdopen
  74999. # define fdopen(fd,mode) NULL /* No fdopen() */
  75000. # endif
  75001. # endif
  75002. #endif
  75003. #ifdef TOPS20
  75004. # define OS_CODE 0x0a
  75005. #endif
  75006. #ifdef WIN32
  75007. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  75008. # define OS_CODE 0x0b
  75009. # endif
  75010. #endif
  75011. #ifdef __50SERIES /* Prime/PRIMOS */
  75012. # define OS_CODE 0x0f
  75013. #endif
  75014. #if defined(_BEOS_) || defined(RISCOS)
  75015. # define fdopen(fd,mode) NULL /* No fdopen() */
  75016. #endif
  75017. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  75018. # if defined(_WIN32_WCE)
  75019. # define fdopen(fd,mode) NULL /* No fdopen() */
  75020. # ifndef _PTRDIFF_T_DEFINED
  75021. typedef int ptrdiff_t;
  75022. # define _PTRDIFF_T_DEFINED
  75023. # endif
  75024. # else
  75025. # define fdopen(fd,type) _fdopen(fd,type)
  75026. # endif
  75027. #endif
  75028. /* common defaults */
  75029. #ifndef OS_CODE
  75030. # define OS_CODE 0x03 /* assume Unix */
  75031. #endif
  75032. #ifndef F_OPEN
  75033. # define F_OPEN(name, mode) fopen((name), (mode))
  75034. #endif
  75035. /* functions */
  75036. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  75037. # ifndef HAVE_VSNPRINTF
  75038. # define HAVE_VSNPRINTF
  75039. # endif
  75040. #endif
  75041. #if defined(__CYGWIN__)
  75042. # ifndef HAVE_VSNPRINTF
  75043. # define HAVE_VSNPRINTF
  75044. # endif
  75045. #endif
  75046. #ifndef HAVE_VSNPRINTF
  75047. # ifdef MSDOS
  75048. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  75049. but for now we just assume it doesn't. */
  75050. # define NO_vsnprintf
  75051. # endif
  75052. # ifdef __TURBOC__
  75053. # define NO_vsnprintf
  75054. # endif
  75055. # ifdef WIN32
  75056. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  75057. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  75058. # define vsnprintf _vsnprintf
  75059. # endif
  75060. # endif
  75061. # ifdef __SASC
  75062. # define NO_vsnprintf
  75063. # endif
  75064. #endif
  75065. #ifdef VMS
  75066. # define NO_vsnprintf
  75067. #endif
  75068. #if defined(pyr)
  75069. # define NO_MEMCPY
  75070. #endif
  75071. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  75072. /* Use our own functions for small and medium model with MSC <= 5.0.
  75073. * You may have to use the same strategy for Borland C (untested).
  75074. * The __SC__ check is for Symantec.
  75075. */
  75076. # define NO_MEMCPY
  75077. #endif
  75078. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  75079. # define HAVE_MEMCPY
  75080. #endif
  75081. #ifdef HAVE_MEMCPY
  75082. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  75083. # define zmemcpy _fmemcpy
  75084. # define zmemcmp _fmemcmp
  75085. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  75086. # else
  75087. # define zmemcpy memcpy
  75088. # define zmemcmp memcmp
  75089. # define zmemzero(dest, len) memset(dest, 0, len)
  75090. # endif
  75091. #else
  75092. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  75093. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  75094. extern void zmemzero OF((Bytef* dest, uInt len));
  75095. #endif
  75096. /* Diagnostic functions */
  75097. #ifdef DEBUG
  75098. # include <stdio.h>
  75099. extern int z_verbose;
  75100. extern void z_error OF((const char *m));
  75101. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  75102. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  75103. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  75104. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  75105. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  75106. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  75107. #else
  75108. # define Assert(cond,msg)
  75109. # define Trace(x)
  75110. # define Tracev(x)
  75111. # define Tracevv(x)
  75112. # define Tracec(c,x)
  75113. # define Tracecv(c,x)
  75114. #endif
  75115. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  75116. void zcfree OF((voidpf opaque, voidpf ptr));
  75117. #define ZALLOC(strm, items, size) \
  75118. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  75119. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  75120. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  75121. #endif /* ZUTIL_H */
  75122. /********* End of inlined file: zutil.h *********/
  75123. /* for STDC and FAR definitions */
  75124. #define local static
  75125. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  75126. #ifndef NOBYFOUR
  75127. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  75128. # include <limits.h>
  75129. # define BYFOUR
  75130. # if (UINT_MAX == 0xffffffffUL)
  75131. typedef unsigned int u4;
  75132. # else
  75133. # if (ULONG_MAX == 0xffffffffUL)
  75134. typedef unsigned long u4;
  75135. # else
  75136. # if (USHRT_MAX == 0xffffffffUL)
  75137. typedef unsigned short u4;
  75138. # else
  75139. # undef BYFOUR /* can't find a four-byte integer type! */
  75140. # endif
  75141. # endif
  75142. # endif
  75143. # endif /* STDC */
  75144. #endif /* !NOBYFOUR */
  75145. /* Definitions for doing the crc four data bytes at a time. */
  75146. #ifdef BYFOUR
  75147. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  75148. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  75149. local unsigned long crc32_little OF((unsigned long,
  75150. const unsigned char FAR *, unsigned));
  75151. local unsigned long crc32_big OF((unsigned long,
  75152. const unsigned char FAR *, unsigned));
  75153. # define TBLS 8
  75154. #else
  75155. # define TBLS 1
  75156. #endif /* BYFOUR */
  75157. /* Local functions for crc concatenation */
  75158. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  75159. unsigned long vec));
  75160. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  75161. #ifdef DYNAMIC_CRC_TABLE
  75162. local volatile int crc_table_empty = 1;
  75163. local unsigned long FAR crc_table[TBLS][256];
  75164. local void make_crc_table OF((void));
  75165. #ifdef MAKECRCH
  75166. local void write_table OF((FILE *, const unsigned long FAR *));
  75167. #endif /* MAKECRCH */
  75168. /*
  75169. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  75170. 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.
  75171. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  75172. with the lowest powers in the most significant bit. Then adding polynomials
  75173. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  75174. one. If we call the above polynomial p, and represent a byte as the
  75175. polynomial q, also with the lowest power in the most significant bit (so the
  75176. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  75177. where a mod b means the remainder after dividing a by b.
  75178. This calculation is done using the shift-register method of multiplying and
  75179. taking the remainder. The register is initialized to zero, and for each
  75180. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  75181. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  75182. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  75183. out is a one). We start with the highest power (least significant bit) of
  75184. q and repeat for all eight bits of q.
  75185. The first table is simply the CRC of all possible eight bit values. This is
  75186. all the information needed to generate CRCs on data a byte at a time for all
  75187. combinations of CRC register values and incoming bytes. The remaining tables
  75188. allow for word-at-a-time CRC calculation for both big-endian and little-
  75189. endian machines, where a word is four bytes.
  75190. */
  75191. local void make_crc_table()
  75192. {
  75193. unsigned long c;
  75194. int n, k;
  75195. unsigned long poly; /* polynomial exclusive-or pattern */
  75196. /* terms of polynomial defining this crc (except x^32): */
  75197. static volatile int first = 1; /* flag to limit concurrent making */
  75198. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  75199. /* See if another task is already doing this (not thread-safe, but better
  75200. than nothing -- significantly reduces duration of vulnerability in
  75201. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  75202. if (first) {
  75203. first = 0;
  75204. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  75205. poly = 0UL;
  75206. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  75207. poly |= 1UL << (31 - p[n]);
  75208. /* generate a crc for every 8-bit value */
  75209. for (n = 0; n < 256; n++) {
  75210. c = (unsigned long)n;
  75211. for (k = 0; k < 8; k++)
  75212. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  75213. crc_table[0][n] = c;
  75214. }
  75215. #ifdef BYFOUR
  75216. /* generate crc for each value followed by one, two, and three zeros,
  75217. and then the byte reversal of those as well as the first table */
  75218. for (n = 0; n < 256; n++) {
  75219. c = crc_table[0][n];
  75220. crc_table[4][n] = REV(c);
  75221. for (k = 1; k < 4; k++) {
  75222. c = crc_table[0][c & 0xff] ^ (c >> 8);
  75223. crc_table[k][n] = c;
  75224. crc_table[k + 4][n] = REV(c);
  75225. }
  75226. }
  75227. #endif /* BYFOUR */
  75228. crc_table_empty = 0;
  75229. }
  75230. else { /* not first */
  75231. /* wait for the other guy to finish (not efficient, but rare) */
  75232. while (crc_table_empty)
  75233. ;
  75234. }
  75235. #ifdef MAKECRCH
  75236. /* write out CRC tables to crc32.h */
  75237. {
  75238. FILE *out;
  75239. out = fopen("crc32.h", "w");
  75240. if (out == NULL) return;
  75241. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  75242. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  75243. fprintf(out, "local const unsigned long FAR ");
  75244. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  75245. write_table(out, crc_table[0]);
  75246. # ifdef BYFOUR
  75247. fprintf(out, "#ifdef BYFOUR\n");
  75248. for (k = 1; k < 8; k++) {
  75249. fprintf(out, " },\n {\n");
  75250. write_table(out, crc_table[k]);
  75251. }
  75252. fprintf(out, "#endif\n");
  75253. # endif /* BYFOUR */
  75254. fprintf(out, " }\n};\n");
  75255. fclose(out);
  75256. }
  75257. #endif /* MAKECRCH */
  75258. }
  75259. #ifdef MAKECRCH
  75260. local void write_table(out, table)
  75261. FILE *out;
  75262. const unsigned long FAR *table;
  75263. {
  75264. int n;
  75265. for (n = 0; n < 256; n++)
  75266. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  75267. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  75268. }
  75269. #endif /* MAKECRCH */
  75270. #else /* !DYNAMIC_CRC_TABLE */
  75271. /* ========================================================================
  75272. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  75273. */
  75274. /********* Start of inlined file: crc32.h *********/
  75275. local const unsigned long FAR crc_table[TBLS][256] =
  75276. {
  75277. {
  75278. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  75279. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  75280. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  75281. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  75282. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  75283. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  75284. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  75285. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  75286. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  75287. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  75288. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  75289. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  75290. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  75291. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  75292. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  75293. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  75294. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  75295. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  75296. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  75297. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  75298. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  75299. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  75300. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  75301. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  75302. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  75303. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  75304. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  75305. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  75306. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  75307. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  75308. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  75309. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  75310. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  75311. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  75312. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  75313. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  75314. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  75315. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  75316. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  75317. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  75318. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  75319. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  75320. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  75321. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  75322. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  75323. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  75324. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  75325. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  75326. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  75327. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  75328. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  75329. 0x2d02ef8dUL
  75330. #ifdef BYFOUR
  75331. },
  75332. {
  75333. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  75334. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  75335. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  75336. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  75337. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  75338. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  75339. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  75340. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  75341. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  75342. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  75343. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  75344. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  75345. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  75346. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  75347. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  75348. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  75349. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  75350. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  75351. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  75352. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  75353. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  75354. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  75355. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  75356. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  75357. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  75358. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  75359. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  75360. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  75361. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  75362. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  75363. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  75364. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  75365. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  75366. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  75367. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  75368. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  75369. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  75370. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  75371. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  75372. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  75373. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  75374. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  75375. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  75376. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  75377. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  75378. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  75379. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  75380. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  75381. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  75382. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  75383. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  75384. 0x9324fd72UL
  75385. },
  75386. {
  75387. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  75388. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  75389. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  75390. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  75391. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  75392. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  75393. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  75394. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  75395. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  75396. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  75397. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  75398. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  75399. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  75400. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  75401. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  75402. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  75403. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  75404. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  75405. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  75406. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  75407. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  75408. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  75409. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  75410. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  75411. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  75412. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  75413. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  75414. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  75415. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  75416. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  75417. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  75418. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  75419. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  75420. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  75421. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  75422. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  75423. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  75424. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  75425. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  75426. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  75427. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  75428. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  75429. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  75430. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  75431. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  75432. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  75433. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  75434. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  75435. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  75436. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  75437. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  75438. 0xbe9834edUL
  75439. },
  75440. {
  75441. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  75442. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  75443. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  75444. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  75445. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  75446. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  75447. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  75448. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  75449. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  75450. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  75451. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  75452. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  75453. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  75454. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  75455. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  75456. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  75457. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  75458. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  75459. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  75460. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  75461. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  75462. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  75463. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  75464. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  75465. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  75466. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  75467. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  75468. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  75469. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  75470. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  75471. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  75472. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  75473. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  75474. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  75475. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  75476. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  75477. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  75478. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  75479. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  75480. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  75481. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  75482. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  75483. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  75484. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  75485. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  75486. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  75487. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  75488. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  75489. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  75490. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  75491. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  75492. 0xde0506f1UL
  75493. },
  75494. {
  75495. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  75496. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  75497. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  75498. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  75499. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  75500. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  75501. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  75502. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  75503. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  75504. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  75505. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  75506. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  75507. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  75508. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  75509. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  75510. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  75511. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  75512. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  75513. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  75514. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  75515. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  75516. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  75517. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  75518. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  75519. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  75520. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  75521. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  75522. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  75523. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  75524. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  75525. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  75526. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  75527. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  75528. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  75529. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  75530. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  75531. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  75532. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  75533. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  75534. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  75535. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  75536. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  75537. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  75538. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  75539. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  75540. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  75541. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  75542. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  75543. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  75544. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  75545. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  75546. 0x8def022dUL
  75547. },
  75548. {
  75549. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  75550. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  75551. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  75552. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  75553. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  75554. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  75555. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  75556. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  75557. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  75558. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  75559. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  75560. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  75561. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  75562. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  75563. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  75564. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  75565. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  75566. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  75567. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  75568. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  75569. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  75570. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  75571. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  75572. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  75573. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  75574. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  75575. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  75576. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  75577. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  75578. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  75579. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  75580. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  75581. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  75582. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  75583. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  75584. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  75585. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  75586. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  75587. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  75588. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  75589. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  75590. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  75591. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  75592. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  75593. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  75594. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  75595. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  75596. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  75597. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  75598. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  75599. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  75600. 0x72fd2493UL
  75601. },
  75602. {
  75603. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  75604. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  75605. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  75606. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  75607. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  75608. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  75609. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  75610. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  75611. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  75612. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  75613. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  75614. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  75615. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  75616. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  75617. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  75618. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  75619. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  75620. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  75621. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  75622. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  75623. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  75624. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  75625. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  75626. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  75627. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  75628. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  75629. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  75630. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  75631. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  75632. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  75633. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  75634. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  75635. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  75636. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  75637. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  75638. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  75639. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  75640. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  75641. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  75642. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  75643. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  75644. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  75645. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  75646. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  75647. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  75648. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  75649. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  75650. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  75651. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  75652. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  75653. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  75654. 0xed3498beUL
  75655. },
  75656. {
  75657. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  75658. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  75659. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  75660. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  75661. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  75662. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  75663. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  75664. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  75665. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  75666. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  75667. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  75668. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  75669. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  75670. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  75671. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  75672. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  75673. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  75674. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  75675. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  75676. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  75677. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  75678. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  75679. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  75680. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  75681. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  75682. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  75683. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  75684. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  75685. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  75686. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  75687. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  75688. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  75689. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  75690. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  75691. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  75692. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  75693. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  75694. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  75695. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  75696. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  75697. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  75698. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  75699. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  75700. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  75701. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  75702. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  75703. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  75704. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  75705. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  75706. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  75707. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  75708. 0xf10605deUL
  75709. #endif
  75710. }
  75711. };
  75712. /********* End of inlined file: crc32.h *********/
  75713. #endif /* DYNAMIC_CRC_TABLE */
  75714. /* =========================================================================
  75715. * This function can be used by asm versions of crc32()
  75716. */
  75717. const unsigned long FAR * ZEXPORT get_crc_table()
  75718. {
  75719. #ifdef DYNAMIC_CRC_TABLE
  75720. if (crc_table_empty)
  75721. make_crc_table();
  75722. #endif /* DYNAMIC_CRC_TABLE */
  75723. return (const unsigned long FAR *)crc_table;
  75724. }
  75725. /* ========================================================================= */
  75726. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  75727. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  75728. /* ========================================================================= */
  75729. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  75730. {
  75731. if (buf == Z_NULL) return 0UL;
  75732. #ifdef DYNAMIC_CRC_TABLE
  75733. if (crc_table_empty)
  75734. make_crc_table();
  75735. #endif /* DYNAMIC_CRC_TABLE */
  75736. #ifdef BYFOUR
  75737. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  75738. u4 endian;
  75739. endian = 1;
  75740. if (*((unsigned char *)(&endian)))
  75741. return crc32_little(crc, buf, len);
  75742. else
  75743. return crc32_big(crc, buf, len);
  75744. }
  75745. #endif /* BYFOUR */
  75746. crc = crc ^ 0xffffffffUL;
  75747. while (len >= 8) {
  75748. DO8;
  75749. len -= 8;
  75750. }
  75751. if (len) do {
  75752. DO1;
  75753. } while (--len);
  75754. return crc ^ 0xffffffffUL;
  75755. }
  75756. #ifdef BYFOUR
  75757. /* ========================================================================= */
  75758. #define DOLIT4 c ^= *buf4++; \
  75759. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  75760. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  75761. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  75762. /* ========================================================================= */
  75763. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  75764. {
  75765. register u4 c;
  75766. register const u4 FAR *buf4;
  75767. c = (u4)crc;
  75768. c = ~c;
  75769. while (len && ((ptrdiff_t)buf & 3)) {
  75770. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  75771. len--;
  75772. }
  75773. buf4 = (const u4 FAR *)(const void FAR *)buf;
  75774. while (len >= 32) {
  75775. DOLIT32;
  75776. len -= 32;
  75777. }
  75778. while (len >= 4) {
  75779. DOLIT4;
  75780. len -= 4;
  75781. }
  75782. buf = (const unsigned char FAR *)buf4;
  75783. if (len) do {
  75784. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  75785. } while (--len);
  75786. c = ~c;
  75787. return (unsigned long)c;
  75788. }
  75789. /* ========================================================================= */
  75790. #define DOBIG4 c ^= *++buf4; \
  75791. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  75792. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  75793. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  75794. /* ========================================================================= */
  75795. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  75796. {
  75797. register u4 c;
  75798. register const u4 FAR *buf4;
  75799. c = REV((u4)crc);
  75800. c = ~c;
  75801. while (len && ((ptrdiff_t)buf & 3)) {
  75802. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  75803. len--;
  75804. }
  75805. buf4 = (const u4 FAR *)(const void FAR *)buf;
  75806. buf4--;
  75807. while (len >= 32) {
  75808. DOBIG32;
  75809. len -= 32;
  75810. }
  75811. while (len >= 4) {
  75812. DOBIG4;
  75813. len -= 4;
  75814. }
  75815. buf4++;
  75816. buf = (const unsigned char FAR *)buf4;
  75817. if (len) do {
  75818. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  75819. } while (--len);
  75820. c = ~c;
  75821. return (unsigned long)(REV(c));
  75822. }
  75823. #endif /* BYFOUR */
  75824. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  75825. /* ========================================================================= */
  75826. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  75827. {
  75828. unsigned long sum;
  75829. sum = 0;
  75830. while (vec) {
  75831. if (vec & 1)
  75832. sum ^= *mat;
  75833. vec >>= 1;
  75834. mat++;
  75835. }
  75836. return sum;
  75837. }
  75838. /* ========================================================================= */
  75839. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  75840. {
  75841. int n;
  75842. for (n = 0; n < GF2_DIM; n++)
  75843. square[n] = gf2_matrix_times(mat, mat[n]);
  75844. }
  75845. /* ========================================================================= */
  75846. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  75847. {
  75848. int n;
  75849. unsigned long row;
  75850. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  75851. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  75852. /* degenerate case */
  75853. if (len2 == 0)
  75854. return crc1;
  75855. /* put operator for one zero bit in odd */
  75856. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  75857. row = 1;
  75858. for (n = 1; n < GF2_DIM; n++) {
  75859. odd[n] = row;
  75860. row <<= 1;
  75861. }
  75862. /* put operator for two zero bits in even */
  75863. gf2_matrix_square(even, odd);
  75864. /* put operator for four zero bits in odd */
  75865. gf2_matrix_square(odd, even);
  75866. /* apply len2 zeros to crc1 (first square will put the operator for one
  75867. zero byte, eight zero bits, in even) */
  75868. do {
  75869. /* apply zeros operator for this bit of len2 */
  75870. gf2_matrix_square(even, odd);
  75871. if (len2 & 1)
  75872. crc1 = gf2_matrix_times(even, crc1);
  75873. len2 >>= 1;
  75874. /* if no more bits set, then done */
  75875. if (len2 == 0)
  75876. break;
  75877. /* another iteration of the loop with odd and even swapped */
  75878. gf2_matrix_square(odd, even);
  75879. if (len2 & 1)
  75880. crc1 = gf2_matrix_times(odd, crc1);
  75881. len2 >>= 1;
  75882. /* if no more bits set, then done */
  75883. } while (len2 != 0);
  75884. /* return combined crc */
  75885. crc1 ^= crc2;
  75886. return crc1;
  75887. }
  75888. /********* End of inlined file: crc32.c *********/
  75889. /********* Start of inlined file: deflate.c *********/
  75890. /*
  75891. * ALGORITHM
  75892. *
  75893. * The "deflation" process depends on being able to identify portions
  75894. * of the input text which are identical to earlier input (within a
  75895. * sliding window trailing behind the input currently being processed).
  75896. *
  75897. * The most straightforward technique turns out to be the fastest for
  75898. * most input files: try all possible matches and select the longest.
  75899. * The key feature of this algorithm is that insertions into the string
  75900. * dictionary are very simple and thus fast, and deletions are avoided
  75901. * completely. Insertions are performed at each input character, whereas
  75902. * string matches are performed only when the previous match ends. So it
  75903. * is preferable to spend more time in matches to allow very fast string
  75904. * insertions and avoid deletions. The matching algorithm for small
  75905. * strings is inspired from that of Rabin & Karp. A brute force approach
  75906. * is used to find longer strings when a small match has been found.
  75907. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  75908. * (by Leonid Broukhis).
  75909. * A previous version of this file used a more sophisticated algorithm
  75910. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  75911. * time, but has a larger average cost, uses more memory and is patented.
  75912. * However the F&G algorithm may be faster for some highly redundant
  75913. * files if the parameter max_chain_length (described below) is too large.
  75914. *
  75915. * ACKNOWLEDGEMENTS
  75916. *
  75917. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  75918. * I found it in 'freeze' written by Leonid Broukhis.
  75919. * Thanks to many people for bug reports and testing.
  75920. *
  75921. * REFERENCES
  75922. *
  75923. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  75924. * Available in http://www.ietf.org/rfc/rfc1951.txt
  75925. *
  75926. * A description of the Rabin and Karp algorithm is given in the book
  75927. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  75928. *
  75929. * Fiala,E.R., and Greene,D.H.
  75930. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  75931. *
  75932. */
  75933. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75934. /********* Start of inlined file: deflate.h *********/
  75935. /* WARNING: this file should *not* be used by applications. It is
  75936. part of the implementation of the compression library and is
  75937. subject to change. Applications should only use zlib.h.
  75938. */
  75939. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75940. #ifndef DEFLATE_H
  75941. #define DEFLATE_H
  75942. /* define NO_GZIP when compiling if you want to disable gzip header and
  75943. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  75944. the crc code when it is not needed. For shared libraries, gzip encoding
  75945. should be left enabled. */
  75946. #ifndef NO_GZIP
  75947. # define GZIP
  75948. #endif
  75949. #define NO_DUMMY_DECL
  75950. /* ===========================================================================
  75951. * Internal compression state.
  75952. */
  75953. #define LENGTH_CODES 29
  75954. /* number of length codes, not counting the special END_BLOCK code */
  75955. #define LITERALS 256
  75956. /* number of literal bytes 0..255 */
  75957. #define L_CODES (LITERALS+1+LENGTH_CODES)
  75958. /* number of Literal or Length codes, including the END_BLOCK code */
  75959. #define D_CODES 30
  75960. /* number of distance codes */
  75961. #define BL_CODES 19
  75962. /* number of codes used to transfer the bit lengths */
  75963. #define HEAP_SIZE (2*L_CODES+1)
  75964. /* maximum heap size */
  75965. #define MAX_BITS 15
  75966. /* All codes must not exceed MAX_BITS bits */
  75967. #define INIT_STATE 42
  75968. #define EXTRA_STATE 69
  75969. #define NAME_STATE 73
  75970. #define COMMENT_STATE 91
  75971. #define HCRC_STATE 103
  75972. #define BUSY_STATE 113
  75973. #define FINISH_STATE 666
  75974. /* Stream status */
  75975. /* Data structure describing a single value and its code string. */
  75976. typedef struct ct_data_s {
  75977. union {
  75978. ush freq; /* frequency count */
  75979. ush code; /* bit string */
  75980. } fc;
  75981. union {
  75982. ush dad; /* father node in Huffman tree */
  75983. ush len; /* length of bit string */
  75984. } dl;
  75985. } FAR ct_data;
  75986. #define Freq fc.freq
  75987. #define Code fc.code
  75988. #define Dad dl.dad
  75989. #define Len dl.len
  75990. typedef struct static_tree_desc_s static_tree_desc;
  75991. typedef struct tree_desc_s {
  75992. ct_data *dyn_tree; /* the dynamic tree */
  75993. int max_code; /* largest code with non zero frequency */
  75994. static_tree_desc *stat_desc; /* the corresponding static tree */
  75995. } FAR tree_desc;
  75996. typedef ush Pos;
  75997. typedef Pos FAR Posf;
  75998. typedef unsigned IPos;
  75999. /* A Pos is an index in the character window. We use short instead of int to
  76000. * save space in the various tables. IPos is used only for parameter passing.
  76001. */
  76002. typedef struct internal_state {
  76003. z_streamp strm; /* pointer back to this zlib stream */
  76004. int status; /* as the name implies */
  76005. Bytef *pending_buf; /* output still pending */
  76006. ulg pending_buf_size; /* size of pending_buf */
  76007. Bytef *pending_out; /* next pending byte to output to the stream */
  76008. uInt pending; /* nb of bytes in the pending buffer */
  76009. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76010. gz_headerp gzhead; /* gzip header information to write */
  76011. uInt gzindex; /* where in extra, name, or comment */
  76012. Byte method; /* STORED (for zip only) or DEFLATED */
  76013. int last_flush; /* value of flush param for previous deflate call */
  76014. /* used by deflate.c: */
  76015. uInt w_size; /* LZ77 window size (32K by default) */
  76016. uInt w_bits; /* log2(w_size) (8..16) */
  76017. uInt w_mask; /* w_size - 1 */
  76018. Bytef *window;
  76019. /* Sliding window. Input bytes are read into the second half of the window,
  76020. * and move to the first half later to keep a dictionary of at least wSize
  76021. * bytes. With this organization, matches are limited to a distance of
  76022. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  76023. * performed with a length multiple of the block size. Also, it limits
  76024. * the window size to 64K, which is quite useful on MSDOS.
  76025. * To do: use the user input buffer as sliding window.
  76026. */
  76027. ulg window_size;
  76028. /* Actual size of window: 2*wSize, except when the user input buffer
  76029. * is directly used as sliding window.
  76030. */
  76031. Posf *prev;
  76032. /* Link to older string with same hash index. To limit the size of this
  76033. * array to 64K, this link is maintained only for the last 32K strings.
  76034. * An index in this array is thus a window index modulo 32K.
  76035. */
  76036. Posf *head; /* Heads of the hash chains or NIL. */
  76037. uInt ins_h; /* hash index of string to be inserted */
  76038. uInt hash_size; /* number of elements in hash table */
  76039. uInt hash_bits; /* log2(hash_size) */
  76040. uInt hash_mask; /* hash_size-1 */
  76041. uInt hash_shift;
  76042. /* Number of bits by which ins_h must be shifted at each input
  76043. * step. It must be such that after MIN_MATCH steps, the oldest
  76044. * byte no longer takes part in the hash key, that is:
  76045. * hash_shift * MIN_MATCH >= hash_bits
  76046. */
  76047. long block_start;
  76048. /* Window position at the beginning of the current output block. Gets
  76049. * negative when the window is moved backwards.
  76050. */
  76051. uInt match_length; /* length of best match */
  76052. IPos prev_match; /* previous match */
  76053. int match_available; /* set if previous match exists */
  76054. uInt strstart; /* start of string to insert */
  76055. uInt match_start; /* start of matching string */
  76056. uInt lookahead; /* number of valid bytes ahead in window */
  76057. uInt prev_length;
  76058. /* Length of the best match at previous step. Matches not greater than this
  76059. * are discarded. This is used in the lazy match evaluation.
  76060. */
  76061. uInt max_chain_length;
  76062. /* To speed up deflation, hash chains are never searched beyond this
  76063. * length. A higher limit improves compression ratio but degrades the
  76064. * speed.
  76065. */
  76066. uInt max_lazy_match;
  76067. /* Attempt to find a better match only when the current match is strictly
  76068. * smaller than this value. This mechanism is used only for compression
  76069. * levels >= 4.
  76070. */
  76071. # define max_insert_length max_lazy_match
  76072. /* Insert new strings in the hash table only if the match length is not
  76073. * greater than this length. This saves time but degrades compression.
  76074. * max_insert_length is used only for compression levels <= 3.
  76075. */
  76076. int level; /* compression level (1..9) */
  76077. int strategy; /* favor or force Huffman coding*/
  76078. uInt good_match;
  76079. /* Use a faster search when the previous match is longer than this */
  76080. int nice_match; /* Stop searching when current match exceeds this */
  76081. /* used by trees.c: */
  76082. /* Didn't use ct_data typedef below to supress compiler warning */
  76083. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  76084. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  76085. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  76086. struct tree_desc_s l_desc; /* desc. for literal tree */
  76087. struct tree_desc_s d_desc; /* desc. for distance tree */
  76088. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  76089. ush bl_count[MAX_BITS+1];
  76090. /* number of codes at each bit length for an optimal tree */
  76091. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  76092. int heap_len; /* number of elements in the heap */
  76093. int heap_max; /* element of largest frequency */
  76094. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  76095. * The same heap array is used to build all trees.
  76096. */
  76097. uch depth[2*L_CODES+1];
  76098. /* Depth of each subtree used as tie breaker for trees of equal frequency
  76099. */
  76100. uchf *l_buf; /* buffer for literals or lengths */
  76101. uInt lit_bufsize;
  76102. /* Size of match buffer for literals/lengths. There are 4 reasons for
  76103. * limiting lit_bufsize to 64K:
  76104. * - frequencies can be kept in 16 bit counters
  76105. * - if compression is not successful for the first block, all input
  76106. * data is still in the window so we can still emit a stored block even
  76107. * when input comes from standard input. (This can also be done for
  76108. * all blocks if lit_bufsize is not greater than 32K.)
  76109. * - if compression is not successful for a file smaller than 64K, we can
  76110. * even emit a stored file instead of a stored block (saving 5 bytes).
  76111. * This is applicable only for zip (not gzip or zlib).
  76112. * - creating new Huffman trees less frequently may not provide fast
  76113. * adaptation to changes in the input data statistics. (Take for
  76114. * example a binary file with poorly compressible code followed by
  76115. * a highly compressible string table.) Smaller buffer sizes give
  76116. * fast adaptation but have of course the overhead of transmitting
  76117. * trees more frequently.
  76118. * - I can't count above 4
  76119. */
  76120. uInt last_lit; /* running index in l_buf */
  76121. ushf *d_buf;
  76122. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  76123. * the same number of elements. To use different lengths, an extra flag
  76124. * array would be necessary.
  76125. */
  76126. ulg opt_len; /* bit length of current block with optimal trees */
  76127. ulg static_len; /* bit length of current block with static trees */
  76128. uInt matches; /* number of string matches in current block */
  76129. int last_eob_len; /* bit length of EOB code for last block */
  76130. #ifdef DEBUG
  76131. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  76132. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  76133. #endif
  76134. ush bi_buf;
  76135. /* Output buffer. bits are inserted starting at the bottom (least
  76136. * significant bits).
  76137. */
  76138. int bi_valid;
  76139. /* Number of valid bits in bi_buf. All bits above the last valid bit
  76140. * are always zero.
  76141. */
  76142. } FAR deflate_state;
  76143. /* Output a byte on the stream.
  76144. * IN assertion: there is enough room in pending_buf.
  76145. */
  76146. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  76147. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76148. /* Minimum amount of lookahead, except at the end of the input file.
  76149. * See deflate.c for comments about the MIN_MATCH+1.
  76150. */
  76151. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  76152. /* In order to simplify the code, particularly on 16 bit machines, match
  76153. * distances are limited to MAX_DIST instead of WSIZE.
  76154. */
  76155. /* in trees.c */
  76156. void _tr_init OF((deflate_state *s));
  76157. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  76158. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76159. int eof));
  76160. void _tr_align OF((deflate_state *s));
  76161. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76162. int eof));
  76163. #define d_code(dist) \
  76164. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  76165. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  76166. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  76167. * used.
  76168. */
  76169. #ifndef DEBUG
  76170. /* Inline versions of _tr_tally for speed: */
  76171. #if defined(GEN_TREES_H) || !defined(STDC)
  76172. extern uch _length_code[];
  76173. extern uch _dist_code[];
  76174. #else
  76175. extern const uch _length_code[];
  76176. extern const uch _dist_code[];
  76177. #endif
  76178. # define _tr_tally_lit(s, c, flush) \
  76179. { uch cc = (c); \
  76180. s->d_buf[s->last_lit] = 0; \
  76181. s->l_buf[s->last_lit++] = cc; \
  76182. s->dyn_ltree[cc].Freq++; \
  76183. flush = (s->last_lit == s->lit_bufsize-1); \
  76184. }
  76185. # define _tr_tally_dist(s, distance, length, flush) \
  76186. { uch len = (length); \
  76187. ush dist = (distance); \
  76188. s->d_buf[s->last_lit] = dist; \
  76189. s->l_buf[s->last_lit++] = len; \
  76190. dist--; \
  76191. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  76192. s->dyn_dtree[d_code(dist)].Freq++; \
  76193. flush = (s->last_lit == s->lit_bufsize-1); \
  76194. }
  76195. #else
  76196. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  76197. # define _tr_tally_dist(s, distance, length, flush) \
  76198. flush = _tr_tally(s, distance, length)
  76199. #endif
  76200. #endif /* DEFLATE_H */
  76201. /********* End of inlined file: deflate.h *********/
  76202. const char deflate_copyright[] =
  76203. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  76204. /*
  76205. If you use the zlib library in a product, an acknowledgment is welcome
  76206. in the documentation of your product. If for some reason you cannot
  76207. include such an acknowledgment, I would appreciate that you keep this
  76208. copyright string in the executable of your product.
  76209. */
  76210. /* ===========================================================================
  76211. * Function prototypes.
  76212. */
  76213. typedef enum {
  76214. need_more, /* block not completed, need more input or more output */
  76215. block_done, /* block flush performed */
  76216. finish_started, /* finish started, need only more output at next deflate */
  76217. finish_done /* finish done, accept no more input or output */
  76218. } block_state;
  76219. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  76220. /* Compression function. Returns the block state after the call. */
  76221. local void fill_window OF((deflate_state *s));
  76222. local block_state deflate_stored OF((deflate_state *s, int flush));
  76223. local block_state deflate_fast OF((deflate_state *s, int flush));
  76224. #ifndef FASTEST
  76225. local block_state deflate_slow OF((deflate_state *s, int flush));
  76226. #endif
  76227. local void lm_init OF((deflate_state *s));
  76228. local void putShortMSB OF((deflate_state *s, uInt b));
  76229. local void flush_pending OF((z_streamp strm));
  76230. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  76231. #ifndef FASTEST
  76232. #ifdef ASMV
  76233. void match_init OF((void)); /* asm code initialization */
  76234. uInt longest_match OF((deflate_state *s, IPos cur_match));
  76235. #else
  76236. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  76237. #endif
  76238. #endif
  76239. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  76240. #ifdef DEBUG
  76241. local void check_match OF((deflate_state *s, IPos start, IPos match,
  76242. int length));
  76243. #endif
  76244. /* ===========================================================================
  76245. * Local data
  76246. */
  76247. #define NIL 0
  76248. /* Tail of hash chains */
  76249. #ifndef TOO_FAR
  76250. # define TOO_FAR 4096
  76251. #endif
  76252. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  76253. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76254. /* Minimum amount of lookahead, except at the end of the input file.
  76255. * See deflate.c for comments about the MIN_MATCH+1.
  76256. */
  76257. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  76258. * the desired pack level (0..9). The values given below have been tuned to
  76259. * exclude worst case performance for pathological files. Better values may be
  76260. * found for specific files.
  76261. */
  76262. typedef struct config_s {
  76263. ush good_length; /* reduce lazy search above this match length */
  76264. ush max_lazy; /* do not perform lazy search above this match length */
  76265. ush nice_length; /* quit search above this match length */
  76266. ush max_chain;
  76267. compress_func func;
  76268. } config;
  76269. #ifdef FASTEST
  76270. local const config configuration_table[2] = {
  76271. /* good lazy nice chain */
  76272. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76273. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  76274. #else
  76275. local const config configuration_table[10] = {
  76276. /* good lazy nice chain */
  76277. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76278. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  76279. /* 2 */ {4, 5, 16, 8, deflate_fast},
  76280. /* 3 */ {4, 6, 32, 32, deflate_fast},
  76281. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  76282. /* 5 */ {8, 16, 32, 32, deflate_slow},
  76283. /* 6 */ {8, 16, 128, 128, deflate_slow},
  76284. /* 7 */ {8, 32, 128, 256, deflate_slow},
  76285. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  76286. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  76287. #endif
  76288. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  76289. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  76290. * meaning.
  76291. */
  76292. #define EQUAL 0
  76293. /* result of memcmp for equal strings */
  76294. #ifndef NO_DUMMY_DECL
  76295. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  76296. #endif
  76297. /* ===========================================================================
  76298. * Update a hash value with the given input byte
  76299. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  76300. * input characters, so that a running hash key can be computed from the
  76301. * previous key instead of complete recalculation each time.
  76302. */
  76303. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  76304. /* ===========================================================================
  76305. * Insert string str in the dictionary and set match_head to the previous head
  76306. * of the hash chain (the most recent string with same hash key). Return
  76307. * the previous length of the hash chain.
  76308. * If this file is compiled with -DFASTEST, the compression level is forced
  76309. * to 1, and no hash chains are maintained.
  76310. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  76311. * input characters and the first MIN_MATCH bytes of str are valid
  76312. * (except for the last MIN_MATCH-1 bytes of the input file).
  76313. */
  76314. #ifdef FASTEST
  76315. #define INSERT_STRING(s, str, match_head) \
  76316. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76317. match_head = s->head[s->ins_h], \
  76318. s->head[s->ins_h] = (Pos)(str))
  76319. #else
  76320. #define INSERT_STRING(s, str, match_head) \
  76321. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76322. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  76323. s->head[s->ins_h] = (Pos)(str))
  76324. #endif
  76325. /* ===========================================================================
  76326. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  76327. * prev[] will be initialized on the fly.
  76328. */
  76329. #define CLEAR_HASH(s) \
  76330. s->head[s->hash_size-1] = NIL; \
  76331. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  76332. /* ========================================================================= */
  76333. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  76334. {
  76335. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  76336. Z_DEFAULT_STRATEGY, version, stream_size);
  76337. /* To do: ignore strm->next_in if we use it as window */
  76338. }
  76339. /* ========================================================================= */
  76340. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  76341. {
  76342. deflate_state *s;
  76343. int wrap = 1;
  76344. static const char my_version[] = ZLIB_VERSION;
  76345. ushf *overlay;
  76346. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  76347. * output size for (length,distance) codes is <= 24 bits.
  76348. */
  76349. if (version == Z_NULL || version[0] != my_version[0] ||
  76350. stream_size != sizeof(z_stream)) {
  76351. return Z_VERSION_ERROR;
  76352. }
  76353. if (strm == Z_NULL) return Z_STREAM_ERROR;
  76354. strm->msg = Z_NULL;
  76355. if (strm->zalloc == (alloc_func)0) {
  76356. strm->zalloc = zcalloc;
  76357. strm->opaque = (voidpf)0;
  76358. }
  76359. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76360. #ifdef FASTEST
  76361. if (level != 0) level = 1;
  76362. #else
  76363. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  76364. #endif
  76365. if (windowBits < 0) { /* suppress zlib wrapper */
  76366. wrap = 0;
  76367. windowBits = -windowBits;
  76368. }
  76369. #ifdef GZIP
  76370. else if (windowBits > 15) {
  76371. wrap = 2; /* write gzip wrapper instead */
  76372. windowBits -= 16;
  76373. }
  76374. #endif
  76375. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  76376. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  76377. strategy < 0 || strategy > Z_FIXED) {
  76378. return Z_STREAM_ERROR;
  76379. }
  76380. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  76381. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  76382. if (s == Z_NULL) return Z_MEM_ERROR;
  76383. strm->state = (struct internal_state FAR *)s;
  76384. s->strm = strm;
  76385. s->wrap = wrap;
  76386. s->gzhead = Z_NULL;
  76387. s->w_bits = windowBits;
  76388. s->w_size = 1 << s->w_bits;
  76389. s->w_mask = s->w_size - 1;
  76390. s->hash_bits = memLevel + 7;
  76391. s->hash_size = 1 << s->hash_bits;
  76392. s->hash_mask = s->hash_size - 1;
  76393. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  76394. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  76395. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  76396. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  76397. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  76398. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  76399. s->pending_buf = (uchf *) overlay;
  76400. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  76401. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  76402. s->pending_buf == Z_NULL) {
  76403. s->status = FINISH_STATE;
  76404. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  76405. deflateEnd (strm);
  76406. return Z_MEM_ERROR;
  76407. }
  76408. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  76409. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  76410. s->level = level;
  76411. s->strategy = strategy;
  76412. s->method = (Byte)method;
  76413. return deflateReset(strm);
  76414. }
  76415. /* ========================================================================= */
  76416. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  76417. {
  76418. deflate_state *s;
  76419. uInt length = dictLength;
  76420. uInt n;
  76421. IPos hash_head = 0;
  76422. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  76423. strm->state->wrap == 2 ||
  76424. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  76425. return Z_STREAM_ERROR;
  76426. s = strm->state;
  76427. if (s->wrap)
  76428. strm->adler = adler32(strm->adler, dictionary, dictLength);
  76429. if (length < MIN_MATCH) return Z_OK;
  76430. if (length > MAX_DIST(s)) {
  76431. length = MAX_DIST(s);
  76432. dictionary += dictLength - length; /* use the tail of the dictionary */
  76433. }
  76434. zmemcpy(s->window, dictionary, length);
  76435. s->strstart = length;
  76436. s->block_start = (long)length;
  76437. /* Insert all strings in the hash table (except for the last two bytes).
  76438. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  76439. * call of fill_window.
  76440. */
  76441. s->ins_h = s->window[0];
  76442. UPDATE_HASH(s, s->ins_h, s->window[1]);
  76443. for (n = 0; n <= length - MIN_MATCH; n++) {
  76444. INSERT_STRING(s, n, hash_head);
  76445. }
  76446. if (hash_head) hash_head = 0; /* to make compiler happy */
  76447. return Z_OK;
  76448. }
  76449. /* ========================================================================= */
  76450. int ZEXPORT deflateReset (z_streamp strm)
  76451. {
  76452. deflate_state *s;
  76453. if (strm == Z_NULL || strm->state == Z_NULL ||
  76454. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  76455. return Z_STREAM_ERROR;
  76456. }
  76457. strm->total_in = strm->total_out = 0;
  76458. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  76459. strm->data_type = Z_UNKNOWN;
  76460. s = (deflate_state *)strm->state;
  76461. s->pending = 0;
  76462. s->pending_out = s->pending_buf;
  76463. if (s->wrap < 0) {
  76464. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  76465. }
  76466. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  76467. strm->adler =
  76468. #ifdef GZIP
  76469. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  76470. #endif
  76471. adler32(0L, Z_NULL, 0);
  76472. s->last_flush = Z_NO_FLUSH;
  76473. _tr_init(s);
  76474. lm_init(s);
  76475. return Z_OK;
  76476. }
  76477. /* ========================================================================= */
  76478. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  76479. {
  76480. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76481. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  76482. strm->state->gzhead = head;
  76483. return Z_OK;
  76484. }
  76485. /* ========================================================================= */
  76486. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  76487. {
  76488. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76489. strm->state->bi_valid = bits;
  76490. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  76491. return Z_OK;
  76492. }
  76493. /* ========================================================================= */
  76494. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  76495. {
  76496. deflate_state *s;
  76497. compress_func func;
  76498. int err = Z_OK;
  76499. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76500. s = strm->state;
  76501. #ifdef FASTEST
  76502. if (level != 0) level = 1;
  76503. #else
  76504. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  76505. #endif
  76506. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  76507. return Z_STREAM_ERROR;
  76508. }
  76509. func = configuration_table[s->level].func;
  76510. if (func != configuration_table[level].func && strm->total_in != 0) {
  76511. /* Flush the last buffer: */
  76512. err = deflate(strm, Z_PARTIAL_FLUSH);
  76513. }
  76514. if (s->level != level) {
  76515. s->level = level;
  76516. s->max_lazy_match = configuration_table[level].max_lazy;
  76517. s->good_match = configuration_table[level].good_length;
  76518. s->nice_match = configuration_table[level].nice_length;
  76519. s->max_chain_length = configuration_table[level].max_chain;
  76520. }
  76521. s->strategy = strategy;
  76522. return err;
  76523. }
  76524. /* ========================================================================= */
  76525. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  76526. {
  76527. deflate_state *s;
  76528. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76529. s = strm->state;
  76530. s->good_match = good_length;
  76531. s->max_lazy_match = max_lazy;
  76532. s->nice_match = nice_length;
  76533. s->max_chain_length = max_chain;
  76534. return Z_OK;
  76535. }
  76536. /* =========================================================================
  76537. * For the default windowBits of 15 and memLevel of 8, this function returns
  76538. * a close to exact, as well as small, upper bound on the compressed size.
  76539. * They are coded as constants here for a reason--if the #define's are
  76540. * changed, then this function needs to be changed as well. The return
  76541. * value for 15 and 8 only works for those exact settings.
  76542. *
  76543. * For any setting other than those defaults for windowBits and memLevel,
  76544. * the value returned is a conservative worst case for the maximum expansion
  76545. * resulting from using fixed blocks instead of stored blocks, which deflate
  76546. * can emit on compressed data for some combinations of the parameters.
  76547. *
  76548. * This function could be more sophisticated to provide closer upper bounds
  76549. * for every combination of windowBits and memLevel, as well as wrap.
  76550. * But even the conservative upper bound of about 14% expansion does not
  76551. * seem onerous for output buffer allocation.
  76552. */
  76553. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  76554. {
  76555. deflate_state *s;
  76556. uLong destLen;
  76557. /* conservative upper bound */
  76558. destLen = sourceLen +
  76559. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  76560. /* if can't get parameters, return conservative bound */
  76561. if (strm == Z_NULL || strm->state == Z_NULL)
  76562. return destLen;
  76563. /* if not default parameters, return conservative bound */
  76564. s = strm->state;
  76565. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  76566. return destLen;
  76567. /* default settings: return tight bound for that case */
  76568. return compressBound(sourceLen);
  76569. }
  76570. /* =========================================================================
  76571. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  76572. * IN assertion: the stream state is correct and there is enough room in
  76573. * pending_buf.
  76574. */
  76575. local void putShortMSB (deflate_state *s, uInt b)
  76576. {
  76577. put_byte(s, (Byte)(b >> 8));
  76578. put_byte(s, (Byte)(b & 0xff));
  76579. }
  76580. /* =========================================================================
  76581. * Flush as much pending output as possible. All deflate() output goes
  76582. * through this function so some applications may wish to modify it
  76583. * to avoid allocating a large strm->next_out buffer and copying into it.
  76584. * (See also read_buf()).
  76585. */
  76586. local void flush_pending (z_streamp strm)
  76587. {
  76588. unsigned len = strm->state->pending;
  76589. if (len > strm->avail_out) len = strm->avail_out;
  76590. if (len == 0) return;
  76591. zmemcpy(strm->next_out, strm->state->pending_out, len);
  76592. strm->next_out += len;
  76593. strm->state->pending_out += len;
  76594. strm->total_out += len;
  76595. strm->avail_out -= len;
  76596. strm->state->pending -= len;
  76597. if (strm->state->pending == 0) {
  76598. strm->state->pending_out = strm->state->pending_buf;
  76599. }
  76600. }
  76601. /* ========================================================================= */
  76602. int ZEXPORT deflate (z_streamp strm, int flush)
  76603. {
  76604. int old_flush; /* value of flush param for previous deflate call */
  76605. deflate_state *s;
  76606. if (strm == Z_NULL || strm->state == Z_NULL ||
  76607. flush > Z_FINISH || flush < 0) {
  76608. return Z_STREAM_ERROR;
  76609. }
  76610. s = strm->state;
  76611. if (strm->next_out == Z_NULL ||
  76612. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  76613. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  76614. ERR_RETURN(strm, Z_STREAM_ERROR);
  76615. }
  76616. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  76617. s->strm = strm; /* just in case */
  76618. old_flush = s->last_flush;
  76619. s->last_flush = flush;
  76620. /* Write the header */
  76621. if (s->status == INIT_STATE) {
  76622. #ifdef GZIP
  76623. if (s->wrap == 2) {
  76624. strm->adler = crc32(0L, Z_NULL, 0);
  76625. put_byte(s, 31);
  76626. put_byte(s, 139);
  76627. put_byte(s, 8);
  76628. if (s->gzhead == NULL) {
  76629. put_byte(s, 0);
  76630. put_byte(s, 0);
  76631. put_byte(s, 0);
  76632. put_byte(s, 0);
  76633. put_byte(s, 0);
  76634. put_byte(s, s->level == 9 ? 2 :
  76635. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  76636. 4 : 0));
  76637. put_byte(s, OS_CODE);
  76638. s->status = BUSY_STATE;
  76639. }
  76640. else {
  76641. put_byte(s, (s->gzhead->text ? 1 : 0) +
  76642. (s->gzhead->hcrc ? 2 : 0) +
  76643. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  76644. (s->gzhead->name == Z_NULL ? 0 : 8) +
  76645. (s->gzhead->comment == Z_NULL ? 0 : 16)
  76646. );
  76647. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  76648. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  76649. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  76650. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  76651. put_byte(s, s->level == 9 ? 2 :
  76652. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  76653. 4 : 0));
  76654. put_byte(s, s->gzhead->os & 0xff);
  76655. if (s->gzhead->extra != NULL) {
  76656. put_byte(s, s->gzhead->extra_len & 0xff);
  76657. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  76658. }
  76659. if (s->gzhead->hcrc)
  76660. strm->adler = crc32(strm->adler, s->pending_buf,
  76661. s->pending);
  76662. s->gzindex = 0;
  76663. s->status = EXTRA_STATE;
  76664. }
  76665. }
  76666. else
  76667. #endif
  76668. {
  76669. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  76670. uInt level_flags;
  76671. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  76672. level_flags = 0;
  76673. else if (s->level < 6)
  76674. level_flags = 1;
  76675. else if (s->level == 6)
  76676. level_flags = 2;
  76677. else
  76678. level_flags = 3;
  76679. header |= (level_flags << 6);
  76680. if (s->strstart != 0) header |= PRESET_DICT;
  76681. header += 31 - (header % 31);
  76682. s->status = BUSY_STATE;
  76683. putShortMSB(s, header);
  76684. /* Save the adler32 of the preset dictionary: */
  76685. if (s->strstart != 0) {
  76686. putShortMSB(s, (uInt)(strm->adler >> 16));
  76687. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  76688. }
  76689. strm->adler = adler32(0L, Z_NULL, 0);
  76690. }
  76691. }
  76692. #ifdef GZIP
  76693. if (s->status == EXTRA_STATE) {
  76694. if (s->gzhead->extra != NULL) {
  76695. uInt beg = s->pending; /* start of bytes to update crc */
  76696. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  76697. if (s->pending == s->pending_buf_size) {
  76698. if (s->gzhead->hcrc && s->pending > beg)
  76699. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76700. s->pending - beg);
  76701. flush_pending(strm);
  76702. beg = s->pending;
  76703. if (s->pending == s->pending_buf_size)
  76704. break;
  76705. }
  76706. put_byte(s, s->gzhead->extra[s->gzindex]);
  76707. s->gzindex++;
  76708. }
  76709. if (s->gzhead->hcrc && s->pending > beg)
  76710. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76711. s->pending - beg);
  76712. if (s->gzindex == s->gzhead->extra_len) {
  76713. s->gzindex = 0;
  76714. s->status = NAME_STATE;
  76715. }
  76716. }
  76717. else
  76718. s->status = NAME_STATE;
  76719. }
  76720. if (s->status == NAME_STATE) {
  76721. if (s->gzhead->name != NULL) {
  76722. uInt beg = s->pending; /* start of bytes to update crc */
  76723. int val;
  76724. do {
  76725. if (s->pending == s->pending_buf_size) {
  76726. if (s->gzhead->hcrc && s->pending > beg)
  76727. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76728. s->pending - beg);
  76729. flush_pending(strm);
  76730. beg = s->pending;
  76731. if (s->pending == s->pending_buf_size) {
  76732. val = 1;
  76733. break;
  76734. }
  76735. }
  76736. val = s->gzhead->name[s->gzindex++];
  76737. put_byte(s, val);
  76738. } while (val != 0);
  76739. if (s->gzhead->hcrc && s->pending > beg)
  76740. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76741. s->pending - beg);
  76742. if (val == 0) {
  76743. s->gzindex = 0;
  76744. s->status = COMMENT_STATE;
  76745. }
  76746. }
  76747. else
  76748. s->status = COMMENT_STATE;
  76749. }
  76750. if (s->status == COMMENT_STATE) {
  76751. if (s->gzhead->comment != NULL) {
  76752. uInt beg = s->pending; /* start of bytes to update crc */
  76753. int val;
  76754. do {
  76755. if (s->pending == s->pending_buf_size) {
  76756. if (s->gzhead->hcrc && s->pending > beg)
  76757. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76758. s->pending - beg);
  76759. flush_pending(strm);
  76760. beg = s->pending;
  76761. if (s->pending == s->pending_buf_size) {
  76762. val = 1;
  76763. break;
  76764. }
  76765. }
  76766. val = s->gzhead->comment[s->gzindex++];
  76767. put_byte(s, val);
  76768. } while (val != 0);
  76769. if (s->gzhead->hcrc && s->pending > beg)
  76770. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76771. s->pending - beg);
  76772. if (val == 0)
  76773. s->status = HCRC_STATE;
  76774. }
  76775. else
  76776. s->status = HCRC_STATE;
  76777. }
  76778. if (s->status == HCRC_STATE) {
  76779. if (s->gzhead->hcrc) {
  76780. if (s->pending + 2 > s->pending_buf_size)
  76781. flush_pending(strm);
  76782. if (s->pending + 2 <= s->pending_buf_size) {
  76783. put_byte(s, (Byte)(strm->adler & 0xff));
  76784. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  76785. strm->adler = crc32(0L, Z_NULL, 0);
  76786. s->status = BUSY_STATE;
  76787. }
  76788. }
  76789. else
  76790. s->status = BUSY_STATE;
  76791. }
  76792. #endif
  76793. /* Flush as much pending output as possible */
  76794. if (s->pending != 0) {
  76795. flush_pending(strm);
  76796. if (strm->avail_out == 0) {
  76797. /* Since avail_out is 0, deflate will be called again with
  76798. * more output space, but possibly with both pending and
  76799. * avail_in equal to zero. There won't be anything to do,
  76800. * but this is not an error situation so make sure we
  76801. * return OK instead of BUF_ERROR at next call of deflate:
  76802. */
  76803. s->last_flush = -1;
  76804. return Z_OK;
  76805. }
  76806. /* Make sure there is something to do and avoid duplicate consecutive
  76807. * flushes. For repeated and useless calls with Z_FINISH, we keep
  76808. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  76809. */
  76810. } else if (strm->avail_in == 0 && flush <= old_flush &&
  76811. flush != Z_FINISH) {
  76812. ERR_RETURN(strm, Z_BUF_ERROR);
  76813. }
  76814. /* User must not provide more input after the first FINISH: */
  76815. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  76816. ERR_RETURN(strm, Z_BUF_ERROR);
  76817. }
  76818. /* Start a new block or continue the current one.
  76819. */
  76820. if (strm->avail_in != 0 || s->lookahead != 0 ||
  76821. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  76822. block_state bstate;
  76823. bstate = (*(configuration_table[s->level].func))(s, flush);
  76824. if (bstate == finish_started || bstate == finish_done) {
  76825. s->status = FINISH_STATE;
  76826. }
  76827. if (bstate == need_more || bstate == finish_started) {
  76828. if (strm->avail_out == 0) {
  76829. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  76830. }
  76831. return Z_OK;
  76832. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  76833. * of deflate should use the same flush parameter to make sure
  76834. * that the flush is complete. So we don't have to output an
  76835. * empty block here, this will be done at next call. This also
  76836. * ensures that for a very small output buffer, we emit at most
  76837. * one empty block.
  76838. */
  76839. }
  76840. if (bstate == block_done) {
  76841. if (flush == Z_PARTIAL_FLUSH) {
  76842. _tr_align(s);
  76843. } else { /* FULL_FLUSH or SYNC_FLUSH */
  76844. _tr_stored_block(s, (char*)0, 0L, 0);
  76845. /* For a full flush, this empty block will be recognized
  76846. * as a special marker by inflate_sync().
  76847. */
  76848. if (flush == Z_FULL_FLUSH) {
  76849. CLEAR_HASH(s); /* forget history */
  76850. }
  76851. }
  76852. flush_pending(strm);
  76853. if (strm->avail_out == 0) {
  76854. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  76855. return Z_OK;
  76856. }
  76857. }
  76858. }
  76859. Assert(strm->avail_out > 0, "bug2");
  76860. if (flush != Z_FINISH) return Z_OK;
  76861. if (s->wrap <= 0) return Z_STREAM_END;
  76862. /* Write the trailer */
  76863. #ifdef GZIP
  76864. if (s->wrap == 2) {
  76865. put_byte(s, (Byte)(strm->adler & 0xff));
  76866. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  76867. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  76868. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  76869. put_byte(s, (Byte)(strm->total_in & 0xff));
  76870. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  76871. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  76872. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  76873. }
  76874. else
  76875. #endif
  76876. {
  76877. putShortMSB(s, (uInt)(strm->adler >> 16));
  76878. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  76879. }
  76880. flush_pending(strm);
  76881. /* If avail_out is zero, the application will call deflate again
  76882. * to flush the rest.
  76883. */
  76884. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  76885. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  76886. }
  76887. /* ========================================================================= */
  76888. int ZEXPORT deflateEnd (z_streamp strm)
  76889. {
  76890. int status;
  76891. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76892. status = strm->state->status;
  76893. if (status != INIT_STATE &&
  76894. status != EXTRA_STATE &&
  76895. status != NAME_STATE &&
  76896. status != COMMENT_STATE &&
  76897. status != HCRC_STATE &&
  76898. status != BUSY_STATE &&
  76899. status != FINISH_STATE) {
  76900. return Z_STREAM_ERROR;
  76901. }
  76902. /* Deallocate in reverse order of allocations: */
  76903. TRY_FREE(strm, strm->state->pending_buf);
  76904. TRY_FREE(strm, strm->state->head);
  76905. TRY_FREE(strm, strm->state->prev);
  76906. TRY_FREE(strm, strm->state->window);
  76907. ZFREE(strm, strm->state);
  76908. strm->state = Z_NULL;
  76909. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  76910. }
  76911. /* =========================================================================
  76912. * Copy the source state to the destination state.
  76913. * To simplify the source, this is not supported for 16-bit MSDOS (which
  76914. * doesn't have enough memory anyway to duplicate compression states).
  76915. */
  76916. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  76917. {
  76918. #ifdef MAXSEG_64K
  76919. return Z_STREAM_ERROR;
  76920. #else
  76921. deflate_state *ds;
  76922. deflate_state *ss;
  76923. ushf *overlay;
  76924. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  76925. return Z_STREAM_ERROR;
  76926. }
  76927. ss = source->state;
  76928. zmemcpy(dest, source, sizeof(z_stream));
  76929. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  76930. if (ds == Z_NULL) return Z_MEM_ERROR;
  76931. dest->state = (struct internal_state FAR *) ds;
  76932. zmemcpy(ds, ss, sizeof(deflate_state));
  76933. ds->strm = dest;
  76934. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  76935. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  76936. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  76937. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  76938. ds->pending_buf = (uchf *) overlay;
  76939. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  76940. ds->pending_buf == Z_NULL) {
  76941. deflateEnd (dest);
  76942. return Z_MEM_ERROR;
  76943. }
  76944. /* following zmemcpy do not work for 16-bit MSDOS */
  76945. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  76946. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  76947. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  76948. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  76949. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  76950. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  76951. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  76952. ds->l_desc.dyn_tree = ds->dyn_ltree;
  76953. ds->d_desc.dyn_tree = ds->dyn_dtree;
  76954. ds->bl_desc.dyn_tree = ds->bl_tree;
  76955. return Z_OK;
  76956. #endif /* MAXSEG_64K */
  76957. }
  76958. /* ===========================================================================
  76959. * Read a new buffer from the current input stream, update the adler32
  76960. * and total number of bytes read. All deflate() input goes through
  76961. * this function so some applications may wish to modify it to avoid
  76962. * allocating a large strm->next_in buffer and copying from it.
  76963. * (See also flush_pending()).
  76964. */
  76965. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  76966. {
  76967. unsigned len = strm->avail_in;
  76968. if (len > size) len = size;
  76969. if (len == 0) return 0;
  76970. strm->avail_in -= len;
  76971. if (strm->state->wrap == 1) {
  76972. strm->adler = adler32(strm->adler, strm->next_in, len);
  76973. }
  76974. #ifdef GZIP
  76975. else if (strm->state->wrap == 2) {
  76976. strm->adler = crc32(strm->adler, strm->next_in, len);
  76977. }
  76978. #endif
  76979. zmemcpy(buf, strm->next_in, len);
  76980. strm->next_in += len;
  76981. strm->total_in += len;
  76982. return (int)len;
  76983. }
  76984. /* ===========================================================================
  76985. * Initialize the "longest match" routines for a new zlib stream
  76986. */
  76987. local void lm_init (deflate_state *s)
  76988. {
  76989. s->window_size = (ulg)2L*s->w_size;
  76990. CLEAR_HASH(s);
  76991. /* Set the default configuration parameters:
  76992. */
  76993. s->max_lazy_match = configuration_table[s->level].max_lazy;
  76994. s->good_match = configuration_table[s->level].good_length;
  76995. s->nice_match = configuration_table[s->level].nice_length;
  76996. s->max_chain_length = configuration_table[s->level].max_chain;
  76997. s->strstart = 0;
  76998. s->block_start = 0L;
  76999. s->lookahead = 0;
  77000. s->match_length = s->prev_length = MIN_MATCH-1;
  77001. s->match_available = 0;
  77002. s->ins_h = 0;
  77003. #ifndef FASTEST
  77004. #ifdef ASMV
  77005. match_init(); /* initialize the asm code */
  77006. #endif
  77007. #endif
  77008. }
  77009. #ifndef FASTEST
  77010. /* ===========================================================================
  77011. * Set match_start to the longest match starting at the given string and
  77012. * return its length. Matches shorter or equal to prev_length are discarded,
  77013. * in which case the result is equal to prev_length and match_start is
  77014. * garbage.
  77015. * IN assertions: cur_match is the head of the hash chain for the current
  77016. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  77017. * OUT assertion: the match length is not greater than s->lookahead.
  77018. */
  77019. #ifndef ASMV
  77020. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  77021. * match.S. The code will be functionally equivalent.
  77022. */
  77023. local uInt longest_match(deflate_state *s, IPos cur_match)
  77024. {
  77025. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  77026. register Bytef *scan = s->window + s->strstart; /* current string */
  77027. register Bytef *match; /* matched string */
  77028. register int len; /* length of current match */
  77029. int best_len = s->prev_length; /* best match length so far */
  77030. int nice_match = s->nice_match; /* stop if match long enough */
  77031. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  77032. s->strstart - (IPos)MAX_DIST(s) : NIL;
  77033. /* Stop when cur_match becomes <= limit. To simplify the code,
  77034. * we prevent matches with the string of window index 0.
  77035. */
  77036. Posf *prev = s->prev;
  77037. uInt wmask = s->w_mask;
  77038. #ifdef UNALIGNED_OK
  77039. /* Compare two bytes at a time. Note: this is not always beneficial.
  77040. * Try with and without -DUNALIGNED_OK to check.
  77041. */
  77042. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  77043. register ush scan_start = *(ushf*)scan;
  77044. register ush scan_end = *(ushf*)(scan+best_len-1);
  77045. #else
  77046. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77047. register Byte scan_end1 = scan[best_len-1];
  77048. register Byte scan_end = scan[best_len];
  77049. #endif
  77050. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77051. * It is easy to get rid of this optimization if necessary.
  77052. */
  77053. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77054. /* Do not waste too much time if we already have a good match: */
  77055. if (s->prev_length >= s->good_match) {
  77056. chain_length >>= 2;
  77057. }
  77058. /* Do not look for matches beyond the end of the input. This is necessary
  77059. * to make deflate deterministic.
  77060. */
  77061. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  77062. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77063. do {
  77064. Assert(cur_match < s->strstart, "no future");
  77065. match = s->window + cur_match;
  77066. /* Skip to next match if the match length cannot increase
  77067. * or if the match length is less than 2. Note that the checks below
  77068. * for insufficient lookahead only occur occasionally for performance
  77069. * reasons. Therefore uninitialized memory will be accessed, and
  77070. * conditional jumps will be made that depend on those values.
  77071. * However the length of the match is limited to the lookahead, so
  77072. * the output of deflate is not affected by the uninitialized values.
  77073. */
  77074. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  77075. /* This code assumes sizeof(unsigned short) == 2. Do not use
  77076. * UNALIGNED_OK if your compiler uses a different size.
  77077. */
  77078. if (*(ushf*)(match+best_len-1) != scan_end ||
  77079. *(ushf*)match != scan_start) continue;
  77080. /* It is not necessary to compare scan[2] and match[2] since they are
  77081. * always equal when the other bytes match, given that the hash keys
  77082. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  77083. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  77084. * lookahead only every 4th comparison; the 128th check will be made
  77085. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  77086. * necessary to put more guard bytes at the end of the window, or
  77087. * to check more often for insufficient lookahead.
  77088. */
  77089. Assert(scan[2] == match[2], "scan[2]?");
  77090. scan++, match++;
  77091. do {
  77092. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77093. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77094. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77095. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77096. scan < strend);
  77097. /* The funny "do {}" generates better code on most compilers */
  77098. /* Here, scan <= window+strstart+257 */
  77099. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77100. if (*scan == *match) scan++;
  77101. len = (MAX_MATCH - 1) - (int)(strend-scan);
  77102. scan = strend - (MAX_MATCH-1);
  77103. #else /* UNALIGNED_OK */
  77104. if (match[best_len] != scan_end ||
  77105. match[best_len-1] != scan_end1 ||
  77106. *match != *scan ||
  77107. *++match != scan[1]) continue;
  77108. /* The check at best_len-1 can be removed because it will be made
  77109. * again later. (This heuristic is not always a win.)
  77110. * It is not necessary to compare scan[2] and match[2] since they
  77111. * are always equal when the other bytes match, given that
  77112. * the hash keys are equal and that HASH_BITS >= 8.
  77113. */
  77114. scan += 2, match++;
  77115. Assert(*scan == *match, "match[2]?");
  77116. /* We check for insufficient lookahead only every 8th comparison;
  77117. * the 256th check will be made at strstart+258.
  77118. */
  77119. do {
  77120. } while (*++scan == *++match && *++scan == *++match &&
  77121. *++scan == *++match && *++scan == *++match &&
  77122. *++scan == *++match && *++scan == *++match &&
  77123. *++scan == *++match && *++scan == *++match &&
  77124. scan < strend);
  77125. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77126. len = MAX_MATCH - (int)(strend - scan);
  77127. scan = strend - MAX_MATCH;
  77128. #endif /* UNALIGNED_OK */
  77129. if (len > best_len) {
  77130. s->match_start = cur_match;
  77131. best_len = len;
  77132. if (len >= nice_match) break;
  77133. #ifdef UNALIGNED_OK
  77134. scan_end = *(ushf*)(scan+best_len-1);
  77135. #else
  77136. scan_end1 = scan[best_len-1];
  77137. scan_end = scan[best_len];
  77138. #endif
  77139. }
  77140. } while ((cur_match = prev[cur_match & wmask]) > limit
  77141. && --chain_length != 0);
  77142. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  77143. return s->lookahead;
  77144. }
  77145. #endif /* ASMV */
  77146. #endif /* FASTEST */
  77147. /* ---------------------------------------------------------------------------
  77148. * Optimized version for level == 1 or strategy == Z_RLE only
  77149. */
  77150. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  77151. {
  77152. register Bytef *scan = s->window + s->strstart; /* current string */
  77153. register Bytef *match; /* matched string */
  77154. register int len; /* length of current match */
  77155. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77156. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77157. * It is easy to get rid of this optimization if necessary.
  77158. */
  77159. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77160. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77161. Assert(cur_match < s->strstart, "no future");
  77162. match = s->window + cur_match;
  77163. /* Return failure if the match length is less than 2:
  77164. */
  77165. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  77166. /* The check at best_len-1 can be removed because it will be made
  77167. * again later. (This heuristic is not always a win.)
  77168. * It is not necessary to compare scan[2] and match[2] since they
  77169. * are always equal when the other bytes match, given that
  77170. * the hash keys are equal and that HASH_BITS >= 8.
  77171. */
  77172. scan += 2, match += 2;
  77173. Assert(*scan == *match, "match[2]?");
  77174. /* We check for insufficient lookahead only every 8th comparison;
  77175. * the 256th check will be made at strstart+258.
  77176. */
  77177. do {
  77178. } while (*++scan == *++match && *++scan == *++match &&
  77179. *++scan == *++match && *++scan == *++match &&
  77180. *++scan == *++match && *++scan == *++match &&
  77181. *++scan == *++match && *++scan == *++match &&
  77182. scan < strend);
  77183. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77184. len = MAX_MATCH - (int)(strend - scan);
  77185. if (len < MIN_MATCH) return MIN_MATCH - 1;
  77186. s->match_start = cur_match;
  77187. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  77188. }
  77189. #ifdef DEBUG
  77190. /* ===========================================================================
  77191. * Check that the match at match_start is indeed a match.
  77192. */
  77193. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  77194. {
  77195. /* check that the match is indeed a match */
  77196. if (zmemcmp(s->window + match,
  77197. s->window + start, length) != EQUAL) {
  77198. fprintf(stderr, " start %u, match %u, length %d\n",
  77199. start, match, length);
  77200. do {
  77201. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  77202. } while (--length != 0);
  77203. z_error("invalid match");
  77204. }
  77205. if (z_verbose > 1) {
  77206. fprintf(stderr,"\\[%d,%d]", start-match, length);
  77207. do { putc(s->window[start++], stderr); } while (--length != 0);
  77208. }
  77209. }
  77210. #else
  77211. # define check_match(s, start, match, length)
  77212. #endif /* DEBUG */
  77213. /* ===========================================================================
  77214. * Fill the window when the lookahead becomes insufficient.
  77215. * Updates strstart and lookahead.
  77216. *
  77217. * IN assertion: lookahead < MIN_LOOKAHEAD
  77218. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  77219. * At least one byte has been read, or avail_in == 0; reads are
  77220. * performed for at least two bytes (required for the zip translate_eol
  77221. * option -- not supported here).
  77222. */
  77223. local void fill_window (deflate_state *s)
  77224. {
  77225. register unsigned n, m;
  77226. register Posf *p;
  77227. unsigned more; /* Amount of free space at the end of the window. */
  77228. uInt wsize = s->w_size;
  77229. do {
  77230. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  77231. /* Deal with !@#$% 64K limit: */
  77232. if (sizeof(int) <= 2) {
  77233. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  77234. more = wsize;
  77235. } else if (more == (unsigned)(-1)) {
  77236. /* Very unlikely, but possible on 16 bit machine if
  77237. * strstart == 0 && lookahead == 1 (input done a byte at time)
  77238. */
  77239. more--;
  77240. }
  77241. }
  77242. /* If the window is almost full and there is insufficient lookahead,
  77243. * move the upper half to the lower one to make room in the upper half.
  77244. */
  77245. if (s->strstart >= wsize+MAX_DIST(s)) {
  77246. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  77247. s->match_start -= wsize;
  77248. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  77249. s->block_start -= (long) wsize;
  77250. /* Slide the hash table (could be avoided with 32 bit values
  77251. at the expense of memory usage). We slide even when level == 0
  77252. to keep the hash table consistent if we switch back to level > 0
  77253. later. (Using level 0 permanently is not an optimal usage of
  77254. zlib, so we don't care about this pathological case.)
  77255. */
  77256. /* %%% avoid this when Z_RLE */
  77257. n = s->hash_size;
  77258. p = &s->head[n];
  77259. do {
  77260. m = *--p;
  77261. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77262. } while (--n);
  77263. n = wsize;
  77264. #ifndef FASTEST
  77265. p = &s->prev[n];
  77266. do {
  77267. m = *--p;
  77268. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77269. /* If n is not on any hash chain, prev[n] is garbage but
  77270. * its value will never be used.
  77271. */
  77272. } while (--n);
  77273. #endif
  77274. more += wsize;
  77275. }
  77276. if (s->strm->avail_in == 0) return;
  77277. /* If there was no sliding:
  77278. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  77279. * more == window_size - lookahead - strstart
  77280. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  77281. * => more >= window_size - 2*WSIZE + 2
  77282. * In the BIG_MEM or MMAP case (not yet supported),
  77283. * window_size == input_size + MIN_LOOKAHEAD &&
  77284. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  77285. * Otherwise, window_size == 2*WSIZE so more >= 2.
  77286. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  77287. */
  77288. Assert(more >= 2, "more < 2");
  77289. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  77290. s->lookahead += n;
  77291. /* Initialize the hash value now that we have some input: */
  77292. if (s->lookahead >= MIN_MATCH) {
  77293. s->ins_h = s->window[s->strstart];
  77294. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77295. #if MIN_MATCH != 3
  77296. Call UPDATE_HASH() MIN_MATCH-3 more times
  77297. #endif
  77298. }
  77299. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  77300. * but this is not important since only literal bytes will be emitted.
  77301. */
  77302. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  77303. }
  77304. /* ===========================================================================
  77305. * Flush the current block, with given end-of-file flag.
  77306. * IN assertion: strstart is set to the end of the current match.
  77307. */
  77308. #define FLUSH_BLOCK_ONLY(s, eof) { \
  77309. _tr_flush_block(s, (s->block_start >= 0L ? \
  77310. (charf *)&s->window[(unsigned)s->block_start] : \
  77311. (charf *)Z_NULL), \
  77312. (ulg)((long)s->strstart - s->block_start), \
  77313. (eof)); \
  77314. s->block_start = s->strstart; \
  77315. flush_pending(s->strm); \
  77316. Tracev((stderr,"[FLUSH]")); \
  77317. }
  77318. /* Same but force premature exit if necessary. */
  77319. #define FLUSH_BLOCK(s, eof) { \
  77320. FLUSH_BLOCK_ONLY(s, eof); \
  77321. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  77322. }
  77323. /* ===========================================================================
  77324. * Copy without compression as much as possible from the input stream, return
  77325. * the current block state.
  77326. * This function does not insert new strings in the dictionary since
  77327. * uncompressible data is probably not useful. This function is used
  77328. * only for the level=0 compression option.
  77329. * NOTE: this function should be optimized to avoid extra copying from
  77330. * window to pending_buf.
  77331. */
  77332. local block_state deflate_stored(deflate_state *s, int flush)
  77333. {
  77334. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  77335. * to pending_buf_size, and each stored block has a 5 byte header:
  77336. */
  77337. ulg max_block_size = 0xffff;
  77338. ulg max_start;
  77339. if (max_block_size > s->pending_buf_size - 5) {
  77340. max_block_size = s->pending_buf_size - 5;
  77341. }
  77342. /* Copy as much as possible from input to output: */
  77343. for (;;) {
  77344. /* Fill the window as much as possible: */
  77345. if (s->lookahead <= 1) {
  77346. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  77347. s->block_start >= (long)s->w_size, "slide too late");
  77348. fill_window(s);
  77349. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  77350. if (s->lookahead == 0) break; /* flush the current block */
  77351. }
  77352. Assert(s->block_start >= 0L, "block gone");
  77353. s->strstart += s->lookahead;
  77354. s->lookahead = 0;
  77355. /* Emit a stored block if pending_buf will be full: */
  77356. max_start = s->block_start + max_block_size;
  77357. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  77358. /* strstart == 0 is possible when wraparound on 16-bit machine */
  77359. s->lookahead = (uInt)(s->strstart - max_start);
  77360. s->strstart = (uInt)max_start;
  77361. FLUSH_BLOCK(s, 0);
  77362. }
  77363. /* Flush if we may have to slide, otherwise block_start may become
  77364. * negative and the data will be gone:
  77365. */
  77366. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  77367. FLUSH_BLOCK(s, 0);
  77368. }
  77369. }
  77370. FLUSH_BLOCK(s, flush == Z_FINISH);
  77371. return flush == Z_FINISH ? finish_done : block_done;
  77372. }
  77373. /* ===========================================================================
  77374. * Compress as much as possible from the input stream, return the current
  77375. * block state.
  77376. * This function does not perform lazy evaluation of matches and inserts
  77377. * new strings in the dictionary only for unmatched strings or for short
  77378. * matches. It is used only for the fast compression options.
  77379. */
  77380. local block_state deflate_fast(deflate_state *s, int flush)
  77381. {
  77382. IPos hash_head = NIL; /* head of the hash chain */
  77383. int bflush; /* set if current block must be flushed */
  77384. for (;;) {
  77385. /* Make sure that we always have enough lookahead, except
  77386. * at the end of the input file. We need MAX_MATCH bytes
  77387. * for the next match, plus MIN_MATCH bytes to insert the
  77388. * string following the next match.
  77389. */
  77390. if (s->lookahead < MIN_LOOKAHEAD) {
  77391. fill_window(s);
  77392. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  77393. return need_more;
  77394. }
  77395. if (s->lookahead == 0) break; /* flush the current block */
  77396. }
  77397. /* Insert the string window[strstart .. strstart+2] in the
  77398. * dictionary, and set hash_head to the head of the hash chain:
  77399. */
  77400. if (s->lookahead >= MIN_MATCH) {
  77401. INSERT_STRING(s, s->strstart, hash_head);
  77402. }
  77403. /* Find the longest match, discarding those <= prev_length.
  77404. * At this point we have always match_length < MIN_MATCH
  77405. */
  77406. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  77407. /* To simplify the code, we prevent matches with the string
  77408. * of window index 0 (in particular we have to avoid a match
  77409. * of the string with itself at the start of the input file).
  77410. */
  77411. #ifdef FASTEST
  77412. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  77413. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  77414. s->match_length = longest_match_fast (s, hash_head);
  77415. }
  77416. #else
  77417. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  77418. s->match_length = longest_match (s, hash_head);
  77419. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  77420. s->match_length = longest_match_fast (s, hash_head);
  77421. }
  77422. #endif
  77423. /* longest_match() or longest_match_fast() sets match_start */
  77424. }
  77425. if (s->match_length >= MIN_MATCH) {
  77426. check_match(s, s->strstart, s->match_start, s->match_length);
  77427. _tr_tally_dist(s, s->strstart - s->match_start,
  77428. s->match_length - MIN_MATCH, bflush);
  77429. s->lookahead -= s->match_length;
  77430. /* Insert new strings in the hash table only if the match length
  77431. * is not too large. This saves time but degrades compression.
  77432. */
  77433. #ifndef FASTEST
  77434. if (s->match_length <= s->max_insert_length &&
  77435. s->lookahead >= MIN_MATCH) {
  77436. s->match_length--; /* string at strstart already in table */
  77437. do {
  77438. s->strstart++;
  77439. INSERT_STRING(s, s->strstart, hash_head);
  77440. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  77441. * always MIN_MATCH bytes ahead.
  77442. */
  77443. } while (--s->match_length != 0);
  77444. s->strstart++;
  77445. } else
  77446. #endif
  77447. {
  77448. s->strstart += s->match_length;
  77449. s->match_length = 0;
  77450. s->ins_h = s->window[s->strstart];
  77451. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77452. #if MIN_MATCH != 3
  77453. Call UPDATE_HASH() MIN_MATCH-3 more times
  77454. #endif
  77455. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  77456. * matter since it will be recomputed at next deflate call.
  77457. */
  77458. }
  77459. } else {
  77460. /* No match, output a literal byte */
  77461. Tracevv((stderr,"%c", s->window[s->strstart]));
  77462. _tr_tally_lit (s, s->window[s->strstart], bflush);
  77463. s->lookahead--;
  77464. s->strstart++;
  77465. }
  77466. if (bflush) FLUSH_BLOCK(s, 0);
  77467. }
  77468. FLUSH_BLOCK(s, flush == Z_FINISH);
  77469. return flush == Z_FINISH ? finish_done : block_done;
  77470. }
  77471. #ifndef FASTEST
  77472. /* ===========================================================================
  77473. * Same as above, but achieves better compression. We use a lazy
  77474. * evaluation for matches: a match is finally adopted only if there is
  77475. * no better match at the next window position.
  77476. */
  77477. local block_state deflate_slow(deflate_state *s, int flush)
  77478. {
  77479. IPos hash_head = NIL; /* head of hash chain */
  77480. int bflush; /* set if current block must be flushed */
  77481. /* Process the input block. */
  77482. for (;;) {
  77483. /* Make sure that we always have enough lookahead, except
  77484. * at the end of the input file. We need MAX_MATCH bytes
  77485. * for the next match, plus MIN_MATCH bytes to insert the
  77486. * string following the next match.
  77487. */
  77488. if (s->lookahead < MIN_LOOKAHEAD) {
  77489. fill_window(s);
  77490. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  77491. return need_more;
  77492. }
  77493. if (s->lookahead == 0) break; /* flush the current block */
  77494. }
  77495. /* Insert the string window[strstart .. strstart+2] in the
  77496. * dictionary, and set hash_head to the head of the hash chain:
  77497. */
  77498. if (s->lookahead >= MIN_MATCH) {
  77499. INSERT_STRING(s, s->strstart, hash_head);
  77500. }
  77501. /* Find the longest match, discarding those <= prev_length.
  77502. */
  77503. s->prev_length = s->match_length, s->prev_match = s->match_start;
  77504. s->match_length = MIN_MATCH-1;
  77505. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  77506. s->strstart - hash_head <= MAX_DIST(s)) {
  77507. /* To simplify the code, we prevent matches with the string
  77508. * of window index 0 (in particular we have to avoid a match
  77509. * of the string with itself at the start of the input file).
  77510. */
  77511. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  77512. s->match_length = longest_match (s, hash_head);
  77513. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  77514. s->match_length = longest_match_fast (s, hash_head);
  77515. }
  77516. /* longest_match() or longest_match_fast() sets match_start */
  77517. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  77518. #if TOO_FAR <= 32767
  77519. || (s->match_length == MIN_MATCH &&
  77520. s->strstart - s->match_start > TOO_FAR)
  77521. #endif
  77522. )) {
  77523. /* If prev_match is also MIN_MATCH, match_start is garbage
  77524. * but we will ignore the current match anyway.
  77525. */
  77526. s->match_length = MIN_MATCH-1;
  77527. }
  77528. }
  77529. /* If there was a match at the previous step and the current
  77530. * match is not better, output the previous match:
  77531. */
  77532. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  77533. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  77534. /* Do not insert strings in hash table beyond this. */
  77535. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  77536. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  77537. s->prev_length - MIN_MATCH, bflush);
  77538. /* Insert in hash table all strings up to the end of the match.
  77539. * strstart-1 and strstart are already inserted. If there is not
  77540. * enough lookahead, the last two strings are not inserted in
  77541. * the hash table.
  77542. */
  77543. s->lookahead -= s->prev_length-1;
  77544. s->prev_length -= 2;
  77545. do {
  77546. if (++s->strstart <= max_insert) {
  77547. INSERT_STRING(s, s->strstart, hash_head);
  77548. }
  77549. } while (--s->prev_length != 0);
  77550. s->match_available = 0;
  77551. s->match_length = MIN_MATCH-1;
  77552. s->strstart++;
  77553. if (bflush) FLUSH_BLOCK(s, 0);
  77554. } else if (s->match_available) {
  77555. /* If there was no match at the previous position, output a
  77556. * single literal. If there was a match but the current match
  77557. * is longer, truncate the previous match to a single literal.
  77558. */
  77559. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  77560. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  77561. if (bflush) {
  77562. FLUSH_BLOCK_ONLY(s, 0);
  77563. }
  77564. s->strstart++;
  77565. s->lookahead--;
  77566. if (s->strm->avail_out == 0) return need_more;
  77567. } else {
  77568. /* There is no previous match to compare with, wait for
  77569. * the next step to decide.
  77570. */
  77571. s->match_available = 1;
  77572. s->strstart++;
  77573. s->lookahead--;
  77574. }
  77575. }
  77576. Assert (flush != Z_NO_FLUSH, "no flush?");
  77577. if (s->match_available) {
  77578. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  77579. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  77580. s->match_available = 0;
  77581. }
  77582. FLUSH_BLOCK(s, flush == Z_FINISH);
  77583. return flush == Z_FINISH ? finish_done : block_done;
  77584. }
  77585. #endif /* FASTEST */
  77586. #if 0
  77587. /* ===========================================================================
  77588. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  77589. * one. Do not maintain a hash table. (It will be regenerated if this run of
  77590. * deflate switches away from Z_RLE.)
  77591. */
  77592. local block_state deflate_rle(s, flush)
  77593. deflate_state *s;
  77594. int flush;
  77595. {
  77596. int bflush; /* set if current block must be flushed */
  77597. uInt run; /* length of run */
  77598. uInt max; /* maximum length of run */
  77599. uInt prev; /* byte at distance one to match */
  77600. Bytef *scan; /* scan for end of run */
  77601. for (;;) {
  77602. /* Make sure that we always have enough lookahead, except
  77603. * at the end of the input file. We need MAX_MATCH bytes
  77604. * for the longest encodable run.
  77605. */
  77606. if (s->lookahead < MAX_MATCH) {
  77607. fill_window(s);
  77608. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  77609. return need_more;
  77610. }
  77611. if (s->lookahead == 0) break; /* flush the current block */
  77612. }
  77613. /* See how many times the previous byte repeats */
  77614. run = 0;
  77615. if (s->strstart > 0) { /* if there is a previous byte, that is */
  77616. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  77617. scan = s->window + s->strstart - 1;
  77618. prev = *scan++;
  77619. do {
  77620. if (*scan++ != prev)
  77621. break;
  77622. } while (++run < max);
  77623. }
  77624. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  77625. if (run >= MIN_MATCH) {
  77626. check_match(s, s->strstart, s->strstart - 1, run);
  77627. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  77628. s->lookahead -= run;
  77629. s->strstart += run;
  77630. } else {
  77631. /* No match, output a literal byte */
  77632. Tracevv((stderr,"%c", s->window[s->strstart]));
  77633. _tr_tally_lit (s, s->window[s->strstart], bflush);
  77634. s->lookahead--;
  77635. s->strstart++;
  77636. }
  77637. if (bflush) FLUSH_BLOCK(s, 0);
  77638. }
  77639. FLUSH_BLOCK(s, flush == Z_FINISH);
  77640. return flush == Z_FINISH ? finish_done : block_done;
  77641. }
  77642. #endif
  77643. /********* End of inlined file: deflate.c *********/
  77644. /********* Start of inlined file: inffast.c *********/
  77645. /********* Start of inlined file: inftrees.h *********/
  77646. /* WARNING: this file should *not* be used by applications. It is
  77647. part of the implementation of the compression library and is
  77648. subject to change. Applications should only use zlib.h.
  77649. */
  77650. #ifndef _INFTREES_H_
  77651. #define _INFTREES_H_
  77652. /* Structure for decoding tables. Each entry provides either the
  77653. information needed to do the operation requested by the code that
  77654. indexed that table entry, or it provides a pointer to another
  77655. table that indexes more bits of the code. op indicates whether
  77656. the entry is a pointer to another table, a literal, a length or
  77657. distance, an end-of-block, or an invalid code. For a table
  77658. pointer, the low four bits of op is the number of index bits of
  77659. that table. For a length or distance, the low four bits of op
  77660. is the number of extra bits to get after the code. bits is
  77661. the number of bits in this code or part of the code to drop off
  77662. of the bit buffer. val is the actual byte to output in the case
  77663. of a literal, the base length or distance, or the offset from
  77664. the current table to the next table. Each entry is four bytes. */
  77665. typedef struct {
  77666. unsigned char op; /* operation, extra bits, table bits */
  77667. unsigned char bits; /* bits in this part of the code */
  77668. unsigned short val; /* offset in table or code value */
  77669. } code;
  77670. /* op values as set by inflate_table():
  77671. 00000000 - literal
  77672. 0000tttt - table link, tttt != 0 is the number of table index bits
  77673. 0001eeee - length or distance, eeee is the number of extra bits
  77674. 01100000 - end of block
  77675. 01000000 - invalid code
  77676. */
  77677. /* Maximum size of dynamic tree. The maximum found in a long but non-
  77678. exhaustive search was 1444 code structures (852 for length/literals
  77679. and 592 for distances, the latter actually the result of an
  77680. exhaustive search). The true maximum is not known, but the value
  77681. below is more than safe. */
  77682. #define ENOUGH 2048
  77683. #define MAXD 592
  77684. /* Type of code to build for inftable() */
  77685. typedef enum {
  77686. CODES,
  77687. LENS,
  77688. DISTS
  77689. } codetype;
  77690. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  77691. unsigned codes, code FAR * FAR *table,
  77692. unsigned FAR *bits, unsigned short FAR *work));
  77693. #endif
  77694. /********* End of inlined file: inftrees.h *********/
  77695. /********* Start of inlined file: inflate.h *********/
  77696. /* WARNING: this file should *not* be used by applications. It is
  77697. part of the implementation of the compression library and is
  77698. subject to change. Applications should only use zlib.h.
  77699. */
  77700. #ifndef _INFLATE_H_
  77701. #define _INFLATE_H_
  77702. /* define NO_GZIP when compiling if you want to disable gzip header and
  77703. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  77704. the crc code when it is not needed. For shared libraries, gzip decoding
  77705. should be left enabled. */
  77706. #ifndef NO_GZIP
  77707. # define GUNZIP
  77708. #endif
  77709. /* Possible inflate modes between inflate() calls */
  77710. typedef enum {
  77711. HEAD, /* i: waiting for magic header */
  77712. FLAGS, /* i: waiting for method and flags (gzip) */
  77713. TIME, /* i: waiting for modification time (gzip) */
  77714. OS, /* i: waiting for extra flags and operating system (gzip) */
  77715. EXLEN, /* i: waiting for extra length (gzip) */
  77716. EXTRA, /* i: waiting for extra bytes (gzip) */
  77717. NAME, /* i: waiting for end of file name (gzip) */
  77718. COMMENT, /* i: waiting for end of comment (gzip) */
  77719. HCRC, /* i: waiting for header crc (gzip) */
  77720. DICTID, /* i: waiting for dictionary check value */
  77721. DICT, /* waiting for inflateSetDictionary() call */
  77722. TYPE, /* i: waiting for type bits, including last-flag bit */
  77723. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  77724. STORED, /* i: waiting for stored size (length and complement) */
  77725. COPY, /* i/o: waiting for input or output to copy stored block */
  77726. TABLE, /* i: waiting for dynamic block table lengths */
  77727. LENLENS, /* i: waiting for code length code lengths */
  77728. CODELENS, /* i: waiting for length/lit and distance code lengths */
  77729. LEN, /* i: waiting for length/lit code */
  77730. LENEXT, /* i: waiting for length extra bits */
  77731. DIST, /* i: waiting for distance code */
  77732. DISTEXT, /* i: waiting for distance extra bits */
  77733. MATCH, /* o: waiting for output space to copy string */
  77734. LIT, /* o: waiting for output space to write literal */
  77735. CHECK, /* i: waiting for 32-bit check value */
  77736. LENGTH, /* i: waiting for 32-bit length (gzip) */
  77737. DONE, /* finished check, done -- remain here until reset */
  77738. BAD, /* got a data error -- remain here until reset */
  77739. MEM, /* got an inflate() memory error -- remain here until reset */
  77740. SYNC /* looking for synchronization bytes to restart inflate() */
  77741. } inflate_mode;
  77742. /*
  77743. State transitions between above modes -
  77744. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  77745. Process header:
  77746. HEAD -> (gzip) or (zlib)
  77747. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  77748. NAME -> COMMENT -> HCRC -> TYPE
  77749. (zlib) -> DICTID or TYPE
  77750. DICTID -> DICT -> TYPE
  77751. Read deflate blocks:
  77752. TYPE -> STORED or TABLE or LEN or CHECK
  77753. STORED -> COPY -> TYPE
  77754. TABLE -> LENLENS -> CODELENS -> LEN
  77755. Read deflate codes:
  77756. LEN -> LENEXT or LIT or TYPE
  77757. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  77758. LIT -> LEN
  77759. Process trailer:
  77760. CHECK -> LENGTH -> DONE
  77761. */
  77762. /* state maintained between inflate() calls. Approximately 7K bytes. */
  77763. struct inflate_state {
  77764. inflate_mode mode; /* current inflate mode */
  77765. int last; /* true if processing last block */
  77766. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  77767. int havedict; /* true if dictionary provided */
  77768. int flags; /* gzip header method and flags (0 if zlib) */
  77769. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  77770. unsigned long check; /* protected copy of check value */
  77771. unsigned long total; /* protected copy of output count */
  77772. gz_headerp head; /* where to save gzip header information */
  77773. /* sliding window */
  77774. unsigned wbits; /* log base 2 of requested window size */
  77775. unsigned wsize; /* window size or zero if not using window */
  77776. unsigned whave; /* valid bytes in the window */
  77777. unsigned write; /* window write index */
  77778. unsigned char FAR *window; /* allocated sliding window, if needed */
  77779. /* bit accumulator */
  77780. unsigned long hold; /* input bit accumulator */
  77781. unsigned bits; /* number of bits in "in" */
  77782. /* for string and stored block copying */
  77783. unsigned length; /* literal or length of data to copy */
  77784. unsigned offset; /* distance back to copy string from */
  77785. /* for table and code decoding */
  77786. unsigned extra; /* extra bits needed */
  77787. /* fixed and dynamic code tables */
  77788. code const FAR *lencode; /* starting table for length/literal codes */
  77789. code const FAR *distcode; /* starting table for distance codes */
  77790. unsigned lenbits; /* index bits for lencode */
  77791. unsigned distbits; /* index bits for distcode */
  77792. /* dynamic table building */
  77793. unsigned ncode; /* number of code length code lengths */
  77794. unsigned nlen; /* number of length code lengths */
  77795. unsigned ndist; /* number of distance code lengths */
  77796. unsigned have; /* number of code lengths in lens[] */
  77797. code FAR *next; /* next available space in codes[] */
  77798. unsigned short lens[320]; /* temporary storage for code lengths */
  77799. unsigned short work[288]; /* work area for code table building */
  77800. code codes[ENOUGH]; /* space for code tables */
  77801. };
  77802. #endif
  77803. /********* End of inlined file: inflate.h *********/
  77804. /********* Start of inlined file: inffast.h *********/
  77805. /* WARNING: this file should *not* be used by applications. It is
  77806. part of the implementation of the compression library and is
  77807. subject to change. Applications should only use zlib.h.
  77808. */
  77809. void inflate_fast OF((z_streamp strm, unsigned start));
  77810. /********* End of inlined file: inffast.h *********/
  77811. #ifndef ASMINF
  77812. /* Allow machine dependent optimization for post-increment or pre-increment.
  77813. Based on testing to date,
  77814. Pre-increment preferred for:
  77815. - PowerPC G3 (Adler)
  77816. - MIPS R5000 (Randers-Pehrson)
  77817. Post-increment preferred for:
  77818. - none
  77819. No measurable difference:
  77820. - Pentium III (Anderson)
  77821. - M68060 (Nikl)
  77822. */
  77823. #ifdef POSTINC
  77824. # define OFF 0
  77825. # define PUP(a) *(a)++
  77826. #else
  77827. # define OFF 1
  77828. # define PUP(a) *++(a)
  77829. #endif
  77830. /*
  77831. Decode literal, length, and distance codes and write out the resulting
  77832. literal and match bytes until either not enough input or output is
  77833. available, an end-of-block is encountered, or a data error is encountered.
  77834. When large enough input and output buffers are supplied to inflate(), for
  77835. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  77836. inflate execution time is spent in this routine.
  77837. Entry assumptions:
  77838. state->mode == LEN
  77839. strm->avail_in >= 6
  77840. strm->avail_out >= 258
  77841. start >= strm->avail_out
  77842. state->bits < 8
  77843. On return, state->mode is one of:
  77844. LEN -- ran out of enough output space or enough available input
  77845. TYPE -- reached end of block code, inflate() to interpret next block
  77846. BAD -- error in block data
  77847. Notes:
  77848. - The maximum input bits used by a length/distance pair is 15 bits for the
  77849. length code, 5 bits for the length extra, 15 bits for the distance code,
  77850. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  77851. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  77852. checking for available input while decoding.
  77853. - The maximum bytes that a single length/distance pair can output is 258
  77854. bytes, which is the maximum length that can be coded. inflate_fast()
  77855. requires strm->avail_out >= 258 for each loop to avoid checking for
  77856. output space.
  77857. */
  77858. void inflate_fast (z_streamp strm, unsigned start)
  77859. {
  77860. struct inflate_state FAR *state;
  77861. unsigned char FAR *in; /* local strm->next_in */
  77862. unsigned char FAR *last; /* while in < last, enough input available */
  77863. unsigned char FAR *out; /* local strm->next_out */
  77864. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  77865. unsigned char FAR *end; /* while out < end, enough space available */
  77866. #ifdef INFLATE_STRICT
  77867. unsigned dmax; /* maximum distance from zlib header */
  77868. #endif
  77869. unsigned wsize; /* window size or zero if not using window */
  77870. unsigned whave; /* valid bytes in the window */
  77871. unsigned write; /* window write index */
  77872. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  77873. unsigned long hold; /* local strm->hold */
  77874. unsigned bits; /* local strm->bits */
  77875. code const FAR *lcode; /* local strm->lencode */
  77876. code const FAR *dcode; /* local strm->distcode */
  77877. unsigned lmask; /* mask for first level of length codes */
  77878. unsigned dmask; /* mask for first level of distance codes */
  77879. code thisx; /* retrieved table entry */
  77880. unsigned op; /* code bits, operation, extra bits, or */
  77881. /* window position, window bytes to copy */
  77882. unsigned len; /* match length, unused bytes */
  77883. unsigned dist; /* match distance */
  77884. unsigned char FAR *from; /* where to copy match from */
  77885. /* copy state to local variables */
  77886. state = (struct inflate_state FAR *)strm->state;
  77887. in = strm->next_in - OFF;
  77888. last = in + (strm->avail_in - 5);
  77889. out = strm->next_out - OFF;
  77890. beg = out - (start - strm->avail_out);
  77891. end = out + (strm->avail_out - 257);
  77892. #ifdef INFLATE_STRICT
  77893. dmax = state->dmax;
  77894. #endif
  77895. wsize = state->wsize;
  77896. whave = state->whave;
  77897. write = state->write;
  77898. window = state->window;
  77899. hold = state->hold;
  77900. bits = state->bits;
  77901. lcode = state->lencode;
  77902. dcode = state->distcode;
  77903. lmask = (1U << state->lenbits) - 1;
  77904. dmask = (1U << state->distbits) - 1;
  77905. /* decode literals and length/distances until end-of-block or not enough
  77906. input data or output space */
  77907. do {
  77908. if (bits < 15) {
  77909. hold += (unsigned long)(PUP(in)) << bits;
  77910. bits += 8;
  77911. hold += (unsigned long)(PUP(in)) << bits;
  77912. bits += 8;
  77913. }
  77914. thisx = lcode[hold & lmask];
  77915. dolen:
  77916. op = (unsigned)(thisx.bits);
  77917. hold >>= op;
  77918. bits -= op;
  77919. op = (unsigned)(thisx.op);
  77920. if (op == 0) { /* literal */
  77921. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  77922. "inflate: literal '%c'\n" :
  77923. "inflate: literal 0x%02x\n", thisx.val));
  77924. PUP(out) = (unsigned char)(thisx.val);
  77925. }
  77926. else if (op & 16) { /* length base */
  77927. len = (unsigned)(thisx.val);
  77928. op &= 15; /* number of extra bits */
  77929. if (op) {
  77930. if (bits < op) {
  77931. hold += (unsigned long)(PUP(in)) << bits;
  77932. bits += 8;
  77933. }
  77934. len += (unsigned)hold & ((1U << op) - 1);
  77935. hold >>= op;
  77936. bits -= op;
  77937. }
  77938. Tracevv((stderr, "inflate: length %u\n", len));
  77939. if (bits < 15) {
  77940. hold += (unsigned long)(PUP(in)) << bits;
  77941. bits += 8;
  77942. hold += (unsigned long)(PUP(in)) << bits;
  77943. bits += 8;
  77944. }
  77945. thisx = dcode[hold & dmask];
  77946. dodist:
  77947. op = (unsigned)(thisx.bits);
  77948. hold >>= op;
  77949. bits -= op;
  77950. op = (unsigned)(thisx.op);
  77951. if (op & 16) { /* distance base */
  77952. dist = (unsigned)(thisx.val);
  77953. op &= 15; /* number of extra bits */
  77954. if (bits < op) {
  77955. hold += (unsigned long)(PUP(in)) << bits;
  77956. bits += 8;
  77957. if (bits < op) {
  77958. hold += (unsigned long)(PUP(in)) << bits;
  77959. bits += 8;
  77960. }
  77961. }
  77962. dist += (unsigned)hold & ((1U << op) - 1);
  77963. #ifdef INFLATE_STRICT
  77964. if (dist > dmax) {
  77965. strm->msg = (char *)"invalid distance too far back";
  77966. state->mode = BAD;
  77967. break;
  77968. }
  77969. #endif
  77970. hold >>= op;
  77971. bits -= op;
  77972. Tracevv((stderr, "inflate: distance %u\n", dist));
  77973. op = (unsigned)(out - beg); /* max distance in output */
  77974. if (dist > op) { /* see if copy from window */
  77975. op = dist - op; /* distance back in window */
  77976. if (op > whave) {
  77977. strm->msg = (char *)"invalid distance too far back";
  77978. state->mode = BAD;
  77979. break;
  77980. }
  77981. from = window - OFF;
  77982. if (write == 0) { /* very common case */
  77983. from += wsize - op;
  77984. if (op < len) { /* some from window */
  77985. len -= op;
  77986. do {
  77987. PUP(out) = PUP(from);
  77988. } while (--op);
  77989. from = out - dist; /* rest from output */
  77990. }
  77991. }
  77992. else if (write < op) { /* wrap around window */
  77993. from += wsize + write - op;
  77994. op -= write;
  77995. if (op < len) { /* some from end of window */
  77996. len -= op;
  77997. do {
  77998. PUP(out) = PUP(from);
  77999. } while (--op);
  78000. from = window - OFF;
  78001. if (write < len) { /* some from start of window */
  78002. op = write;
  78003. len -= op;
  78004. do {
  78005. PUP(out) = PUP(from);
  78006. } while (--op);
  78007. from = out - dist; /* rest from output */
  78008. }
  78009. }
  78010. }
  78011. else { /* contiguous in window */
  78012. from += write - op;
  78013. if (op < len) { /* some from window */
  78014. len -= op;
  78015. do {
  78016. PUP(out) = PUP(from);
  78017. } while (--op);
  78018. from = out - dist; /* rest from output */
  78019. }
  78020. }
  78021. while (len > 2) {
  78022. PUP(out) = PUP(from);
  78023. PUP(out) = PUP(from);
  78024. PUP(out) = PUP(from);
  78025. len -= 3;
  78026. }
  78027. if (len) {
  78028. PUP(out) = PUP(from);
  78029. if (len > 1)
  78030. PUP(out) = PUP(from);
  78031. }
  78032. }
  78033. else {
  78034. from = out - dist; /* copy direct from output */
  78035. do { /* minimum length is three */
  78036. PUP(out) = PUP(from);
  78037. PUP(out) = PUP(from);
  78038. PUP(out) = PUP(from);
  78039. len -= 3;
  78040. } while (len > 2);
  78041. if (len) {
  78042. PUP(out) = PUP(from);
  78043. if (len > 1)
  78044. PUP(out) = PUP(from);
  78045. }
  78046. }
  78047. }
  78048. else if ((op & 64) == 0) { /* 2nd level distance code */
  78049. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  78050. goto dodist;
  78051. }
  78052. else {
  78053. strm->msg = (char *)"invalid distance code";
  78054. state->mode = BAD;
  78055. break;
  78056. }
  78057. }
  78058. else if ((op & 64) == 0) { /* 2nd level length code */
  78059. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  78060. goto dolen;
  78061. }
  78062. else if (op & 32) { /* end-of-block */
  78063. Tracevv((stderr, "inflate: end of block\n"));
  78064. state->mode = TYPE;
  78065. break;
  78066. }
  78067. else {
  78068. strm->msg = (char *)"invalid literal/length code";
  78069. state->mode = BAD;
  78070. break;
  78071. }
  78072. } while (in < last && out < end);
  78073. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  78074. len = bits >> 3;
  78075. in -= len;
  78076. bits -= len << 3;
  78077. hold &= (1U << bits) - 1;
  78078. /* update state and return */
  78079. strm->next_in = in + OFF;
  78080. strm->next_out = out + OFF;
  78081. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  78082. strm->avail_out = (unsigned)(out < end ?
  78083. 257 + (end - out) : 257 - (out - end));
  78084. state->hold = hold;
  78085. state->bits = bits;
  78086. return;
  78087. }
  78088. /*
  78089. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  78090. - Using bit fields for code structure
  78091. - Different op definition to avoid & for extra bits (do & for table bits)
  78092. - Three separate decoding do-loops for direct, window, and write == 0
  78093. - Special case for distance > 1 copies to do overlapped load and store copy
  78094. - Explicit branch predictions (based on measured branch probabilities)
  78095. - Deferring match copy and interspersed it with decoding subsequent codes
  78096. - Swapping literal/length else
  78097. - Swapping window/direct else
  78098. - Larger unrolled copy loops (three is about right)
  78099. - Moving len -= 3 statement into middle of loop
  78100. */
  78101. #endif /* !ASMINF */
  78102. /********* End of inlined file: inffast.c *********/
  78103. #undef PULLBYTE
  78104. #undef LOAD
  78105. #undef RESTORE
  78106. #undef INITBITS
  78107. #undef NEEDBITS
  78108. #undef DROPBITS
  78109. #undef BYTEBITS
  78110. /********* Start of inlined file: inflate.c *********/
  78111. /*
  78112. * Change history:
  78113. *
  78114. * 1.2.beta0 24 Nov 2002
  78115. * - First version -- complete rewrite of inflate to simplify code, avoid
  78116. * creation of window when not needed, minimize use of window when it is
  78117. * needed, make inffast.c even faster, implement gzip decoding, and to
  78118. * improve code readability and style over the previous zlib inflate code
  78119. *
  78120. * 1.2.beta1 25 Nov 2002
  78121. * - Use pointers for available input and output checking in inffast.c
  78122. * - Remove input and output counters in inffast.c
  78123. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  78124. * - Remove unnecessary second byte pull from length extra in inffast.c
  78125. * - Unroll direct copy to three copies per loop in inffast.c
  78126. *
  78127. * 1.2.beta2 4 Dec 2002
  78128. * - Change external routine names to reduce potential conflicts
  78129. * - Correct filename to inffixed.h for fixed tables in inflate.c
  78130. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  78131. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  78132. * to avoid negation problem on Alphas (64 bit) in inflate.c
  78133. *
  78134. * 1.2.beta3 22 Dec 2002
  78135. * - Add comments on state->bits assertion in inffast.c
  78136. * - Add comments on op field in inftrees.h
  78137. * - Fix bug in reuse of allocated window after inflateReset()
  78138. * - Remove bit fields--back to byte structure for speed
  78139. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  78140. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  78141. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  78142. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  78143. * - Use local copies of stream next and avail values, as well as local bit
  78144. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  78145. *
  78146. * 1.2.beta4 1 Jan 2003
  78147. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  78148. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  78149. * - Add comments in inffast.c to introduce the inflate_fast() routine
  78150. * - Rearrange window copies in inflate_fast() for speed and simplification
  78151. * - Unroll last copy for window match in inflate_fast()
  78152. * - Use local copies of window variables in inflate_fast() for speed
  78153. * - Pull out common write == 0 case for speed in inflate_fast()
  78154. * - Make op and len in inflate_fast() unsigned for consistency
  78155. * - Add FAR to lcode and dcode declarations in inflate_fast()
  78156. * - Simplified bad distance check in inflate_fast()
  78157. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  78158. * source file infback.c to provide a call-back interface to inflate for
  78159. * programs like gzip and unzip -- uses window as output buffer to avoid
  78160. * window copying
  78161. *
  78162. * 1.2.beta5 1 Jan 2003
  78163. * - Improved inflateBack() interface to allow the caller to provide initial
  78164. * input in strm.
  78165. * - Fixed stored blocks bug in inflateBack()
  78166. *
  78167. * 1.2.beta6 4 Jan 2003
  78168. * - Added comments in inffast.c on effectiveness of POSTINC
  78169. * - Typecasting all around to reduce compiler warnings
  78170. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  78171. * make compilers happy
  78172. * - Changed type of window in inflateBackInit() to unsigned char *
  78173. *
  78174. * 1.2.beta7 27 Jan 2003
  78175. * - Changed many types to unsigned or unsigned short to avoid warnings
  78176. * - Added inflateCopy() function
  78177. *
  78178. * 1.2.0 9 Mar 2003
  78179. * - Changed inflateBack() interface to provide separate opaque descriptors
  78180. * for the in() and out() functions
  78181. * - Changed inflateBack() argument and in_func typedef to swap the length
  78182. * and buffer address return values for the input function
  78183. * - Check next_in and next_out for Z_NULL on entry to inflate()
  78184. *
  78185. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  78186. */
  78187. /********* Start of inlined file: inffast.h *********/
  78188. /* WARNING: this file should *not* be used by applications. It is
  78189. part of the implementation of the compression library and is
  78190. subject to change. Applications should only use zlib.h.
  78191. */
  78192. void inflate_fast OF((z_streamp strm, unsigned start));
  78193. /********* End of inlined file: inffast.h *********/
  78194. #ifdef MAKEFIXED
  78195. # ifndef BUILDFIXED
  78196. # define BUILDFIXED
  78197. # endif
  78198. #endif
  78199. /* function prototypes */
  78200. local void fixedtables OF((struct inflate_state FAR *state));
  78201. local int updatewindow OF((z_streamp strm, unsigned out));
  78202. #ifdef BUILDFIXED
  78203. void makefixed OF((void));
  78204. #endif
  78205. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  78206. unsigned len));
  78207. int ZEXPORT inflateReset (z_streamp strm)
  78208. {
  78209. struct inflate_state FAR *state;
  78210. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78211. state = (struct inflate_state FAR *)strm->state;
  78212. strm->total_in = strm->total_out = state->total = 0;
  78213. strm->msg = Z_NULL;
  78214. strm->adler = 1; /* to support ill-conceived Java test suite */
  78215. state->mode = HEAD;
  78216. state->last = 0;
  78217. state->havedict = 0;
  78218. state->dmax = 32768U;
  78219. state->head = Z_NULL;
  78220. state->wsize = 0;
  78221. state->whave = 0;
  78222. state->write = 0;
  78223. state->hold = 0;
  78224. state->bits = 0;
  78225. state->lencode = state->distcode = state->next = state->codes;
  78226. Tracev((stderr, "inflate: reset\n"));
  78227. return Z_OK;
  78228. }
  78229. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  78230. {
  78231. struct inflate_state FAR *state;
  78232. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78233. state = (struct inflate_state FAR *)strm->state;
  78234. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  78235. value &= (1L << bits) - 1;
  78236. state->hold += value << state->bits;
  78237. state->bits += bits;
  78238. return Z_OK;
  78239. }
  78240. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  78241. {
  78242. struct inflate_state FAR *state;
  78243. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  78244. stream_size != (int)(sizeof(z_stream)))
  78245. return Z_VERSION_ERROR;
  78246. if (strm == Z_NULL) return Z_STREAM_ERROR;
  78247. strm->msg = Z_NULL; /* in case we return an error */
  78248. if (strm->zalloc == (alloc_func)0) {
  78249. strm->zalloc = zcalloc;
  78250. strm->opaque = (voidpf)0;
  78251. }
  78252. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  78253. state = (struct inflate_state FAR *)
  78254. ZALLOC(strm, 1, sizeof(struct inflate_state));
  78255. if (state == Z_NULL) return Z_MEM_ERROR;
  78256. Tracev((stderr, "inflate: allocated\n"));
  78257. strm->state = (struct internal_state FAR *)state;
  78258. if (windowBits < 0) {
  78259. state->wrap = 0;
  78260. windowBits = -windowBits;
  78261. }
  78262. else {
  78263. state->wrap = (windowBits >> 4) + 1;
  78264. #ifdef GUNZIP
  78265. if (windowBits < 48) windowBits &= 15;
  78266. #endif
  78267. }
  78268. if (windowBits < 8 || windowBits > 15) {
  78269. ZFREE(strm, state);
  78270. strm->state = Z_NULL;
  78271. return Z_STREAM_ERROR;
  78272. }
  78273. state->wbits = (unsigned)windowBits;
  78274. state->window = Z_NULL;
  78275. return inflateReset(strm);
  78276. }
  78277. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  78278. {
  78279. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  78280. }
  78281. /*
  78282. Return state with length and distance decoding tables and index sizes set to
  78283. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  78284. If BUILDFIXED is defined, then instead this routine builds the tables the
  78285. first time it's called, and returns those tables the first time and
  78286. thereafter. This reduces the size of the code by about 2K bytes, in
  78287. exchange for a little execution time. However, BUILDFIXED should not be
  78288. used for threaded applications, since the rewriting of the tables and virgin
  78289. may not be thread-safe.
  78290. */
  78291. local void fixedtables (struct inflate_state FAR *state)
  78292. {
  78293. #ifdef BUILDFIXED
  78294. static int virgin = 1;
  78295. static code *lenfix, *distfix;
  78296. static code fixed[544];
  78297. /* build fixed huffman tables if first call (may not be thread safe) */
  78298. if (virgin) {
  78299. unsigned sym, bits;
  78300. static code *next;
  78301. /* literal/length table */
  78302. sym = 0;
  78303. while (sym < 144) state->lens[sym++] = 8;
  78304. while (sym < 256) state->lens[sym++] = 9;
  78305. while (sym < 280) state->lens[sym++] = 7;
  78306. while (sym < 288) state->lens[sym++] = 8;
  78307. next = fixed;
  78308. lenfix = next;
  78309. bits = 9;
  78310. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  78311. /* distance table */
  78312. sym = 0;
  78313. while (sym < 32) state->lens[sym++] = 5;
  78314. distfix = next;
  78315. bits = 5;
  78316. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  78317. /* do this just once */
  78318. virgin = 0;
  78319. }
  78320. #else /* !BUILDFIXED */
  78321. /********* Start of inlined file: inffixed.h *********/
  78322. /* inffixed.h -- table for decoding fixed codes
  78323. * Generated automatically by makefixed().
  78324. */
  78325. /* WARNING: this file should *not* be used by applications. It
  78326. is part of the implementation of the compression library and
  78327. is subject to change. Applications should only use zlib.h.
  78328. */
  78329. static const code lenfix[512] = {
  78330. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  78331. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  78332. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  78333. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  78334. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  78335. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  78336. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  78337. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  78338. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  78339. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  78340. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  78341. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  78342. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  78343. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  78344. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  78345. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  78346. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  78347. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  78348. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  78349. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  78350. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  78351. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  78352. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  78353. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  78354. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  78355. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  78356. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  78357. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  78358. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  78359. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  78360. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  78361. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  78362. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  78363. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  78364. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  78365. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  78366. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  78367. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  78368. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  78369. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  78370. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  78371. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  78372. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  78373. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  78374. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  78375. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  78376. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  78377. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  78378. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  78379. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  78380. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  78381. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  78382. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  78383. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  78384. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  78385. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  78386. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  78387. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  78388. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  78389. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  78390. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  78391. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  78392. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  78393. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  78394. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  78395. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  78396. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  78397. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  78398. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  78399. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  78400. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  78401. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  78402. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  78403. {0,9,255}
  78404. };
  78405. static const code distfix[32] = {
  78406. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  78407. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  78408. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  78409. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  78410. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  78411. {22,5,193},{64,5,0}
  78412. };
  78413. /********* End of inlined file: inffixed.h *********/
  78414. #endif /* BUILDFIXED */
  78415. state->lencode = lenfix;
  78416. state->lenbits = 9;
  78417. state->distcode = distfix;
  78418. state->distbits = 5;
  78419. }
  78420. #ifdef MAKEFIXED
  78421. #include <stdio.h>
  78422. /*
  78423. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  78424. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  78425. those tables to stdout, which would be piped to inffixed.h. A small program
  78426. can simply call makefixed to do this:
  78427. void makefixed(void);
  78428. int main(void)
  78429. {
  78430. makefixed();
  78431. return 0;
  78432. }
  78433. Then that can be linked with zlib built with MAKEFIXED defined and run:
  78434. a.out > inffixed.h
  78435. */
  78436. void makefixed()
  78437. {
  78438. unsigned low, size;
  78439. struct inflate_state state;
  78440. fixedtables(&state);
  78441. puts(" /* inffixed.h -- table for decoding fixed codes");
  78442. puts(" * Generated automatically by makefixed().");
  78443. puts(" */");
  78444. puts("");
  78445. puts(" /* WARNING: this file should *not* be used by applications.");
  78446. puts(" It is part of the implementation of this library and is");
  78447. puts(" subject to change. Applications should only use zlib.h.");
  78448. puts(" */");
  78449. puts("");
  78450. size = 1U << 9;
  78451. printf(" static const code lenfix[%u] = {", size);
  78452. low = 0;
  78453. for (;;) {
  78454. if ((low % 7) == 0) printf("\n ");
  78455. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  78456. state.lencode[low].val);
  78457. if (++low == size) break;
  78458. putchar(',');
  78459. }
  78460. puts("\n };");
  78461. size = 1U << 5;
  78462. printf("\n static const code distfix[%u] = {", size);
  78463. low = 0;
  78464. for (;;) {
  78465. if ((low % 6) == 0) printf("\n ");
  78466. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  78467. state.distcode[low].val);
  78468. if (++low == size) break;
  78469. putchar(',');
  78470. }
  78471. puts("\n };");
  78472. }
  78473. #endif /* MAKEFIXED */
  78474. /*
  78475. Update the window with the last wsize (normally 32K) bytes written before
  78476. returning. If window does not exist yet, create it. This is only called
  78477. when a window is already in use, or when output has been written during this
  78478. inflate call, but the end of the deflate stream has not been reached yet.
  78479. It is also called to create a window for dictionary data when a dictionary
  78480. is loaded.
  78481. Providing output buffers larger than 32K to inflate() should provide a speed
  78482. advantage, since only the last 32K of output is copied to the sliding window
  78483. upon return from inflate(), and since all distances after the first 32K of
  78484. output will fall in the output data, making match copies simpler and faster.
  78485. The advantage may be dependent on the size of the processor's data caches.
  78486. */
  78487. local int updatewindow (z_streamp strm, unsigned out)
  78488. {
  78489. struct inflate_state FAR *state;
  78490. unsigned copy, dist;
  78491. state = (struct inflate_state FAR *)strm->state;
  78492. /* if it hasn't been done already, allocate space for the window */
  78493. if (state->window == Z_NULL) {
  78494. state->window = (unsigned char FAR *)
  78495. ZALLOC(strm, 1U << state->wbits,
  78496. sizeof(unsigned char));
  78497. if (state->window == Z_NULL) return 1;
  78498. }
  78499. /* if window not in use yet, initialize */
  78500. if (state->wsize == 0) {
  78501. state->wsize = 1U << state->wbits;
  78502. state->write = 0;
  78503. state->whave = 0;
  78504. }
  78505. /* copy state->wsize or less output bytes into the circular window */
  78506. copy = out - strm->avail_out;
  78507. if (copy >= state->wsize) {
  78508. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  78509. state->write = 0;
  78510. state->whave = state->wsize;
  78511. }
  78512. else {
  78513. dist = state->wsize - state->write;
  78514. if (dist > copy) dist = copy;
  78515. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  78516. copy -= dist;
  78517. if (copy) {
  78518. zmemcpy(state->window, strm->next_out - copy, copy);
  78519. state->write = copy;
  78520. state->whave = state->wsize;
  78521. }
  78522. else {
  78523. state->write += dist;
  78524. if (state->write == state->wsize) state->write = 0;
  78525. if (state->whave < state->wsize) state->whave += dist;
  78526. }
  78527. }
  78528. return 0;
  78529. }
  78530. /* Macros for inflate(): */
  78531. /* check function to use adler32() for zlib or crc32() for gzip */
  78532. #ifdef GUNZIP
  78533. # define UPDATE(check, buf, len) \
  78534. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  78535. #else
  78536. # define UPDATE(check, buf, len) adler32(check, buf, len)
  78537. #endif
  78538. /* check macros for header crc */
  78539. #ifdef GUNZIP
  78540. # define CRC2(check, word) \
  78541. do { \
  78542. hbuf[0] = (unsigned char)(word); \
  78543. hbuf[1] = (unsigned char)((word) >> 8); \
  78544. check = crc32(check, hbuf, 2); \
  78545. } while (0)
  78546. # define CRC4(check, word) \
  78547. do { \
  78548. hbuf[0] = (unsigned char)(word); \
  78549. hbuf[1] = (unsigned char)((word) >> 8); \
  78550. hbuf[2] = (unsigned char)((word) >> 16); \
  78551. hbuf[3] = (unsigned char)((word) >> 24); \
  78552. check = crc32(check, hbuf, 4); \
  78553. } while (0)
  78554. #endif
  78555. /* Load registers with state in inflate() for speed */
  78556. #define LOAD() \
  78557. do { \
  78558. put = strm->next_out; \
  78559. left = strm->avail_out; \
  78560. next = strm->next_in; \
  78561. have = strm->avail_in; \
  78562. hold = state->hold; \
  78563. bits = state->bits; \
  78564. } while (0)
  78565. /* Restore state from registers in inflate() */
  78566. #define RESTORE() \
  78567. do { \
  78568. strm->next_out = put; \
  78569. strm->avail_out = left; \
  78570. strm->next_in = next; \
  78571. strm->avail_in = have; \
  78572. state->hold = hold; \
  78573. state->bits = bits; \
  78574. } while (0)
  78575. /* Clear the input bit accumulator */
  78576. #define INITBITS() \
  78577. do { \
  78578. hold = 0; \
  78579. bits = 0; \
  78580. } while (0)
  78581. /* Get a byte of input into the bit accumulator, or return from inflate()
  78582. if there is no input available. */
  78583. #define PULLBYTE() \
  78584. do { \
  78585. if (have == 0) goto inf_leave; \
  78586. have--; \
  78587. hold += (unsigned long)(*next++) << bits; \
  78588. bits += 8; \
  78589. } while (0)
  78590. /* Assure that there are at least n bits in the bit accumulator. If there is
  78591. not enough available input to do that, then return from inflate(). */
  78592. #define NEEDBITS(n) \
  78593. do { \
  78594. while (bits < (unsigned)(n)) \
  78595. PULLBYTE(); \
  78596. } while (0)
  78597. /* Return the low n bits of the bit accumulator (n < 16) */
  78598. #define BITS(n) \
  78599. ((unsigned)hold & ((1U << (n)) - 1))
  78600. /* Remove n bits from the bit accumulator */
  78601. #define DROPBITS(n) \
  78602. do { \
  78603. hold >>= (n); \
  78604. bits -= (unsigned)(n); \
  78605. } while (0)
  78606. /* Remove zero to seven bits as needed to go to a byte boundary */
  78607. #define BYTEBITS() \
  78608. do { \
  78609. hold >>= bits & 7; \
  78610. bits -= bits & 7; \
  78611. } while (0)
  78612. /* Reverse the bytes in a 32-bit value */
  78613. #define REVERSE(q) \
  78614. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  78615. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  78616. /*
  78617. inflate() uses a state machine to process as much input data and generate as
  78618. much output data as possible before returning. The state machine is
  78619. structured roughly as follows:
  78620. for (;;) switch (state) {
  78621. ...
  78622. case STATEn:
  78623. if (not enough input data or output space to make progress)
  78624. return;
  78625. ... make progress ...
  78626. state = STATEm;
  78627. break;
  78628. ...
  78629. }
  78630. so when inflate() is called again, the same case is attempted again, and
  78631. if the appropriate resources are provided, the machine proceeds to the
  78632. next state. The NEEDBITS() macro is usually the way the state evaluates
  78633. whether it can proceed or should return. NEEDBITS() does the return if
  78634. the requested bits are not available. The typical use of the BITS macros
  78635. is:
  78636. NEEDBITS(n);
  78637. ... do something with BITS(n) ...
  78638. DROPBITS(n);
  78639. where NEEDBITS(n) either returns from inflate() if there isn't enough
  78640. input left to load n bits into the accumulator, or it continues. BITS(n)
  78641. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  78642. the low n bits off the accumulator. INITBITS() clears the accumulator
  78643. and sets the number of available bits to zero. BYTEBITS() discards just
  78644. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  78645. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  78646. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  78647. if there is no input available. The decoding of variable length codes uses
  78648. PULLBYTE() directly in order to pull just enough bytes to decode the next
  78649. code, and no more.
  78650. Some states loop until they get enough input, making sure that enough
  78651. state information is maintained to continue the loop where it left off
  78652. if NEEDBITS() returns in the loop. For example, want, need, and keep
  78653. would all have to actually be part of the saved state in case NEEDBITS()
  78654. returns:
  78655. case STATEw:
  78656. while (want < need) {
  78657. NEEDBITS(n);
  78658. keep[want++] = BITS(n);
  78659. DROPBITS(n);
  78660. }
  78661. state = STATEx;
  78662. case STATEx:
  78663. As shown above, if the next state is also the next case, then the break
  78664. is omitted.
  78665. A state may also return if there is not enough output space available to
  78666. complete that state. Those states are copying stored data, writing a
  78667. literal byte, and copying a matching string.
  78668. When returning, a "goto inf_leave" is used to update the total counters,
  78669. update the check value, and determine whether any progress has been made
  78670. during that inflate() call in order to return the proper return code.
  78671. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  78672. When there is a window, goto inf_leave will update the window with the last
  78673. output written. If a goto inf_leave occurs in the middle of decompression
  78674. and there is no window currently, goto inf_leave will create one and copy
  78675. output to the window for the next call of inflate().
  78676. In this implementation, the flush parameter of inflate() only affects the
  78677. return code (per zlib.h). inflate() always writes as much as possible to
  78678. strm->next_out, given the space available and the provided input--the effect
  78679. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  78680. the allocation of and copying into a sliding window until necessary, which
  78681. provides the effect documented in zlib.h for Z_FINISH when the entire input
  78682. stream available. So the only thing the flush parameter actually does is:
  78683. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  78684. will return Z_BUF_ERROR if it has not reached the end of the stream.
  78685. */
  78686. int ZEXPORT inflate (z_streamp strm, int flush)
  78687. {
  78688. struct inflate_state FAR *state;
  78689. unsigned char FAR *next; /* next input */
  78690. unsigned char FAR *put; /* next output */
  78691. unsigned have, left; /* available input and output */
  78692. unsigned long hold; /* bit buffer */
  78693. unsigned bits; /* bits in bit buffer */
  78694. unsigned in, out; /* save starting available input and output */
  78695. unsigned copy; /* number of stored or match bytes to copy */
  78696. unsigned char FAR *from; /* where to copy match bytes from */
  78697. code thisx; /* current decoding table entry */
  78698. code last; /* parent table entry */
  78699. unsigned len; /* length to copy for repeats, bits to drop */
  78700. int ret; /* return code */
  78701. #ifdef GUNZIP
  78702. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  78703. #endif
  78704. static const unsigned short order[19] = /* permutation of code lengths */
  78705. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  78706. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  78707. (strm->next_in == Z_NULL && strm->avail_in != 0))
  78708. return Z_STREAM_ERROR;
  78709. state = (struct inflate_state FAR *)strm->state;
  78710. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  78711. LOAD();
  78712. in = have;
  78713. out = left;
  78714. ret = Z_OK;
  78715. for (;;)
  78716. switch (state->mode) {
  78717. case HEAD:
  78718. if (state->wrap == 0) {
  78719. state->mode = TYPEDO;
  78720. break;
  78721. }
  78722. NEEDBITS(16);
  78723. #ifdef GUNZIP
  78724. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  78725. state->check = crc32(0L, Z_NULL, 0);
  78726. CRC2(state->check, hold);
  78727. INITBITS();
  78728. state->mode = FLAGS;
  78729. break;
  78730. }
  78731. state->flags = 0; /* expect zlib header */
  78732. if (state->head != Z_NULL)
  78733. state->head->done = -1;
  78734. if (!(state->wrap & 1) || /* check if zlib header allowed */
  78735. #else
  78736. if (
  78737. #endif
  78738. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  78739. strm->msg = (char *)"incorrect header check";
  78740. state->mode = BAD;
  78741. break;
  78742. }
  78743. if (BITS(4) != Z_DEFLATED) {
  78744. strm->msg = (char *)"unknown compression method";
  78745. state->mode = BAD;
  78746. break;
  78747. }
  78748. DROPBITS(4);
  78749. len = BITS(4) + 8;
  78750. if (len > state->wbits) {
  78751. strm->msg = (char *)"invalid window size";
  78752. state->mode = BAD;
  78753. break;
  78754. }
  78755. state->dmax = 1U << len;
  78756. Tracev((stderr, "inflate: zlib header ok\n"));
  78757. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  78758. state->mode = hold & 0x200 ? DICTID : TYPE;
  78759. INITBITS();
  78760. break;
  78761. #ifdef GUNZIP
  78762. case FLAGS:
  78763. NEEDBITS(16);
  78764. state->flags = (int)(hold);
  78765. if ((state->flags & 0xff) != Z_DEFLATED) {
  78766. strm->msg = (char *)"unknown compression method";
  78767. state->mode = BAD;
  78768. break;
  78769. }
  78770. if (state->flags & 0xe000) {
  78771. strm->msg = (char *)"unknown header flags set";
  78772. state->mode = BAD;
  78773. break;
  78774. }
  78775. if (state->head != Z_NULL)
  78776. state->head->text = (int)((hold >> 8) & 1);
  78777. if (state->flags & 0x0200) CRC2(state->check, hold);
  78778. INITBITS();
  78779. state->mode = TIME;
  78780. case TIME:
  78781. NEEDBITS(32);
  78782. if (state->head != Z_NULL)
  78783. state->head->time = hold;
  78784. if (state->flags & 0x0200) CRC4(state->check, hold);
  78785. INITBITS();
  78786. state->mode = OS;
  78787. case OS:
  78788. NEEDBITS(16);
  78789. if (state->head != Z_NULL) {
  78790. state->head->xflags = (int)(hold & 0xff);
  78791. state->head->os = (int)(hold >> 8);
  78792. }
  78793. if (state->flags & 0x0200) CRC2(state->check, hold);
  78794. INITBITS();
  78795. state->mode = EXLEN;
  78796. case EXLEN:
  78797. if (state->flags & 0x0400) {
  78798. NEEDBITS(16);
  78799. state->length = (unsigned)(hold);
  78800. if (state->head != Z_NULL)
  78801. state->head->extra_len = (unsigned)hold;
  78802. if (state->flags & 0x0200) CRC2(state->check, hold);
  78803. INITBITS();
  78804. }
  78805. else if (state->head != Z_NULL)
  78806. state->head->extra = Z_NULL;
  78807. state->mode = EXTRA;
  78808. case EXTRA:
  78809. if (state->flags & 0x0400) {
  78810. copy = state->length;
  78811. if (copy > have) copy = have;
  78812. if (copy) {
  78813. if (state->head != Z_NULL &&
  78814. state->head->extra != Z_NULL) {
  78815. len = state->head->extra_len - state->length;
  78816. zmemcpy(state->head->extra + len, next,
  78817. len + copy > state->head->extra_max ?
  78818. state->head->extra_max - len : copy);
  78819. }
  78820. if (state->flags & 0x0200)
  78821. state->check = crc32(state->check, next, copy);
  78822. have -= copy;
  78823. next += copy;
  78824. state->length -= copy;
  78825. }
  78826. if (state->length) goto inf_leave;
  78827. }
  78828. state->length = 0;
  78829. state->mode = NAME;
  78830. case NAME:
  78831. if (state->flags & 0x0800) {
  78832. if (have == 0) goto inf_leave;
  78833. copy = 0;
  78834. do {
  78835. len = (unsigned)(next[copy++]);
  78836. if (state->head != Z_NULL &&
  78837. state->head->name != Z_NULL &&
  78838. state->length < state->head->name_max)
  78839. state->head->name[state->length++] = len;
  78840. } while (len && copy < have);
  78841. if (state->flags & 0x0200)
  78842. state->check = crc32(state->check, next, copy);
  78843. have -= copy;
  78844. next += copy;
  78845. if (len) goto inf_leave;
  78846. }
  78847. else if (state->head != Z_NULL)
  78848. state->head->name = Z_NULL;
  78849. state->length = 0;
  78850. state->mode = COMMENT;
  78851. case COMMENT:
  78852. if (state->flags & 0x1000) {
  78853. if (have == 0) goto inf_leave;
  78854. copy = 0;
  78855. do {
  78856. len = (unsigned)(next[copy++]);
  78857. if (state->head != Z_NULL &&
  78858. state->head->comment != Z_NULL &&
  78859. state->length < state->head->comm_max)
  78860. state->head->comment[state->length++] = len;
  78861. } while (len && copy < have);
  78862. if (state->flags & 0x0200)
  78863. state->check = crc32(state->check, next, copy);
  78864. have -= copy;
  78865. next += copy;
  78866. if (len) goto inf_leave;
  78867. }
  78868. else if (state->head != Z_NULL)
  78869. state->head->comment = Z_NULL;
  78870. state->mode = HCRC;
  78871. case HCRC:
  78872. if (state->flags & 0x0200) {
  78873. NEEDBITS(16);
  78874. if (hold != (state->check & 0xffff)) {
  78875. strm->msg = (char *)"header crc mismatch";
  78876. state->mode = BAD;
  78877. break;
  78878. }
  78879. INITBITS();
  78880. }
  78881. if (state->head != Z_NULL) {
  78882. state->head->hcrc = (int)((state->flags >> 9) & 1);
  78883. state->head->done = 1;
  78884. }
  78885. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  78886. state->mode = TYPE;
  78887. break;
  78888. #endif
  78889. case DICTID:
  78890. NEEDBITS(32);
  78891. strm->adler = state->check = REVERSE(hold);
  78892. INITBITS();
  78893. state->mode = DICT;
  78894. case DICT:
  78895. if (state->havedict == 0) {
  78896. RESTORE();
  78897. return Z_NEED_DICT;
  78898. }
  78899. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  78900. state->mode = TYPE;
  78901. case TYPE:
  78902. if (flush == Z_BLOCK) goto inf_leave;
  78903. case TYPEDO:
  78904. if (state->last) {
  78905. BYTEBITS();
  78906. state->mode = CHECK;
  78907. break;
  78908. }
  78909. NEEDBITS(3);
  78910. state->last = BITS(1);
  78911. DROPBITS(1);
  78912. switch (BITS(2)) {
  78913. case 0: /* stored block */
  78914. Tracev((stderr, "inflate: stored block%s\n",
  78915. state->last ? " (last)" : ""));
  78916. state->mode = STORED;
  78917. break;
  78918. case 1: /* fixed block */
  78919. fixedtables(state);
  78920. Tracev((stderr, "inflate: fixed codes block%s\n",
  78921. state->last ? " (last)" : ""));
  78922. state->mode = LEN; /* decode codes */
  78923. break;
  78924. case 2: /* dynamic block */
  78925. Tracev((stderr, "inflate: dynamic codes block%s\n",
  78926. state->last ? " (last)" : ""));
  78927. state->mode = TABLE;
  78928. break;
  78929. case 3:
  78930. strm->msg = (char *)"invalid block type";
  78931. state->mode = BAD;
  78932. }
  78933. DROPBITS(2);
  78934. break;
  78935. case STORED:
  78936. BYTEBITS(); /* go to byte boundary */
  78937. NEEDBITS(32);
  78938. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  78939. strm->msg = (char *)"invalid stored block lengths";
  78940. state->mode = BAD;
  78941. break;
  78942. }
  78943. state->length = (unsigned)hold & 0xffff;
  78944. Tracev((stderr, "inflate: stored length %u\n",
  78945. state->length));
  78946. INITBITS();
  78947. state->mode = COPY;
  78948. case COPY:
  78949. copy = state->length;
  78950. if (copy) {
  78951. if (copy > have) copy = have;
  78952. if (copy > left) copy = left;
  78953. if (copy == 0) goto inf_leave;
  78954. zmemcpy(put, next, copy);
  78955. have -= copy;
  78956. next += copy;
  78957. left -= copy;
  78958. put += copy;
  78959. state->length -= copy;
  78960. break;
  78961. }
  78962. Tracev((stderr, "inflate: stored end\n"));
  78963. state->mode = TYPE;
  78964. break;
  78965. case TABLE:
  78966. NEEDBITS(14);
  78967. state->nlen = BITS(5) + 257;
  78968. DROPBITS(5);
  78969. state->ndist = BITS(5) + 1;
  78970. DROPBITS(5);
  78971. state->ncode = BITS(4) + 4;
  78972. DROPBITS(4);
  78973. #ifndef PKZIP_BUG_WORKAROUND
  78974. if (state->nlen > 286 || state->ndist > 30) {
  78975. strm->msg = (char *)"too many length or distance symbols";
  78976. state->mode = BAD;
  78977. break;
  78978. }
  78979. #endif
  78980. Tracev((stderr, "inflate: table sizes ok\n"));
  78981. state->have = 0;
  78982. state->mode = LENLENS;
  78983. case LENLENS:
  78984. while (state->have < state->ncode) {
  78985. NEEDBITS(3);
  78986. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  78987. DROPBITS(3);
  78988. }
  78989. while (state->have < 19)
  78990. state->lens[order[state->have++]] = 0;
  78991. state->next = state->codes;
  78992. state->lencode = (code const FAR *)(state->next);
  78993. state->lenbits = 7;
  78994. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  78995. &(state->lenbits), state->work);
  78996. if (ret) {
  78997. strm->msg = (char *)"invalid code lengths set";
  78998. state->mode = BAD;
  78999. break;
  79000. }
  79001. Tracev((stderr, "inflate: code lengths ok\n"));
  79002. state->have = 0;
  79003. state->mode = CODELENS;
  79004. case CODELENS:
  79005. while (state->have < state->nlen + state->ndist) {
  79006. for (;;) {
  79007. thisx = state->lencode[BITS(state->lenbits)];
  79008. if ((unsigned)(thisx.bits) <= bits) break;
  79009. PULLBYTE();
  79010. }
  79011. if (thisx.val < 16) {
  79012. NEEDBITS(thisx.bits);
  79013. DROPBITS(thisx.bits);
  79014. state->lens[state->have++] = thisx.val;
  79015. }
  79016. else {
  79017. if (thisx.val == 16) {
  79018. NEEDBITS(thisx.bits + 2);
  79019. DROPBITS(thisx.bits);
  79020. if (state->have == 0) {
  79021. strm->msg = (char *)"invalid bit length repeat";
  79022. state->mode = BAD;
  79023. break;
  79024. }
  79025. len = state->lens[state->have - 1];
  79026. copy = 3 + BITS(2);
  79027. DROPBITS(2);
  79028. }
  79029. else if (thisx.val == 17) {
  79030. NEEDBITS(thisx.bits + 3);
  79031. DROPBITS(thisx.bits);
  79032. len = 0;
  79033. copy = 3 + BITS(3);
  79034. DROPBITS(3);
  79035. }
  79036. else {
  79037. NEEDBITS(thisx.bits + 7);
  79038. DROPBITS(thisx.bits);
  79039. len = 0;
  79040. copy = 11 + BITS(7);
  79041. DROPBITS(7);
  79042. }
  79043. if (state->have + copy > state->nlen + state->ndist) {
  79044. strm->msg = (char *)"invalid bit length repeat";
  79045. state->mode = BAD;
  79046. break;
  79047. }
  79048. while (copy--)
  79049. state->lens[state->have++] = (unsigned short)len;
  79050. }
  79051. }
  79052. /* handle error breaks in while */
  79053. if (state->mode == BAD) break;
  79054. /* build code tables */
  79055. state->next = state->codes;
  79056. state->lencode = (code const FAR *)(state->next);
  79057. state->lenbits = 9;
  79058. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  79059. &(state->lenbits), state->work);
  79060. if (ret) {
  79061. strm->msg = (char *)"invalid literal/lengths set";
  79062. state->mode = BAD;
  79063. break;
  79064. }
  79065. state->distcode = (code const FAR *)(state->next);
  79066. state->distbits = 6;
  79067. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  79068. &(state->next), &(state->distbits), state->work);
  79069. if (ret) {
  79070. strm->msg = (char *)"invalid distances set";
  79071. state->mode = BAD;
  79072. break;
  79073. }
  79074. Tracev((stderr, "inflate: codes ok\n"));
  79075. state->mode = LEN;
  79076. case LEN:
  79077. if (have >= 6 && left >= 258) {
  79078. RESTORE();
  79079. inflate_fast(strm, out);
  79080. LOAD();
  79081. break;
  79082. }
  79083. for (;;) {
  79084. thisx = state->lencode[BITS(state->lenbits)];
  79085. if ((unsigned)(thisx.bits) <= bits) break;
  79086. PULLBYTE();
  79087. }
  79088. if (thisx.op && (thisx.op & 0xf0) == 0) {
  79089. last = thisx;
  79090. for (;;) {
  79091. thisx = state->lencode[last.val +
  79092. (BITS(last.bits + last.op) >> last.bits)];
  79093. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79094. PULLBYTE();
  79095. }
  79096. DROPBITS(last.bits);
  79097. }
  79098. DROPBITS(thisx.bits);
  79099. state->length = (unsigned)thisx.val;
  79100. if ((int)(thisx.op) == 0) {
  79101. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  79102. "inflate: literal '%c'\n" :
  79103. "inflate: literal 0x%02x\n", thisx.val));
  79104. state->mode = LIT;
  79105. break;
  79106. }
  79107. if (thisx.op & 32) {
  79108. Tracevv((stderr, "inflate: end of block\n"));
  79109. state->mode = TYPE;
  79110. break;
  79111. }
  79112. if (thisx.op & 64) {
  79113. strm->msg = (char *)"invalid literal/length code";
  79114. state->mode = BAD;
  79115. break;
  79116. }
  79117. state->extra = (unsigned)(thisx.op) & 15;
  79118. state->mode = LENEXT;
  79119. case LENEXT:
  79120. if (state->extra) {
  79121. NEEDBITS(state->extra);
  79122. state->length += BITS(state->extra);
  79123. DROPBITS(state->extra);
  79124. }
  79125. Tracevv((stderr, "inflate: length %u\n", state->length));
  79126. state->mode = DIST;
  79127. case DIST:
  79128. for (;;) {
  79129. thisx = state->distcode[BITS(state->distbits)];
  79130. if ((unsigned)(thisx.bits) <= bits) break;
  79131. PULLBYTE();
  79132. }
  79133. if ((thisx.op & 0xf0) == 0) {
  79134. last = thisx;
  79135. for (;;) {
  79136. thisx = state->distcode[last.val +
  79137. (BITS(last.bits + last.op) >> last.bits)];
  79138. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79139. PULLBYTE();
  79140. }
  79141. DROPBITS(last.bits);
  79142. }
  79143. DROPBITS(thisx.bits);
  79144. if (thisx.op & 64) {
  79145. strm->msg = (char *)"invalid distance code";
  79146. state->mode = BAD;
  79147. break;
  79148. }
  79149. state->offset = (unsigned)thisx.val;
  79150. state->extra = (unsigned)(thisx.op) & 15;
  79151. state->mode = DISTEXT;
  79152. case DISTEXT:
  79153. if (state->extra) {
  79154. NEEDBITS(state->extra);
  79155. state->offset += BITS(state->extra);
  79156. DROPBITS(state->extra);
  79157. }
  79158. #ifdef INFLATE_STRICT
  79159. if (state->offset > state->dmax) {
  79160. strm->msg = (char *)"invalid distance too far back";
  79161. state->mode = BAD;
  79162. break;
  79163. }
  79164. #endif
  79165. if (state->offset > state->whave + out - left) {
  79166. strm->msg = (char *)"invalid distance too far back";
  79167. state->mode = BAD;
  79168. break;
  79169. }
  79170. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  79171. state->mode = MATCH;
  79172. case MATCH:
  79173. if (left == 0) goto inf_leave;
  79174. copy = out - left;
  79175. if (state->offset > copy) { /* copy from window */
  79176. copy = state->offset - copy;
  79177. if (copy > state->write) {
  79178. copy -= state->write;
  79179. from = state->window + (state->wsize - copy);
  79180. }
  79181. else
  79182. from = state->window + (state->write - copy);
  79183. if (copy > state->length) copy = state->length;
  79184. }
  79185. else { /* copy from output */
  79186. from = put - state->offset;
  79187. copy = state->length;
  79188. }
  79189. if (copy > left) copy = left;
  79190. left -= copy;
  79191. state->length -= copy;
  79192. do {
  79193. *put++ = *from++;
  79194. } while (--copy);
  79195. if (state->length == 0) state->mode = LEN;
  79196. break;
  79197. case LIT:
  79198. if (left == 0) goto inf_leave;
  79199. *put++ = (unsigned char)(state->length);
  79200. left--;
  79201. state->mode = LEN;
  79202. break;
  79203. case CHECK:
  79204. if (state->wrap) {
  79205. NEEDBITS(32);
  79206. out -= left;
  79207. strm->total_out += out;
  79208. state->total += out;
  79209. if (out)
  79210. strm->adler = state->check =
  79211. UPDATE(state->check, put - out, out);
  79212. out = left;
  79213. if ((
  79214. #ifdef GUNZIP
  79215. state->flags ? hold :
  79216. #endif
  79217. REVERSE(hold)) != state->check) {
  79218. strm->msg = (char *)"incorrect data check";
  79219. state->mode = BAD;
  79220. break;
  79221. }
  79222. INITBITS();
  79223. Tracev((stderr, "inflate: check matches trailer\n"));
  79224. }
  79225. #ifdef GUNZIP
  79226. state->mode = LENGTH;
  79227. case LENGTH:
  79228. if (state->wrap && state->flags) {
  79229. NEEDBITS(32);
  79230. if (hold != (state->total & 0xffffffffUL)) {
  79231. strm->msg = (char *)"incorrect length check";
  79232. state->mode = BAD;
  79233. break;
  79234. }
  79235. INITBITS();
  79236. Tracev((stderr, "inflate: length matches trailer\n"));
  79237. }
  79238. #endif
  79239. state->mode = DONE;
  79240. case DONE:
  79241. ret = Z_STREAM_END;
  79242. goto inf_leave;
  79243. case BAD:
  79244. ret = Z_DATA_ERROR;
  79245. goto inf_leave;
  79246. case MEM:
  79247. return Z_MEM_ERROR;
  79248. case SYNC:
  79249. default:
  79250. return Z_STREAM_ERROR;
  79251. }
  79252. /*
  79253. Return from inflate(), updating the total counts and the check value.
  79254. If there was no progress during the inflate() call, return a buffer
  79255. error. Call updatewindow() to create and/or update the window state.
  79256. Note: a memory error from inflate() is non-recoverable.
  79257. */
  79258. inf_leave:
  79259. RESTORE();
  79260. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  79261. if (updatewindow(strm, out)) {
  79262. state->mode = MEM;
  79263. return Z_MEM_ERROR;
  79264. }
  79265. in -= strm->avail_in;
  79266. out -= strm->avail_out;
  79267. strm->total_in += in;
  79268. strm->total_out += out;
  79269. state->total += out;
  79270. if (state->wrap && out)
  79271. strm->adler = state->check =
  79272. UPDATE(state->check, strm->next_out - out, out);
  79273. strm->data_type = state->bits + (state->last ? 64 : 0) +
  79274. (state->mode == TYPE ? 128 : 0);
  79275. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  79276. ret = Z_BUF_ERROR;
  79277. return ret;
  79278. }
  79279. int ZEXPORT inflateEnd (z_streamp strm)
  79280. {
  79281. struct inflate_state FAR *state;
  79282. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  79283. return Z_STREAM_ERROR;
  79284. state = (struct inflate_state FAR *)strm->state;
  79285. if (state->window != Z_NULL) ZFREE(strm, state->window);
  79286. ZFREE(strm, strm->state);
  79287. strm->state = Z_NULL;
  79288. Tracev((stderr, "inflate: end\n"));
  79289. return Z_OK;
  79290. }
  79291. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  79292. {
  79293. struct inflate_state FAR *state;
  79294. unsigned long id_;
  79295. /* check state */
  79296. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79297. state = (struct inflate_state FAR *)strm->state;
  79298. if (state->wrap != 0 && state->mode != DICT)
  79299. return Z_STREAM_ERROR;
  79300. /* check for correct dictionary id */
  79301. if (state->mode == DICT) {
  79302. id_ = adler32(0L, Z_NULL, 0);
  79303. id_ = adler32(id_, dictionary, dictLength);
  79304. if (id_ != state->check)
  79305. return Z_DATA_ERROR;
  79306. }
  79307. /* copy dictionary to window */
  79308. if (updatewindow(strm, strm->avail_out)) {
  79309. state->mode = MEM;
  79310. return Z_MEM_ERROR;
  79311. }
  79312. if (dictLength > state->wsize) {
  79313. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  79314. state->wsize);
  79315. state->whave = state->wsize;
  79316. }
  79317. else {
  79318. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  79319. dictLength);
  79320. state->whave = dictLength;
  79321. }
  79322. state->havedict = 1;
  79323. Tracev((stderr, "inflate: dictionary set\n"));
  79324. return Z_OK;
  79325. }
  79326. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  79327. {
  79328. struct inflate_state FAR *state;
  79329. /* check state */
  79330. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79331. state = (struct inflate_state FAR *)strm->state;
  79332. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  79333. /* save header structure */
  79334. state->head = head;
  79335. head->done = 0;
  79336. return Z_OK;
  79337. }
  79338. /*
  79339. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  79340. or when out of input. When called, *have is the number of pattern bytes
  79341. found in order so far, in 0..3. On return *have is updated to the new
  79342. state. If on return *have equals four, then the pattern was found and the
  79343. return value is how many bytes were read including the last byte of the
  79344. pattern. If *have is less than four, then the pattern has not been found
  79345. yet and the return value is len. In the latter case, syncsearch() can be
  79346. called again with more data and the *have state. *have is initialized to
  79347. zero for the first call.
  79348. */
  79349. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  79350. {
  79351. unsigned got;
  79352. unsigned next;
  79353. got = *have;
  79354. next = 0;
  79355. while (next < len && got < 4) {
  79356. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  79357. got++;
  79358. else if (buf[next])
  79359. got = 0;
  79360. else
  79361. got = 4 - got;
  79362. next++;
  79363. }
  79364. *have = got;
  79365. return next;
  79366. }
  79367. int ZEXPORT inflateSync (z_streamp strm)
  79368. {
  79369. unsigned len; /* number of bytes to look at or looked at */
  79370. unsigned long in, out; /* temporary to save total_in and total_out */
  79371. unsigned char buf[4]; /* to restore bit buffer to byte string */
  79372. struct inflate_state FAR *state;
  79373. /* check parameters */
  79374. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79375. state = (struct inflate_state FAR *)strm->state;
  79376. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  79377. /* if first time, start search in bit buffer */
  79378. if (state->mode != SYNC) {
  79379. state->mode = SYNC;
  79380. state->hold <<= state->bits & 7;
  79381. state->bits -= state->bits & 7;
  79382. len = 0;
  79383. while (state->bits >= 8) {
  79384. buf[len++] = (unsigned char)(state->hold);
  79385. state->hold >>= 8;
  79386. state->bits -= 8;
  79387. }
  79388. state->have = 0;
  79389. syncsearch(&(state->have), buf, len);
  79390. }
  79391. /* search available input */
  79392. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  79393. strm->avail_in -= len;
  79394. strm->next_in += len;
  79395. strm->total_in += len;
  79396. /* return no joy or set up to restart inflate() on a new block */
  79397. if (state->have != 4) return Z_DATA_ERROR;
  79398. in = strm->total_in; out = strm->total_out;
  79399. inflateReset(strm);
  79400. strm->total_in = in; strm->total_out = out;
  79401. state->mode = TYPE;
  79402. return Z_OK;
  79403. }
  79404. /*
  79405. Returns true if inflate is currently at the end of a block generated by
  79406. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  79407. implementation to provide an additional safety check. PPP uses
  79408. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  79409. block. When decompressing, PPP checks that at the end of input packet,
  79410. inflate is waiting for these length bytes.
  79411. */
  79412. int ZEXPORT inflateSyncPoint (z_streamp strm)
  79413. {
  79414. struct inflate_state FAR *state;
  79415. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79416. state = (struct inflate_state FAR *)strm->state;
  79417. return state->mode == STORED && state->bits == 0;
  79418. }
  79419. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  79420. {
  79421. struct inflate_state FAR *state;
  79422. struct inflate_state FAR *copy;
  79423. unsigned char FAR *window;
  79424. unsigned wsize;
  79425. /* check input */
  79426. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  79427. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  79428. return Z_STREAM_ERROR;
  79429. state = (struct inflate_state FAR *)source->state;
  79430. /* allocate space */
  79431. copy = (struct inflate_state FAR *)
  79432. ZALLOC(source, 1, sizeof(struct inflate_state));
  79433. if (copy == Z_NULL) return Z_MEM_ERROR;
  79434. window = Z_NULL;
  79435. if (state->window != Z_NULL) {
  79436. window = (unsigned char FAR *)
  79437. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  79438. if (window == Z_NULL) {
  79439. ZFREE(source, copy);
  79440. return Z_MEM_ERROR;
  79441. }
  79442. }
  79443. /* copy state */
  79444. zmemcpy(dest, source, sizeof(z_stream));
  79445. zmemcpy(copy, state, sizeof(struct inflate_state));
  79446. if (state->lencode >= state->codes &&
  79447. state->lencode <= state->codes + ENOUGH - 1) {
  79448. copy->lencode = copy->codes + (state->lencode - state->codes);
  79449. copy->distcode = copy->codes + (state->distcode - state->codes);
  79450. }
  79451. copy->next = copy->codes + (state->next - state->codes);
  79452. if (window != Z_NULL) {
  79453. wsize = 1U << state->wbits;
  79454. zmemcpy(window, state->window, wsize);
  79455. }
  79456. copy->window = window;
  79457. dest->state = (struct internal_state FAR *)copy;
  79458. return Z_OK;
  79459. }
  79460. /********* End of inlined file: inflate.c *********/
  79461. /********* Start of inlined file: inftrees.c *********/
  79462. #define MAXBITS 15
  79463. const char inflate_copyright[] =
  79464. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  79465. /*
  79466. If you use the zlib library in a product, an acknowledgment is welcome
  79467. in the documentation of your product. If for some reason you cannot
  79468. include such an acknowledgment, I would appreciate that you keep this
  79469. copyright string in the executable of your product.
  79470. */
  79471. /*
  79472. Build a set of tables to decode the provided canonical Huffman code.
  79473. The code lengths are lens[0..codes-1]. The result starts at *table,
  79474. whose indices are 0..2^bits-1. work is a writable array of at least
  79475. lens shorts, which is used as a work area. type is the type of code
  79476. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  79477. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  79478. on return points to the next available entry's address. bits is the
  79479. requested root table index bits, and on return it is the actual root
  79480. table index bits. It will differ if the request is greater than the
  79481. longest code or if it is less than the shortest code.
  79482. */
  79483. int inflate_table (codetype type,
  79484. unsigned short FAR *lens,
  79485. unsigned codes,
  79486. code FAR * FAR *table,
  79487. unsigned FAR *bits,
  79488. unsigned short FAR *work)
  79489. {
  79490. unsigned len; /* a code's length in bits */
  79491. unsigned sym; /* index of code symbols */
  79492. unsigned min, max; /* minimum and maximum code lengths */
  79493. unsigned root; /* number of index bits for root table */
  79494. unsigned curr; /* number of index bits for current table */
  79495. unsigned drop; /* code bits to drop for sub-table */
  79496. int left; /* number of prefix codes available */
  79497. unsigned used; /* code entries in table used */
  79498. unsigned huff; /* Huffman code */
  79499. unsigned incr; /* for incrementing code, index */
  79500. unsigned fill; /* index for replicating entries */
  79501. unsigned low; /* low bits for current root entry */
  79502. unsigned mask; /* mask for low root bits */
  79503. code thisx; /* table entry for duplication */
  79504. code FAR *next; /* next available space in table */
  79505. const unsigned short FAR *base; /* base value table to use */
  79506. const unsigned short FAR *extra; /* extra bits table to use */
  79507. int end; /* use base and extra for symbol > end */
  79508. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  79509. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  79510. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  79511. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  79512. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  79513. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  79514. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  79515. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  79516. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  79517. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  79518. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  79519. 8193, 12289, 16385, 24577, 0, 0};
  79520. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  79521. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  79522. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  79523. 28, 28, 29, 29, 64, 64};
  79524. /*
  79525. Process a set of code lengths to create a canonical Huffman code. The
  79526. code lengths are lens[0..codes-1]. Each length corresponds to the
  79527. symbols 0..codes-1. The Huffman code is generated by first sorting the
  79528. symbols by length from short to long, and retaining the symbol order
  79529. for codes with equal lengths. Then the code starts with all zero bits
  79530. for the first code of the shortest length, and the codes are integer
  79531. increments for the same length, and zeros are appended as the length
  79532. increases. For the deflate format, these bits are stored backwards
  79533. from their more natural integer increment ordering, and so when the
  79534. decoding tables are built in the large loop below, the integer codes
  79535. are incremented backwards.
  79536. This routine assumes, but does not check, that all of the entries in
  79537. lens[] are in the range 0..MAXBITS. The caller must assure this.
  79538. 1..MAXBITS is interpreted as that code length. zero means that that
  79539. symbol does not occur in this code.
  79540. The codes are sorted by computing a count of codes for each length,
  79541. creating from that a table of starting indices for each length in the
  79542. sorted table, and then entering the symbols in order in the sorted
  79543. table. The sorted table is work[], with that space being provided by
  79544. the caller.
  79545. The length counts are used for other purposes as well, i.e. finding
  79546. the minimum and maximum length codes, determining if there are any
  79547. codes at all, checking for a valid set of lengths, and looking ahead
  79548. at length counts to determine sub-table sizes when building the
  79549. decoding tables.
  79550. */
  79551. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  79552. for (len = 0; len <= MAXBITS; len++)
  79553. count[len] = 0;
  79554. for (sym = 0; sym < codes; sym++)
  79555. count[lens[sym]]++;
  79556. /* bound code lengths, force root to be within code lengths */
  79557. root = *bits;
  79558. for (max = MAXBITS; max >= 1; max--)
  79559. if (count[max] != 0) break;
  79560. if (root > max) root = max;
  79561. if (max == 0) { /* no symbols to code at all */
  79562. thisx.op = (unsigned char)64; /* invalid code marker */
  79563. thisx.bits = (unsigned char)1;
  79564. thisx.val = (unsigned short)0;
  79565. *(*table)++ = thisx; /* make a table to force an error */
  79566. *(*table)++ = thisx;
  79567. *bits = 1;
  79568. return 0; /* no symbols, but wait for decoding to report error */
  79569. }
  79570. for (min = 1; min <= MAXBITS; min++)
  79571. if (count[min] != 0) break;
  79572. if (root < min) root = min;
  79573. /* check for an over-subscribed or incomplete set of lengths */
  79574. left = 1;
  79575. for (len = 1; len <= MAXBITS; len++) {
  79576. left <<= 1;
  79577. left -= count[len];
  79578. if (left < 0) return -1; /* over-subscribed */
  79579. }
  79580. if (left > 0 && (type == CODES || max != 1))
  79581. return -1; /* incomplete set */
  79582. /* generate offsets into symbol table for each length for sorting */
  79583. offs[1] = 0;
  79584. for (len = 1; len < MAXBITS; len++)
  79585. offs[len + 1] = offs[len] + count[len];
  79586. /* sort symbols by length, by symbol order within each length */
  79587. for (sym = 0; sym < codes; sym++)
  79588. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  79589. /*
  79590. Create and fill in decoding tables. In this loop, the table being
  79591. filled is at next and has curr index bits. The code being used is huff
  79592. with length len. That code is converted to an index by dropping drop
  79593. bits off of the bottom. For codes where len is less than drop + curr,
  79594. those top drop + curr - len bits are incremented through all values to
  79595. fill the table with replicated entries.
  79596. root is the number of index bits for the root table. When len exceeds
  79597. root, sub-tables are created pointed to by the root entry with an index
  79598. of the low root bits of huff. This is saved in low to check for when a
  79599. new sub-table should be started. drop is zero when the root table is
  79600. being filled, and drop is root when sub-tables are being filled.
  79601. When a new sub-table is needed, it is necessary to look ahead in the
  79602. code lengths to determine what size sub-table is needed. The length
  79603. counts are used for this, and so count[] is decremented as codes are
  79604. entered in the tables.
  79605. used keeps track of how many table entries have been allocated from the
  79606. provided *table space. It is checked when a LENS table is being made
  79607. against the space in *table, ENOUGH, minus the maximum space needed by
  79608. the worst case distance code, MAXD. This should never happen, but the
  79609. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  79610. This assumes that when type == LENS, bits == 9.
  79611. sym increments through all symbols, and the loop terminates when
  79612. all codes of length max, i.e. all codes, have been processed. This
  79613. routine permits incomplete codes, so another loop after this one fills
  79614. in the rest of the decoding tables with invalid code markers.
  79615. */
  79616. /* set up for code type */
  79617. switch (type) {
  79618. case CODES:
  79619. base = extra = work; /* dummy value--not used */
  79620. end = 19;
  79621. break;
  79622. case LENS:
  79623. base = lbase;
  79624. base -= 257;
  79625. extra = lext;
  79626. extra -= 257;
  79627. end = 256;
  79628. break;
  79629. default: /* DISTS */
  79630. base = dbase;
  79631. extra = dext;
  79632. end = -1;
  79633. }
  79634. /* initialize state for loop */
  79635. huff = 0; /* starting code */
  79636. sym = 0; /* starting code symbol */
  79637. len = min; /* starting code length */
  79638. next = *table; /* current table to fill in */
  79639. curr = root; /* current table index bits */
  79640. drop = 0; /* current bits to drop from code for index */
  79641. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  79642. used = 1U << root; /* use root table entries */
  79643. mask = used - 1; /* mask for comparing low */
  79644. /* check available table space */
  79645. if (type == LENS && used >= ENOUGH - MAXD)
  79646. return 1;
  79647. /* process all codes and make table entries */
  79648. for (;;) {
  79649. /* create table entry */
  79650. thisx.bits = (unsigned char)(len - drop);
  79651. if ((int)(work[sym]) < end) {
  79652. thisx.op = (unsigned char)0;
  79653. thisx.val = work[sym];
  79654. }
  79655. else if ((int)(work[sym]) > end) {
  79656. thisx.op = (unsigned char)(extra[work[sym]]);
  79657. thisx.val = base[work[sym]];
  79658. }
  79659. else {
  79660. thisx.op = (unsigned char)(32 + 64); /* end of block */
  79661. thisx.val = 0;
  79662. }
  79663. /* replicate for those indices with low len bits equal to huff */
  79664. incr = 1U << (len - drop);
  79665. fill = 1U << curr;
  79666. min = fill; /* save offset to next table */
  79667. do {
  79668. fill -= incr;
  79669. next[(huff >> drop) + fill] = thisx;
  79670. } while (fill != 0);
  79671. /* backwards increment the len-bit code huff */
  79672. incr = 1U << (len - 1);
  79673. while (huff & incr)
  79674. incr >>= 1;
  79675. if (incr != 0) {
  79676. huff &= incr - 1;
  79677. huff += incr;
  79678. }
  79679. else
  79680. huff = 0;
  79681. /* go to next symbol, update count, len */
  79682. sym++;
  79683. if (--(count[len]) == 0) {
  79684. if (len == max) break;
  79685. len = lens[work[sym]];
  79686. }
  79687. /* create new sub-table if needed */
  79688. if (len > root && (huff & mask) != low) {
  79689. /* if first time, transition to sub-tables */
  79690. if (drop == 0)
  79691. drop = root;
  79692. /* increment past last table */
  79693. next += min; /* here min is 1 << curr */
  79694. /* determine length of next table */
  79695. curr = len - drop;
  79696. left = (int)(1 << curr);
  79697. while (curr + drop < max) {
  79698. left -= count[curr + drop];
  79699. if (left <= 0) break;
  79700. curr++;
  79701. left <<= 1;
  79702. }
  79703. /* check for enough space */
  79704. used += 1U << curr;
  79705. if (type == LENS && used >= ENOUGH - MAXD)
  79706. return 1;
  79707. /* point entry in root table to sub-table */
  79708. low = huff & mask;
  79709. (*table)[low].op = (unsigned char)curr;
  79710. (*table)[low].bits = (unsigned char)root;
  79711. (*table)[low].val = (unsigned short)(next - *table);
  79712. }
  79713. }
  79714. /*
  79715. Fill in rest of table for incomplete codes. This loop is similar to the
  79716. loop above in incrementing huff for table indices. It is assumed that
  79717. len is equal to curr + drop, so there is no loop needed to increment
  79718. through high index bits. When the current sub-table is filled, the loop
  79719. drops back to the root table to fill in any remaining entries there.
  79720. */
  79721. thisx.op = (unsigned char)64; /* invalid code marker */
  79722. thisx.bits = (unsigned char)(len - drop);
  79723. thisx.val = (unsigned short)0;
  79724. while (huff != 0) {
  79725. /* when done with sub-table, drop back to root table */
  79726. if (drop != 0 && (huff & mask) != low) {
  79727. drop = 0;
  79728. len = root;
  79729. next = *table;
  79730. thisx.bits = (unsigned char)len;
  79731. }
  79732. /* put invalid code marker in table */
  79733. next[huff >> drop] = thisx;
  79734. /* backwards increment the len-bit code huff */
  79735. incr = 1U << (len - 1);
  79736. while (huff & incr)
  79737. incr >>= 1;
  79738. if (incr != 0) {
  79739. huff &= incr - 1;
  79740. huff += incr;
  79741. }
  79742. else
  79743. huff = 0;
  79744. }
  79745. /* set return parameters */
  79746. *table += used;
  79747. *bits = root;
  79748. return 0;
  79749. }
  79750. /********* End of inlined file: inftrees.c *********/
  79751. /********* Start of inlined file: trees.c *********/
  79752. /*
  79753. * ALGORITHM
  79754. *
  79755. * The "deflation" process uses several Huffman trees. The more
  79756. * common source values are represented by shorter bit sequences.
  79757. *
  79758. * Each code tree is stored in a compressed form which is itself
  79759. * a Huffman encoding of the lengths of all the code strings (in
  79760. * ascending order by source values). The actual code strings are
  79761. * reconstructed from the lengths in the inflate process, as described
  79762. * in the deflate specification.
  79763. *
  79764. * REFERENCES
  79765. *
  79766. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  79767. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  79768. *
  79769. * Storer, James A.
  79770. * Data Compression: Methods and Theory, pp. 49-50.
  79771. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  79772. *
  79773. * Sedgewick, R.
  79774. * Algorithms, p290.
  79775. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  79776. */
  79777. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79778. /* #define GEN_TREES_H */
  79779. #ifdef DEBUG
  79780. # include <ctype.h>
  79781. #endif
  79782. /* ===========================================================================
  79783. * Constants
  79784. */
  79785. #define MAX_BL_BITS 7
  79786. /* Bit length codes must not exceed MAX_BL_BITS bits */
  79787. #define END_BLOCK 256
  79788. /* end of block literal code */
  79789. #define REP_3_6 16
  79790. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  79791. #define REPZ_3_10 17
  79792. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  79793. #define REPZ_11_138 18
  79794. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  79795. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  79796. = {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};
  79797. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  79798. = {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};
  79799. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  79800. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  79801. local const uch bl_order[BL_CODES]
  79802. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  79803. /* The lengths of the bit length codes are sent in order of decreasing
  79804. * probability, to avoid transmitting the lengths for unused bit length codes.
  79805. */
  79806. #define Buf_size (8 * 2*sizeof(char))
  79807. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  79808. * more than 16 bits on some systems.)
  79809. */
  79810. /* ===========================================================================
  79811. * Local data. These are initialized only once.
  79812. */
  79813. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  79814. #if defined(GEN_TREES_H) || !defined(STDC)
  79815. /* non ANSI compilers may not accept trees.h */
  79816. local ct_data static_ltree[L_CODES+2];
  79817. /* The static literal tree. Since the bit lengths are imposed, there is no
  79818. * need for the L_CODES extra codes used during heap construction. However
  79819. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  79820. * below).
  79821. */
  79822. local ct_data static_dtree[D_CODES];
  79823. /* The static distance tree. (Actually a trivial tree since all codes use
  79824. * 5 bits.)
  79825. */
  79826. uch _dist_code[DIST_CODE_LEN];
  79827. /* Distance codes. The first 256 values correspond to the distances
  79828. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  79829. * the 15 bit distances.
  79830. */
  79831. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  79832. /* length code for each normalized match length (0 == MIN_MATCH) */
  79833. local int base_length[LENGTH_CODES];
  79834. /* First normalized length for each code (0 = MIN_MATCH) */
  79835. local int base_dist[D_CODES];
  79836. /* First normalized distance for each code (0 = distance of 1) */
  79837. #else
  79838. /********* Start of inlined file: trees.h *********/
  79839. local const ct_data static_ltree[L_CODES+2] = {
  79840. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  79841. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  79842. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  79843. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  79844. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  79845. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  79846. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  79847. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  79848. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  79849. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  79850. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  79851. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  79852. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  79853. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  79854. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  79855. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  79856. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  79857. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  79858. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  79859. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  79860. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  79861. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  79862. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  79863. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  79864. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  79865. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  79866. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  79867. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  79868. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  79869. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  79870. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  79871. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  79872. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  79873. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  79874. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  79875. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  79876. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  79877. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  79878. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  79879. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  79880. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  79881. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  79882. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  79883. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  79884. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  79885. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  79886. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  79887. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  79888. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  79889. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  79890. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  79891. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  79892. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  79893. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  79894. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  79895. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  79896. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  79897. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  79898. };
  79899. local const ct_data static_dtree[D_CODES] = {
  79900. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  79901. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  79902. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  79903. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  79904. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  79905. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  79906. };
  79907. const uch _dist_code[DIST_CODE_LEN] = {
  79908. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  79909. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  79910. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  79911. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  79912. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  79913. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  79914. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79915. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79916. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79917. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  79918. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  79919. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  79920. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  79921. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  79922. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79923. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  79924. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  79925. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  79926. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  79927. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79928. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79929. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79930. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79931. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79932. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79933. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  79934. };
  79935. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  79936. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  79937. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  79938. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  79939. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  79940. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  79941. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  79942. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79943. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79944. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  79945. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  79946. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  79947. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  79948. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  79949. };
  79950. local const int base_length[LENGTH_CODES] = {
  79951. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  79952. 64, 80, 96, 112, 128, 160, 192, 224, 0
  79953. };
  79954. local const int base_dist[D_CODES] = {
  79955. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  79956. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  79957. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  79958. };
  79959. /********* End of inlined file: trees.h *********/
  79960. #endif /* GEN_TREES_H */
  79961. struct static_tree_desc_s {
  79962. const ct_data *static_tree; /* static tree or NULL */
  79963. const intf *extra_bits; /* extra bits for each code or NULL */
  79964. int extra_base; /* base index for extra_bits */
  79965. int elems; /* max number of elements in the tree */
  79966. int max_length; /* max bit length for the codes */
  79967. };
  79968. local static_tree_desc static_l_desc =
  79969. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  79970. local static_tree_desc static_d_desc =
  79971. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  79972. local static_tree_desc static_bl_desc =
  79973. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  79974. /* ===========================================================================
  79975. * Local (static) routines in this file.
  79976. */
  79977. local void tr_static_init OF((void));
  79978. local void init_block OF((deflate_state *s));
  79979. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  79980. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  79981. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  79982. local void build_tree OF((deflate_state *s, tree_desc *desc));
  79983. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  79984. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  79985. local int build_bl_tree OF((deflate_state *s));
  79986. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  79987. int blcodes));
  79988. local void compress_block OF((deflate_state *s, ct_data *ltree,
  79989. ct_data *dtree));
  79990. local void set_data_type OF((deflate_state *s));
  79991. local unsigned bi_reverse OF((unsigned value, int length));
  79992. local void bi_windup OF((deflate_state *s));
  79993. local void bi_flush OF((deflate_state *s));
  79994. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  79995. int header));
  79996. #ifdef GEN_TREES_H
  79997. local void gen_trees_header OF((void));
  79998. #endif
  79999. #ifndef DEBUG
  80000. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  80001. /* Send a code of the given tree. c and tree must not have side effects */
  80002. #else /* DEBUG */
  80003. # define send_code(s, c, tree) \
  80004. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  80005. send_bits(s, tree[c].Code, tree[c].Len); }
  80006. #endif
  80007. /* ===========================================================================
  80008. * Output a short LSB first on the stream.
  80009. * IN assertion: there is enough room in pendingBuf.
  80010. */
  80011. #define put_short(s, w) { \
  80012. put_byte(s, (uch)((w) & 0xff)); \
  80013. put_byte(s, (uch)((ush)(w) >> 8)); \
  80014. }
  80015. /* ===========================================================================
  80016. * Send a value on a given number of bits.
  80017. * IN assertion: length <= 16 and value fits in length bits.
  80018. */
  80019. #ifdef DEBUG
  80020. local void send_bits OF((deflate_state *s, int value, int length));
  80021. local void send_bits (deflate_state *s, int value, int length)
  80022. {
  80023. Tracevv((stderr," l %2d v %4x ", length, value));
  80024. Assert(length > 0 && length <= 15, "invalid length");
  80025. s->bits_sent += (ulg)length;
  80026. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  80027. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  80028. * unused bits in value.
  80029. */
  80030. if (s->bi_valid > (int)Buf_size - length) {
  80031. s->bi_buf |= (value << s->bi_valid);
  80032. put_short(s, s->bi_buf);
  80033. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  80034. s->bi_valid += length - Buf_size;
  80035. } else {
  80036. s->bi_buf |= value << s->bi_valid;
  80037. s->bi_valid += length;
  80038. }
  80039. }
  80040. #else /* !DEBUG */
  80041. #define send_bits(s, value, length) \
  80042. { int len = length;\
  80043. if (s->bi_valid > (int)Buf_size - len) {\
  80044. int val = value;\
  80045. s->bi_buf |= (val << s->bi_valid);\
  80046. put_short(s, s->bi_buf);\
  80047. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  80048. s->bi_valid += len - Buf_size;\
  80049. } else {\
  80050. s->bi_buf |= (value) << s->bi_valid;\
  80051. s->bi_valid += len;\
  80052. }\
  80053. }
  80054. #endif /* DEBUG */
  80055. /* the arguments must not have side effects */
  80056. /* ===========================================================================
  80057. * Initialize the various 'constant' tables.
  80058. */
  80059. local void tr_static_init()
  80060. {
  80061. #if defined(GEN_TREES_H) || !defined(STDC)
  80062. static int static_init_done = 0;
  80063. int n; /* iterates over tree elements */
  80064. int bits; /* bit counter */
  80065. int length; /* length value */
  80066. int code; /* code value */
  80067. int dist; /* distance index */
  80068. ush bl_count[MAX_BITS+1];
  80069. /* number of codes at each bit length for an optimal tree */
  80070. if (static_init_done) return;
  80071. /* For some embedded targets, global variables are not initialized: */
  80072. static_l_desc.static_tree = static_ltree;
  80073. static_l_desc.extra_bits = extra_lbits;
  80074. static_d_desc.static_tree = static_dtree;
  80075. static_d_desc.extra_bits = extra_dbits;
  80076. static_bl_desc.extra_bits = extra_blbits;
  80077. /* Initialize the mapping length (0..255) -> length code (0..28) */
  80078. length = 0;
  80079. for (code = 0; code < LENGTH_CODES-1; code++) {
  80080. base_length[code] = length;
  80081. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  80082. _length_code[length++] = (uch)code;
  80083. }
  80084. }
  80085. Assert (length == 256, "tr_static_init: length != 256");
  80086. /* Note that the length 255 (match length 258) can be represented
  80087. * in two different ways: code 284 + 5 bits or code 285, so we
  80088. * overwrite length_code[255] to use the best encoding:
  80089. */
  80090. _length_code[length-1] = (uch)code;
  80091. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  80092. dist = 0;
  80093. for (code = 0 ; code < 16; code++) {
  80094. base_dist[code] = dist;
  80095. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  80096. _dist_code[dist++] = (uch)code;
  80097. }
  80098. }
  80099. Assert (dist == 256, "tr_static_init: dist != 256");
  80100. dist >>= 7; /* from now on, all distances are divided by 128 */
  80101. for ( ; code < D_CODES; code++) {
  80102. base_dist[code] = dist << 7;
  80103. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  80104. _dist_code[256 + dist++] = (uch)code;
  80105. }
  80106. }
  80107. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  80108. /* Construct the codes of the static literal tree */
  80109. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  80110. n = 0;
  80111. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  80112. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  80113. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  80114. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  80115. /* Codes 286 and 287 do not exist, but we must include them in the
  80116. * tree construction to get a canonical Huffman tree (longest code
  80117. * all ones)
  80118. */
  80119. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  80120. /* The static distance tree is trivial: */
  80121. for (n = 0; n < D_CODES; n++) {
  80122. static_dtree[n].Len = 5;
  80123. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  80124. }
  80125. static_init_done = 1;
  80126. # ifdef GEN_TREES_H
  80127. gen_trees_header();
  80128. # endif
  80129. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  80130. }
  80131. /* ===========================================================================
  80132. * Genererate the file trees.h describing the static trees.
  80133. */
  80134. #ifdef GEN_TREES_H
  80135. # ifndef DEBUG
  80136. # include <stdio.h>
  80137. # endif
  80138. # define SEPARATOR(i, last, width) \
  80139. ((i) == (last)? "\n};\n\n" : \
  80140. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  80141. void gen_trees_header()
  80142. {
  80143. FILE *header = fopen("trees.h", "w");
  80144. int i;
  80145. Assert (header != NULL, "Can't open trees.h");
  80146. fprintf(header,
  80147. "/* header created automatically with -DGEN_TREES_H */\n\n");
  80148. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  80149. for (i = 0; i < L_CODES+2; i++) {
  80150. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  80151. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  80152. }
  80153. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  80154. for (i = 0; i < D_CODES; i++) {
  80155. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  80156. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  80157. }
  80158. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  80159. for (i = 0; i < DIST_CODE_LEN; i++) {
  80160. fprintf(header, "%2u%s", _dist_code[i],
  80161. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  80162. }
  80163. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  80164. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  80165. fprintf(header, "%2u%s", _length_code[i],
  80166. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  80167. }
  80168. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  80169. for (i = 0; i < LENGTH_CODES; i++) {
  80170. fprintf(header, "%1u%s", base_length[i],
  80171. SEPARATOR(i, LENGTH_CODES-1, 20));
  80172. }
  80173. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  80174. for (i = 0; i < D_CODES; i++) {
  80175. fprintf(header, "%5u%s", base_dist[i],
  80176. SEPARATOR(i, D_CODES-1, 10));
  80177. }
  80178. fclose(header);
  80179. }
  80180. #endif /* GEN_TREES_H */
  80181. /* ===========================================================================
  80182. * Initialize the tree data structures for a new zlib stream.
  80183. */
  80184. void _tr_init(deflate_state *s)
  80185. {
  80186. tr_static_init();
  80187. s->l_desc.dyn_tree = s->dyn_ltree;
  80188. s->l_desc.stat_desc = &static_l_desc;
  80189. s->d_desc.dyn_tree = s->dyn_dtree;
  80190. s->d_desc.stat_desc = &static_d_desc;
  80191. s->bl_desc.dyn_tree = s->bl_tree;
  80192. s->bl_desc.stat_desc = &static_bl_desc;
  80193. s->bi_buf = 0;
  80194. s->bi_valid = 0;
  80195. s->last_eob_len = 8; /* enough lookahead for inflate */
  80196. #ifdef DEBUG
  80197. s->compressed_len = 0L;
  80198. s->bits_sent = 0L;
  80199. #endif
  80200. /* Initialize the first block of the first file: */
  80201. init_block(s);
  80202. }
  80203. /* ===========================================================================
  80204. * Initialize a new block.
  80205. */
  80206. local void init_block (deflate_state *s)
  80207. {
  80208. int n; /* iterates over tree elements */
  80209. /* Initialize the trees. */
  80210. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  80211. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  80212. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  80213. s->dyn_ltree[END_BLOCK].Freq = 1;
  80214. s->opt_len = s->static_len = 0L;
  80215. s->last_lit = s->matches = 0;
  80216. }
  80217. #define SMALLEST 1
  80218. /* Index within the heap array of least frequent node in the Huffman tree */
  80219. /* ===========================================================================
  80220. * Remove the smallest element from the heap and recreate the heap with
  80221. * one less element. Updates heap and heap_len.
  80222. */
  80223. #define pqremove(s, tree, top) \
  80224. {\
  80225. top = s->heap[SMALLEST]; \
  80226. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  80227. pqdownheap(s, tree, SMALLEST); \
  80228. }
  80229. /* ===========================================================================
  80230. * Compares to subtrees, using the tree depth as tie breaker when
  80231. * the subtrees have equal frequency. This minimizes the worst case length.
  80232. */
  80233. #define smaller(tree, n, m, depth) \
  80234. (tree[n].Freq < tree[m].Freq || \
  80235. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  80236. /* ===========================================================================
  80237. * Restore the heap property by moving down the tree starting at node k,
  80238. * exchanging a node with the smallest of its two sons if necessary, stopping
  80239. * when the heap property is re-established (each father smaller than its
  80240. * two sons).
  80241. */
  80242. local void pqdownheap (deflate_state *s,
  80243. ct_data *tree, /* the tree to restore */
  80244. int k) /* node to move down */
  80245. {
  80246. int v = s->heap[k];
  80247. int j = k << 1; /* left son of k */
  80248. while (j <= s->heap_len) {
  80249. /* Set j to the smallest of the two sons: */
  80250. if (j < s->heap_len &&
  80251. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  80252. j++;
  80253. }
  80254. /* Exit if v is smaller than both sons */
  80255. if (smaller(tree, v, s->heap[j], s->depth)) break;
  80256. /* Exchange v with the smallest son */
  80257. s->heap[k] = s->heap[j]; k = j;
  80258. /* And continue down the tree, setting j to the left son of k */
  80259. j <<= 1;
  80260. }
  80261. s->heap[k] = v;
  80262. }
  80263. /* ===========================================================================
  80264. * Compute the optimal bit lengths for a tree and update the total bit length
  80265. * for the current block.
  80266. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  80267. * above are the tree nodes sorted by increasing frequency.
  80268. * OUT assertions: the field len is set to the optimal bit length, the
  80269. * array bl_count contains the frequencies for each bit length.
  80270. * The length opt_len is updated; static_len is also updated if stree is
  80271. * not null.
  80272. */
  80273. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  80274. {
  80275. ct_data *tree = desc->dyn_tree;
  80276. int max_code = desc->max_code;
  80277. const ct_data *stree = desc->stat_desc->static_tree;
  80278. const intf *extra = desc->stat_desc->extra_bits;
  80279. int base = desc->stat_desc->extra_base;
  80280. int max_length = desc->stat_desc->max_length;
  80281. int h; /* heap index */
  80282. int n, m; /* iterate over the tree elements */
  80283. int bits; /* bit length */
  80284. int xbits; /* extra bits */
  80285. ush f; /* frequency */
  80286. int overflow = 0; /* number of elements with bit length too large */
  80287. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  80288. /* In a first pass, compute the optimal bit lengths (which may
  80289. * overflow in the case of the bit length tree).
  80290. */
  80291. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  80292. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  80293. n = s->heap[h];
  80294. bits = tree[tree[n].Dad].Len + 1;
  80295. if (bits > max_length) bits = max_length, overflow++;
  80296. tree[n].Len = (ush)bits;
  80297. /* We overwrite tree[n].Dad which is no longer needed */
  80298. if (n > max_code) continue; /* not a leaf node */
  80299. s->bl_count[bits]++;
  80300. xbits = 0;
  80301. if (n >= base) xbits = extra[n-base];
  80302. f = tree[n].Freq;
  80303. s->opt_len += (ulg)f * (bits + xbits);
  80304. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  80305. }
  80306. if (overflow == 0) return;
  80307. Trace((stderr,"\nbit length overflow\n"));
  80308. /* This happens for example on obj2 and pic of the Calgary corpus */
  80309. /* Find the first bit length which could increase: */
  80310. do {
  80311. bits = max_length-1;
  80312. while (s->bl_count[bits] == 0) bits--;
  80313. s->bl_count[bits]--; /* move one leaf down the tree */
  80314. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  80315. s->bl_count[max_length]--;
  80316. /* The brother of the overflow item also moves one step up,
  80317. * but this does not affect bl_count[max_length]
  80318. */
  80319. overflow -= 2;
  80320. } while (overflow > 0);
  80321. /* Now recompute all bit lengths, scanning in increasing frequency.
  80322. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  80323. * lengths instead of fixing only the wrong ones. This idea is taken
  80324. * from 'ar' written by Haruhiko Okumura.)
  80325. */
  80326. for (bits = max_length; bits != 0; bits--) {
  80327. n = s->bl_count[bits];
  80328. while (n != 0) {
  80329. m = s->heap[--h];
  80330. if (m > max_code) continue;
  80331. if ((unsigned) tree[m].Len != (unsigned) bits) {
  80332. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  80333. s->opt_len += ((long)bits - (long)tree[m].Len)
  80334. *(long)tree[m].Freq;
  80335. tree[m].Len = (ush)bits;
  80336. }
  80337. n--;
  80338. }
  80339. }
  80340. }
  80341. /* ===========================================================================
  80342. * Generate the codes for a given tree and bit counts (which need not be
  80343. * optimal).
  80344. * IN assertion: the array bl_count contains the bit length statistics for
  80345. * the given tree and the field len is set for all tree elements.
  80346. * OUT assertion: the field code is set for all tree elements of non
  80347. * zero code length.
  80348. */
  80349. local void gen_codes (ct_data *tree, /* the tree to decorate */
  80350. int max_code, /* largest code with non zero frequency */
  80351. ushf *bl_count) /* number of codes at each bit length */
  80352. {
  80353. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  80354. ush code = 0; /* running code value */
  80355. int bits; /* bit index */
  80356. int n; /* code index */
  80357. /* The distribution counts are first used to generate the code values
  80358. * without bit reversal.
  80359. */
  80360. for (bits = 1; bits <= MAX_BITS; bits++) {
  80361. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  80362. }
  80363. /* Check that the bit counts in bl_count are consistent. The last code
  80364. * must be all ones.
  80365. */
  80366. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  80367. "inconsistent bit counts");
  80368. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  80369. for (n = 0; n <= max_code; n++) {
  80370. int len = tree[n].Len;
  80371. if (len == 0) continue;
  80372. /* Now reverse the bits */
  80373. tree[n].Code = bi_reverse(next_code[len]++, len);
  80374. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  80375. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  80376. }
  80377. }
  80378. /* ===========================================================================
  80379. * Construct one Huffman tree and assigns the code bit strings and lengths.
  80380. * Update the total bit length for the current block.
  80381. * IN assertion: the field freq is set for all tree elements.
  80382. * OUT assertions: the fields len and code are set to the optimal bit length
  80383. * and corresponding code. The length opt_len is updated; static_len is
  80384. * also updated if stree is not null. The field max_code is set.
  80385. */
  80386. local void build_tree (deflate_state *s,
  80387. tree_desc *desc) /* the tree descriptor */
  80388. {
  80389. ct_data *tree = desc->dyn_tree;
  80390. const ct_data *stree = desc->stat_desc->static_tree;
  80391. int elems = desc->stat_desc->elems;
  80392. int n, m; /* iterate over heap elements */
  80393. int max_code = -1; /* largest code with non zero frequency */
  80394. int node; /* new node being created */
  80395. /* Construct the initial heap, with least frequent element in
  80396. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  80397. * heap[0] is not used.
  80398. */
  80399. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  80400. for (n = 0; n < elems; n++) {
  80401. if (tree[n].Freq != 0) {
  80402. s->heap[++(s->heap_len)] = max_code = n;
  80403. s->depth[n] = 0;
  80404. } else {
  80405. tree[n].Len = 0;
  80406. }
  80407. }
  80408. /* The pkzip format requires that at least one distance code exists,
  80409. * and that at least one bit should be sent even if there is only one
  80410. * possible code. So to avoid special checks later on we force at least
  80411. * two codes of non zero frequency.
  80412. */
  80413. while (s->heap_len < 2) {
  80414. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  80415. tree[node].Freq = 1;
  80416. s->depth[node] = 0;
  80417. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  80418. /* node is 0 or 1 so it does not have extra bits */
  80419. }
  80420. desc->max_code = max_code;
  80421. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  80422. * establish sub-heaps of increasing lengths:
  80423. */
  80424. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  80425. /* Construct the Huffman tree by repeatedly combining the least two
  80426. * frequent nodes.
  80427. */
  80428. node = elems; /* next internal node of the tree */
  80429. do {
  80430. pqremove(s, tree, n); /* n = node of least frequency */
  80431. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  80432. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  80433. s->heap[--(s->heap_max)] = m;
  80434. /* Create a new node father of n and m */
  80435. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  80436. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  80437. s->depth[n] : s->depth[m]) + 1);
  80438. tree[n].Dad = tree[m].Dad = (ush)node;
  80439. #ifdef DUMP_BL_TREE
  80440. if (tree == s->bl_tree) {
  80441. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  80442. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  80443. }
  80444. #endif
  80445. /* and insert the new node in the heap */
  80446. s->heap[SMALLEST] = node++;
  80447. pqdownheap(s, tree, SMALLEST);
  80448. } while (s->heap_len >= 2);
  80449. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  80450. /* At this point, the fields freq and dad are set. We can now
  80451. * generate the bit lengths.
  80452. */
  80453. gen_bitlen(s, (tree_desc *)desc);
  80454. /* The field len is now set, we can generate the bit codes */
  80455. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  80456. }
  80457. /* ===========================================================================
  80458. * Scan a literal or distance tree to determine the frequencies of the codes
  80459. * in the bit length tree.
  80460. */
  80461. local void scan_tree (deflate_state *s,
  80462. ct_data *tree, /* the tree to be scanned */
  80463. int max_code) /* and its largest code of non zero frequency */
  80464. {
  80465. int n; /* iterates over all tree elements */
  80466. int prevlen = -1; /* last emitted length */
  80467. int curlen; /* length of current code */
  80468. int nextlen = tree[0].Len; /* length of next code */
  80469. int count = 0; /* repeat count of the current code */
  80470. int max_count = 7; /* max repeat count */
  80471. int min_count = 4; /* min repeat count */
  80472. if (nextlen == 0) max_count = 138, min_count = 3;
  80473. tree[max_code+1].Len = (ush)0xffff; /* guard */
  80474. for (n = 0; n <= max_code; n++) {
  80475. curlen = nextlen; nextlen = tree[n+1].Len;
  80476. if (++count < max_count && curlen == nextlen) {
  80477. continue;
  80478. } else if (count < min_count) {
  80479. s->bl_tree[curlen].Freq += count;
  80480. } else if (curlen != 0) {
  80481. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  80482. s->bl_tree[REP_3_6].Freq++;
  80483. } else if (count <= 10) {
  80484. s->bl_tree[REPZ_3_10].Freq++;
  80485. } else {
  80486. s->bl_tree[REPZ_11_138].Freq++;
  80487. }
  80488. count = 0; prevlen = curlen;
  80489. if (nextlen == 0) {
  80490. max_count = 138, min_count = 3;
  80491. } else if (curlen == nextlen) {
  80492. max_count = 6, min_count = 3;
  80493. } else {
  80494. max_count = 7, min_count = 4;
  80495. }
  80496. }
  80497. }
  80498. /* ===========================================================================
  80499. * Send a literal or distance tree in compressed form, using the codes in
  80500. * bl_tree.
  80501. */
  80502. local void send_tree (deflate_state *s,
  80503. ct_data *tree, /* the tree to be scanned */
  80504. int max_code) /* and its largest code of non zero frequency */
  80505. {
  80506. int n; /* iterates over all tree elements */
  80507. int prevlen = -1; /* last emitted length */
  80508. int curlen; /* length of current code */
  80509. int nextlen = tree[0].Len; /* length of next code */
  80510. int count = 0; /* repeat count of the current code */
  80511. int max_count = 7; /* max repeat count */
  80512. int min_count = 4; /* min repeat count */
  80513. /* tree[max_code+1].Len = -1; */ /* guard already set */
  80514. if (nextlen == 0) max_count = 138, min_count = 3;
  80515. for (n = 0; n <= max_code; n++) {
  80516. curlen = nextlen; nextlen = tree[n+1].Len;
  80517. if (++count < max_count && curlen == nextlen) {
  80518. continue;
  80519. } else if (count < min_count) {
  80520. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  80521. } else if (curlen != 0) {
  80522. if (curlen != prevlen) {
  80523. send_code(s, curlen, s->bl_tree); count--;
  80524. }
  80525. Assert(count >= 3 && count <= 6, " 3_6?");
  80526. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  80527. } else if (count <= 10) {
  80528. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  80529. } else {
  80530. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  80531. }
  80532. count = 0; prevlen = curlen;
  80533. if (nextlen == 0) {
  80534. max_count = 138, min_count = 3;
  80535. } else if (curlen == nextlen) {
  80536. max_count = 6, min_count = 3;
  80537. } else {
  80538. max_count = 7, min_count = 4;
  80539. }
  80540. }
  80541. }
  80542. /* ===========================================================================
  80543. * Construct the Huffman tree for the bit lengths and return the index in
  80544. * bl_order of the last bit length code to send.
  80545. */
  80546. local int build_bl_tree (deflate_state *s)
  80547. {
  80548. int max_blindex; /* index of last bit length code of non zero freq */
  80549. /* Determine the bit length frequencies for literal and distance trees */
  80550. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  80551. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  80552. /* Build the bit length tree: */
  80553. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  80554. /* opt_len now includes the length of the tree representations, except
  80555. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  80556. */
  80557. /* Determine the number of bit length codes to send. The pkzip format
  80558. * requires that at least 4 bit length codes be sent. (appnote.txt says
  80559. * 3 but the actual value used is 4.)
  80560. */
  80561. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  80562. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  80563. }
  80564. /* Update opt_len to include the bit length tree and counts */
  80565. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  80566. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  80567. s->opt_len, s->static_len));
  80568. return max_blindex;
  80569. }
  80570. /* ===========================================================================
  80571. * Send the header for a block using dynamic Huffman trees: the counts, the
  80572. * lengths of the bit length codes, the literal tree and the distance tree.
  80573. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  80574. */
  80575. local void send_all_trees (deflate_state *s,
  80576. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  80577. {
  80578. int rank; /* index in bl_order */
  80579. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  80580. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  80581. "too many codes");
  80582. Tracev((stderr, "\nbl counts: "));
  80583. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  80584. send_bits(s, dcodes-1, 5);
  80585. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  80586. for (rank = 0; rank < blcodes; rank++) {
  80587. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  80588. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  80589. }
  80590. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  80591. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  80592. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  80593. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  80594. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  80595. }
  80596. /* ===========================================================================
  80597. * Send a stored block
  80598. */
  80599. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  80600. {
  80601. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  80602. #ifdef DEBUG
  80603. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  80604. s->compressed_len += (stored_len + 4) << 3;
  80605. #endif
  80606. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  80607. }
  80608. /* ===========================================================================
  80609. * Send one empty static block to give enough lookahead for inflate.
  80610. * This takes 10 bits, of which 7 may remain in the bit buffer.
  80611. * The current inflate code requires 9 bits of lookahead. If the
  80612. * last two codes for the previous block (real code plus EOB) were coded
  80613. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  80614. * the last real code. In this case we send two empty static blocks instead
  80615. * of one. (There are no problems if the previous block is stored or fixed.)
  80616. * To simplify the code, we assume the worst case of last real code encoded
  80617. * on one bit only.
  80618. */
  80619. void _tr_align (deflate_state *s)
  80620. {
  80621. send_bits(s, STATIC_TREES<<1, 3);
  80622. send_code(s, END_BLOCK, static_ltree);
  80623. #ifdef DEBUG
  80624. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  80625. #endif
  80626. bi_flush(s);
  80627. /* Of the 10 bits for the empty block, we have already sent
  80628. * (10 - bi_valid) bits. The lookahead for the last real code (before
  80629. * the EOB of the previous block) was thus at least one plus the length
  80630. * of the EOB plus what we have just sent of the empty static block.
  80631. */
  80632. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  80633. send_bits(s, STATIC_TREES<<1, 3);
  80634. send_code(s, END_BLOCK, static_ltree);
  80635. #ifdef DEBUG
  80636. s->compressed_len += 10L;
  80637. #endif
  80638. bi_flush(s);
  80639. }
  80640. s->last_eob_len = 7;
  80641. }
  80642. /* ===========================================================================
  80643. * Determine the best encoding for the current block: dynamic trees, static
  80644. * trees or store, and output the encoded block to the zip file.
  80645. */
  80646. void _tr_flush_block (deflate_state *s,
  80647. charf *buf, /* input block, or NULL if too old */
  80648. ulg stored_len, /* length of input block */
  80649. int eof) /* true if this is the last block for a file */
  80650. {
  80651. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  80652. int max_blindex = 0; /* index of last bit length code of non zero freq */
  80653. /* Build the Huffman trees unless a stored block is forced */
  80654. if (s->level > 0) {
  80655. /* Check if the file is binary or text */
  80656. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  80657. set_data_type(s);
  80658. /* Construct the literal and distance trees */
  80659. build_tree(s, (tree_desc *)(&(s->l_desc)));
  80660. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  80661. s->static_len));
  80662. build_tree(s, (tree_desc *)(&(s->d_desc)));
  80663. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  80664. s->static_len));
  80665. /* At this point, opt_len and static_len are the total bit lengths of
  80666. * the compressed block data, excluding the tree representations.
  80667. */
  80668. /* Build the bit length tree for the above two trees, and get the index
  80669. * in bl_order of the last bit length code to send.
  80670. */
  80671. max_blindex = build_bl_tree(s);
  80672. /* Determine the best encoding. Compute the block lengths in bytes. */
  80673. opt_lenb = (s->opt_len+3+7)>>3;
  80674. static_lenb = (s->static_len+3+7)>>3;
  80675. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  80676. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  80677. s->last_lit));
  80678. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  80679. } else {
  80680. Assert(buf != (char*)0, "lost buf");
  80681. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  80682. }
  80683. #ifdef FORCE_STORED
  80684. if (buf != (char*)0) { /* force stored block */
  80685. #else
  80686. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  80687. /* 4: two words for the lengths */
  80688. #endif
  80689. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  80690. * Otherwise we can't have processed more than WSIZE input bytes since
  80691. * the last block flush, because compression would have been
  80692. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  80693. * transform a block into a stored block.
  80694. */
  80695. _tr_stored_block(s, buf, stored_len, eof);
  80696. #ifdef FORCE_STATIC
  80697. } else if (static_lenb >= 0) { /* force static trees */
  80698. #else
  80699. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  80700. #endif
  80701. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  80702. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  80703. #ifdef DEBUG
  80704. s->compressed_len += 3 + s->static_len;
  80705. #endif
  80706. } else {
  80707. send_bits(s, (DYN_TREES<<1)+eof, 3);
  80708. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  80709. max_blindex+1);
  80710. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  80711. #ifdef DEBUG
  80712. s->compressed_len += 3 + s->opt_len;
  80713. #endif
  80714. }
  80715. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  80716. /* The above check is made mod 2^32, for files larger than 512 MB
  80717. * and uLong implemented on 32 bits.
  80718. */
  80719. init_block(s);
  80720. if (eof) {
  80721. bi_windup(s);
  80722. #ifdef DEBUG
  80723. s->compressed_len += 7; /* align on byte boundary */
  80724. #endif
  80725. }
  80726. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  80727. s->compressed_len-7*eof));
  80728. }
  80729. /* ===========================================================================
  80730. * Save the match info and tally the frequency counts. Return true if
  80731. * the current block must be flushed.
  80732. */
  80733. int _tr_tally (deflate_state *s,
  80734. unsigned dist, /* distance of matched string */
  80735. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  80736. {
  80737. s->d_buf[s->last_lit] = (ush)dist;
  80738. s->l_buf[s->last_lit++] = (uch)lc;
  80739. if (dist == 0) {
  80740. /* lc is the unmatched char */
  80741. s->dyn_ltree[lc].Freq++;
  80742. } else {
  80743. s->matches++;
  80744. /* Here, lc is the match length - MIN_MATCH */
  80745. dist--; /* dist = match distance - 1 */
  80746. Assert((ush)dist < (ush)MAX_DIST(s) &&
  80747. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  80748. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  80749. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  80750. s->dyn_dtree[d_code(dist)].Freq++;
  80751. }
  80752. #ifdef TRUNCATE_BLOCK
  80753. /* Try to guess if it is profitable to stop the current block here */
  80754. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  80755. /* Compute an upper bound for the compressed length */
  80756. ulg out_length = (ulg)s->last_lit*8L;
  80757. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  80758. int dcode;
  80759. for (dcode = 0; dcode < D_CODES; dcode++) {
  80760. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  80761. (5L+extra_dbits[dcode]);
  80762. }
  80763. out_length >>= 3;
  80764. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  80765. s->last_lit, in_length, out_length,
  80766. 100L - out_length*100L/in_length));
  80767. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  80768. }
  80769. #endif
  80770. return (s->last_lit == s->lit_bufsize-1);
  80771. /* We avoid equality with lit_bufsize because of wraparound at 64K
  80772. * on 16 bit machines and because stored blocks are restricted to
  80773. * 64K-1 bytes.
  80774. */
  80775. }
  80776. /* ===========================================================================
  80777. * Send the block data compressed using the given Huffman trees
  80778. */
  80779. local void compress_block (deflate_state *s,
  80780. ct_data *ltree, /* literal tree */
  80781. ct_data *dtree) /* distance tree */
  80782. {
  80783. unsigned dist; /* distance of matched string */
  80784. int lc; /* match length or unmatched char (if dist == 0) */
  80785. unsigned lx = 0; /* running index in l_buf */
  80786. unsigned code; /* the code to send */
  80787. int extra; /* number of extra bits to send */
  80788. if (s->last_lit != 0) do {
  80789. dist = s->d_buf[lx];
  80790. lc = s->l_buf[lx++];
  80791. if (dist == 0) {
  80792. send_code(s, lc, ltree); /* send a literal byte */
  80793. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  80794. } else {
  80795. /* Here, lc is the match length - MIN_MATCH */
  80796. code = _length_code[lc];
  80797. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  80798. extra = extra_lbits[code];
  80799. if (extra != 0) {
  80800. lc -= base_length[code];
  80801. send_bits(s, lc, extra); /* send the extra length bits */
  80802. }
  80803. dist--; /* dist is now the match distance - 1 */
  80804. code = d_code(dist);
  80805. Assert (code < D_CODES, "bad d_code");
  80806. send_code(s, code, dtree); /* send the distance code */
  80807. extra = extra_dbits[code];
  80808. if (extra != 0) {
  80809. dist -= base_dist[code];
  80810. send_bits(s, dist, extra); /* send the extra distance bits */
  80811. }
  80812. } /* literal or match pair ? */
  80813. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  80814. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  80815. "pendingBuf overflow");
  80816. } while (lx < s->last_lit);
  80817. send_code(s, END_BLOCK, ltree);
  80818. s->last_eob_len = ltree[END_BLOCK].Len;
  80819. }
  80820. /* ===========================================================================
  80821. * Set the data type to BINARY or TEXT, using a crude approximation:
  80822. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  80823. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  80824. * IN assertion: the fields Freq of dyn_ltree are set.
  80825. */
  80826. local void set_data_type (deflate_state *s)
  80827. {
  80828. int n;
  80829. for (n = 0; n < 9; n++)
  80830. if (s->dyn_ltree[n].Freq != 0)
  80831. break;
  80832. if (n == 9)
  80833. for (n = 14; n < 32; n++)
  80834. if (s->dyn_ltree[n].Freq != 0)
  80835. break;
  80836. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  80837. }
  80838. /* ===========================================================================
  80839. * Reverse the first len bits of a code, using straightforward code (a faster
  80840. * method would use a table)
  80841. * IN assertion: 1 <= len <= 15
  80842. */
  80843. local unsigned bi_reverse (unsigned code, int len)
  80844. {
  80845. register unsigned res = 0;
  80846. do {
  80847. res |= code & 1;
  80848. code >>= 1, res <<= 1;
  80849. } while (--len > 0);
  80850. return res >> 1;
  80851. }
  80852. /* ===========================================================================
  80853. * Flush the bit buffer, keeping at most 7 bits in it.
  80854. */
  80855. local void bi_flush (deflate_state *s)
  80856. {
  80857. if (s->bi_valid == 16) {
  80858. put_short(s, s->bi_buf);
  80859. s->bi_buf = 0;
  80860. s->bi_valid = 0;
  80861. } else if (s->bi_valid >= 8) {
  80862. put_byte(s, (Byte)s->bi_buf);
  80863. s->bi_buf >>= 8;
  80864. s->bi_valid -= 8;
  80865. }
  80866. }
  80867. /* ===========================================================================
  80868. * Flush the bit buffer and align the output on a byte boundary
  80869. */
  80870. local void bi_windup (deflate_state *s)
  80871. {
  80872. if (s->bi_valid > 8) {
  80873. put_short(s, s->bi_buf);
  80874. } else if (s->bi_valid > 0) {
  80875. put_byte(s, (Byte)s->bi_buf);
  80876. }
  80877. s->bi_buf = 0;
  80878. s->bi_valid = 0;
  80879. #ifdef DEBUG
  80880. s->bits_sent = (s->bits_sent+7) & ~7;
  80881. #endif
  80882. }
  80883. /* ===========================================================================
  80884. * Copy a stored block, storing first the length and its
  80885. * one's complement if requested.
  80886. */
  80887. local void copy_block(deflate_state *s,
  80888. charf *buf, /* the input data */
  80889. unsigned len, /* its length */
  80890. int header) /* true if block header must be written */
  80891. {
  80892. bi_windup(s); /* align on byte boundary */
  80893. s->last_eob_len = 8; /* enough lookahead for inflate */
  80894. if (header) {
  80895. put_short(s, (ush)len);
  80896. put_short(s, (ush)~len);
  80897. #ifdef DEBUG
  80898. s->bits_sent += 2*16;
  80899. #endif
  80900. }
  80901. #ifdef DEBUG
  80902. s->bits_sent += (ulg)len<<3;
  80903. #endif
  80904. while (len--) {
  80905. put_byte(s, *buf++);
  80906. }
  80907. }
  80908. /********* End of inlined file: trees.c *********/
  80909. /********* Start of inlined file: zutil.c *********/
  80910. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80911. #ifndef NO_DUMMY_DECL
  80912. struct internal_state {int dummy;}; /* for buggy compilers */
  80913. #endif
  80914. const char * const z_errmsg[10] = {
  80915. "need dictionary", /* Z_NEED_DICT 2 */
  80916. "stream end", /* Z_STREAM_END 1 */
  80917. "", /* Z_OK 0 */
  80918. "file error", /* Z_ERRNO (-1) */
  80919. "stream error", /* Z_STREAM_ERROR (-2) */
  80920. "data error", /* Z_DATA_ERROR (-3) */
  80921. "insufficient memory", /* Z_MEM_ERROR (-4) */
  80922. "buffer error", /* Z_BUF_ERROR (-5) */
  80923. "incompatible version",/* Z_VERSION_ERROR (-6) */
  80924. ""};
  80925. /*const char * ZEXPORT zlibVersion()
  80926. {
  80927. return ZLIB_VERSION;
  80928. }
  80929. uLong ZEXPORT zlibCompileFlags()
  80930. {
  80931. uLong flags;
  80932. flags = 0;
  80933. switch (sizeof(uInt)) {
  80934. case 2: break;
  80935. case 4: flags += 1; break;
  80936. case 8: flags += 2; break;
  80937. default: flags += 3;
  80938. }
  80939. switch (sizeof(uLong)) {
  80940. case 2: break;
  80941. case 4: flags += 1 << 2; break;
  80942. case 8: flags += 2 << 2; break;
  80943. default: flags += 3 << 2;
  80944. }
  80945. switch (sizeof(voidpf)) {
  80946. case 2: break;
  80947. case 4: flags += 1 << 4; break;
  80948. case 8: flags += 2 << 4; break;
  80949. default: flags += 3 << 4;
  80950. }
  80951. switch (sizeof(z_off_t)) {
  80952. case 2: break;
  80953. case 4: flags += 1 << 6; break;
  80954. case 8: flags += 2 << 6; break;
  80955. default: flags += 3 << 6;
  80956. }
  80957. #ifdef DEBUG
  80958. flags += 1 << 8;
  80959. #endif
  80960. #if defined(ASMV) || defined(ASMINF)
  80961. flags += 1 << 9;
  80962. #endif
  80963. #ifdef ZLIB_WINAPI
  80964. flags += 1 << 10;
  80965. #endif
  80966. #ifdef BUILDFIXED
  80967. flags += 1 << 12;
  80968. #endif
  80969. #ifdef DYNAMIC_CRC_TABLE
  80970. flags += 1 << 13;
  80971. #endif
  80972. #ifdef NO_GZCOMPRESS
  80973. flags += 1L << 16;
  80974. #endif
  80975. #ifdef NO_GZIP
  80976. flags += 1L << 17;
  80977. #endif
  80978. #ifdef PKZIP_BUG_WORKAROUND
  80979. flags += 1L << 20;
  80980. #endif
  80981. #ifdef FASTEST
  80982. flags += 1L << 21;
  80983. #endif
  80984. #ifdef STDC
  80985. # ifdef NO_vsnprintf
  80986. flags += 1L << 25;
  80987. # ifdef HAS_vsprintf_void
  80988. flags += 1L << 26;
  80989. # endif
  80990. # else
  80991. # ifdef HAS_vsnprintf_void
  80992. flags += 1L << 26;
  80993. # endif
  80994. # endif
  80995. #else
  80996. flags += 1L << 24;
  80997. # ifdef NO_snprintf
  80998. flags += 1L << 25;
  80999. # ifdef HAS_sprintf_void
  81000. flags += 1L << 26;
  81001. # endif
  81002. # else
  81003. # ifdef HAS_snprintf_void
  81004. flags += 1L << 26;
  81005. # endif
  81006. # endif
  81007. #endif
  81008. return flags;
  81009. }*/
  81010. #ifdef DEBUG
  81011. # ifndef verbose
  81012. # define verbose 0
  81013. # endif
  81014. int z_verbose = verbose;
  81015. void z_error (const char *m)
  81016. {
  81017. fprintf(stderr, "%s\n", m);
  81018. exit(1);
  81019. }
  81020. #endif
  81021. /* exported to allow conversion of error code to string for compress() and
  81022. * uncompress()
  81023. */
  81024. const char * ZEXPORT zError(int err)
  81025. {
  81026. return ERR_MSG(err);
  81027. }
  81028. #if defined(_WIN32_WCE)
  81029. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  81030. * errno. We define it as a global variable to simplify porting.
  81031. * Its value is always 0 and should not be used.
  81032. */
  81033. int errno = 0;
  81034. #endif
  81035. #ifndef HAVE_MEMCPY
  81036. void zmemcpy(dest, source, len)
  81037. Bytef* dest;
  81038. const Bytef* source;
  81039. uInt len;
  81040. {
  81041. if (len == 0) return;
  81042. do {
  81043. *dest++ = *source++; /* ??? to be unrolled */
  81044. } while (--len != 0);
  81045. }
  81046. int zmemcmp(s1, s2, len)
  81047. const Bytef* s1;
  81048. const Bytef* s2;
  81049. uInt len;
  81050. {
  81051. uInt j;
  81052. for (j = 0; j < len; j++) {
  81053. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  81054. }
  81055. return 0;
  81056. }
  81057. void zmemzero(dest, len)
  81058. Bytef* dest;
  81059. uInt len;
  81060. {
  81061. if (len == 0) return;
  81062. do {
  81063. *dest++ = 0; /* ??? to be unrolled */
  81064. } while (--len != 0);
  81065. }
  81066. #endif
  81067. #ifdef SYS16BIT
  81068. #ifdef __TURBOC__
  81069. /* Turbo C in 16-bit mode */
  81070. # define MY_ZCALLOC
  81071. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  81072. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  81073. * must fix the pointer. Warning: the pointer must be put back to its
  81074. * original form in order to free it, use zcfree().
  81075. */
  81076. #define MAX_PTR 10
  81077. /* 10*64K = 640K */
  81078. local int next_ptr = 0;
  81079. typedef struct ptr_table_s {
  81080. voidpf org_ptr;
  81081. voidpf new_ptr;
  81082. } ptr_table;
  81083. local ptr_table table[MAX_PTR];
  81084. /* This table is used to remember the original form of pointers
  81085. * to large buffers (64K). Such pointers are normalized with a zero offset.
  81086. * Since MSDOS is not a preemptive multitasking OS, this table is not
  81087. * protected from concurrent access. This hack doesn't work anyway on
  81088. * a protected system like OS/2. Use Microsoft C instead.
  81089. */
  81090. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81091. {
  81092. voidpf buf = opaque; /* just to make some compilers happy */
  81093. ulg bsize = (ulg)items*size;
  81094. /* If we allocate less than 65520 bytes, we assume that farmalloc
  81095. * will return a usable pointer which doesn't have to be normalized.
  81096. */
  81097. if (bsize < 65520L) {
  81098. buf = farmalloc(bsize);
  81099. if (*(ush*)&buf != 0) return buf;
  81100. } else {
  81101. buf = farmalloc(bsize + 16L);
  81102. }
  81103. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  81104. table[next_ptr].org_ptr = buf;
  81105. /* Normalize the pointer to seg:0 */
  81106. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  81107. *(ush*)&buf = 0;
  81108. table[next_ptr++].new_ptr = buf;
  81109. return buf;
  81110. }
  81111. void zcfree (voidpf opaque, voidpf ptr)
  81112. {
  81113. int n;
  81114. if (*(ush*)&ptr != 0) { /* object < 64K */
  81115. farfree(ptr);
  81116. return;
  81117. }
  81118. /* Find the original pointer */
  81119. for (n = 0; n < next_ptr; n++) {
  81120. if (ptr != table[n].new_ptr) continue;
  81121. farfree(table[n].org_ptr);
  81122. while (++n < next_ptr) {
  81123. table[n-1] = table[n];
  81124. }
  81125. next_ptr--;
  81126. return;
  81127. }
  81128. ptr = opaque; /* just to make some compilers happy */
  81129. Assert(0, "zcfree: ptr not found");
  81130. }
  81131. #endif /* __TURBOC__ */
  81132. #ifdef M_I86
  81133. /* Microsoft C in 16-bit mode */
  81134. # define MY_ZCALLOC
  81135. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  81136. # define _halloc halloc
  81137. # define _hfree hfree
  81138. #endif
  81139. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81140. {
  81141. if (opaque) opaque = 0; /* to make compiler happy */
  81142. return _halloc((long)items, size);
  81143. }
  81144. void zcfree (voidpf opaque, voidpf ptr)
  81145. {
  81146. if (opaque) opaque = 0; /* to make compiler happy */
  81147. _hfree(ptr);
  81148. }
  81149. #endif /* M_I86 */
  81150. #endif /* SYS16BIT */
  81151. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  81152. #ifndef STDC
  81153. extern voidp malloc OF((uInt size));
  81154. extern voidp calloc OF((uInt items, uInt size));
  81155. extern void free OF((voidpf ptr));
  81156. #endif
  81157. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81158. {
  81159. if (opaque) items += size - size; /* make compiler happy */
  81160. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  81161. (voidpf)calloc(items, size);
  81162. }
  81163. void zcfree (voidpf opaque, voidpf ptr)
  81164. {
  81165. free(ptr);
  81166. if (opaque) return; /* make compiler happy */
  81167. }
  81168. #endif /* MY_ZCALLOC */
  81169. /********* End of inlined file: zutil.c *********/
  81170. #undef Byte
  81171. }
  81172. #else
  81173. #include <zlib.h>
  81174. #endif
  81175. }
  81176. #if JUCE_MSVC
  81177. #pragma warning (pop)
  81178. #endif
  81179. BEGIN_JUCE_NAMESPACE
  81180. using namespace zlibNamespace;
  81181. // internal helper object that holds the zlib structures so they don't have to be
  81182. // included publicly.
  81183. class GZIPDecompressHelper
  81184. {
  81185. private:
  81186. z_stream* stream;
  81187. uint8* data;
  81188. int dataSize;
  81189. public:
  81190. bool finished, needsDictionary, error;
  81191. GZIPDecompressHelper (const bool noWrap) throw()
  81192. : data (0),
  81193. dataSize (0),
  81194. finished (false),
  81195. needsDictionary (false),
  81196. error (false)
  81197. {
  81198. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  81199. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  81200. : MAX_WBITS) != Z_OK)
  81201. {
  81202. juce_free (stream);
  81203. stream = 0;
  81204. error = true;
  81205. finished = true;
  81206. }
  81207. }
  81208. ~GZIPDecompressHelper() throw()
  81209. {
  81210. if (stream != 0)
  81211. {
  81212. inflateEnd (stream);
  81213. juce_free (stream);
  81214. }
  81215. }
  81216. bool needsInput() const throw() { return dataSize <= 0; }
  81217. void setInput (uint8* const data_, const int size) throw()
  81218. {
  81219. data = data_;
  81220. dataSize = size;
  81221. }
  81222. int doNextBlock (uint8* const dest, const int destSize) throw()
  81223. {
  81224. if (stream != 0 && data != 0 && ! finished)
  81225. {
  81226. stream->next_in = data;
  81227. stream->next_out = dest;
  81228. stream->avail_in = dataSize;
  81229. stream->avail_out = destSize;
  81230. switch (inflate (stream, Z_PARTIAL_FLUSH))
  81231. {
  81232. case Z_STREAM_END:
  81233. finished = true;
  81234. // deliberate fall-through
  81235. case Z_OK:
  81236. data += dataSize - stream->avail_in;
  81237. dataSize = stream->avail_in;
  81238. return destSize - stream->avail_out;
  81239. case Z_NEED_DICT:
  81240. needsDictionary = true;
  81241. data += dataSize - stream->avail_in;
  81242. dataSize = stream->avail_in;
  81243. break;
  81244. case Z_DATA_ERROR:
  81245. case Z_MEM_ERROR:
  81246. error = true;
  81247. default:
  81248. break;
  81249. }
  81250. }
  81251. return 0;
  81252. }
  81253. };
  81254. const int gzipDecompBufferSize = 32768;
  81255. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  81256. const bool deleteSourceWhenDestroyed_,
  81257. const bool noWrap_,
  81258. const int64 uncompressedStreamLength_)
  81259. : sourceStream (sourceStream_),
  81260. uncompressedStreamLength (uncompressedStreamLength_),
  81261. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  81262. noWrap (noWrap_),
  81263. isEof (false),
  81264. activeBufferSize (0),
  81265. originalSourcePos (sourceStream_->getPosition()),
  81266. currentPos (0)
  81267. {
  81268. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  81269. helper = new GZIPDecompressHelper (noWrap_);
  81270. }
  81271. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  81272. {
  81273. juce_free (buffer);
  81274. if (deleteSourceWhenDestroyed)
  81275. delete sourceStream;
  81276. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81277. delete h;
  81278. }
  81279. int64 GZIPDecompressorInputStream::getTotalLength()
  81280. {
  81281. return uncompressedStreamLength;
  81282. }
  81283. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  81284. {
  81285. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81286. if ((howMany > 0) && ! isEof)
  81287. {
  81288. jassert (destBuffer != 0);
  81289. if (destBuffer != 0)
  81290. {
  81291. int numRead = 0;
  81292. uint8* d = (uint8*) destBuffer;
  81293. while (! h->error)
  81294. {
  81295. const int n = h->doNextBlock (d, howMany);
  81296. currentPos += n;
  81297. if (n == 0)
  81298. {
  81299. if (h->finished || h->needsDictionary)
  81300. {
  81301. isEof = true;
  81302. return numRead;
  81303. }
  81304. if (h->needsInput())
  81305. {
  81306. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  81307. if (activeBufferSize > 0)
  81308. {
  81309. h->setInput ((uint8*) buffer, activeBufferSize);
  81310. }
  81311. else
  81312. {
  81313. isEof = true;
  81314. return numRead;
  81315. }
  81316. }
  81317. }
  81318. else
  81319. {
  81320. numRead += n;
  81321. howMany -= n;
  81322. d += n;
  81323. if (howMany <= 0)
  81324. return numRead;
  81325. }
  81326. }
  81327. }
  81328. }
  81329. return 0;
  81330. }
  81331. bool GZIPDecompressorInputStream::isExhausted()
  81332. {
  81333. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81334. return h->error || isEof;
  81335. }
  81336. int64 GZIPDecompressorInputStream::getPosition()
  81337. {
  81338. return currentPos;
  81339. }
  81340. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  81341. {
  81342. if (newPos != currentPos)
  81343. {
  81344. if (newPos > currentPos)
  81345. {
  81346. skipNextBytes (newPos - currentPos);
  81347. }
  81348. else
  81349. {
  81350. // reset the stream and start again..
  81351. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81352. delete h;
  81353. isEof = false;
  81354. activeBufferSize = 0;
  81355. currentPos = 0;
  81356. helper = new GZIPDecompressHelper (noWrap);
  81357. sourceStream->setPosition (originalSourcePos);
  81358. skipNextBytes (newPos);
  81359. }
  81360. }
  81361. return true;
  81362. }
  81363. END_JUCE_NAMESPACE
  81364. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  81365. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  81366. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  81367. #ifdef _MSC_VER
  81368. #include <windows.h>
  81369. #endif
  81370. #if JUCE_USE_FLAC
  81371. #ifdef _MSC_VER
  81372. #pragma warning (disable : 4505)
  81373. #pragma warning (push)
  81374. #endif
  81375. namespace FlacNamespace
  81376. {
  81377. #if JUCE_INCLUDE_FLAC_CODE
  81378. #define FLAC__NO_DLL 1
  81379. #if ! defined (SIZE_MAX)
  81380. #define SIZE_MAX 0xffffffff
  81381. #endif
  81382. #define __STDC_LIMIT_MACROS 1
  81383. /********* Start of inlined file: all.h *********/
  81384. #ifndef FLAC__ALL_H
  81385. #define FLAC__ALL_H
  81386. /********* Start of inlined file: export.h *********/
  81387. #ifndef FLAC__EXPORT_H
  81388. #define FLAC__EXPORT_H
  81389. /** \file include/FLAC/export.h
  81390. *
  81391. * \brief
  81392. * This module contains #defines and symbols for exporting function
  81393. * calls, and providing version information and compiled-in features.
  81394. *
  81395. * See the \link flac_export export \endlink module.
  81396. */
  81397. /** \defgroup flac_export FLAC/export.h: export symbols
  81398. * \ingroup flac
  81399. *
  81400. * \brief
  81401. * This module contains #defines and symbols for exporting function
  81402. * calls, and providing version information and compiled-in features.
  81403. *
  81404. * If you are compiling with MSVC and will link to the static library
  81405. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  81406. * make sure the symbols are exported properly.
  81407. *
  81408. * \{
  81409. */
  81410. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  81411. #define FLAC_API
  81412. #else
  81413. #ifdef FLAC_API_EXPORTS
  81414. #define FLAC_API _declspec(dllexport)
  81415. #else
  81416. #define FLAC_API _declspec(dllimport)
  81417. #endif
  81418. #endif
  81419. /** These #defines will mirror the libtool-based library version number, see
  81420. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  81421. */
  81422. #define FLAC_API_VERSION_CURRENT 10
  81423. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  81424. #define FLAC_API_VERSION_AGE 2 /**< see above */
  81425. #ifdef __cplusplus
  81426. extern "C" {
  81427. #endif
  81428. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  81429. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  81430. #ifdef __cplusplus
  81431. }
  81432. #endif
  81433. /* \} */
  81434. #endif
  81435. /********* End of inlined file: export.h *********/
  81436. /********* Start of inlined file: assert.h *********/
  81437. #ifndef FLAC__ASSERT_H
  81438. #define FLAC__ASSERT_H
  81439. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  81440. #ifdef DEBUG
  81441. #include <assert.h>
  81442. #define FLAC__ASSERT(x) assert(x)
  81443. #define FLAC__ASSERT_DECLARATION(x) x
  81444. #else
  81445. #define FLAC__ASSERT(x)
  81446. #define FLAC__ASSERT_DECLARATION(x)
  81447. #endif
  81448. #endif
  81449. /********* End of inlined file: assert.h *********/
  81450. /********* Start of inlined file: callback.h *********/
  81451. #ifndef FLAC__CALLBACK_H
  81452. #define FLAC__CALLBACK_H
  81453. /********* Start of inlined file: ordinals.h *********/
  81454. #ifndef FLAC__ORDINALS_H
  81455. #define FLAC__ORDINALS_H
  81456. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  81457. #include <inttypes.h>
  81458. #endif
  81459. typedef signed char FLAC__int8;
  81460. typedef unsigned char FLAC__uint8;
  81461. #if defined(_MSC_VER) || defined(__BORLANDC__)
  81462. typedef __int16 FLAC__int16;
  81463. typedef __int32 FLAC__int32;
  81464. typedef __int64 FLAC__int64;
  81465. typedef unsigned __int16 FLAC__uint16;
  81466. typedef unsigned __int32 FLAC__uint32;
  81467. typedef unsigned __int64 FLAC__uint64;
  81468. #elif defined(__EMX__)
  81469. typedef short FLAC__int16;
  81470. typedef long FLAC__int32;
  81471. typedef long long FLAC__int64;
  81472. typedef unsigned short FLAC__uint16;
  81473. typedef unsigned long FLAC__uint32;
  81474. typedef unsigned long long FLAC__uint64;
  81475. #else
  81476. typedef int16_t FLAC__int16;
  81477. typedef int32_t FLAC__int32;
  81478. typedef int64_t FLAC__int64;
  81479. typedef uint16_t FLAC__uint16;
  81480. typedef uint32_t FLAC__uint32;
  81481. typedef uint64_t FLAC__uint64;
  81482. #endif
  81483. typedef int FLAC__bool;
  81484. typedef FLAC__uint8 FLAC__byte;
  81485. #ifdef true
  81486. #undef true
  81487. #endif
  81488. #ifdef false
  81489. #undef false
  81490. #endif
  81491. #ifndef __cplusplus
  81492. #define true 1
  81493. #define false 0
  81494. #endif
  81495. #endif
  81496. /********* End of inlined file: ordinals.h *********/
  81497. #include <stdlib.h> /* for size_t */
  81498. /** \file include/FLAC/callback.h
  81499. *
  81500. * \brief
  81501. * This module defines the structures for describing I/O callbacks
  81502. * to the other FLAC interfaces.
  81503. *
  81504. * See the detailed documentation for callbacks in the
  81505. * \link flac_callbacks callbacks \endlink module.
  81506. */
  81507. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  81508. * \ingroup flac
  81509. *
  81510. * \brief
  81511. * This module defines the structures for describing I/O callbacks
  81512. * to the other FLAC interfaces.
  81513. *
  81514. * The purpose of the I/O callback functions is to create a common way
  81515. * for the metadata interfaces to handle I/O.
  81516. *
  81517. * Originally the metadata interfaces required filenames as the way of
  81518. * specifying FLAC files to operate on. This is problematic in some
  81519. * environments so there is an additional option to specify a set of
  81520. * callbacks for doing I/O on the FLAC file, instead of the filename.
  81521. *
  81522. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  81523. * opaque structure for a data source.
  81524. *
  81525. * The callback function prototypes are similar (but not identical) to the
  81526. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  81527. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  81528. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  81529. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  81530. * is required. \warning You generally CANNOT directly use fseek or ftell
  81531. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  81532. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  81533. * large files. You will have to find an equivalent function (e.g. ftello),
  81534. * or write a wrapper. The same is true for feof() since this is usually
  81535. * implemented as a macro, not as a function whose address can be taken.
  81536. *
  81537. * \{
  81538. */
  81539. #ifdef __cplusplus
  81540. extern "C" {
  81541. #endif
  81542. /** This is the opaque handle type used by the callbacks. Typically
  81543. * this is a \c FILE* or address of a file descriptor.
  81544. */
  81545. typedef void* FLAC__IOHandle;
  81546. /** Signature for the read callback.
  81547. * The signature and semantics match POSIX fread() implementations
  81548. * and can generally be used interchangeably.
  81549. *
  81550. * \param ptr The address of the read buffer.
  81551. * \param size The size of the records to be read.
  81552. * \param nmemb The number of records to be read.
  81553. * \param handle The handle to the data source.
  81554. * \retval size_t
  81555. * The number of records read.
  81556. */
  81557. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  81558. /** Signature for the write callback.
  81559. * The signature and semantics match POSIX fwrite() implementations
  81560. * and can generally be used interchangeably.
  81561. *
  81562. * \param ptr The address of the write buffer.
  81563. * \param size The size of the records to be written.
  81564. * \param nmemb The number of records to be written.
  81565. * \param handle The handle to the data source.
  81566. * \retval size_t
  81567. * The number of records written.
  81568. */
  81569. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  81570. /** Signature for the seek callback.
  81571. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  81572. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  81573. * and 32-bits wide.
  81574. *
  81575. * \param handle The handle to the data source.
  81576. * \param offset The new position, relative to \a whence
  81577. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  81578. * \retval int
  81579. * \c 0 on success, \c -1 on error.
  81580. */
  81581. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  81582. /** Signature for the tell callback.
  81583. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  81584. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  81585. * and 32-bits wide.
  81586. *
  81587. * \param handle The handle to the data source.
  81588. * \retval FLAC__int64
  81589. * The current position on success, \c -1 on error.
  81590. */
  81591. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  81592. /** Signature for the EOF callback.
  81593. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  81594. * on many systems, feof() is a macro, so in this case a wrapper function
  81595. * must be provided instead.
  81596. *
  81597. * \param handle The handle to the data source.
  81598. * \retval int
  81599. * \c 0 if not at end of file, nonzero if at end of file.
  81600. */
  81601. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  81602. /** Signature for the close callback.
  81603. * The signature and semantics match POSIX fclose() implementations
  81604. * and can generally be used interchangeably.
  81605. *
  81606. * \param handle The handle to the data source.
  81607. * \retval int
  81608. * \c 0 on success, \c EOF on error.
  81609. */
  81610. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  81611. /** A structure for holding a set of callbacks.
  81612. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  81613. * describe which of the callbacks are required. The ones that are not
  81614. * required may be set to NULL.
  81615. *
  81616. * If the seek requirement for an interface is optional, you can signify that
  81617. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  81618. */
  81619. typedef struct {
  81620. FLAC__IOCallback_Read read;
  81621. FLAC__IOCallback_Write write;
  81622. FLAC__IOCallback_Seek seek;
  81623. FLAC__IOCallback_Tell tell;
  81624. FLAC__IOCallback_Eof eof;
  81625. FLAC__IOCallback_Close close;
  81626. } FLAC__IOCallbacks;
  81627. /* \} */
  81628. #ifdef __cplusplus
  81629. }
  81630. #endif
  81631. #endif
  81632. /********* End of inlined file: callback.h *********/
  81633. /********* Start of inlined file: format.h *********/
  81634. #ifndef FLAC__FORMAT_H
  81635. #define FLAC__FORMAT_H
  81636. #ifdef __cplusplus
  81637. extern "C" {
  81638. #endif
  81639. /** \file include/FLAC/format.h
  81640. *
  81641. * \brief
  81642. * This module contains structure definitions for the representation
  81643. * of FLAC format components in memory. These are the basic
  81644. * structures used by the rest of the interfaces.
  81645. *
  81646. * See the detailed documentation in the
  81647. * \link flac_format format \endlink module.
  81648. */
  81649. /** \defgroup flac_format FLAC/format.h: format components
  81650. * \ingroup flac
  81651. *
  81652. * \brief
  81653. * This module contains structure definitions for the representation
  81654. * of FLAC format components in memory. These are the basic
  81655. * structures used by the rest of the interfaces.
  81656. *
  81657. * First, you should be familiar with the
  81658. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  81659. * follow directly from the specification. As a user of libFLAC, the
  81660. * interesting parts really are the structures that describe the frame
  81661. * header and metadata blocks.
  81662. *
  81663. * The format structures here are very primitive, designed to store
  81664. * information in an efficient way. Reading information from the
  81665. * structures is easy but creating or modifying them directly is
  81666. * more complex. For the most part, as a user of a library, editing
  81667. * is not necessary; however, for metadata blocks it is, so there are
  81668. * convenience functions provided in the \link flac_metadata metadata
  81669. * module \endlink to simplify the manipulation of metadata blocks.
  81670. *
  81671. * \note
  81672. * It's not the best convention, but symbols ending in _LEN are in bits
  81673. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  81674. * global variables because they are usually used when declaring byte
  81675. * arrays and some compilers require compile-time knowledge of array
  81676. * sizes when declared on the stack.
  81677. *
  81678. * \{
  81679. */
  81680. /*
  81681. Most of the values described in this file are defined by the FLAC
  81682. format specification. There is nothing to tune here.
  81683. */
  81684. /** The largest legal metadata type code. */
  81685. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  81686. /** The minimum block size, in samples, permitted by the format. */
  81687. #define FLAC__MIN_BLOCK_SIZE (16u)
  81688. /** The maximum block size, in samples, permitted by the format. */
  81689. #define FLAC__MAX_BLOCK_SIZE (65535u)
  81690. /** The maximum block size, in samples, permitted by the FLAC subset for
  81691. * sample rates up to 48kHz. */
  81692. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  81693. /** The maximum number of channels permitted by the format. */
  81694. #define FLAC__MAX_CHANNELS (8u)
  81695. /** The minimum sample resolution permitted by the format. */
  81696. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  81697. /** The maximum sample resolution permitted by the format. */
  81698. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  81699. /** The maximum sample resolution permitted by libFLAC.
  81700. *
  81701. * \warning
  81702. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  81703. * the reference encoder/decoder is currently limited to 24 bits because
  81704. * of prevalent 32-bit math, so make sure and use this value when
  81705. * appropriate.
  81706. */
  81707. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  81708. /** The maximum sample rate permitted by the format. The value is
  81709. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  81710. * as to why.
  81711. */
  81712. #define FLAC__MAX_SAMPLE_RATE (655350u)
  81713. /** The maximum LPC order permitted by the format. */
  81714. #define FLAC__MAX_LPC_ORDER (32u)
  81715. /** The maximum LPC order permitted by the FLAC subset for sample rates
  81716. * up to 48kHz. */
  81717. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  81718. /** The minimum quantized linear predictor coefficient precision
  81719. * permitted by the format.
  81720. */
  81721. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  81722. /** The maximum quantized linear predictor coefficient precision
  81723. * permitted by the format.
  81724. */
  81725. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  81726. /** The maximum order of the fixed predictors permitted by the format. */
  81727. #define FLAC__MAX_FIXED_ORDER (4u)
  81728. /** The maximum Rice partition order permitted by the format. */
  81729. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  81730. /** The maximum Rice partition order permitted by the FLAC Subset. */
  81731. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  81732. /** The version string of the release, stamped onto the libraries and binaries.
  81733. *
  81734. * \note
  81735. * This does not correspond to the shared library version number, which
  81736. * is used to determine binary compatibility.
  81737. */
  81738. extern FLAC_API const char *FLAC__VERSION_STRING;
  81739. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  81740. * This is a NUL-terminated ASCII string; when inserted into the
  81741. * VORBIS_COMMENT the trailing null is stripped.
  81742. */
  81743. extern FLAC_API const char *FLAC__VENDOR_STRING;
  81744. /** The byte string representation of the beginning of a FLAC stream. */
  81745. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  81746. /** The 32-bit integer big-endian representation of the beginning of
  81747. * a FLAC stream.
  81748. */
  81749. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  81750. /** The length of the FLAC signature in bits. */
  81751. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  81752. /** The length of the FLAC signature in bytes. */
  81753. #define FLAC__STREAM_SYNC_LENGTH (4u)
  81754. /*****************************************************************************
  81755. *
  81756. * Subframe structures
  81757. *
  81758. *****************************************************************************/
  81759. /*****************************************************************************/
  81760. /** An enumeration of the available entropy coding methods. */
  81761. typedef enum {
  81762. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  81763. /**< Residual is coded by partitioning into contexts, each with it's own
  81764. * 4-bit Rice parameter. */
  81765. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  81766. /**< Residual is coded by partitioning into contexts, each with it's own
  81767. * 5-bit Rice parameter. */
  81768. } FLAC__EntropyCodingMethodType;
  81769. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  81770. *
  81771. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  81772. * give the string equivalent. The contents should not be modified.
  81773. */
  81774. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  81775. /** Contents of a Rice partitioned residual
  81776. */
  81777. typedef struct {
  81778. unsigned *parameters;
  81779. /**< The Rice parameters for each context. */
  81780. unsigned *raw_bits;
  81781. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  81782. * partitions and zero for unescaped partitions.
  81783. */
  81784. unsigned capacity_by_order;
  81785. /**< The capacity of the \a parameters and \a raw_bits arrays
  81786. * specified as an order, i.e. the number of array elements
  81787. * allocated is 2 ^ \a capacity_by_order.
  81788. */
  81789. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  81790. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  81791. */
  81792. typedef struct {
  81793. unsigned order;
  81794. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  81795. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  81796. /**< The context's Rice parameters and/or raw bits. */
  81797. } FLAC__EntropyCodingMethod_PartitionedRice;
  81798. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  81799. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  81800. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  81801. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  81802. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  81803. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  81804. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  81805. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  81806. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  81807. */
  81808. typedef struct {
  81809. FLAC__EntropyCodingMethodType type;
  81810. union {
  81811. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  81812. } data;
  81813. } FLAC__EntropyCodingMethod;
  81814. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  81815. /*****************************************************************************/
  81816. /** An enumeration of the available subframe types. */
  81817. typedef enum {
  81818. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  81819. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  81820. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  81821. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  81822. } FLAC__SubframeType;
  81823. /** Maps a FLAC__SubframeType to a C string.
  81824. *
  81825. * Using a FLAC__SubframeType as the index to this array will
  81826. * give the string equivalent. The contents should not be modified.
  81827. */
  81828. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  81829. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  81830. */
  81831. typedef struct {
  81832. FLAC__int32 value; /**< The constant signal value. */
  81833. } FLAC__Subframe_Constant;
  81834. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  81835. */
  81836. typedef struct {
  81837. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  81838. } FLAC__Subframe_Verbatim;
  81839. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  81840. */
  81841. typedef struct {
  81842. FLAC__EntropyCodingMethod entropy_coding_method;
  81843. /**< The residual coding method. */
  81844. unsigned order;
  81845. /**< The polynomial order. */
  81846. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  81847. /**< Warmup samples to prime the predictor, length == order. */
  81848. const FLAC__int32 *residual;
  81849. /**< The residual signal, length == (blocksize minus order) samples. */
  81850. } FLAC__Subframe_Fixed;
  81851. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  81852. */
  81853. typedef struct {
  81854. FLAC__EntropyCodingMethod entropy_coding_method;
  81855. /**< The residual coding method. */
  81856. unsigned order;
  81857. /**< The FIR order. */
  81858. unsigned qlp_coeff_precision;
  81859. /**< Quantized FIR filter coefficient precision in bits. */
  81860. int quantization_level;
  81861. /**< The qlp coeff shift needed. */
  81862. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  81863. /**< FIR filter coefficients. */
  81864. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  81865. /**< Warmup samples to prime the predictor, length == order. */
  81866. const FLAC__int32 *residual;
  81867. /**< The residual signal, length == (blocksize minus order) samples. */
  81868. } FLAC__Subframe_LPC;
  81869. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  81870. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  81871. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  81872. */
  81873. typedef struct {
  81874. FLAC__SubframeType type;
  81875. union {
  81876. FLAC__Subframe_Constant constant;
  81877. FLAC__Subframe_Fixed fixed;
  81878. FLAC__Subframe_LPC lpc;
  81879. FLAC__Subframe_Verbatim verbatim;
  81880. } data;
  81881. unsigned wasted_bits;
  81882. } FLAC__Subframe;
  81883. /** == 1 (bit)
  81884. *
  81885. * This used to be a zero-padding bit (hence the name
  81886. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  81887. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  81888. * to mean something else.
  81889. */
  81890. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  81891. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  81892. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  81893. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  81894. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  81895. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  81896. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  81897. /*****************************************************************************/
  81898. /*****************************************************************************
  81899. *
  81900. * Frame structures
  81901. *
  81902. *****************************************************************************/
  81903. /** An enumeration of the available channel assignments. */
  81904. typedef enum {
  81905. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  81906. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  81907. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  81908. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  81909. } FLAC__ChannelAssignment;
  81910. /** Maps a FLAC__ChannelAssignment to a C string.
  81911. *
  81912. * Using a FLAC__ChannelAssignment as the index to this array will
  81913. * give the string equivalent. The contents should not be modified.
  81914. */
  81915. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  81916. /** An enumeration of the possible frame numbering methods. */
  81917. typedef enum {
  81918. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  81919. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  81920. } FLAC__FrameNumberType;
  81921. /** Maps a FLAC__FrameNumberType to a C string.
  81922. *
  81923. * Using a FLAC__FrameNumberType as the index to this array will
  81924. * give the string equivalent. The contents should not be modified.
  81925. */
  81926. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  81927. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  81928. */
  81929. typedef struct {
  81930. unsigned blocksize;
  81931. /**< The number of samples per subframe. */
  81932. unsigned sample_rate;
  81933. /**< The sample rate in Hz. */
  81934. unsigned channels;
  81935. /**< The number of channels (== number of subframes). */
  81936. FLAC__ChannelAssignment channel_assignment;
  81937. /**< The channel assignment for the frame. */
  81938. unsigned bits_per_sample;
  81939. /**< The sample resolution. */
  81940. FLAC__FrameNumberType number_type;
  81941. /**< The numbering scheme used for the frame. As a convenience, the
  81942. * decoder will always convert a frame number to a sample number because
  81943. * the rules are complex. */
  81944. union {
  81945. FLAC__uint32 frame_number;
  81946. FLAC__uint64 sample_number;
  81947. } number;
  81948. /**< The frame number or sample number of first sample in frame;
  81949. * use the \a number_type value to determine which to use. */
  81950. FLAC__uint8 crc;
  81951. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  81952. * of the raw frame header bytes, meaning everything before the CRC byte
  81953. * including the sync code.
  81954. */
  81955. } FLAC__FrameHeader;
  81956. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  81957. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  81958. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  81959. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  81960. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  81961. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  81962. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  81963. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  81964. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  81965. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  81966. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  81967. */
  81968. typedef struct {
  81969. FLAC__uint16 crc;
  81970. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  81971. * 0) of the bytes before the crc, back to and including the frame header
  81972. * sync code.
  81973. */
  81974. } FLAC__FrameFooter;
  81975. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  81976. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  81977. */
  81978. typedef struct {
  81979. FLAC__FrameHeader header;
  81980. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  81981. FLAC__FrameFooter footer;
  81982. } FLAC__Frame;
  81983. /*****************************************************************************/
  81984. /*****************************************************************************
  81985. *
  81986. * Meta-data structures
  81987. *
  81988. *****************************************************************************/
  81989. /** An enumeration of the available metadata block types. */
  81990. typedef enum {
  81991. FLAC__METADATA_TYPE_STREAMINFO = 0,
  81992. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  81993. FLAC__METADATA_TYPE_PADDING = 1,
  81994. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  81995. FLAC__METADATA_TYPE_APPLICATION = 2,
  81996. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  81997. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  81998. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  81999. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  82000. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  82001. FLAC__METADATA_TYPE_CUESHEET = 5,
  82002. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  82003. FLAC__METADATA_TYPE_PICTURE = 6,
  82004. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  82005. FLAC__METADATA_TYPE_UNDEFINED = 7
  82006. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  82007. } FLAC__MetadataType;
  82008. /** Maps a FLAC__MetadataType to a C string.
  82009. *
  82010. * Using a FLAC__MetadataType as the index to this array will
  82011. * give the string equivalent. The contents should not be modified.
  82012. */
  82013. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  82014. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  82015. */
  82016. typedef struct {
  82017. unsigned min_blocksize, max_blocksize;
  82018. unsigned min_framesize, max_framesize;
  82019. unsigned sample_rate;
  82020. unsigned channels;
  82021. unsigned bits_per_sample;
  82022. FLAC__uint64 total_samples;
  82023. FLAC__byte md5sum[16];
  82024. } FLAC__StreamMetadata_StreamInfo;
  82025. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82026. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82027. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82028. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82029. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  82030. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  82031. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  82032. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  82033. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  82034. /** The total stream length of the STREAMINFO block in bytes. */
  82035. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  82036. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  82037. */
  82038. typedef struct {
  82039. int dummy;
  82040. /**< Conceptually this is an empty struct since we don't store the
  82041. * padding bytes. Empty structs are not allowed by some C compilers,
  82042. * hence the dummy.
  82043. */
  82044. } FLAC__StreamMetadata_Padding;
  82045. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  82046. */
  82047. typedef struct {
  82048. FLAC__byte id[4];
  82049. FLAC__byte *data;
  82050. } FLAC__StreamMetadata_Application;
  82051. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  82052. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  82053. */
  82054. typedef struct {
  82055. FLAC__uint64 sample_number;
  82056. /**< The sample number of the target frame. */
  82057. FLAC__uint64 stream_offset;
  82058. /**< The offset, in bytes, of the target frame with respect to
  82059. * beginning of the first frame. */
  82060. unsigned frame_samples;
  82061. /**< The number of samples in the target frame. */
  82062. } FLAC__StreamMetadata_SeekPoint;
  82063. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  82064. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  82065. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  82066. /** The total stream length of a seek point in bytes. */
  82067. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  82068. /** The value used in the \a sample_number field of
  82069. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  82070. * point (== 0xffffffffffffffff).
  82071. */
  82072. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  82073. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  82074. *
  82075. * \note From the format specification:
  82076. * - The seek points must be sorted by ascending sample number.
  82077. * - Each seek point's sample number must be the first sample of the
  82078. * target frame.
  82079. * - Each seek point's sample number must be unique within the table.
  82080. * - Existence of a SEEKTABLE block implies a correct setting of
  82081. * total_samples in the stream_info block.
  82082. * - Behavior is undefined when more than one SEEKTABLE block is
  82083. * present in a stream.
  82084. */
  82085. typedef struct {
  82086. unsigned num_points;
  82087. FLAC__StreamMetadata_SeekPoint *points;
  82088. } FLAC__StreamMetadata_SeekTable;
  82089. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82090. *
  82091. * For convenience, the APIs maintain a trailing NUL character at the end of
  82092. * \a entry which is not counted toward \a length, i.e.
  82093. * \code strlen(entry) == length \endcode
  82094. */
  82095. typedef struct {
  82096. FLAC__uint32 length;
  82097. FLAC__byte *entry;
  82098. } FLAC__StreamMetadata_VorbisComment_Entry;
  82099. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  82100. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82101. */
  82102. typedef struct {
  82103. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  82104. FLAC__uint32 num_comments;
  82105. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  82106. } FLAC__StreamMetadata_VorbisComment;
  82107. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  82108. /** FLAC CUESHEET track index structure. (See the
  82109. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  82110. * the full description of each field.)
  82111. */
  82112. typedef struct {
  82113. FLAC__uint64 offset;
  82114. /**< Offset in samples, relative to the track offset, of the index
  82115. * point.
  82116. */
  82117. FLAC__byte number;
  82118. /**< The index point number. */
  82119. } FLAC__StreamMetadata_CueSheet_Index;
  82120. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  82121. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  82122. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  82123. /** FLAC CUESHEET track structure. (See the
  82124. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  82125. * the full description of each field.)
  82126. */
  82127. typedef struct {
  82128. FLAC__uint64 offset;
  82129. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  82130. FLAC__byte number;
  82131. /**< The track number. */
  82132. char isrc[13];
  82133. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  82134. unsigned type:1;
  82135. /**< The track type: 0 for audio, 1 for non-audio. */
  82136. unsigned pre_emphasis:1;
  82137. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  82138. FLAC__byte num_indices;
  82139. /**< The number of track index points. */
  82140. FLAC__StreamMetadata_CueSheet_Index *indices;
  82141. /**< NULL if num_indices == 0, else pointer to array of index points. */
  82142. } FLAC__StreamMetadata_CueSheet_Track;
  82143. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  82144. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  82145. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  82146. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  82147. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  82148. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  82149. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  82150. /** FLAC CUESHEET structure. (See the
  82151. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  82152. * for the full description of each field.)
  82153. */
  82154. typedef struct {
  82155. char media_catalog_number[129];
  82156. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  82157. * general, the media catalog number may be 0 to 128 bytes long; any
  82158. * unused characters should be right-padded with NUL characters.
  82159. */
  82160. FLAC__uint64 lead_in;
  82161. /**< The number of lead-in samples. */
  82162. FLAC__bool is_cd;
  82163. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  82164. unsigned num_tracks;
  82165. /**< The number of tracks. */
  82166. FLAC__StreamMetadata_CueSheet_Track *tracks;
  82167. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  82168. } FLAC__StreamMetadata_CueSheet;
  82169. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  82170. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  82171. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  82172. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  82173. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  82174. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  82175. typedef enum {
  82176. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  82177. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  82178. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  82179. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  82180. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  82181. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  82182. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  82183. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  82184. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  82185. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  82186. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  82187. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  82188. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  82189. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  82190. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  82191. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  82192. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  82193. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  82194. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  82195. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  82196. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  82197. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  82198. } FLAC__StreamMetadata_Picture_Type;
  82199. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  82200. *
  82201. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  82202. * will give the string equivalent. The contents should not be
  82203. * modified.
  82204. */
  82205. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  82206. /** FLAC PICTURE structure. (See the
  82207. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  82208. * for the full description of each field.)
  82209. */
  82210. typedef struct {
  82211. FLAC__StreamMetadata_Picture_Type type;
  82212. /**< The kind of picture stored. */
  82213. char *mime_type;
  82214. /**< Picture data's MIME type, in ASCII printable characters
  82215. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  82216. * use picture data of MIME type \c image/jpeg or \c image/png. A
  82217. * MIME type of '-->' is also allowed, in which case the picture
  82218. * data should be a complete URL. In file storage, the MIME type is
  82219. * stored as a 32-bit length followed by the ASCII string with no NUL
  82220. * terminator, but is converted to a plain C string in this structure
  82221. * for convenience.
  82222. */
  82223. FLAC__byte *description;
  82224. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  82225. * the description is stored as a 32-bit length followed by the UTF-8
  82226. * string with no NUL terminator, but is converted to a plain C string
  82227. * in this structure for convenience.
  82228. */
  82229. FLAC__uint32 width;
  82230. /**< Picture's width in pixels. */
  82231. FLAC__uint32 height;
  82232. /**< Picture's height in pixels. */
  82233. FLAC__uint32 depth;
  82234. /**< Picture's color depth in bits-per-pixel. */
  82235. FLAC__uint32 colors;
  82236. /**< For indexed palettes (like GIF), picture's number of colors (the
  82237. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  82238. */
  82239. FLAC__uint32 data_length;
  82240. /**< Length of binary picture data in bytes. */
  82241. FLAC__byte *data;
  82242. /**< Binary picture data. */
  82243. } FLAC__StreamMetadata_Picture;
  82244. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  82245. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  82246. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  82247. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  82248. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  82249. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  82250. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  82251. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  82252. /** Structure that is used when a metadata block of unknown type is loaded.
  82253. * The contents are opaque. The structure is used only internally to
  82254. * correctly handle unknown metadata.
  82255. */
  82256. typedef struct {
  82257. FLAC__byte *data;
  82258. } FLAC__StreamMetadata_Unknown;
  82259. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  82260. */
  82261. typedef struct {
  82262. FLAC__MetadataType type;
  82263. /**< The type of the metadata block; used determine which member of the
  82264. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  82265. * then \a data.unknown must be used. */
  82266. FLAC__bool is_last;
  82267. /**< \c true if this metadata block is the last, else \a false */
  82268. unsigned length;
  82269. /**< Length, in bytes, of the block data as it appears in the stream. */
  82270. union {
  82271. FLAC__StreamMetadata_StreamInfo stream_info;
  82272. FLAC__StreamMetadata_Padding padding;
  82273. FLAC__StreamMetadata_Application application;
  82274. FLAC__StreamMetadata_SeekTable seek_table;
  82275. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  82276. FLAC__StreamMetadata_CueSheet cue_sheet;
  82277. FLAC__StreamMetadata_Picture picture;
  82278. FLAC__StreamMetadata_Unknown unknown;
  82279. } data;
  82280. /**< Polymorphic block data; use the \a type value to determine which
  82281. * to use. */
  82282. } FLAC__StreamMetadata;
  82283. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  82284. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  82285. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  82286. /** The total stream length of a metadata block header in bytes. */
  82287. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  82288. /*****************************************************************************/
  82289. /*****************************************************************************
  82290. *
  82291. * Utility functions
  82292. *
  82293. *****************************************************************************/
  82294. /** Tests that a sample rate is valid for FLAC.
  82295. *
  82296. * \param sample_rate The sample rate to test for compliance.
  82297. * \retval FLAC__bool
  82298. * \c true if the given sample rate conforms to the specification, else
  82299. * \c false.
  82300. */
  82301. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  82302. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  82303. * for valid sample rates are slightly more complex since the rate has to
  82304. * be expressible completely in the frame header.
  82305. *
  82306. * \param sample_rate The sample rate to test for compliance.
  82307. * \retval FLAC__bool
  82308. * \c true if the given sample rate conforms to the specification for the
  82309. * subset, else \c false.
  82310. */
  82311. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  82312. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  82313. * comment specification.
  82314. *
  82315. * Vorbis comment names must be composed only of characters from
  82316. * [0x20-0x3C,0x3E-0x7D].
  82317. *
  82318. * \param name A NUL-terminated string to be checked.
  82319. * \assert
  82320. * \code name != NULL \endcode
  82321. * \retval FLAC__bool
  82322. * \c false if entry name is illegal, else \c true.
  82323. */
  82324. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  82325. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  82326. * comment specification.
  82327. *
  82328. * Vorbis comment values must be valid UTF-8 sequences.
  82329. *
  82330. * \param value A string to be checked.
  82331. * \param length A the length of \a value in bytes. May be
  82332. * \c (unsigned)(-1) to indicate that \a value is a plain
  82333. * UTF-8 NUL-terminated string.
  82334. * \assert
  82335. * \code value != NULL \endcode
  82336. * \retval FLAC__bool
  82337. * \c false if entry name is illegal, else \c true.
  82338. */
  82339. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  82340. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  82341. * comment specification.
  82342. *
  82343. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  82344. * 'value' must be legal according to
  82345. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  82346. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  82347. *
  82348. * \param entry An entry to be checked.
  82349. * \param length The length of \a entry in bytes.
  82350. * \assert
  82351. * \code value != NULL \endcode
  82352. * \retval FLAC__bool
  82353. * \c false if entry name is illegal, else \c true.
  82354. */
  82355. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  82356. /** Check a seek table to see if it conforms to the FLAC specification.
  82357. * See the format specification for limits on the contents of the
  82358. * seek table.
  82359. *
  82360. * \param seek_table A pointer to a seek table to be checked.
  82361. * \assert
  82362. * \code seek_table != NULL \endcode
  82363. * \retval FLAC__bool
  82364. * \c false if seek table is illegal, else \c true.
  82365. */
  82366. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  82367. /** Sort a seek table's seek points according to the format specification.
  82368. * This includes a "unique-ification" step to remove duplicates, i.e.
  82369. * seek points with identical \a sample_number values. Duplicate seek
  82370. * points are converted into placeholder points and sorted to the end of
  82371. * the table.
  82372. *
  82373. * \param seek_table A pointer to a seek table to be sorted.
  82374. * \assert
  82375. * \code seek_table != NULL \endcode
  82376. * \retval unsigned
  82377. * The number of duplicate seek points converted into placeholders.
  82378. */
  82379. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  82380. /** Check a cue sheet to see if it conforms to the FLAC specification.
  82381. * See the format specification for limits on the contents of the
  82382. * cue sheet.
  82383. *
  82384. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  82385. * \param check_cd_da_subset If \c true, check CUESHEET against more
  82386. * stringent requirements for a CD-DA (audio) disc.
  82387. * \param violation Address of a pointer to a string. If there is a
  82388. * violation, a pointer to a string explanation of the
  82389. * violation will be returned here. \a violation may be
  82390. * \c NULL if you don't need the returned string. Do not
  82391. * free the returned string; it will always point to static
  82392. * data.
  82393. * \assert
  82394. * \code cue_sheet != NULL \endcode
  82395. * \retval FLAC__bool
  82396. * \c false if cue sheet is illegal, else \c true.
  82397. */
  82398. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  82399. /** Check picture data to see if it conforms to the FLAC specification.
  82400. * See the format specification for limits on the contents of the
  82401. * PICTURE block.
  82402. *
  82403. * \param picture A pointer to existing picture data to be checked.
  82404. * \param violation Address of a pointer to a string. If there is a
  82405. * violation, a pointer to a string explanation of the
  82406. * violation will be returned here. \a violation may be
  82407. * \c NULL if you don't need the returned string. Do not
  82408. * free the returned string; it will always point to static
  82409. * data.
  82410. * \assert
  82411. * \code picture != NULL \endcode
  82412. * \retval FLAC__bool
  82413. * \c false if picture data is illegal, else \c true.
  82414. */
  82415. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  82416. /* \} */
  82417. #ifdef __cplusplus
  82418. }
  82419. #endif
  82420. #endif
  82421. /********* End of inlined file: format.h *********/
  82422. /********* Start of inlined file: metadata.h *********/
  82423. #ifndef FLAC__METADATA_H
  82424. #define FLAC__METADATA_H
  82425. #include <sys/types.h> /* for off_t */
  82426. /* --------------------------------------------------------------------
  82427. (For an example of how all these routines are used, see the source
  82428. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  82429. metaflac in src/metaflac/)
  82430. ------------------------------------------------------------------*/
  82431. /** \file include/FLAC/metadata.h
  82432. *
  82433. * \brief
  82434. * This module provides functions for creating and manipulating FLAC
  82435. * metadata blocks in memory, and three progressively more powerful
  82436. * interfaces for traversing and editing metadata in FLAC files.
  82437. *
  82438. * See the detailed documentation for each interface in the
  82439. * \link flac_metadata metadata \endlink module.
  82440. */
  82441. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  82442. * \ingroup flac
  82443. *
  82444. * \brief
  82445. * This module provides functions for creating and manipulating FLAC
  82446. * metadata blocks in memory, and three progressively more powerful
  82447. * interfaces for traversing and editing metadata in native FLAC files.
  82448. * Note that currently only the Chain interface (level 2) supports Ogg
  82449. * FLAC files, and it is read-only i.e. no writing back changed
  82450. * metadata to file.
  82451. *
  82452. * There are three metadata interfaces of increasing complexity:
  82453. *
  82454. * Level 0:
  82455. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  82456. * PICTURE blocks.
  82457. *
  82458. * Level 1:
  82459. * Read-write access to all metadata blocks. This level is write-
  82460. * efficient in most cases (more on this below), and uses less memory
  82461. * than level 2.
  82462. *
  82463. * Level 2:
  82464. * Read-write access to all metadata blocks. This level is write-
  82465. * efficient in all cases, but uses more memory since all metadata for
  82466. * the whole file is read into memory and manipulated before writing
  82467. * out again.
  82468. *
  82469. * What do we mean by efficient? Since FLAC metadata appears at the
  82470. * beginning of the file, when writing metadata back to a FLAC file
  82471. * it is possible to grow or shrink the metadata such that the entire
  82472. * file must be rewritten. However, if the size remains the same during
  82473. * changes or PADDING blocks are utilized, only the metadata needs to be
  82474. * overwritten, which is much faster.
  82475. *
  82476. * Efficient means the whole file is rewritten at most one time, and only
  82477. * when necessary. Level 1 is not efficient only in the case that you
  82478. * cause more than one metadata block to grow or shrink beyond what can
  82479. * be accomodated by padding. In this case you should probably use level
  82480. * 2, which allows you to edit all the metadata for a file in memory and
  82481. * write it out all at once.
  82482. *
  82483. * All levels know how to skip over and not disturb an ID3v2 tag at the
  82484. * front of the file.
  82485. *
  82486. * All levels access files via their filenames. In addition, level 2
  82487. * has additional alternative read and write functions that take an I/O
  82488. * handle and callbacks, for situations where access by filename is not
  82489. * possible.
  82490. *
  82491. * In addition to the three interfaces, this module defines functions for
  82492. * creating and manipulating various metadata objects in memory. As we see
  82493. * from the Format module, FLAC metadata blocks in memory are very primitive
  82494. * structures for storing information in an efficient way. Reading
  82495. * information from the structures is easy but creating or modifying them
  82496. * directly is more complex. The metadata object routines here facilitate
  82497. * this by taking care of the consistency and memory management drudgery.
  82498. *
  82499. * Unless you will be using the level 1 or 2 interfaces to modify existing
  82500. * metadata however, you will not probably not need these.
  82501. *
  82502. * From a dependency standpoint, none of the encoders or decoders require
  82503. * the metadata module. This is so that embedded users can strip out the
  82504. * metadata module from libFLAC to reduce the size and complexity.
  82505. */
  82506. #ifdef __cplusplus
  82507. extern "C" {
  82508. #endif
  82509. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  82510. * \ingroup flac_metadata
  82511. *
  82512. * \brief
  82513. * The level 0 interface consists of individual routines to read the
  82514. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  82515. * only a filename.
  82516. *
  82517. * They try to skip any ID3v2 tag at the head of the file.
  82518. *
  82519. * \{
  82520. */
  82521. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  82522. * will try to skip any ID3v2 tag at the head of the file.
  82523. *
  82524. * \param filename The path to the FLAC file to read.
  82525. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  82526. * FLAC__StreamMetadata is a simple structure with no
  82527. * memory allocation involved, you pass the address of
  82528. * an existing structure. It need not be initialized.
  82529. * \assert
  82530. * \code filename != NULL \endcode
  82531. * \code streaminfo != NULL \endcode
  82532. * \retval FLAC__bool
  82533. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  82534. * \c false if there was a memory allocation error, a file decoder error,
  82535. * or the file contained no STREAMINFO block. (A memory allocation error
  82536. * is possible because this function must set up a file decoder.)
  82537. */
  82538. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  82539. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  82540. * function will try to skip any ID3v2 tag at the head of the file.
  82541. *
  82542. * \param filename The path to the FLAC file to read.
  82543. * \param tags The address where the returned pointer will be
  82544. * stored. The \a tags object must be deleted by
  82545. * the caller using FLAC__metadata_object_delete().
  82546. * \assert
  82547. * \code filename != NULL \endcode
  82548. * \code tags != NULL \endcode
  82549. * \retval FLAC__bool
  82550. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  82551. * and \a *tags will be set to the address of the metadata structure.
  82552. * Returns \c false if there was a memory allocation error, a file
  82553. * decoder error, or the file contained no VORBIS_COMMENT block, and
  82554. * \a *tags will be set to \c NULL.
  82555. */
  82556. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  82557. /** Read the CUESHEET metadata block of the given FLAC file. This
  82558. * function will try to skip any ID3v2 tag at the head of the file.
  82559. *
  82560. * \param filename The path to the FLAC file to read.
  82561. * \param cuesheet The address where the returned pointer will be
  82562. * stored. The \a cuesheet object must be deleted by
  82563. * the caller using FLAC__metadata_object_delete().
  82564. * \assert
  82565. * \code filename != NULL \endcode
  82566. * \code cuesheet != NULL \endcode
  82567. * \retval FLAC__bool
  82568. * \c true if a valid CUESHEET block was read from \a filename,
  82569. * and \a *cuesheet will be set to the address of the metadata
  82570. * structure. Returns \c false if there was a memory allocation
  82571. * error, a file decoder error, or the file contained no CUESHEET
  82572. * block, and \a *cuesheet will be set to \c NULL.
  82573. */
  82574. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  82575. /** Read a PICTURE metadata block of the given FLAC file. This
  82576. * function will try to skip any ID3v2 tag at the head of the file.
  82577. * Since there can be more than one PICTURE block in a file, this
  82578. * function takes a number of parameters that act as constraints to
  82579. * the search. The PICTURE block with the largest area matching all
  82580. * the constraints will be returned, or \a *picture will be set to
  82581. * \c NULL if there was no such block.
  82582. *
  82583. * \param filename The path to the FLAC file to read.
  82584. * \param picture The address where the returned pointer will be
  82585. * stored. The \a picture object must be deleted by
  82586. * the caller using FLAC__metadata_object_delete().
  82587. * \param type The desired picture type. Use \c -1 to mean
  82588. * "any type".
  82589. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  82590. * string will be matched exactly. Use \c NULL to
  82591. * mean "any MIME type".
  82592. * \param description The desired description. The string will be
  82593. * matched exactly. Use \c NULL to mean "any
  82594. * description".
  82595. * \param max_width The maximum width in pixels desired. Use
  82596. * \c (unsigned)(-1) to mean "any width".
  82597. * \param max_height The maximum height in pixels desired. Use
  82598. * \c (unsigned)(-1) to mean "any height".
  82599. * \param max_depth The maximum color depth in bits-per-pixel desired.
  82600. * Use \c (unsigned)(-1) to mean "any depth".
  82601. * \param max_colors The maximum number of colors desired. Use
  82602. * \c (unsigned)(-1) to mean "any number of colors".
  82603. * \assert
  82604. * \code filename != NULL \endcode
  82605. * \code picture != NULL \endcode
  82606. * \retval FLAC__bool
  82607. * \c true if a valid PICTURE block was read from \a filename,
  82608. * and \a *picture will be set to the address of the metadata
  82609. * structure. Returns \c false if there was a memory allocation
  82610. * error, a file decoder error, or the file contained no PICTURE
  82611. * block, and \a *picture will be set to \c NULL.
  82612. */
  82613. 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);
  82614. /* \} */
  82615. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  82616. * \ingroup flac_metadata
  82617. *
  82618. * \brief
  82619. * The level 1 interface provides read-write access to FLAC file metadata and
  82620. * operates directly on the FLAC file.
  82621. *
  82622. * The general usage of this interface is:
  82623. *
  82624. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  82625. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  82626. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  82627. * see if the file is writable, or only read access is allowed.
  82628. * - Use FLAC__metadata_simple_iterator_next() and
  82629. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  82630. * This is does not read the actual blocks themselves.
  82631. * FLAC__metadata_simple_iterator_next() is relatively fast.
  82632. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  82633. * forward from the front of the file.
  82634. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  82635. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  82636. * the current iterator position. The returned object is yours to modify
  82637. * and free.
  82638. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  82639. * back. You must have write permission to the original file. Make sure to
  82640. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  82641. * below.
  82642. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  82643. * Use the object creation functions from
  82644. * \link flac_metadata_object here \endlink to generate new objects.
  82645. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  82646. * currently referred to by the iterator, or replace it with padding.
  82647. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  82648. * finished.
  82649. *
  82650. * \note
  82651. * The FLAC file remains open the whole time between
  82652. * FLAC__metadata_simple_iterator_init() and
  82653. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  82654. * the file during this time.
  82655. *
  82656. * \note
  82657. * Do not modify the \a is_last, \a length, or \a type fields of returned
  82658. * FLAC__StreamMetadata objects. These are managed automatically.
  82659. *
  82660. * \note
  82661. * If any of the modification functions
  82662. * (FLAC__metadata_simple_iterator_set_block(),
  82663. * FLAC__metadata_simple_iterator_delete_block(),
  82664. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  82665. * you should delete the iterator as it may no longer be valid.
  82666. *
  82667. * \{
  82668. */
  82669. struct FLAC__Metadata_SimpleIterator;
  82670. /** The opaque structure definition for the level 1 iterator type.
  82671. * See the
  82672. * \link flac_metadata_level1 metadata level 1 module \endlink
  82673. * for a detailed description.
  82674. */
  82675. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  82676. /** Status type for FLAC__Metadata_SimpleIterator.
  82677. *
  82678. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  82679. */
  82680. typedef enum {
  82681. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  82682. /**< The iterator is in the normal OK state */
  82683. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  82684. /**< The data passed into a function violated the function's usage criteria */
  82685. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  82686. /**< The iterator could not open the target file */
  82687. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  82688. /**< The iterator could not find the FLAC signature at the start of the file */
  82689. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  82690. /**< The iterator tried to write to a file that was not writable */
  82691. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  82692. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  82693. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  82694. /**< The iterator encountered an error while reading the FLAC file */
  82695. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  82696. /**< The iterator encountered an error while seeking in the FLAC file */
  82697. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  82698. /**< The iterator encountered an error while writing the FLAC file */
  82699. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  82700. /**< The iterator encountered an error renaming the FLAC file */
  82701. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  82702. /**< The iterator encountered an error removing the temporary file */
  82703. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  82704. /**< Memory allocation failed */
  82705. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  82706. /**< The caller violated an assertion or an unexpected error occurred */
  82707. } FLAC__Metadata_SimpleIteratorStatus;
  82708. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  82709. *
  82710. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  82711. * will give the string equivalent. The contents should not be modified.
  82712. */
  82713. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  82714. /** Create a new iterator instance.
  82715. *
  82716. * \retval FLAC__Metadata_SimpleIterator*
  82717. * \c NULL if there was an error allocating memory, else the new instance.
  82718. */
  82719. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  82720. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  82721. *
  82722. * \param iterator A pointer to an existing iterator.
  82723. * \assert
  82724. * \code iterator != NULL \endcode
  82725. */
  82726. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  82727. /** Get the current status of the iterator. Call this after a function
  82728. * returns \c false to get the reason for the error. Also resets the status
  82729. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  82730. *
  82731. * \param iterator A pointer to an existing iterator.
  82732. * \assert
  82733. * \code iterator != NULL \endcode
  82734. * \retval FLAC__Metadata_SimpleIteratorStatus
  82735. * The current status of the iterator.
  82736. */
  82737. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  82738. /** Initialize the iterator to point to the first metadata block in the
  82739. * given FLAC file.
  82740. *
  82741. * \param iterator A pointer to an existing iterator.
  82742. * \param filename The path to the FLAC file.
  82743. * \param read_only If \c true, the FLAC file will be opened
  82744. * in read-only mode; if \c false, the FLAC
  82745. * file will be opened for edit even if no
  82746. * edits are performed.
  82747. * \param preserve_file_stats If \c true, the owner and modification
  82748. * time will be preserved even if the FLAC
  82749. * file is written to.
  82750. * \assert
  82751. * \code iterator != NULL \endcode
  82752. * \code filename != NULL \endcode
  82753. * \retval FLAC__bool
  82754. * \c false if a memory allocation error occurs, the file can't be
  82755. * opened, or another error occurs, else \c true.
  82756. */
  82757. 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);
  82758. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  82759. * FLAC__metadata_simple_iterator_set_block() and
  82760. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  82761. *
  82762. * \param iterator A pointer to an existing iterator.
  82763. * \assert
  82764. * \code iterator != NULL \endcode
  82765. * \retval FLAC__bool
  82766. * See above.
  82767. */
  82768. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  82769. /** Moves the iterator forward one metadata block, returning \c false if
  82770. * already at the end.
  82771. *
  82772. * \param iterator A pointer to an existing initialized iterator.
  82773. * \assert
  82774. * \code iterator != NULL \endcode
  82775. * \a iterator has been successfully initialized with
  82776. * FLAC__metadata_simple_iterator_init()
  82777. * \retval FLAC__bool
  82778. * \c false if already at the last metadata block of the chain, else
  82779. * \c true.
  82780. */
  82781. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  82782. /** Moves the iterator backward one metadata block, returning \c false if
  82783. * already at the beginning.
  82784. *
  82785. * \param iterator A pointer to an existing initialized iterator.
  82786. * \assert
  82787. * \code iterator != NULL \endcode
  82788. * \a iterator has been successfully initialized with
  82789. * FLAC__metadata_simple_iterator_init()
  82790. * \retval FLAC__bool
  82791. * \c false if already at the first metadata block of the chain, else
  82792. * \c true.
  82793. */
  82794. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  82795. /** Returns a flag telling if the current metadata block is the last.
  82796. *
  82797. * \param iterator A pointer to an existing initialized iterator.
  82798. * \assert
  82799. * \code iterator != NULL \endcode
  82800. * \a iterator has been successfully initialized with
  82801. * FLAC__metadata_simple_iterator_init()
  82802. * \retval FLAC__bool
  82803. * \c true if the current metadata block is the last in the file,
  82804. * else \c false.
  82805. */
  82806. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  82807. /** Get the offset of the metadata block at the current position. This
  82808. * avoids reading the actual block data which can save time for large
  82809. * blocks.
  82810. *
  82811. * \param iterator A pointer to an existing initialized iterator.
  82812. * \assert
  82813. * \code iterator != NULL \endcode
  82814. * \a iterator has been successfully initialized with
  82815. * FLAC__metadata_simple_iterator_init()
  82816. * \retval off_t
  82817. * The offset of the metadata block at the current iterator position.
  82818. * This is the byte offset relative to the beginning of the file of
  82819. * the current metadata block's header.
  82820. */
  82821. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  82822. /** Get the type of the metadata block at the current position. This
  82823. * avoids reading the actual block data which can save time for large
  82824. * blocks.
  82825. *
  82826. * \param iterator A pointer to an existing initialized iterator.
  82827. * \assert
  82828. * \code iterator != NULL \endcode
  82829. * \a iterator has been successfully initialized with
  82830. * FLAC__metadata_simple_iterator_init()
  82831. * \retval FLAC__MetadataType
  82832. * The type of the metadata block at the current iterator position.
  82833. */
  82834. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  82835. /** Get the length of the metadata block at the current position. This
  82836. * avoids reading the actual block data which can save time for large
  82837. * blocks.
  82838. *
  82839. * \param iterator A pointer to an existing initialized iterator.
  82840. * \assert
  82841. * \code iterator != NULL \endcode
  82842. * \a iterator has been successfully initialized with
  82843. * FLAC__metadata_simple_iterator_init()
  82844. * \retval unsigned
  82845. * The length of the metadata block at the current iterator position.
  82846. * The is same length as that in the
  82847. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  82848. * i.e. the length of the metadata body that follows the header.
  82849. */
  82850. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  82851. /** Get the application ID of the \c APPLICATION block at the current
  82852. * position. This avoids reading the actual block data which can save
  82853. * time for large blocks.
  82854. *
  82855. * \param iterator A pointer to an existing initialized iterator.
  82856. * \param id A pointer to a buffer of at least \c 4 bytes where
  82857. * the ID will be stored.
  82858. * \assert
  82859. * \code iterator != NULL \endcode
  82860. * \code id != NULL \endcode
  82861. * \a iterator has been successfully initialized with
  82862. * FLAC__metadata_simple_iterator_init()
  82863. * \retval FLAC__bool
  82864. * \c true if the ID was successfully read, else \c false, in which
  82865. * case you should check FLAC__metadata_simple_iterator_status() to
  82866. * find out why. If the status is
  82867. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  82868. * current metadata block is not an \c APPLICATION block. Otherwise
  82869. * if the status is
  82870. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  82871. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  82872. * occurred and the iterator can no longer be used.
  82873. */
  82874. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  82875. /** Get the metadata block at the current position. You can modify the
  82876. * block but must use FLAC__metadata_simple_iterator_set_block() to
  82877. * write it back to the FLAC file.
  82878. *
  82879. * You must call FLAC__metadata_object_delete() on the returned object
  82880. * when you are finished with it.
  82881. *
  82882. * \param iterator A pointer to an existing initialized iterator.
  82883. * \assert
  82884. * \code iterator != NULL \endcode
  82885. * \a iterator has been successfully initialized with
  82886. * FLAC__metadata_simple_iterator_init()
  82887. * \retval FLAC__StreamMetadata*
  82888. * The current metadata block, or \c NULL if there was a memory
  82889. * allocation error.
  82890. */
  82891. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  82892. /** Write a block back to the FLAC file. This function tries to be
  82893. * as efficient as possible; how the block is actually written is
  82894. * shown by the following:
  82895. *
  82896. * Existing block is a STREAMINFO block and the new block is a
  82897. * STREAMINFO block: the new block is written in place. Make sure
  82898. * you know what you're doing when changing the values of a
  82899. * STREAMINFO block.
  82900. *
  82901. * Existing block is a STREAMINFO block and the new block is a
  82902. * not a STREAMINFO block: this is an error since the first block
  82903. * must be a STREAMINFO block. Returns \c false without altering the
  82904. * file.
  82905. *
  82906. * Existing block is not a STREAMINFO block and the new block is a
  82907. * STREAMINFO block: this is an error since there may be only one
  82908. * STREAMINFO block. Returns \c false without altering the file.
  82909. *
  82910. * Existing block and new block are the same length: the existing
  82911. * block will be replaced by the new block, written in place.
  82912. *
  82913. * Existing block is longer than new block: if use_padding is \c true,
  82914. * the existing block will be overwritten in place with the new
  82915. * block followed by a PADDING block, if possible, to make the total
  82916. * size the same as the existing block. Remember that a padding
  82917. * block requires at least four bytes so if the difference in size
  82918. * between the new block and existing block is less than that, the
  82919. * entire file will have to be rewritten, using the new block's
  82920. * exact size. If use_padding is \c false, the entire file will be
  82921. * rewritten, replacing the existing block by the new block.
  82922. *
  82923. * Existing block is shorter than new block: if use_padding is \c true,
  82924. * the function will try and expand the new block into the following
  82925. * PADDING block, if it exists and doing so won't shrink the PADDING
  82926. * block to less than 4 bytes. If there is no following PADDING
  82927. * block, or it will shrink to less than 4 bytes, or use_padding is
  82928. * \c false, the entire file is rewritten, replacing the existing block
  82929. * with the new block. Note that in this case any following PADDING
  82930. * block is preserved as is.
  82931. *
  82932. * After writing the block, the iterator will remain in the same
  82933. * place, i.e. pointing to the new block.
  82934. *
  82935. * \param iterator A pointer to an existing initialized iterator.
  82936. * \param block The block to set.
  82937. * \param use_padding See above.
  82938. * \assert
  82939. * \code iterator != NULL \endcode
  82940. * \a iterator has been successfully initialized with
  82941. * FLAC__metadata_simple_iterator_init()
  82942. * \code block != NULL \endcode
  82943. * \retval FLAC__bool
  82944. * \c true if successful, else \c false.
  82945. */
  82946. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  82947. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  82948. * except that instead of writing over an existing block, it appends
  82949. * a block after the existing block. \a use_padding is again used to
  82950. * tell the function to try an expand into following padding in an
  82951. * attempt to avoid rewriting the entire file.
  82952. *
  82953. * This function will fail and return \c false if given a STREAMINFO
  82954. * block.
  82955. *
  82956. * After writing the block, the iterator will be pointing to the
  82957. * new block.
  82958. *
  82959. * \param iterator A pointer to an existing initialized iterator.
  82960. * \param block The block to set.
  82961. * \param use_padding See above.
  82962. * \assert
  82963. * \code iterator != NULL \endcode
  82964. * \a iterator has been successfully initialized with
  82965. * FLAC__metadata_simple_iterator_init()
  82966. * \code block != NULL \endcode
  82967. * \retval FLAC__bool
  82968. * \c true if successful, else \c false.
  82969. */
  82970. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  82971. /** Deletes the block at the current position. This will cause the
  82972. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  82973. * in which case the block will be replaced by an equal-sized PADDING
  82974. * block. The iterator will be left pointing to the block before the
  82975. * one just deleted.
  82976. *
  82977. * You may not delete the STREAMINFO block.
  82978. *
  82979. * \param iterator A pointer to an existing initialized iterator.
  82980. * \param use_padding See above.
  82981. * \assert
  82982. * \code iterator != NULL \endcode
  82983. * \a iterator has been successfully initialized with
  82984. * FLAC__metadata_simple_iterator_init()
  82985. * \retval FLAC__bool
  82986. * \c true if successful, else \c false.
  82987. */
  82988. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  82989. /* \} */
  82990. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  82991. * \ingroup flac_metadata
  82992. *
  82993. * \brief
  82994. * The level 2 interface provides read-write access to FLAC file metadata;
  82995. * all metadata is read into memory, operated on in memory, and then written
  82996. * to file, which is more efficient than level 1 when editing multiple blocks.
  82997. *
  82998. * Currently Ogg FLAC is supported for read only, via
  82999. * FLAC__metadata_chain_read_ogg() but a subsequent
  83000. * FLAC__metadata_chain_write() will fail.
  83001. *
  83002. * The general usage of this interface is:
  83003. *
  83004. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  83005. * linked list of FLAC metadata blocks.
  83006. * - Read all metadata into the the chain from a FLAC file using
  83007. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  83008. * check the status.
  83009. * - Optionally, consolidate the padding using
  83010. * FLAC__metadata_chain_merge_padding() or
  83011. * FLAC__metadata_chain_sort_padding().
  83012. * - Create a new iterator using FLAC__metadata_iterator_new()
  83013. * - Initialize the iterator to point to the first element in the chain
  83014. * using FLAC__metadata_iterator_init()
  83015. * - Traverse the chain using FLAC__metadata_iterator_next and
  83016. * FLAC__metadata_iterator_prev().
  83017. * - Get a block for reading or modification using
  83018. * FLAC__metadata_iterator_get_block(). The pointer to the object
  83019. * inside the chain is returned, so the block is yours to modify.
  83020. * Changes will be reflected in the FLAC file when you write the
  83021. * chain. You can also add and delete blocks (see functions below).
  83022. * - When done, write out the chain using FLAC__metadata_chain_write().
  83023. * Make sure to read the whole comment to the function below.
  83024. * - Delete the chain using FLAC__metadata_chain_delete().
  83025. *
  83026. * \note
  83027. * Even though the FLAC file is not open while the chain is being
  83028. * manipulated, you must not alter the file externally during
  83029. * this time. The chain assumes the FLAC file will not change
  83030. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  83031. * and FLAC__metadata_chain_write().
  83032. *
  83033. * \note
  83034. * Do not modify the is_last, length, or type fields of returned
  83035. * FLAC__StreamMetadata objects. These are managed automatically.
  83036. *
  83037. * \note
  83038. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  83039. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  83040. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  83041. * become owned by the chain and they will be deleted when the chain is
  83042. * deleted.
  83043. *
  83044. * \{
  83045. */
  83046. struct FLAC__Metadata_Chain;
  83047. /** The opaque structure definition for the level 2 chain type.
  83048. */
  83049. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  83050. struct FLAC__Metadata_Iterator;
  83051. /** The opaque structure definition for the level 2 iterator type.
  83052. */
  83053. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  83054. typedef enum {
  83055. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  83056. /**< The chain is in the normal OK state */
  83057. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  83058. /**< The data passed into a function violated the function's usage criteria */
  83059. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  83060. /**< The chain could not open the target file */
  83061. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  83062. /**< The chain could not find the FLAC signature at the start of the file */
  83063. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  83064. /**< The chain tried to write to a file that was not writable */
  83065. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  83066. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  83067. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  83068. /**< The chain encountered an error while reading the FLAC file */
  83069. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  83070. /**< The chain encountered an error while seeking in the FLAC file */
  83071. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  83072. /**< The chain encountered an error while writing the FLAC file */
  83073. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  83074. /**< The chain encountered an error renaming the FLAC file */
  83075. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  83076. /**< The chain encountered an error removing the temporary file */
  83077. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  83078. /**< Memory allocation failed */
  83079. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  83080. /**< The caller violated an assertion or an unexpected error occurred */
  83081. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  83082. /**< One or more of the required callbacks was NULL */
  83083. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  83084. /**< FLAC__metadata_chain_write() was called on a chain read by
  83085. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83086. * or
  83087. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  83088. * was called on a chain read by
  83089. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83090. * Matching read/write methods must always be used. */
  83091. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  83092. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  83093. * chain write requires a tempfile; use
  83094. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  83095. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  83096. * called when the chain write does not require a tempfile; use
  83097. * FLAC__metadata_chain_write_with_callbacks() instead.
  83098. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  83099. * before writing via callbacks. */
  83100. } FLAC__Metadata_ChainStatus;
  83101. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  83102. *
  83103. * Using a FLAC__Metadata_ChainStatus as the index to this array
  83104. * will give the string equivalent. The contents should not be modified.
  83105. */
  83106. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  83107. /*********** FLAC__Metadata_Chain ***********/
  83108. /** Create a new chain instance.
  83109. *
  83110. * \retval FLAC__Metadata_Chain*
  83111. * \c NULL if there was an error allocating memory, else the new instance.
  83112. */
  83113. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  83114. /** Free a chain instance. Deletes the object pointed to by \a chain.
  83115. *
  83116. * \param chain A pointer to an existing chain.
  83117. * \assert
  83118. * \code chain != NULL \endcode
  83119. */
  83120. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  83121. /** Get the current status of the chain. Call this after a function
  83122. * returns \c false to get the reason for the error. Also resets the
  83123. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  83124. *
  83125. * \param chain A pointer to an existing chain.
  83126. * \assert
  83127. * \code chain != NULL \endcode
  83128. * \retval FLAC__Metadata_ChainStatus
  83129. * The current status of the chain.
  83130. */
  83131. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  83132. /** Read all metadata from a FLAC file into the chain.
  83133. *
  83134. * \param chain A pointer to an existing chain.
  83135. * \param filename The path to the FLAC file to read.
  83136. * \assert
  83137. * \code chain != NULL \endcode
  83138. * \code filename != NULL \endcode
  83139. * \retval FLAC__bool
  83140. * \c true if a valid list of metadata blocks was read from
  83141. * \a filename, else \c false. On failure, check the status with
  83142. * FLAC__metadata_chain_status().
  83143. */
  83144. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  83145. /** Read all metadata from an Ogg FLAC file into the chain.
  83146. *
  83147. * \note Ogg FLAC metadata data writing is not supported yet and
  83148. * FLAC__metadata_chain_write() will fail.
  83149. *
  83150. * \param chain A pointer to an existing chain.
  83151. * \param filename The path to the Ogg FLAC file to read.
  83152. * \assert
  83153. * \code chain != NULL \endcode
  83154. * \code filename != NULL \endcode
  83155. * \retval FLAC__bool
  83156. * \c true if a valid list of metadata blocks was read from
  83157. * \a filename, else \c false. On failure, check the status with
  83158. * FLAC__metadata_chain_status().
  83159. */
  83160. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  83161. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  83162. *
  83163. * The \a handle need only be open for reading, but must be seekable.
  83164. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83165. * for Windows).
  83166. *
  83167. * \param chain A pointer to an existing chain.
  83168. * \param handle The I/O handle of the FLAC stream to read. The
  83169. * handle will NOT be closed after the metadata is read;
  83170. * that is the duty of the caller.
  83171. * \param callbacks
  83172. * A set of callbacks to use for I/O. The mandatory
  83173. * callbacks are \a read, \a seek, and \a tell.
  83174. * \assert
  83175. * \code chain != NULL \endcode
  83176. * \retval FLAC__bool
  83177. * \c true if a valid list of metadata blocks was read from
  83178. * \a handle, else \c false. On failure, check the status with
  83179. * FLAC__metadata_chain_status().
  83180. */
  83181. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83182. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  83183. *
  83184. * The \a handle need only be open for reading, but must be seekable.
  83185. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83186. * for Windows).
  83187. *
  83188. * \note Ogg FLAC metadata data writing is not supported yet and
  83189. * FLAC__metadata_chain_write() will fail.
  83190. *
  83191. * \param chain A pointer to an existing chain.
  83192. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  83193. * handle will NOT be closed after the metadata is read;
  83194. * that is the duty of the caller.
  83195. * \param callbacks
  83196. * A set of callbacks to use for I/O. The mandatory
  83197. * callbacks are \a read, \a seek, and \a tell.
  83198. * \assert
  83199. * \code chain != NULL \endcode
  83200. * \retval FLAC__bool
  83201. * \c true if a valid list of metadata blocks was read from
  83202. * \a handle, else \c false. On failure, check the status with
  83203. * FLAC__metadata_chain_status().
  83204. */
  83205. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83206. /** Checks if writing the given chain would require the use of a
  83207. * temporary file, or if it could be written in place.
  83208. *
  83209. * Under certain conditions, padding can be utilized so that writing
  83210. * edited metadata back to the FLAC file does not require rewriting the
  83211. * entire file. If rewriting is required, then a temporary workfile is
  83212. * required. When writing metadata using callbacks, you must check
  83213. * this function to know whether to call
  83214. * FLAC__metadata_chain_write_with_callbacks() or
  83215. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  83216. * writing with FLAC__metadata_chain_write(), the temporary file is
  83217. * handled internally.
  83218. *
  83219. * \param chain A pointer to an existing chain.
  83220. * \param use_padding
  83221. * Whether or not padding will be allowed to be used
  83222. * during the write. The value of \a use_padding given
  83223. * here must match the value later passed to
  83224. * FLAC__metadata_chain_write_with_callbacks() or
  83225. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  83226. * \assert
  83227. * \code chain != NULL \endcode
  83228. * \retval FLAC__bool
  83229. * \c true if writing the current chain would require a tempfile, or
  83230. * \c false if metadata can be written in place.
  83231. */
  83232. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  83233. /** Write all metadata out to the FLAC file. This function tries to be as
  83234. * efficient as possible; how the metadata is actually written is shown by
  83235. * the following:
  83236. *
  83237. * If the current chain is the same size as the existing metadata, the new
  83238. * data is written in place.
  83239. *
  83240. * If the current chain is longer than the existing metadata, and
  83241. * \a use_padding is \c true, and the last block is a PADDING block of
  83242. * sufficient length, the function will truncate the final padding block
  83243. * so that the overall size of the metadata is the same as the existing
  83244. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  83245. * the above conditions are met, the entire FLAC file must be rewritten.
  83246. * If you want to use padding this way it is a good idea to call
  83247. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  83248. * amount of padding to work with, unless you need to preserve ordering
  83249. * of the PADDING blocks for some reason.
  83250. *
  83251. * If the current chain is shorter than the existing metadata, and
  83252. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  83253. * is extended to make the overall size the same as the existing data. If
  83254. * \a use_padding is \c true and the last block is not a PADDING block, a new
  83255. * PADDING block is added to the end of the new data to make it the same
  83256. * size as the existing data (if possible, see the note to
  83257. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  83258. * and the new data is written in place. If none of the above apply or
  83259. * \a use_padding is \c false, the entire FLAC file is rewritten.
  83260. *
  83261. * If \a preserve_file_stats is \c true, the owner and modification time will
  83262. * be preserved even if the FLAC file is written.
  83263. *
  83264. * For this write function to be used, the chain must have been read with
  83265. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  83266. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  83267. *
  83268. * \param chain A pointer to an existing chain.
  83269. * \param use_padding See above.
  83270. * \param preserve_file_stats See above.
  83271. * \assert
  83272. * \code chain != NULL \endcode
  83273. * \retval FLAC__bool
  83274. * \c true if the write succeeded, else \c false. On failure,
  83275. * check the status with FLAC__metadata_chain_status().
  83276. */
  83277. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  83278. /** Write all metadata out to a FLAC stream via callbacks.
  83279. *
  83280. * (See FLAC__metadata_chain_write() for the details on how padding is
  83281. * used to write metadata in place if possible.)
  83282. *
  83283. * The \a handle must be open for updating and be seekable. The
  83284. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  83285. * for Windows).
  83286. *
  83287. * For this write function to be used, the chain must have been read with
  83288. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83289. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83290. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83291. * \c false.
  83292. *
  83293. * \param chain A pointer to an existing chain.
  83294. * \param use_padding See FLAC__metadata_chain_write()
  83295. * \param handle The I/O handle of the FLAC stream to write. The
  83296. * handle will NOT be closed after the metadata is
  83297. * written; that is the duty of the caller.
  83298. * \param callbacks A set of callbacks to use for I/O. The mandatory
  83299. * callbacks are \a write and \a seek.
  83300. * \assert
  83301. * \code chain != NULL \endcode
  83302. * \retval FLAC__bool
  83303. * \c true if the write succeeded, else \c false. On failure,
  83304. * check the status with FLAC__metadata_chain_status().
  83305. */
  83306. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83307. /** Write all metadata out to a FLAC stream via callbacks.
  83308. *
  83309. * (See FLAC__metadata_chain_write() for the details on how padding is
  83310. * used to write metadata in place if possible.)
  83311. *
  83312. * This version of the write-with-callbacks function must be used when
  83313. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  83314. * this function, you must supply an I/O handle corresponding to the
  83315. * FLAC file to edit, and a temporary handle to which the new FLAC
  83316. * file will be written. It is the caller's job to move this temporary
  83317. * FLAC file on top of the original FLAC file to complete the metadata
  83318. * edit.
  83319. *
  83320. * The \a handle must be open for reading and be seekable. The
  83321. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83322. * for Windows).
  83323. *
  83324. * The \a temp_handle must be open for writing. The
  83325. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  83326. * for Windows). It should be an empty stream, or at least positioned
  83327. * at the start-of-file (in which case it is the caller's duty to
  83328. * truncate it on return).
  83329. *
  83330. * For this write function to be used, the chain must have been read with
  83331. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83332. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83333. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83334. * \c true.
  83335. *
  83336. * \param chain A pointer to an existing chain.
  83337. * \param use_padding See FLAC__metadata_chain_write()
  83338. * \param handle The I/O handle of the original FLAC stream to read.
  83339. * The handle will NOT be closed after the metadata is
  83340. * written; that is the duty of the caller.
  83341. * \param callbacks A set of callbacks to use for I/O on \a handle.
  83342. * The mandatory callbacks are \a read, \a seek, and
  83343. * \a eof.
  83344. * \param temp_handle The I/O handle of the FLAC stream to write. The
  83345. * handle will NOT be closed after the metadata is
  83346. * written; that is the duty of the caller.
  83347. * \param temp_callbacks
  83348. * A set of callbacks to use for I/O on temp_handle.
  83349. * The only mandatory callback is \a write.
  83350. * \assert
  83351. * \code chain != NULL \endcode
  83352. * \retval FLAC__bool
  83353. * \c true if the write succeeded, else \c false. On failure,
  83354. * check the status with FLAC__metadata_chain_status().
  83355. */
  83356. 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);
  83357. /** Merge adjacent PADDING blocks into a single block.
  83358. *
  83359. * \note This function does not write to the FLAC file, it only
  83360. * modifies the chain.
  83361. *
  83362. * \warning Any iterator on the current chain will become invalid after this
  83363. * call. You should delete the iterator and get a new one.
  83364. *
  83365. * \param chain A pointer to an existing chain.
  83366. * \assert
  83367. * \code chain != NULL \endcode
  83368. */
  83369. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  83370. /** This function will move all PADDING blocks to the end on the metadata,
  83371. * then merge them into a single block.
  83372. *
  83373. * \note This function does not write to the FLAC file, it only
  83374. * modifies the chain.
  83375. *
  83376. * \warning Any iterator on the current chain will become invalid after this
  83377. * call. You should delete the iterator and get a new one.
  83378. *
  83379. * \param chain A pointer to an existing chain.
  83380. * \assert
  83381. * \code chain != NULL \endcode
  83382. */
  83383. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  83384. /*********** FLAC__Metadata_Iterator ***********/
  83385. /** Create a new iterator instance.
  83386. *
  83387. * \retval FLAC__Metadata_Iterator*
  83388. * \c NULL if there was an error allocating memory, else the new instance.
  83389. */
  83390. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  83391. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  83392. *
  83393. * \param iterator A pointer to an existing iterator.
  83394. * \assert
  83395. * \code iterator != NULL \endcode
  83396. */
  83397. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  83398. /** Initialize the iterator to point to the first metadata block in the
  83399. * given chain.
  83400. *
  83401. * \param iterator A pointer to an existing iterator.
  83402. * \param chain A pointer to an existing and initialized (read) chain.
  83403. * \assert
  83404. * \code iterator != NULL \endcode
  83405. * \code chain != NULL \endcode
  83406. */
  83407. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  83408. /** Moves the iterator forward one metadata block, returning \c false if
  83409. * already at the end.
  83410. *
  83411. * \param iterator A pointer to an existing initialized iterator.
  83412. * \assert
  83413. * \code iterator != NULL \endcode
  83414. * \a iterator has been successfully initialized with
  83415. * FLAC__metadata_iterator_init()
  83416. * \retval FLAC__bool
  83417. * \c false if already at the last metadata block of the chain, else
  83418. * \c true.
  83419. */
  83420. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  83421. /** Moves the iterator backward one metadata block, returning \c false if
  83422. * already at the beginning.
  83423. *
  83424. * \param iterator A pointer to an existing initialized iterator.
  83425. * \assert
  83426. * \code iterator != NULL \endcode
  83427. * \a iterator has been successfully initialized with
  83428. * FLAC__metadata_iterator_init()
  83429. * \retval FLAC__bool
  83430. * \c false if already at the first metadata block of the chain, else
  83431. * \c true.
  83432. */
  83433. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  83434. /** Get the type of the metadata block at the current position.
  83435. *
  83436. * \param iterator A pointer to an existing initialized iterator.
  83437. * \assert
  83438. * \code iterator != NULL \endcode
  83439. * \a iterator has been successfully initialized with
  83440. * FLAC__metadata_iterator_init()
  83441. * \retval FLAC__MetadataType
  83442. * The type of the metadata block at the current iterator position.
  83443. */
  83444. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  83445. /** Get the metadata block at the current position. You can modify
  83446. * the block in place but must write the chain before the changes
  83447. * are reflected to the FLAC file. You do not need to call
  83448. * FLAC__metadata_iterator_set_block() to reflect the changes;
  83449. * the pointer returned by FLAC__metadata_iterator_get_block()
  83450. * points directly into the chain.
  83451. *
  83452. * \warning
  83453. * Do not call FLAC__metadata_object_delete() on the returned object;
  83454. * to delete a block use FLAC__metadata_iterator_delete_block().
  83455. *
  83456. * \param iterator A pointer to an existing initialized iterator.
  83457. * \assert
  83458. * \code iterator != NULL \endcode
  83459. * \a iterator has been successfully initialized with
  83460. * FLAC__metadata_iterator_init()
  83461. * \retval FLAC__StreamMetadata*
  83462. * The current metadata block.
  83463. */
  83464. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  83465. /** Set the metadata block at the current position, replacing the existing
  83466. * block. The new block passed in becomes owned by the chain and it will be
  83467. * deleted when the chain is deleted.
  83468. *
  83469. * \param iterator A pointer to an existing initialized iterator.
  83470. * \param block A pointer to a metadata block.
  83471. * \assert
  83472. * \code iterator != NULL \endcode
  83473. * \a iterator has been successfully initialized with
  83474. * FLAC__metadata_iterator_init()
  83475. * \code block != NULL \endcode
  83476. * \retval FLAC__bool
  83477. * \c false if the conditions in the above description are not met, or
  83478. * a memory allocation error occurs, otherwise \c true.
  83479. */
  83480. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  83481. /** Removes the current block from the chain. If \a replace_with_padding is
  83482. * \c true, the block will instead be replaced with a padding block of equal
  83483. * size. You can not delete the STREAMINFO block. The iterator will be
  83484. * left pointing to the block before the one just "deleted", even if
  83485. * \a replace_with_padding is \c true.
  83486. *
  83487. * \param iterator A pointer to an existing initialized iterator.
  83488. * \param replace_with_padding See above.
  83489. * \assert
  83490. * \code iterator != NULL \endcode
  83491. * \a iterator has been successfully initialized with
  83492. * FLAC__metadata_iterator_init()
  83493. * \retval FLAC__bool
  83494. * \c false if the conditions in the above description are not met,
  83495. * otherwise \c true.
  83496. */
  83497. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  83498. /** Insert a new block before the current block. You cannot insert a block
  83499. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  83500. * as there can be only one, the one that already exists at the head when you
  83501. * read in a chain. The chain takes ownership of the new block and it will be
  83502. * deleted when the chain is deleted. The iterator will be left pointing to
  83503. * the new block.
  83504. *
  83505. * \param iterator A pointer to an existing initialized iterator.
  83506. * \param block A pointer to a metadata block to insert.
  83507. * \assert
  83508. * \code iterator != NULL \endcode
  83509. * \a iterator has been successfully initialized with
  83510. * FLAC__metadata_iterator_init()
  83511. * \retval FLAC__bool
  83512. * \c false if the conditions in the above description are not met, or
  83513. * a memory allocation error occurs, otherwise \c true.
  83514. */
  83515. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  83516. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  83517. * block as there can be only one, the one that already exists at the head when
  83518. * you read in a chain. The chain takes ownership of the new block and it will
  83519. * be deleted when the chain is deleted. The iterator will be left pointing to
  83520. * the new block.
  83521. *
  83522. * \param iterator A pointer to an existing initialized iterator.
  83523. * \param block A pointer to a metadata block to insert.
  83524. * \assert
  83525. * \code iterator != NULL \endcode
  83526. * \a iterator has been successfully initialized with
  83527. * FLAC__metadata_iterator_init()
  83528. * \retval FLAC__bool
  83529. * \c false if the conditions in the above description are not met, or
  83530. * a memory allocation error occurs, otherwise \c true.
  83531. */
  83532. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  83533. /* \} */
  83534. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  83535. * \ingroup flac_metadata
  83536. *
  83537. * \brief
  83538. * This module contains methods for manipulating FLAC metadata objects.
  83539. *
  83540. * Since many are variable length we have to be careful about the memory
  83541. * management. We decree that all pointers to data in the object are
  83542. * owned by the object and memory-managed by the object.
  83543. *
  83544. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  83545. * functions to create all instances. When using the
  83546. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  83547. * \a copy to \c true to have the function make it's own copy of the data, or
  83548. * to \c false to give the object ownership of your data. In the latter case
  83549. * your pointer must be freeable by free() and will be free()d when the object
  83550. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  83551. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  83552. * the length argument is 0 and the \a copy argument is \c false.
  83553. *
  83554. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  83555. * will return \c NULL in the case of a memory allocation error, otherwise a new
  83556. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  83557. * case of a memory allocation error.
  83558. *
  83559. * We don't have the convenience of C++ here, so note that the library relies
  83560. * on you to keep the types straight. In other words, if you pass, for
  83561. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  83562. * FLAC__metadata_object_application_set_data(), you will get an assertion
  83563. * failure.
  83564. *
  83565. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  83566. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  83567. * toward the length or stored in the stream, but it can make working with plain
  83568. * comments (those that don't contain embedded-NULs in the value) easier.
  83569. * Entries passed into these functions have trailing NULs added if missing, and
  83570. * returned entries are guaranteed to have a trailing NUL.
  83571. *
  83572. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  83573. * comment entry/name/value will first validate that it complies with the Vorbis
  83574. * comment specification and return false if it does not.
  83575. *
  83576. * There is no need to recalculate the length field on metadata blocks you
  83577. * have modified. They will be calculated automatically before they are
  83578. * written back to a file.
  83579. *
  83580. * \{
  83581. */
  83582. /** Create a new metadata object instance of the given type.
  83583. *
  83584. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  83585. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  83586. * the vendor string set (but zero comments).
  83587. *
  83588. * Do not pass in a value greater than or equal to
  83589. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  83590. * doing.
  83591. *
  83592. * \param type Type of object to create
  83593. * \retval FLAC__StreamMetadata*
  83594. * \c NULL if there was an error allocating memory or the type code is
  83595. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  83596. */
  83597. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  83598. /** Create a copy of an existing metadata object.
  83599. *
  83600. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  83601. * object is also copied. The caller takes ownership of the new block and
  83602. * is responsible for freeing it with FLAC__metadata_object_delete().
  83603. *
  83604. * \param object Pointer to object to copy.
  83605. * \assert
  83606. * \code object != NULL \endcode
  83607. * \retval FLAC__StreamMetadata*
  83608. * \c NULL if there was an error allocating memory, else the new instance.
  83609. */
  83610. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  83611. /** Free a metadata object. Deletes the object pointed to by \a object.
  83612. *
  83613. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  83614. * object is also deleted.
  83615. *
  83616. * \param object A pointer to an existing object.
  83617. * \assert
  83618. * \code object != NULL \endcode
  83619. */
  83620. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  83621. /** Compares two metadata objects.
  83622. *
  83623. * The compare is "deep", i.e. dynamically allocated data within the
  83624. * object is also compared.
  83625. *
  83626. * \param block1 A pointer to an existing object.
  83627. * \param block2 A pointer to an existing object.
  83628. * \assert
  83629. * \code block1 != NULL \endcode
  83630. * \code block2 != NULL \endcode
  83631. * \retval FLAC__bool
  83632. * \c true if objects are identical, else \c false.
  83633. */
  83634. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  83635. /** Sets the application data of an APPLICATION block.
  83636. *
  83637. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  83638. * takes ownership of the pointer. The existing data will be freed if this
  83639. * function is successful, otherwise the original data will remain if \a copy
  83640. * is \c true and malloc() fails.
  83641. *
  83642. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  83643. *
  83644. * \param object A pointer to an existing APPLICATION object.
  83645. * \param data A pointer to the data to set.
  83646. * \param length The length of \a data in bytes.
  83647. * \param copy See above.
  83648. * \assert
  83649. * \code object != NULL \endcode
  83650. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  83651. * \code (data != NULL && length > 0) ||
  83652. * (data == NULL && length == 0 && copy == false) \endcode
  83653. * \retval FLAC__bool
  83654. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83655. */
  83656. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  83657. /** Resize the seekpoint array.
  83658. *
  83659. * If the size shrinks, elements will truncated; if it grows, new placeholder
  83660. * points will be added to the end.
  83661. *
  83662. * \param object A pointer to an existing SEEKTABLE object.
  83663. * \param new_num_points The desired length of the array; may be \c 0.
  83664. * \assert
  83665. * \code object != NULL \endcode
  83666. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83667. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  83668. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  83669. * \retval FLAC__bool
  83670. * \c false if memory allocation error, else \c true.
  83671. */
  83672. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  83673. /** Set a seekpoint in a seektable.
  83674. *
  83675. * \param object A pointer to an existing SEEKTABLE object.
  83676. * \param point_num Index into seekpoint array to set.
  83677. * \param point The point to set.
  83678. * \assert
  83679. * \code object != NULL \endcode
  83680. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83681. * \code object->data.seek_table.num_points > point_num \endcode
  83682. */
  83683. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  83684. /** Insert a seekpoint into a seektable.
  83685. *
  83686. * \param object A pointer to an existing SEEKTABLE object.
  83687. * \param point_num Index into seekpoint array to set.
  83688. * \param point The point to set.
  83689. * \assert
  83690. * \code object != NULL \endcode
  83691. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83692. * \code object->data.seek_table.num_points >= point_num \endcode
  83693. * \retval FLAC__bool
  83694. * \c false if memory allocation error, else \c true.
  83695. */
  83696. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  83697. /** Delete a seekpoint from a seektable.
  83698. *
  83699. * \param object A pointer to an existing SEEKTABLE object.
  83700. * \param point_num Index into seekpoint array to set.
  83701. * \assert
  83702. * \code object != NULL \endcode
  83703. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83704. * \code object->data.seek_table.num_points > point_num \endcode
  83705. * \retval FLAC__bool
  83706. * \c false if memory allocation error, else \c true.
  83707. */
  83708. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  83709. /** Check a seektable to see if it conforms to the FLAC specification.
  83710. * See the format specification for limits on the contents of the
  83711. * seektable.
  83712. *
  83713. * \param object A pointer to an existing SEEKTABLE object.
  83714. * \assert
  83715. * \code object != NULL \endcode
  83716. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83717. * \retval FLAC__bool
  83718. * \c false if seek table is illegal, else \c true.
  83719. */
  83720. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  83721. /** Append a number of placeholder points to the end of a seek table.
  83722. *
  83723. * \note
  83724. * As with the other ..._seektable_template_... functions, you should
  83725. * call FLAC__metadata_object_seektable_template_sort() when finished
  83726. * to make the seek table legal.
  83727. *
  83728. * \param object A pointer to an existing SEEKTABLE object.
  83729. * \param num The number of placeholder points to append.
  83730. * \assert
  83731. * \code object != NULL \endcode
  83732. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83733. * \retval FLAC__bool
  83734. * \c false if memory allocation fails, else \c true.
  83735. */
  83736. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  83737. /** Append a specific seek point template to the end of a seek table.
  83738. *
  83739. * \note
  83740. * As with the other ..._seektable_template_... functions, you should
  83741. * call FLAC__metadata_object_seektable_template_sort() when finished
  83742. * to make the seek table legal.
  83743. *
  83744. * \param object A pointer to an existing SEEKTABLE object.
  83745. * \param sample_number The sample number of the seek point template.
  83746. * \assert
  83747. * \code object != NULL \endcode
  83748. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83749. * \retval FLAC__bool
  83750. * \c false if memory allocation fails, else \c true.
  83751. */
  83752. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  83753. /** Append specific seek point templates to the end of a seek table.
  83754. *
  83755. * \note
  83756. * As with the other ..._seektable_template_... functions, you should
  83757. * call FLAC__metadata_object_seektable_template_sort() when finished
  83758. * to make the seek table legal.
  83759. *
  83760. * \param object A pointer to an existing SEEKTABLE object.
  83761. * \param sample_numbers An array of sample numbers for the seek points.
  83762. * \param num The number of seek point templates to append.
  83763. * \assert
  83764. * \code object != NULL \endcode
  83765. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83766. * \retval FLAC__bool
  83767. * \c false if memory allocation fails, else \c true.
  83768. */
  83769. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  83770. /** Append a set of evenly-spaced seek point templates to the end of a
  83771. * seek table.
  83772. *
  83773. * \note
  83774. * As with the other ..._seektable_template_... functions, you should
  83775. * call FLAC__metadata_object_seektable_template_sort() when finished
  83776. * to make the seek table legal.
  83777. *
  83778. * \param object A pointer to an existing SEEKTABLE object.
  83779. * \param num The number of placeholder points to append.
  83780. * \param total_samples The total number of samples to be encoded;
  83781. * the seekpoints will be spaced approximately
  83782. * \a total_samples / \a num samples apart.
  83783. * \assert
  83784. * \code object != NULL \endcode
  83785. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83786. * \code total_samples > 0 \endcode
  83787. * \retval FLAC__bool
  83788. * \c false if memory allocation fails, else \c true.
  83789. */
  83790. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  83791. /** Append a set of evenly-spaced seek point templates to the end of a
  83792. * seek table.
  83793. *
  83794. * \note
  83795. * As with the other ..._seektable_template_... functions, you should
  83796. * call FLAC__metadata_object_seektable_template_sort() when finished
  83797. * to make the seek table legal.
  83798. *
  83799. * \param object A pointer to an existing SEEKTABLE object.
  83800. * \param samples The number of samples apart to space the placeholder
  83801. * points. The first point will be at sample \c 0, the
  83802. * second at sample \a samples, then 2*\a samples, and
  83803. * so on. As long as \a samples and \a total_samples
  83804. * are greater than \c 0, there will always be at least
  83805. * one seekpoint at sample \c 0.
  83806. * \param total_samples The total number of samples to be encoded;
  83807. * the seekpoints will be spaced
  83808. * \a samples samples apart.
  83809. * \assert
  83810. * \code object != NULL \endcode
  83811. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83812. * \code samples > 0 \endcode
  83813. * \code total_samples > 0 \endcode
  83814. * \retval FLAC__bool
  83815. * \c false if memory allocation fails, else \c true.
  83816. */
  83817. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  83818. /** Sort a seek table's seek points according to the format specification,
  83819. * removing duplicates.
  83820. *
  83821. * \param object A pointer to a seek table to be sorted.
  83822. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  83823. * If \c true, duplicates are deleted and the seek table is
  83824. * shrunk appropriately; the number of placeholder points
  83825. * present in the seek table will be the same after the call
  83826. * as before.
  83827. * \assert
  83828. * \code object != NULL \endcode
  83829. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83830. * \retval FLAC__bool
  83831. * \c false if realloc() fails, else \c true.
  83832. */
  83833. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  83834. /** Sets the vendor string in a VORBIS_COMMENT block.
  83835. *
  83836. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83837. * one already.
  83838. *
  83839. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83840. * takes ownership of the \c entry.entry pointer.
  83841. *
  83842. * \note If this function returns \c false, the caller still owns the
  83843. * pointer.
  83844. *
  83845. * \param object A pointer to an existing VORBIS_COMMENT object.
  83846. * \param entry The entry to set the vendor string to.
  83847. * \param copy See above.
  83848. * \assert
  83849. * \code object != NULL \endcode
  83850. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83851. * \code (entry.entry != NULL && entry.length > 0) ||
  83852. * (entry.entry == NULL && entry.length == 0) \endcode
  83853. * \retval FLAC__bool
  83854. * \c false if memory allocation fails or \a entry does not comply with the
  83855. * Vorbis comment specification, else \c true.
  83856. */
  83857. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83858. /** Resize the comment array.
  83859. *
  83860. * If the size shrinks, elements will truncated; if it grows, new empty
  83861. * fields will be added to the end.
  83862. *
  83863. * \param object A pointer to an existing VORBIS_COMMENT object.
  83864. * \param new_num_comments The desired length of the array; may be \c 0.
  83865. * \assert
  83866. * \code object != NULL \endcode
  83867. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83868. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  83869. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  83870. * \retval FLAC__bool
  83871. * \c false if memory allocation fails, else \c true.
  83872. */
  83873. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  83874. /** Sets a comment in a VORBIS_COMMENT block.
  83875. *
  83876. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83877. * one already.
  83878. *
  83879. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83880. * takes ownership of the \c entry.entry pointer.
  83881. *
  83882. * \note If this function returns \c false, the caller still owns the
  83883. * pointer.
  83884. *
  83885. * \param object A pointer to an existing VORBIS_COMMENT object.
  83886. * \param comment_num Index into comment array to set.
  83887. * \param entry The entry to set the comment to.
  83888. * \param copy See above.
  83889. * \assert
  83890. * \code object != NULL \endcode
  83891. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83892. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  83893. * \code (entry.entry != NULL && entry.length > 0) ||
  83894. * (entry.entry == NULL && entry.length == 0) \endcode
  83895. * \retval FLAC__bool
  83896. * \c false if memory allocation fails or \a entry does not comply with the
  83897. * Vorbis comment specification, else \c true.
  83898. */
  83899. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83900. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  83901. *
  83902. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83903. * one already.
  83904. *
  83905. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83906. * takes ownership of the \c entry.entry pointer.
  83907. *
  83908. * \note If this function returns \c false, the caller still owns the
  83909. * pointer.
  83910. *
  83911. * \param object A pointer to an existing VORBIS_COMMENT object.
  83912. * \param comment_num The index at which to insert the comment. The comments
  83913. * at and after \a comment_num move right one position.
  83914. * To append a comment to the end, set \a comment_num to
  83915. * \c object->data.vorbis_comment.num_comments .
  83916. * \param entry The comment to insert.
  83917. * \param copy See above.
  83918. * \assert
  83919. * \code object != NULL \endcode
  83920. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83921. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  83922. * \code (entry.entry != NULL && entry.length > 0) ||
  83923. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83924. * \retval FLAC__bool
  83925. * \c false if memory allocation fails or \a entry does not comply with the
  83926. * Vorbis comment specification, else \c true.
  83927. */
  83928. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83929. /** Appends a comment to a VORBIS_COMMENT block.
  83930. *
  83931. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83932. * one already.
  83933. *
  83934. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83935. * takes ownership of the \c entry.entry pointer.
  83936. *
  83937. * \note If this function returns \c false, the caller still owns the
  83938. * pointer.
  83939. *
  83940. * \param object A pointer to an existing VORBIS_COMMENT object.
  83941. * \param entry The comment to insert.
  83942. * \param copy See above.
  83943. * \assert
  83944. * \code object != NULL \endcode
  83945. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83946. * \code (entry.entry != NULL && entry.length > 0) ||
  83947. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83948. * \retval FLAC__bool
  83949. * \c false if memory allocation fails or \a entry does not comply with the
  83950. * Vorbis comment specification, else \c true.
  83951. */
  83952. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83953. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  83954. *
  83955. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83956. * one already.
  83957. *
  83958. * Depending on the the value of \a all, either all or just the first comment
  83959. * whose field name(s) match the given entry's name will be replaced by the
  83960. * given entry. If no comments match, \a entry will simply be appended.
  83961. *
  83962. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83963. * takes ownership of the \c entry.entry pointer.
  83964. *
  83965. * \note If this function returns \c false, the caller still owns the
  83966. * pointer.
  83967. *
  83968. * \param object A pointer to an existing VORBIS_COMMENT object.
  83969. * \param entry The comment to insert.
  83970. * \param all If \c true, all comments whose field name matches
  83971. * \a entry's field name will be removed, and \a entry will
  83972. * be inserted at the position of the first matching
  83973. * comment. If \c false, only the first comment whose
  83974. * field name matches \a entry's field name will be
  83975. * replaced with \a entry.
  83976. * \param copy See above.
  83977. * \assert
  83978. * \code object != NULL \endcode
  83979. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83980. * \code (entry.entry != NULL && entry.length > 0) ||
  83981. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83982. * \retval FLAC__bool
  83983. * \c false if memory allocation fails or \a entry does not comply with the
  83984. * Vorbis comment specification, else \c true.
  83985. */
  83986. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  83987. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  83988. *
  83989. * \param object A pointer to an existing VORBIS_COMMENT object.
  83990. * \param comment_num The index of the comment to delete.
  83991. * \assert
  83992. * \code object != NULL \endcode
  83993. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83994. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  83995. * \retval FLAC__bool
  83996. * \c false if realloc() fails, else \c true.
  83997. */
  83998. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  83999. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  84000. *
  84001. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  84002. * memory and shall be owned by the caller. For convenience the entry will
  84003. * have a terminating NUL.
  84004. *
  84005. * \param entry A pointer to a Vorbis comment entry. The entry's
  84006. * \c entry pointer should not point to allocated
  84007. * memory as it will be overwritten.
  84008. * \param field_name The field name in ASCII, \c NUL terminated.
  84009. * \param field_value The field value in UTF-8, \c NUL terminated.
  84010. * \assert
  84011. * \code entry != NULL \endcode
  84012. * \code field_name != NULL \endcode
  84013. * \code field_value != NULL \endcode
  84014. * \retval FLAC__bool
  84015. * \c false if malloc() fails, or if \a field_name or \a field_value does
  84016. * not comply with the Vorbis comment specification, else \c true.
  84017. */
  84018. 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);
  84019. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  84020. *
  84021. * The returned pointers to name and value will be allocated by malloc()
  84022. * and shall be owned by the caller.
  84023. *
  84024. * \param entry An existing Vorbis comment entry.
  84025. * \param field_name The address of where the returned pointer to the
  84026. * field name will be stored.
  84027. * \param field_value The address of where the returned pointer to the
  84028. * field value will be stored.
  84029. * \assert
  84030. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84031. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  84032. * \code field_name != NULL \endcode
  84033. * \code field_value != NULL \endcode
  84034. * \retval FLAC__bool
  84035. * \c false if memory allocation fails or \a entry does not comply with the
  84036. * Vorbis comment specification, else \c true.
  84037. */
  84038. 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);
  84039. /** Check if the given Vorbis comment entry's field name matches the given
  84040. * field name.
  84041. *
  84042. * \param entry An existing Vorbis comment entry.
  84043. * \param field_name The field name to check.
  84044. * \param field_name_length The length of \a field_name, not including the
  84045. * terminating \c NUL.
  84046. * \assert
  84047. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84048. * \retval FLAC__bool
  84049. * \c true if the field names match, else \c false
  84050. */
  84051. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  84052. /** Find a Vorbis comment with the given field name.
  84053. *
  84054. * The search begins at entry number \a offset; use an offset of 0 to
  84055. * search from the beginning of the comment array.
  84056. *
  84057. * \param object A pointer to an existing VORBIS_COMMENT object.
  84058. * \param offset The offset into the comment array from where to start
  84059. * the search.
  84060. * \param field_name The field name of the comment to find.
  84061. * \assert
  84062. * \code object != NULL \endcode
  84063. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84064. * \code field_name != NULL \endcode
  84065. * \retval int
  84066. * The offset in the comment array of the first comment whose field
  84067. * name matches \a field_name, or \c -1 if no match was found.
  84068. */
  84069. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  84070. /** Remove first Vorbis comment matching the given field name.
  84071. *
  84072. * \param object A pointer to an existing VORBIS_COMMENT object.
  84073. * \param field_name The field name of comment to delete.
  84074. * \assert
  84075. * \code object != NULL \endcode
  84076. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84077. * \retval int
  84078. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84079. * \c 1 for one matching entry deleted.
  84080. */
  84081. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  84082. /** Remove all Vorbis comments matching the given field name.
  84083. *
  84084. * \param object A pointer to an existing VORBIS_COMMENT object.
  84085. * \param field_name The field name of comments to delete.
  84086. * \assert
  84087. * \code object != NULL \endcode
  84088. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84089. * \retval int
  84090. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84091. * else the number of matching entries deleted.
  84092. */
  84093. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  84094. /** Create a new CUESHEET track instance.
  84095. *
  84096. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  84097. *
  84098. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84099. * \c NULL if there was an error allocating memory, else the new instance.
  84100. */
  84101. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  84102. /** Create a copy of an existing CUESHEET track object.
  84103. *
  84104. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84105. * object is also copied. The caller takes ownership of the new object and
  84106. * is responsible for freeing it with
  84107. * FLAC__metadata_object_cuesheet_track_delete().
  84108. *
  84109. * \param object Pointer to object to copy.
  84110. * \assert
  84111. * \code object != NULL \endcode
  84112. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84113. * \c NULL if there was an error allocating memory, else the new instance.
  84114. */
  84115. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  84116. /** Delete a CUESHEET track object
  84117. *
  84118. * \param object A pointer to an existing CUESHEET track object.
  84119. * \assert
  84120. * \code object != NULL \endcode
  84121. */
  84122. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  84123. /** Resize a track's index point array.
  84124. *
  84125. * If the size shrinks, elements will truncated; if it grows, new blank
  84126. * indices will be added to the end.
  84127. *
  84128. * \param object A pointer to an existing CUESHEET object.
  84129. * \param track_num The index of the track to modify. NOTE: this is not
  84130. * necessarily the same as the track's \a number field.
  84131. * \param new_num_indices The desired length of the array; may be \c 0.
  84132. * \assert
  84133. * \code object != NULL \endcode
  84134. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84135. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84136. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  84137. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  84138. * \retval FLAC__bool
  84139. * \c false if memory allocation error, else \c true.
  84140. */
  84141. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  84142. /** Insert an index point in a CUESHEET track at the given index.
  84143. *
  84144. * \param object A pointer to an existing CUESHEET object.
  84145. * \param track_num The index of the track to modify. NOTE: this is not
  84146. * necessarily the same as the track's \a number field.
  84147. * \param index_num The index into the track's index array at which to
  84148. * insert the index point. NOTE: this is not necessarily
  84149. * the same as the index point's \a number field. The
  84150. * indices at and after \a index_num move right one
  84151. * position. To append an index point to the end, set
  84152. * \a index_num to
  84153. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84154. * \param index The index point to insert.
  84155. * \assert
  84156. * \code object != NULL \endcode
  84157. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84158. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84159. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84160. * \retval FLAC__bool
  84161. * \c false if realloc() fails, else \c true.
  84162. */
  84163. 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);
  84164. /** Insert a blank index point in a CUESHEET track at the given index.
  84165. *
  84166. * A blank index point is one in which all field values are zero.
  84167. *
  84168. * \param object A pointer to an existing CUESHEET object.
  84169. * \param track_num The index of the track to modify. NOTE: this is not
  84170. * necessarily the same as the track's \a number field.
  84171. * \param index_num The index into the track's index array at which to
  84172. * insert the index point. NOTE: this is not necessarily
  84173. * the same as the index point's \a number field. The
  84174. * indices at and after \a index_num move right one
  84175. * position. To append an index point to the end, set
  84176. * \a index_num to
  84177. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84178. * \assert
  84179. * \code object != NULL \endcode
  84180. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84181. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84182. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84183. * \retval FLAC__bool
  84184. * \c false if realloc() fails, else \c true.
  84185. */
  84186. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84187. /** Delete an index point in a CUESHEET track at the given index.
  84188. *
  84189. * \param object A pointer to an existing CUESHEET object.
  84190. * \param track_num The index into the track array of the track to
  84191. * modify. NOTE: this is not necessarily the same
  84192. * as the track's \a number field.
  84193. * \param index_num The index into the track's index array of the index
  84194. * to delete. NOTE: this is not necessarily the same
  84195. * as the index's \a number field.
  84196. * \assert
  84197. * \code object != NULL \endcode
  84198. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84199. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84200. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  84201. * \retval FLAC__bool
  84202. * \c false if realloc() fails, else \c true.
  84203. */
  84204. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84205. /** Resize the track array.
  84206. *
  84207. * If the size shrinks, elements will truncated; if it grows, new blank
  84208. * tracks will be added to the end.
  84209. *
  84210. * \param object A pointer to an existing CUESHEET object.
  84211. * \param new_num_tracks The desired length of the array; may be \c 0.
  84212. * \assert
  84213. * \code object != NULL \endcode
  84214. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84215. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  84216. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  84217. * \retval FLAC__bool
  84218. * \c false if memory allocation error, else \c true.
  84219. */
  84220. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  84221. /** Sets a track in a CUESHEET block.
  84222. *
  84223. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84224. * takes ownership of the \a track pointer.
  84225. *
  84226. * \param object A pointer to an existing CUESHEET object.
  84227. * \param track_num Index into track array to set. NOTE: this is not
  84228. * necessarily the same as the track's \a number field.
  84229. * \param track The track to set the track to. You may safely pass in
  84230. * a const pointer if \a copy is \c true.
  84231. * \param copy See above.
  84232. * \assert
  84233. * \code object != NULL \endcode
  84234. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84235. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  84236. * \code (track->indices != NULL && track->num_indices > 0) ||
  84237. * (track->indices == NULL && track->num_indices == 0)
  84238. * \retval FLAC__bool
  84239. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84240. */
  84241. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84242. /** Insert a track in a CUESHEET block at the given index.
  84243. *
  84244. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84245. * takes ownership of the \a track pointer.
  84246. *
  84247. * \param object A pointer to an existing CUESHEET object.
  84248. * \param track_num The index at which to insert the track. NOTE: this
  84249. * is not necessarily the same as the track's \a number
  84250. * field. The tracks at and after \a track_num move right
  84251. * one position. To append a track to the end, set
  84252. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84253. * \param track The track to insert. You may safely pass in a const
  84254. * pointer if \a copy is \c true.
  84255. * \param copy See above.
  84256. * \assert
  84257. * \code object != NULL \endcode
  84258. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84259. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84260. * \retval FLAC__bool
  84261. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84262. */
  84263. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84264. /** Insert a blank track in a CUESHEET block at the given index.
  84265. *
  84266. * A blank track is one in which all field values are zero.
  84267. *
  84268. * \param object A pointer to an existing CUESHEET object.
  84269. * \param track_num The index at which to insert the track. NOTE: this
  84270. * is not necessarily the same as the track's \a number
  84271. * field. The tracks at and after \a track_num move right
  84272. * one position. To append a track to the end, set
  84273. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84274. * \assert
  84275. * \code object != NULL \endcode
  84276. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84277. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84278. * \retval FLAC__bool
  84279. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84280. */
  84281. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  84282. /** Delete a track in a CUESHEET block at the given index.
  84283. *
  84284. * \param object A pointer to an existing CUESHEET object.
  84285. * \param track_num The index into the track array of the track to
  84286. * delete. NOTE: this is not necessarily the same
  84287. * as the track's \a number field.
  84288. * \assert
  84289. * \code object != NULL \endcode
  84290. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84291. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84292. * \retval FLAC__bool
  84293. * \c false if realloc() fails, else \c true.
  84294. */
  84295. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  84296. /** Check a cue sheet to see if it conforms to the FLAC specification.
  84297. * See the format specification for limits on the contents of the
  84298. * cue sheet.
  84299. *
  84300. * \param object A pointer to an existing CUESHEET object.
  84301. * \param check_cd_da_subset If \c true, check CUESHEET against more
  84302. * stringent requirements for a CD-DA (audio) disc.
  84303. * \param violation Address of a pointer to a string. If there is a
  84304. * violation, a pointer to a string explanation of the
  84305. * violation will be returned here. \a violation may be
  84306. * \c NULL if you don't need the returned string. Do not
  84307. * free the returned string; it will always point to static
  84308. * data.
  84309. * \assert
  84310. * \code object != NULL \endcode
  84311. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84312. * \retval FLAC__bool
  84313. * \c false if cue sheet is illegal, else \c true.
  84314. */
  84315. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  84316. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  84317. * assumes the cue sheet corresponds to a CD; the result is undefined
  84318. * if the cuesheet's is_cd bit is not set.
  84319. *
  84320. * \param object A pointer to an existing CUESHEET object.
  84321. * \assert
  84322. * \code object != NULL \endcode
  84323. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84324. * \retval FLAC__uint32
  84325. * The unsigned integer representation of the CDDB/freedb ID
  84326. */
  84327. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  84328. /** Sets the MIME type of a PICTURE block.
  84329. *
  84330. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84331. * takes ownership of the pointer. The existing string will be freed if this
  84332. * function is successful, otherwise the original string will remain if \a copy
  84333. * is \c true and malloc() fails.
  84334. *
  84335. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  84336. *
  84337. * \param object A pointer to an existing PICTURE object.
  84338. * \param mime_type A pointer to the MIME type string. The string must be
  84339. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  84340. * is done.
  84341. * \param copy See above.
  84342. * \assert
  84343. * \code object != NULL \endcode
  84344. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84345. * \code (mime_type != NULL) \endcode
  84346. * \retval FLAC__bool
  84347. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84348. */
  84349. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  84350. /** Sets the description of a PICTURE block.
  84351. *
  84352. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84353. * takes ownership of the pointer. The existing string will be freed if this
  84354. * function is successful, otherwise the original string will remain if \a copy
  84355. * is \c true and malloc() fails.
  84356. *
  84357. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  84358. *
  84359. * \param object A pointer to an existing PICTURE object.
  84360. * \param description A pointer to the description string. The string must be
  84361. * valid UTF-8, NUL-terminated. No validation is done.
  84362. * \param copy See above.
  84363. * \assert
  84364. * \code object != NULL \endcode
  84365. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84366. * \code (description != NULL) \endcode
  84367. * \retval FLAC__bool
  84368. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84369. */
  84370. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  84371. /** Sets the picture data of a PICTURE block.
  84372. *
  84373. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  84374. * takes ownership of the pointer. Also sets the \a data_length field of the
  84375. * metadata object to what is passed in as the \a length parameter. The
  84376. * existing data will be freed if this function is successful, otherwise the
  84377. * original data and data_length will remain if \a copy is \c true and
  84378. * malloc() fails.
  84379. *
  84380. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  84381. *
  84382. * \param object A pointer to an existing PICTURE object.
  84383. * \param data A pointer to the data to set.
  84384. * \param length The length of \a data in bytes.
  84385. * \param copy See above.
  84386. * \assert
  84387. * \code object != NULL \endcode
  84388. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84389. * \code (data != NULL && length > 0) ||
  84390. * (data == NULL && length == 0 && copy == false) \endcode
  84391. * \retval FLAC__bool
  84392. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84393. */
  84394. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  84395. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  84396. * See the format specification for limits on the contents of the
  84397. * PICTURE block.
  84398. *
  84399. * \param object A pointer to existing PICTURE block to be checked.
  84400. * \param violation Address of a pointer to a string. If there is a
  84401. * violation, a pointer to a string explanation of the
  84402. * violation will be returned here. \a violation may be
  84403. * \c NULL if you don't need the returned string. Do not
  84404. * free the returned string; it will always point to static
  84405. * data.
  84406. * \assert
  84407. * \code object != NULL \endcode
  84408. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84409. * \retval FLAC__bool
  84410. * \c false if PICTURE block is illegal, else \c true.
  84411. */
  84412. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  84413. /* \} */
  84414. #ifdef __cplusplus
  84415. }
  84416. #endif
  84417. #endif
  84418. /********* End of inlined file: metadata.h *********/
  84419. /********* Start of inlined file: stream_decoder.h *********/
  84420. #ifndef FLAC__STREAM_DECODER_H
  84421. #define FLAC__STREAM_DECODER_H
  84422. #include <stdio.h> /* for FILE */
  84423. #ifdef __cplusplus
  84424. extern "C" {
  84425. #endif
  84426. /** \file include/FLAC/stream_decoder.h
  84427. *
  84428. * \brief
  84429. * This module contains the functions which implement the stream
  84430. * decoder.
  84431. *
  84432. * See the detailed documentation in the
  84433. * \link flac_stream_decoder stream decoder \endlink module.
  84434. */
  84435. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  84436. * \ingroup flac
  84437. *
  84438. * \brief
  84439. * This module describes the decoder layers provided by libFLAC.
  84440. *
  84441. * The stream decoder can be used to decode complete streams either from
  84442. * the client via callbacks, or directly from a file, depending on how
  84443. * it is initialized. When decoding via callbacks, the client provides
  84444. * callbacks for reading FLAC data and writing decoded samples, and
  84445. * handling metadata and errors. If the client also supplies seek-related
  84446. * callback, the decoder function for sample-accurate seeking within the
  84447. * FLAC input is also available. When decoding from a file, the client
  84448. * needs only supply a filename or open \c FILE* and write/metadata/error
  84449. * callbacks; the rest of the callbacks are supplied internally. For more
  84450. * info see the \link flac_stream_decoder stream decoder \endlink module.
  84451. */
  84452. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  84453. * \ingroup flac_decoder
  84454. *
  84455. * \brief
  84456. * This module contains the functions which implement the stream
  84457. * decoder.
  84458. *
  84459. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  84460. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84461. *
  84462. * The basic usage of this decoder is as follows:
  84463. * - The program creates an instance of a decoder using
  84464. * FLAC__stream_decoder_new().
  84465. * - The program overrides the default settings using
  84466. * FLAC__stream_decoder_set_*() functions.
  84467. * - The program initializes the instance to validate the settings and
  84468. * prepare for decoding using
  84469. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  84470. * or FLAC__stream_decoder_init_file() for native FLAC,
  84471. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  84472. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  84473. * - The program calls the FLAC__stream_decoder_process_*() functions
  84474. * to decode data, which subsequently calls the callbacks.
  84475. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  84476. * which flushes the input and output and resets the decoder to the
  84477. * uninitialized state.
  84478. * - The instance may be used again or deleted with
  84479. * FLAC__stream_decoder_delete().
  84480. *
  84481. * In more detail, the program will create a new instance by calling
  84482. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  84483. * functions to override the default decoder options, and call
  84484. * one of the FLAC__stream_decoder_init_*() functions.
  84485. *
  84486. * There are three initialization functions for native FLAC, one for
  84487. * setting up the decoder to decode FLAC data from the client via
  84488. * callbacks, and two for decoding directly from a FLAC file.
  84489. *
  84490. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  84491. * You must also supply several callbacks for handling I/O. Some (like
  84492. * seeking) are optional, depending on the capabilities of the input.
  84493. *
  84494. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  84495. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  84496. * \c FILE* or filename and fewer callbacks; the decoder will handle
  84497. * the other callbacks internally.
  84498. *
  84499. * There are three similarly-named init functions for decoding from Ogg
  84500. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  84501. * library has been built with Ogg support.
  84502. *
  84503. * Once the decoder is initialized, your program will call one of several
  84504. * functions to start the decoding process:
  84505. *
  84506. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  84507. * most one metadata block or audio frame and return, calling either the
  84508. * metadata callback or write callback, respectively, once. If the decoder
  84509. * loses sync it will return with only the error callback being called.
  84510. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  84511. * to process the stream from the current location and stop upon reaching
  84512. * the first audio frame. The client will get one metadata, write, or error
  84513. * callback per metadata block, audio frame, or sync error, respectively.
  84514. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  84515. * to process the stream from the current location until the read callback
  84516. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  84517. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  84518. * write, or error callback per metadata block, audio frame, or sync error,
  84519. * respectively.
  84520. *
  84521. * When the decoder has finished decoding (normally or through an abort),
  84522. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  84523. * ensures the decoder is in the correct state and frees memory. Then the
  84524. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  84525. * again to decode another stream.
  84526. *
  84527. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  84528. * At any point after the stream decoder has been initialized, the client can
  84529. * call this function to seek to an exact sample within the stream.
  84530. * Subsequently, the first time the write callback is called it will be
  84531. * passed a (possibly partial) block starting at that sample.
  84532. *
  84533. * If the client cannot seek via the callback interface provided, but still
  84534. * has another way of seeking, it can flush the decoder using
  84535. * FLAC__stream_decoder_flush() and start feeding data from the new position
  84536. * through the read callback.
  84537. *
  84538. * The stream decoder also provides MD5 signature checking. If this is
  84539. * turned on before initialization, FLAC__stream_decoder_finish() will
  84540. * report when the decoded MD5 signature does not match the one stored
  84541. * in the STREAMINFO block. MD5 checking is automatically turned off
  84542. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  84543. * in the STREAMINFO block or when a seek is attempted.
  84544. *
  84545. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  84546. * attention. By default, the decoder only calls the metadata_callback for
  84547. * the STREAMINFO block. These functions allow you to tell the decoder
  84548. * explicitly which blocks to parse and return via the metadata_callback
  84549. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  84550. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  84551. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  84552. * which blocks to return. Remember that metadata blocks can potentially
  84553. * be big (for example, cover art) so filtering out the ones you don't
  84554. * use can reduce the memory requirements of the decoder. Also note the
  84555. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  84556. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  84557. * filtering APPLICATION blocks based on the application ID.
  84558. *
  84559. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  84560. * they still can legally be filtered from the metadata_callback.
  84561. *
  84562. * \note
  84563. * The "set" functions may only be called when the decoder is in the
  84564. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  84565. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  84566. * before FLAC__stream_decoder_init_*(). If this is the case they will
  84567. * return \c true, otherwise \c false.
  84568. *
  84569. * \note
  84570. * FLAC__stream_decoder_finish() resets all settings to the constructor
  84571. * defaults, including the callbacks.
  84572. *
  84573. * \{
  84574. */
  84575. /** State values for a FLAC__StreamDecoder
  84576. *
  84577. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  84578. */
  84579. typedef enum {
  84580. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  84581. /**< The decoder is ready to search for metadata. */
  84582. FLAC__STREAM_DECODER_READ_METADATA,
  84583. /**< The decoder is ready to or is in the process of reading metadata. */
  84584. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  84585. /**< The decoder is ready to or is in the process of searching for the
  84586. * frame sync code.
  84587. */
  84588. FLAC__STREAM_DECODER_READ_FRAME,
  84589. /**< The decoder is ready to or is in the process of reading a frame. */
  84590. FLAC__STREAM_DECODER_END_OF_STREAM,
  84591. /**< The decoder has reached the end of the stream. */
  84592. FLAC__STREAM_DECODER_OGG_ERROR,
  84593. /**< An error occurred in the underlying Ogg layer. */
  84594. FLAC__STREAM_DECODER_SEEK_ERROR,
  84595. /**< An error occurred while seeking. The decoder must be flushed
  84596. * with FLAC__stream_decoder_flush() or reset with
  84597. * FLAC__stream_decoder_reset() before decoding can continue.
  84598. */
  84599. FLAC__STREAM_DECODER_ABORTED,
  84600. /**< The decoder was aborted by the read callback. */
  84601. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  84602. /**< An error occurred allocating memory. The decoder is in an invalid
  84603. * state and can no longer be used.
  84604. */
  84605. FLAC__STREAM_DECODER_UNINITIALIZED
  84606. /**< The decoder is in the uninitialized state; one of the
  84607. * FLAC__stream_decoder_init_*() functions must be called before samples
  84608. * can be processed.
  84609. */
  84610. } FLAC__StreamDecoderState;
  84611. /** Maps a FLAC__StreamDecoderState to a C string.
  84612. *
  84613. * Using a FLAC__StreamDecoderState as the index to this array
  84614. * will give the string equivalent. The contents should not be modified.
  84615. */
  84616. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  84617. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  84618. */
  84619. typedef enum {
  84620. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  84621. /**< Initialization was successful. */
  84622. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  84623. /**< The library was not compiled with support for the given container
  84624. * format.
  84625. */
  84626. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  84627. /**< A required callback was not supplied. */
  84628. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  84629. /**< An error occurred allocating memory. */
  84630. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  84631. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  84632. * FLAC__stream_decoder_init_ogg_file(). */
  84633. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  84634. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  84635. * already initialized, usually because
  84636. * FLAC__stream_decoder_finish() was not called.
  84637. */
  84638. } FLAC__StreamDecoderInitStatus;
  84639. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  84640. *
  84641. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  84642. * will give the string equivalent. The contents should not be modified.
  84643. */
  84644. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  84645. /** Return values for the FLAC__StreamDecoder read callback.
  84646. */
  84647. typedef enum {
  84648. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  84649. /**< The read was OK and decoding can continue. */
  84650. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  84651. /**< The read was attempted while at the end of the stream. Note that
  84652. * the client must only return this value when the read callback was
  84653. * called when already at the end of the stream. Otherwise, if the read
  84654. * itself moves to the end of the stream, the client should still return
  84655. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  84656. * the next read callback it should return
  84657. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  84658. * of \c 0.
  84659. */
  84660. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  84661. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84662. } FLAC__StreamDecoderReadStatus;
  84663. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  84664. *
  84665. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  84666. * will give the string equivalent. The contents should not be modified.
  84667. */
  84668. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  84669. /** Return values for the FLAC__StreamDecoder seek callback.
  84670. */
  84671. typedef enum {
  84672. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  84673. /**< The seek was OK and decoding can continue. */
  84674. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  84675. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84676. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84677. /**< Client does not support seeking. */
  84678. } FLAC__StreamDecoderSeekStatus;
  84679. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  84680. *
  84681. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  84682. * will give the string equivalent. The contents should not be modified.
  84683. */
  84684. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  84685. /** Return values for the FLAC__StreamDecoder tell callback.
  84686. */
  84687. typedef enum {
  84688. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  84689. /**< The tell was OK and decoding can continue. */
  84690. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  84691. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84692. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84693. /**< Client does not support telling the position. */
  84694. } FLAC__StreamDecoderTellStatus;
  84695. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  84696. *
  84697. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  84698. * will give the string equivalent. The contents should not be modified.
  84699. */
  84700. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  84701. /** Return values for the FLAC__StreamDecoder length callback.
  84702. */
  84703. typedef enum {
  84704. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  84705. /**< The length call was OK and decoding can continue. */
  84706. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  84707. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84708. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84709. /**< Client does not support reporting the length. */
  84710. } FLAC__StreamDecoderLengthStatus;
  84711. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  84712. *
  84713. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  84714. * will give the string equivalent. The contents should not be modified.
  84715. */
  84716. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  84717. /** Return values for the FLAC__StreamDecoder write callback.
  84718. */
  84719. typedef enum {
  84720. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  84721. /**< The write was OK and decoding can continue. */
  84722. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  84723. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84724. } FLAC__StreamDecoderWriteStatus;
  84725. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  84726. *
  84727. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  84728. * will give the string equivalent. The contents should not be modified.
  84729. */
  84730. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  84731. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  84732. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  84733. * all. The rest could be caused by bad sync (false synchronization on
  84734. * data that is not the start of a frame) or corrupted data. The error
  84735. * itself is the decoder's best guess at what happened assuming a correct
  84736. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  84737. * could be caused by a correct sync on the start of a frame, but some
  84738. * data in the frame header was corrupted. Or it could be the result of
  84739. * syncing on a point the stream that looked like the starting of a frame
  84740. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  84741. * could be because the decoder encountered a valid frame made by a future
  84742. * version of the encoder which it cannot parse, or because of a false
  84743. * sync making it appear as though an encountered frame was generated by
  84744. * a future encoder.
  84745. */
  84746. typedef enum {
  84747. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  84748. /**< An error in the stream caused the decoder to lose synchronization. */
  84749. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  84750. /**< The decoder encountered a corrupted frame header. */
  84751. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  84752. /**< The frame's data did not match the CRC in the footer. */
  84753. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  84754. /**< The decoder encountered reserved fields in use in the stream. */
  84755. } FLAC__StreamDecoderErrorStatus;
  84756. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  84757. *
  84758. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  84759. * will give the string equivalent. The contents should not be modified.
  84760. */
  84761. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  84762. /***********************************************************************
  84763. *
  84764. * class FLAC__StreamDecoder
  84765. *
  84766. ***********************************************************************/
  84767. struct FLAC__StreamDecoderProtected;
  84768. struct FLAC__StreamDecoderPrivate;
  84769. /** The opaque structure definition for the stream decoder type.
  84770. * See the \link flac_stream_decoder stream decoder module \endlink
  84771. * for a detailed description.
  84772. */
  84773. typedef struct {
  84774. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  84775. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  84776. } FLAC__StreamDecoder;
  84777. /** Signature for the read callback.
  84778. *
  84779. * A function pointer matching this signature must be passed to
  84780. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84781. * called when the decoder needs more input data. The address of the
  84782. * buffer to be filled is supplied, along with the number of bytes the
  84783. * buffer can hold. The callback may choose to supply less data and
  84784. * modify the byte count but must be careful not to overflow the buffer.
  84785. * The callback then returns a status code chosen from
  84786. * FLAC__StreamDecoderReadStatus.
  84787. *
  84788. * Here is an example of a read callback for stdio streams:
  84789. * \code
  84790. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  84791. * {
  84792. * FILE *file = ((MyClientData*)client_data)->file;
  84793. * if(*bytes > 0) {
  84794. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  84795. * if(ferror(file))
  84796. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  84797. * else if(*bytes == 0)
  84798. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  84799. * else
  84800. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  84801. * }
  84802. * else
  84803. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  84804. * }
  84805. * \endcode
  84806. *
  84807. * \note In general, FLAC__StreamDecoder functions which change the
  84808. * state should not be called on the \a decoder while in the callback.
  84809. *
  84810. * \param decoder The decoder instance calling the callback.
  84811. * \param buffer A pointer to a location for the callee to store
  84812. * data to be decoded.
  84813. * \param bytes A pointer to the size of the buffer. On entry
  84814. * to the callback, it contains the maximum number
  84815. * of bytes that may be stored in \a buffer. The
  84816. * callee must set it to the actual number of bytes
  84817. * stored (0 in case of error or end-of-stream) before
  84818. * returning.
  84819. * \param client_data The callee's client data set through
  84820. * FLAC__stream_decoder_init_*().
  84821. * \retval FLAC__StreamDecoderReadStatus
  84822. * The callee's return status. Note that the callback should return
  84823. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  84824. * zero bytes were read and there is no more data to be read.
  84825. */
  84826. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  84827. /** Signature for the seek callback.
  84828. *
  84829. * A function pointer matching this signature may be passed to
  84830. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84831. * called when the decoder needs to seek the input stream. The decoder
  84832. * will pass the absolute byte offset to seek to, 0 meaning the
  84833. * beginning of the stream.
  84834. *
  84835. * Here is an example of a seek callback for stdio streams:
  84836. * \code
  84837. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  84838. * {
  84839. * FILE *file = ((MyClientData*)client_data)->file;
  84840. * if(file == stdin)
  84841. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  84842. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  84843. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  84844. * else
  84845. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  84846. * }
  84847. * \endcode
  84848. *
  84849. * \note In general, FLAC__StreamDecoder functions which change the
  84850. * state should not be called on the \a decoder while in the callback.
  84851. *
  84852. * \param decoder The decoder instance calling the callback.
  84853. * \param absolute_byte_offset The offset from the beginning of the stream
  84854. * to seek to.
  84855. * \param client_data The callee's client data set through
  84856. * FLAC__stream_decoder_init_*().
  84857. * \retval FLAC__StreamDecoderSeekStatus
  84858. * The callee's return status.
  84859. */
  84860. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  84861. /** Signature for the tell callback.
  84862. *
  84863. * A function pointer matching this signature may be passed to
  84864. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84865. * called when the decoder wants to know the current position of the
  84866. * stream. The callback should return the byte offset from the
  84867. * beginning of the stream.
  84868. *
  84869. * Here is an example of a tell callback for stdio streams:
  84870. * \code
  84871. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  84872. * {
  84873. * FILE *file = ((MyClientData*)client_data)->file;
  84874. * off_t pos;
  84875. * if(file == stdin)
  84876. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  84877. * else if((pos = ftello(file)) < 0)
  84878. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  84879. * else {
  84880. * *absolute_byte_offset = (FLAC__uint64)pos;
  84881. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  84882. * }
  84883. * }
  84884. * \endcode
  84885. *
  84886. * \note In general, FLAC__StreamDecoder functions which change the
  84887. * state should not be called on the \a decoder while in the callback.
  84888. *
  84889. * \param decoder The decoder instance calling the callback.
  84890. * \param absolute_byte_offset A pointer to storage for the current offset
  84891. * from the beginning of the stream.
  84892. * \param client_data The callee's client data set through
  84893. * FLAC__stream_decoder_init_*().
  84894. * \retval FLAC__StreamDecoderTellStatus
  84895. * The callee's return status.
  84896. */
  84897. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  84898. /** Signature for the length callback.
  84899. *
  84900. * A function pointer matching this signature may be passed to
  84901. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84902. * called when the decoder wants to know the total length of the stream
  84903. * in bytes.
  84904. *
  84905. * Here is an example of a length callback for stdio streams:
  84906. * \code
  84907. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  84908. * {
  84909. * FILE *file = ((MyClientData*)client_data)->file;
  84910. * struct stat filestats;
  84911. *
  84912. * if(file == stdin)
  84913. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  84914. * else if(fstat(fileno(file), &filestats) != 0)
  84915. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  84916. * else {
  84917. * *stream_length = (FLAC__uint64)filestats.st_size;
  84918. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  84919. * }
  84920. * }
  84921. * \endcode
  84922. *
  84923. * \note In general, FLAC__StreamDecoder functions which change the
  84924. * state should not be called on the \a decoder while in the callback.
  84925. *
  84926. * \param decoder The decoder instance calling the callback.
  84927. * \param stream_length A pointer to storage for the length of the stream
  84928. * in bytes.
  84929. * \param client_data The callee's client data set through
  84930. * FLAC__stream_decoder_init_*().
  84931. * \retval FLAC__StreamDecoderLengthStatus
  84932. * The callee's return status.
  84933. */
  84934. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  84935. /** Signature for the EOF callback.
  84936. *
  84937. * A function pointer matching this signature may be passed to
  84938. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84939. * called when the decoder needs to know if the end of the stream has
  84940. * been reached.
  84941. *
  84942. * Here is an example of a EOF callback for stdio streams:
  84943. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  84944. * \code
  84945. * {
  84946. * FILE *file = ((MyClientData*)client_data)->file;
  84947. * return feof(file)? true : false;
  84948. * }
  84949. * \endcode
  84950. *
  84951. * \note In general, FLAC__StreamDecoder functions which change the
  84952. * state should not be called on the \a decoder while in the callback.
  84953. *
  84954. * \param decoder The decoder instance calling the callback.
  84955. * \param client_data The callee's client data set through
  84956. * FLAC__stream_decoder_init_*().
  84957. * \retval FLAC__bool
  84958. * \c true if the currently at the end of the stream, else \c false.
  84959. */
  84960. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  84961. /** Signature for the write callback.
  84962. *
  84963. * A function pointer matching this signature must be passed to one of
  84964. * the FLAC__stream_decoder_init_*() functions.
  84965. * The supplied function will be called when the decoder has decoded a
  84966. * single audio frame. The decoder will pass the frame metadata as well
  84967. * as an array of pointers (one for each channel) pointing to the
  84968. * decoded audio.
  84969. *
  84970. * \note In general, FLAC__StreamDecoder functions which change the
  84971. * state should not be called on the \a decoder while in the callback.
  84972. *
  84973. * \param decoder The decoder instance calling the callback.
  84974. * \param frame The description of the decoded frame. See
  84975. * FLAC__Frame.
  84976. * \param buffer An array of pointers to decoded channels of data.
  84977. * Each pointer will point to an array of signed
  84978. * samples of length \a frame->header.blocksize.
  84979. * Channels will be ordered according to the FLAC
  84980. * specification; see the documentation for the
  84981. * <A HREF="../format.html#frame_header">frame header</A>.
  84982. * \param client_data The callee's client data set through
  84983. * FLAC__stream_decoder_init_*().
  84984. * \retval FLAC__StreamDecoderWriteStatus
  84985. * The callee's return status.
  84986. */
  84987. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  84988. /** Signature for the metadata callback.
  84989. *
  84990. * A function pointer matching this signature must be passed to one of
  84991. * the FLAC__stream_decoder_init_*() functions.
  84992. * The supplied function will be called when the decoder has decoded a
  84993. * metadata block. In a valid FLAC file there will always be one
  84994. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  84995. * These will be supplied by the decoder in the same order as they
  84996. * appear in the stream and always before the first audio frame (i.e.
  84997. * write callback). The metadata block that is passed in must not be
  84998. * modified, and it doesn't live beyond the callback, so you should make
  84999. * a copy of it with FLAC__metadata_object_clone() if you will need it
  85000. * elsewhere. Since metadata blocks can potentially be large, by
  85001. * default the decoder only calls the metadata callback for the
  85002. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  85003. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  85004. *
  85005. * \note In general, FLAC__StreamDecoder functions which change the
  85006. * state should not be called on the \a decoder while in the callback.
  85007. *
  85008. * \param decoder The decoder instance calling the callback.
  85009. * \param metadata The decoded metadata block.
  85010. * \param client_data The callee's client data set through
  85011. * FLAC__stream_decoder_init_*().
  85012. */
  85013. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85014. /** Signature for the error callback.
  85015. *
  85016. * A function pointer matching this signature must be passed to one of
  85017. * the FLAC__stream_decoder_init_*() functions.
  85018. * The supplied function will be called whenever an error occurs during
  85019. * decoding.
  85020. *
  85021. * \note In general, FLAC__StreamDecoder functions which change the
  85022. * state should not be called on the \a decoder while in the callback.
  85023. *
  85024. * \param decoder The decoder instance calling the callback.
  85025. * \param status The error encountered by the decoder.
  85026. * \param client_data The callee's client data set through
  85027. * FLAC__stream_decoder_init_*().
  85028. */
  85029. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  85030. /***********************************************************************
  85031. *
  85032. * Class constructor/destructor
  85033. *
  85034. ***********************************************************************/
  85035. /** Create a new stream decoder instance. The instance is created with
  85036. * default settings; see the individual FLAC__stream_decoder_set_*()
  85037. * functions for each setting's default.
  85038. *
  85039. * \retval FLAC__StreamDecoder*
  85040. * \c NULL if there was an error allocating memory, else the new instance.
  85041. */
  85042. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  85043. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  85044. *
  85045. * \param decoder A pointer to an existing decoder.
  85046. * \assert
  85047. * \code decoder != NULL \endcode
  85048. */
  85049. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  85050. /***********************************************************************
  85051. *
  85052. * Public class method prototypes
  85053. *
  85054. ***********************************************************************/
  85055. /** Set the serial number for the FLAC stream within the Ogg container.
  85056. * The default behavior is to use the serial number of the first Ogg
  85057. * page. Setting a serial number here will explicitly specify which
  85058. * stream is to be decoded.
  85059. *
  85060. * \note
  85061. * This does not need to be set for native FLAC decoding.
  85062. *
  85063. * \default \c use serial number of first page
  85064. * \param decoder A decoder instance to set.
  85065. * \param serial_number See above.
  85066. * \assert
  85067. * \code decoder != NULL \endcode
  85068. * \retval FLAC__bool
  85069. * \c false if the decoder is already initialized, else \c true.
  85070. */
  85071. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  85072. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  85073. * compute the MD5 signature of the unencoded audio data while decoding
  85074. * and compare it to the signature from the STREAMINFO block, if it
  85075. * exists, during FLAC__stream_decoder_finish().
  85076. *
  85077. * MD5 signature checking will be turned off (until the next
  85078. * FLAC__stream_decoder_reset()) if there is no signature in the
  85079. * STREAMINFO block or when a seek is attempted.
  85080. *
  85081. * Clients that do not use the MD5 check should leave this off to speed
  85082. * up decoding.
  85083. *
  85084. * \default \c false
  85085. * \param decoder A decoder instance to set.
  85086. * \param value Flag value (see above).
  85087. * \assert
  85088. * \code decoder != NULL \endcode
  85089. * \retval FLAC__bool
  85090. * \c false if the decoder is already initialized, else \c true.
  85091. */
  85092. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  85093. /** Direct the decoder to pass on all metadata blocks of type \a type.
  85094. *
  85095. * \default By default, only the \c STREAMINFO block is returned via the
  85096. * metadata callback.
  85097. * \param decoder A decoder instance to set.
  85098. * \param type See above.
  85099. * \assert
  85100. * \code decoder != NULL \endcode
  85101. * \a type is valid
  85102. * \retval FLAC__bool
  85103. * \c false if the decoder is already initialized, else \c true.
  85104. */
  85105. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85106. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  85107. * given \a id.
  85108. *
  85109. * \default By default, only the \c STREAMINFO block is returned via the
  85110. * metadata callback.
  85111. * \param decoder A decoder instance to set.
  85112. * \param id See above.
  85113. * \assert
  85114. * \code decoder != NULL \endcode
  85115. * \code id != NULL \endcode
  85116. * \retval FLAC__bool
  85117. * \c false if the decoder is already initialized, else \c true.
  85118. */
  85119. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85120. /** Direct the decoder to pass on all metadata blocks of any type.
  85121. *
  85122. * \default By default, only the \c STREAMINFO block is returned via the
  85123. * metadata callback.
  85124. * \param decoder A decoder instance to set.
  85125. * \assert
  85126. * \code decoder != NULL \endcode
  85127. * \retval FLAC__bool
  85128. * \c false if the decoder is already initialized, else \c true.
  85129. */
  85130. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  85131. /** Direct the decoder to filter out all metadata blocks of type \a type.
  85132. *
  85133. * \default By default, only the \c STREAMINFO block is returned via the
  85134. * metadata callback.
  85135. * \param decoder A decoder instance to set.
  85136. * \param type See above.
  85137. * \assert
  85138. * \code decoder != NULL \endcode
  85139. * \a type is valid
  85140. * \retval FLAC__bool
  85141. * \c false if the decoder is already initialized, else \c true.
  85142. */
  85143. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85144. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  85145. * the given \a id.
  85146. *
  85147. * \default By default, only the \c STREAMINFO block is returned via the
  85148. * metadata callback.
  85149. * \param decoder A decoder instance to set.
  85150. * \param id See above.
  85151. * \assert
  85152. * \code decoder != NULL \endcode
  85153. * \code id != NULL \endcode
  85154. * \retval FLAC__bool
  85155. * \c false if the decoder is already initialized, else \c true.
  85156. */
  85157. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85158. /** Direct the decoder to filter out all metadata blocks of any type.
  85159. *
  85160. * \default By default, only the \c STREAMINFO block is returned via the
  85161. * metadata callback.
  85162. * \param decoder A decoder instance to set.
  85163. * \assert
  85164. * \code decoder != NULL \endcode
  85165. * \retval FLAC__bool
  85166. * \c false if the decoder is already initialized, else \c true.
  85167. */
  85168. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  85169. /** Get the current decoder state.
  85170. *
  85171. * \param decoder A decoder instance to query.
  85172. * \assert
  85173. * \code decoder != NULL \endcode
  85174. * \retval FLAC__StreamDecoderState
  85175. * The current decoder state.
  85176. */
  85177. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  85178. /** Get the current decoder state as a C string.
  85179. *
  85180. * \param decoder A decoder instance to query.
  85181. * \assert
  85182. * \code decoder != NULL \endcode
  85183. * \retval const char *
  85184. * The decoder state as a C string. Do not modify the contents.
  85185. */
  85186. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  85187. /** Get the "MD5 signature checking" flag.
  85188. * This is the value of the setting, not whether or not the decoder is
  85189. * currently checking the MD5 (remember, it can be turned off automatically
  85190. * by a seek). When the decoder is reset the flag will be restored to the
  85191. * value returned by this function.
  85192. *
  85193. * \param decoder A decoder instance to query.
  85194. * \assert
  85195. * \code decoder != NULL \endcode
  85196. * \retval FLAC__bool
  85197. * See above.
  85198. */
  85199. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  85200. /** Get the total number of samples in the stream being decoded.
  85201. * Will only be valid after decoding has started and will contain the
  85202. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  85203. *
  85204. * \param decoder A decoder instance to query.
  85205. * \assert
  85206. * \code decoder != NULL \endcode
  85207. * \retval unsigned
  85208. * See above.
  85209. */
  85210. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  85211. /** Get the current number of channels in the stream being decoded.
  85212. * Will only be valid after decoding has started and will contain the
  85213. * value from the most recently decoded frame header.
  85214. *
  85215. * \param decoder A decoder instance to query.
  85216. * \assert
  85217. * \code decoder != NULL \endcode
  85218. * \retval unsigned
  85219. * See above.
  85220. */
  85221. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  85222. /** Get the current channel assignment in the stream being decoded.
  85223. * Will only be valid after decoding has started and will contain the
  85224. * value from the most recently decoded frame header.
  85225. *
  85226. * \param decoder A decoder instance to query.
  85227. * \assert
  85228. * \code decoder != NULL \endcode
  85229. * \retval FLAC__ChannelAssignment
  85230. * See above.
  85231. */
  85232. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  85233. /** Get the current sample resolution in the stream being decoded.
  85234. * Will only be valid after decoding has started and will contain the
  85235. * value from the most recently decoded frame header.
  85236. *
  85237. * \param decoder A decoder instance to query.
  85238. * \assert
  85239. * \code decoder != NULL \endcode
  85240. * \retval unsigned
  85241. * See above.
  85242. */
  85243. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  85244. /** Get the current sample rate in Hz of the stream being decoded.
  85245. * Will only be valid after decoding has started and will contain the
  85246. * value from the most recently decoded frame header.
  85247. *
  85248. * \param decoder A decoder instance to query.
  85249. * \assert
  85250. * \code decoder != NULL \endcode
  85251. * \retval unsigned
  85252. * See above.
  85253. */
  85254. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  85255. /** Get the current blocksize of the stream being decoded.
  85256. * Will only be valid after decoding has started and will contain the
  85257. * value from the most recently decoded frame header.
  85258. *
  85259. * \param decoder A decoder instance to query.
  85260. * \assert
  85261. * \code decoder != NULL \endcode
  85262. * \retval unsigned
  85263. * See above.
  85264. */
  85265. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  85266. /** Returns the decoder's current read position within the stream.
  85267. * The position is the byte offset from the start of the stream.
  85268. * Bytes before this position have been fully decoded. Note that
  85269. * there may still be undecoded bytes in the decoder's read FIFO.
  85270. * The returned position is correct even after a seek.
  85271. *
  85272. * \warning This function currently only works for native FLAC,
  85273. * not Ogg FLAC streams.
  85274. *
  85275. * \param decoder A decoder instance to query.
  85276. * \param position Address at which to return the desired position.
  85277. * \assert
  85278. * \code decoder != NULL \endcode
  85279. * \code position != NULL \endcode
  85280. * \retval FLAC__bool
  85281. * \c true if successful, \c false if the stream is not native FLAC,
  85282. * or there was an error from the 'tell' callback or it returned
  85283. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  85284. */
  85285. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  85286. /** Initialize the decoder instance to decode native FLAC streams.
  85287. *
  85288. * This flavor of initialization sets up the decoder to decode from a
  85289. * native FLAC stream. I/O is performed via callbacks to the client.
  85290. * For decoding from a plain file via filename or open FILE*,
  85291. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  85292. * provide a simpler interface.
  85293. *
  85294. * This function should be called after FLAC__stream_decoder_new() and
  85295. * FLAC__stream_decoder_set_*() but before any of the
  85296. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85297. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85298. * if initialization succeeded.
  85299. *
  85300. * \param decoder An uninitialized decoder instance.
  85301. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85302. * pointer must not be \c NULL.
  85303. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85304. * pointer may be \c NULL if seeking is not
  85305. * supported. If \a seek_callback is not \c NULL then a
  85306. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85307. * Alternatively, a dummy seek callback that just
  85308. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85309. * may also be supplied, all though this is slightly
  85310. * less efficient for the decoder.
  85311. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85312. * pointer may be \c NULL if not supported by the client. If
  85313. * \a seek_callback is not \c NULL then a
  85314. * \a tell_callback must also be supplied.
  85315. * Alternatively, a dummy tell callback that just
  85316. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85317. * may also be supplied, all though this is slightly
  85318. * less efficient for the decoder.
  85319. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85320. * pointer may be \c NULL if not supported by the client. If
  85321. * \a seek_callback is not \c NULL then a
  85322. * \a length_callback must also be supplied.
  85323. * Alternatively, a dummy length callback that just
  85324. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85325. * may also be supplied, all though this is slightly
  85326. * less efficient for the decoder.
  85327. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85328. * pointer may be \c NULL if not supported by the client. If
  85329. * \a seek_callback is not \c NULL then a
  85330. * \a eof_callback must also be supplied.
  85331. * Alternatively, a dummy length callback that just
  85332. * returns \c false
  85333. * may also be supplied, all though this is slightly
  85334. * less efficient for the decoder.
  85335. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85336. * pointer must not be \c NULL.
  85337. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85338. * pointer may be \c NULL if the callback is not
  85339. * desired.
  85340. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85341. * pointer must not be \c NULL.
  85342. * \param client_data This value will be supplied to callbacks in their
  85343. * \a client_data argument.
  85344. * \assert
  85345. * \code decoder != NULL \endcode
  85346. * \retval FLAC__StreamDecoderInitStatus
  85347. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85348. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85349. */
  85350. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  85351. FLAC__StreamDecoder *decoder,
  85352. FLAC__StreamDecoderReadCallback read_callback,
  85353. FLAC__StreamDecoderSeekCallback seek_callback,
  85354. FLAC__StreamDecoderTellCallback tell_callback,
  85355. FLAC__StreamDecoderLengthCallback length_callback,
  85356. FLAC__StreamDecoderEofCallback eof_callback,
  85357. FLAC__StreamDecoderWriteCallback write_callback,
  85358. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85359. FLAC__StreamDecoderErrorCallback error_callback,
  85360. void *client_data
  85361. );
  85362. /** Initialize the decoder instance to decode Ogg FLAC streams.
  85363. *
  85364. * This flavor of initialization sets up the decoder to decode from a
  85365. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  85366. * client. For decoding from a plain file via filename or open FILE*,
  85367. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  85368. * provide a simpler interface.
  85369. *
  85370. * This function should be called after FLAC__stream_decoder_new() and
  85371. * FLAC__stream_decoder_set_*() but before any of the
  85372. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85373. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85374. * if initialization succeeded.
  85375. *
  85376. * \note Support for Ogg FLAC in the library is optional. If this
  85377. * library has been built without support for Ogg FLAC, this function
  85378. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85379. *
  85380. * \param decoder An uninitialized decoder instance.
  85381. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85382. * pointer must not be \c NULL.
  85383. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85384. * pointer may be \c NULL if seeking is not
  85385. * supported. If \a seek_callback is not \c NULL then a
  85386. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85387. * Alternatively, a dummy seek callback that just
  85388. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85389. * may also be supplied, all though this is slightly
  85390. * less efficient for the decoder.
  85391. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85392. * pointer may be \c NULL if not supported by the client. If
  85393. * \a seek_callback is not \c NULL then a
  85394. * \a tell_callback must also be supplied.
  85395. * Alternatively, a dummy tell callback that just
  85396. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85397. * may also be supplied, all though this is slightly
  85398. * less efficient for the decoder.
  85399. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85400. * pointer may be \c NULL if not supported by the client. If
  85401. * \a seek_callback is not \c NULL then a
  85402. * \a length_callback must also be supplied.
  85403. * Alternatively, a dummy length callback that just
  85404. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85405. * may also be supplied, all though this is slightly
  85406. * less efficient for the decoder.
  85407. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85408. * pointer may be \c NULL if not supported by the client. If
  85409. * \a seek_callback is not \c NULL then a
  85410. * \a eof_callback must also be supplied.
  85411. * Alternatively, a dummy length callback that just
  85412. * returns \c false
  85413. * may also be supplied, all though this is slightly
  85414. * less efficient for the decoder.
  85415. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85416. * pointer must not be \c NULL.
  85417. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85418. * pointer may be \c NULL if the callback is not
  85419. * desired.
  85420. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85421. * pointer must not be \c NULL.
  85422. * \param client_data This value will be supplied to callbacks in their
  85423. * \a client_data argument.
  85424. * \assert
  85425. * \code decoder != NULL \endcode
  85426. * \retval FLAC__StreamDecoderInitStatus
  85427. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85428. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85429. */
  85430. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  85431. FLAC__StreamDecoder *decoder,
  85432. FLAC__StreamDecoderReadCallback read_callback,
  85433. FLAC__StreamDecoderSeekCallback seek_callback,
  85434. FLAC__StreamDecoderTellCallback tell_callback,
  85435. FLAC__StreamDecoderLengthCallback length_callback,
  85436. FLAC__StreamDecoderEofCallback eof_callback,
  85437. FLAC__StreamDecoderWriteCallback write_callback,
  85438. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85439. FLAC__StreamDecoderErrorCallback error_callback,
  85440. void *client_data
  85441. );
  85442. /** Initialize the decoder instance to decode native FLAC files.
  85443. *
  85444. * This flavor of initialization sets up the decoder to decode from a
  85445. * plain native FLAC file. For non-stdio streams, you must use
  85446. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  85447. *
  85448. * This function should be called after FLAC__stream_decoder_new() and
  85449. * FLAC__stream_decoder_set_*() but before any of the
  85450. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85451. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85452. * if initialization succeeded.
  85453. *
  85454. * \param decoder An uninitialized decoder instance.
  85455. * \param file An open FLAC file. The file should have been
  85456. * opened with mode \c "rb" and rewound. The file
  85457. * becomes owned by the decoder and should not be
  85458. * manipulated by the client while decoding.
  85459. * Unless \a file is \c stdin, it will be closed
  85460. * when FLAC__stream_decoder_finish() is called.
  85461. * Note however that seeking will not work when
  85462. * decoding from \c stdout since it is not seekable.
  85463. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85464. * pointer must not be \c NULL.
  85465. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85466. * pointer may be \c NULL if the callback is not
  85467. * desired.
  85468. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85469. * pointer must not be \c NULL.
  85470. * \param client_data This value will be supplied to callbacks in their
  85471. * \a client_data argument.
  85472. * \assert
  85473. * \code decoder != NULL \endcode
  85474. * \code file != NULL \endcode
  85475. * \retval FLAC__StreamDecoderInitStatus
  85476. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85477. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85478. */
  85479. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  85480. FLAC__StreamDecoder *decoder,
  85481. FILE *file,
  85482. FLAC__StreamDecoderWriteCallback write_callback,
  85483. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85484. FLAC__StreamDecoderErrorCallback error_callback,
  85485. void *client_data
  85486. );
  85487. /** Initialize the decoder instance to decode Ogg FLAC files.
  85488. *
  85489. * This flavor of initialization sets up the decoder to decode from a
  85490. * plain Ogg FLAC file. For non-stdio streams, you must use
  85491. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  85492. *
  85493. * This function should be called after FLAC__stream_decoder_new() and
  85494. * FLAC__stream_decoder_set_*() but before any of the
  85495. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85496. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85497. * if initialization succeeded.
  85498. *
  85499. * \note Support for Ogg FLAC in the library is optional. If this
  85500. * library has been built without support for Ogg FLAC, this function
  85501. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85502. *
  85503. * \param decoder An uninitialized decoder instance.
  85504. * \param file An open FLAC file. The file should have been
  85505. * opened with mode \c "rb" and rewound. The file
  85506. * becomes owned by the decoder and should not be
  85507. * manipulated by the client while decoding.
  85508. * Unless \a file is \c stdin, it will be closed
  85509. * when FLAC__stream_decoder_finish() is called.
  85510. * Note however that seeking will not work when
  85511. * decoding from \c stdout since it is not seekable.
  85512. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85513. * pointer must not be \c NULL.
  85514. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85515. * pointer may be \c NULL if the callback is not
  85516. * desired.
  85517. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85518. * pointer must not be \c NULL.
  85519. * \param client_data This value will be supplied to callbacks in their
  85520. * \a client_data argument.
  85521. * \assert
  85522. * \code decoder != NULL \endcode
  85523. * \code file != NULL \endcode
  85524. * \retval FLAC__StreamDecoderInitStatus
  85525. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85526. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85527. */
  85528. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  85529. FLAC__StreamDecoder *decoder,
  85530. FILE *file,
  85531. FLAC__StreamDecoderWriteCallback write_callback,
  85532. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85533. FLAC__StreamDecoderErrorCallback error_callback,
  85534. void *client_data
  85535. );
  85536. /** Initialize the decoder instance to decode native FLAC files.
  85537. *
  85538. * This flavor of initialization sets up the decoder to decode from a plain
  85539. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  85540. * example, with Unicode filenames on Windows), you must use
  85541. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  85542. * and provide callbacks for the I/O.
  85543. *
  85544. * This function should be called after FLAC__stream_decoder_new() and
  85545. * FLAC__stream_decoder_set_*() but before any of the
  85546. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85547. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85548. * if initialization succeeded.
  85549. *
  85550. * \param decoder An uninitialized decoder instance.
  85551. * \param filename The name of the file to decode from. The file will
  85552. * be opened with fopen(). Use \c NULL to decode from
  85553. * \c stdin. Note that \c stdin is not seekable.
  85554. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85555. * pointer must not be \c NULL.
  85556. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85557. * pointer may be \c NULL if the callback is not
  85558. * desired.
  85559. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85560. * pointer must not be \c NULL.
  85561. * \param client_data This value will be supplied to callbacks in their
  85562. * \a client_data argument.
  85563. * \assert
  85564. * \code decoder != NULL \endcode
  85565. * \retval FLAC__StreamDecoderInitStatus
  85566. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85567. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85568. */
  85569. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  85570. FLAC__StreamDecoder *decoder,
  85571. const char *filename,
  85572. FLAC__StreamDecoderWriteCallback write_callback,
  85573. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85574. FLAC__StreamDecoderErrorCallback error_callback,
  85575. void *client_data
  85576. );
  85577. /** Initialize the decoder instance to decode Ogg FLAC files.
  85578. *
  85579. * This flavor of initialization sets up the decoder to decode from a plain
  85580. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  85581. * example, with Unicode filenames on Windows), you must use
  85582. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  85583. * and provide callbacks for the I/O.
  85584. *
  85585. * This function should be called after FLAC__stream_decoder_new() and
  85586. * FLAC__stream_decoder_set_*() but before any of the
  85587. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85588. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85589. * if initialization succeeded.
  85590. *
  85591. * \note Support for Ogg FLAC in the library is optional. If this
  85592. * library has been built without support for Ogg FLAC, this function
  85593. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85594. *
  85595. * \param decoder An uninitialized decoder instance.
  85596. * \param filename The name of the file to decode from. The file will
  85597. * be opened with fopen(). Use \c NULL to decode from
  85598. * \c stdin. Note that \c stdin is not seekable.
  85599. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85600. * pointer must not be \c NULL.
  85601. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85602. * pointer may be \c NULL if the callback is not
  85603. * desired.
  85604. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85605. * pointer must not be \c NULL.
  85606. * \param client_data This value will be supplied to callbacks in their
  85607. * \a client_data argument.
  85608. * \assert
  85609. * \code decoder != NULL \endcode
  85610. * \retval FLAC__StreamDecoderInitStatus
  85611. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85612. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85613. */
  85614. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  85615. FLAC__StreamDecoder *decoder,
  85616. const char *filename,
  85617. FLAC__StreamDecoderWriteCallback write_callback,
  85618. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85619. FLAC__StreamDecoderErrorCallback error_callback,
  85620. void *client_data
  85621. );
  85622. /** Finish the decoding process.
  85623. * Flushes the decoding buffer, releases resources, resets the decoder
  85624. * settings to their defaults, and returns the decoder state to
  85625. * FLAC__STREAM_DECODER_UNINITIALIZED.
  85626. *
  85627. * In the event of a prematurely-terminated decode, it is not strictly
  85628. * necessary to call this immediately before FLAC__stream_decoder_delete()
  85629. * but it is good practice to match every FLAC__stream_decoder_init_*()
  85630. * with a FLAC__stream_decoder_finish().
  85631. *
  85632. * \param decoder An uninitialized decoder instance.
  85633. * \assert
  85634. * \code decoder != NULL \endcode
  85635. * \retval FLAC__bool
  85636. * \c false if MD5 checking is on AND a STREAMINFO block was available
  85637. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  85638. * signature does not match the one computed by the decoder; else
  85639. * \c true.
  85640. */
  85641. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  85642. /** Flush the stream input.
  85643. * The decoder's input buffer will be cleared and the state set to
  85644. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  85645. * off MD5 checking.
  85646. *
  85647. * \param decoder A decoder instance.
  85648. * \assert
  85649. * \code decoder != NULL \endcode
  85650. * \retval FLAC__bool
  85651. * \c true if successful, else \c false if a memory allocation
  85652. * error occurs (in which case the state will be set to
  85653. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  85654. */
  85655. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  85656. /** Reset the decoding process.
  85657. * The decoder's input buffer will be cleared and the state set to
  85658. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  85659. * FLAC__stream_decoder_finish() except that the settings are
  85660. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  85661. * before decoding again. MD5 checking will be restored to its original
  85662. * setting.
  85663. *
  85664. * If the decoder is seekable, or was initialized with
  85665. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  85666. * the decoder will also attempt to seek to the beginning of the file.
  85667. * If this rewind fails, this function will return \c false. It follows
  85668. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  85669. * \c stdin.
  85670. *
  85671. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  85672. * and is not seekable (i.e. no seek callback was provided or the seek
  85673. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  85674. * is the duty of the client to start feeding data from the beginning of
  85675. * the stream on the next FLAC__stream_decoder_process() or
  85676. * FLAC__stream_decoder_process_interleaved() call.
  85677. *
  85678. * \param decoder A decoder instance.
  85679. * \assert
  85680. * \code decoder != NULL \endcode
  85681. * \retval FLAC__bool
  85682. * \c true if successful, else \c false if a memory allocation occurs
  85683. * (in which case the state will be set to
  85684. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  85685. * occurs (the state will be unchanged).
  85686. */
  85687. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  85688. /** Decode one metadata block or audio frame.
  85689. * This version instructs the decoder to decode a either a single metadata
  85690. * block or a single frame and stop, unless the callbacks return a fatal
  85691. * error or the read callback returns
  85692. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85693. *
  85694. * As the decoder needs more input it will call the read callback.
  85695. * Depending on what was decoded, the metadata or write callback will be
  85696. * called with the decoded metadata block or audio frame.
  85697. *
  85698. * Unless there is a fatal read error or end of stream, this function
  85699. * will return once one whole frame is decoded. In other words, if the
  85700. * stream is not synchronized or points to a corrupt frame header, the
  85701. * decoder will continue to try and resync until it gets to a valid
  85702. * frame, then decode one frame, then return. If the decoder points to
  85703. * a frame whose frame CRC in the frame footer does not match the
  85704. * computed frame CRC, this function will issue a
  85705. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  85706. * error callback, and return, having decoded one complete, although
  85707. * corrupt, frame. (Such corrupted frames are sent as silence of the
  85708. * correct length to the write callback.)
  85709. *
  85710. * \param decoder An initialized decoder instance.
  85711. * \assert
  85712. * \code decoder != NULL \endcode
  85713. * \retval FLAC__bool
  85714. * \c false if any fatal read, write, or memory allocation error
  85715. * occurred (meaning decoding must stop), else \c true; for more
  85716. * information about the decoder, check the decoder state with
  85717. * FLAC__stream_decoder_get_state().
  85718. */
  85719. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  85720. /** Decode until the end of the metadata.
  85721. * This version instructs the decoder to decode from the current position
  85722. * and continue until all the metadata has been read, or until the
  85723. * callbacks return a fatal error or the read callback returns
  85724. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85725. *
  85726. * As the decoder needs more input it will call the read callback.
  85727. * As each metadata block is decoded, the metadata callback will be called
  85728. * with the decoded metadata.
  85729. *
  85730. * \param decoder An initialized decoder instance.
  85731. * \assert
  85732. * \code decoder != NULL \endcode
  85733. * \retval FLAC__bool
  85734. * \c false if any fatal read, write, or memory allocation error
  85735. * occurred (meaning decoding must stop), else \c true; for more
  85736. * information about the decoder, check the decoder state with
  85737. * FLAC__stream_decoder_get_state().
  85738. */
  85739. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  85740. /** Decode until the end of the stream.
  85741. * This version instructs the decoder to decode from the current position
  85742. * and continue until the end of stream (the read callback returns
  85743. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  85744. * callbacks return a fatal error.
  85745. *
  85746. * As the decoder needs more input it will call the read callback.
  85747. * As each metadata block and frame is decoded, the metadata or write
  85748. * callback will be called with the decoded metadata or frame.
  85749. *
  85750. * \param decoder An initialized decoder instance.
  85751. * \assert
  85752. * \code decoder != NULL \endcode
  85753. * \retval FLAC__bool
  85754. * \c false if any fatal read, write, or memory allocation error
  85755. * occurred (meaning decoding must stop), else \c true; for more
  85756. * information about the decoder, check the decoder state with
  85757. * FLAC__stream_decoder_get_state().
  85758. */
  85759. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  85760. /** Skip one audio frame.
  85761. * This version instructs the decoder to 'skip' a single frame and stop,
  85762. * unless the callbacks return a fatal error or the read callback returns
  85763. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85764. *
  85765. * The decoding flow is the same as what occurs when
  85766. * FLAC__stream_decoder_process_single() is called to process an audio
  85767. * frame, except that this function does not decode the parsed data into
  85768. * PCM or call the write callback. The integrity of the frame is still
  85769. * checked the same way as in the other process functions.
  85770. *
  85771. * This function will return once one whole frame is skipped, in the
  85772. * same way that FLAC__stream_decoder_process_single() will return once
  85773. * one whole frame is decoded.
  85774. *
  85775. * This function can be used in more quickly determining FLAC frame
  85776. * boundaries when decoding of the actual data is not needed, for
  85777. * example when an application is separating a FLAC stream into frames
  85778. * for editing or storing in a container. To do this, the application
  85779. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  85780. * to the next frame, then use
  85781. * FLAC__stream_decoder_get_decode_position() to find the new frame
  85782. * boundary.
  85783. *
  85784. * This function should only be called when the stream has advanced
  85785. * past all the metadata, otherwise it will return \c false.
  85786. *
  85787. * \param decoder An initialized decoder instance not in a metadata
  85788. * state.
  85789. * \assert
  85790. * \code decoder != NULL \endcode
  85791. * \retval FLAC__bool
  85792. * \c false if any fatal read, write, or memory allocation error
  85793. * occurred (meaning decoding must stop), or if the decoder
  85794. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  85795. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  85796. * information about the decoder, check the decoder state with
  85797. * FLAC__stream_decoder_get_state().
  85798. */
  85799. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  85800. /** Flush the input and seek to an absolute sample.
  85801. * Decoding will resume at the given sample. Note that because of
  85802. * this, the next write callback may contain a partial block. The
  85803. * client must support seeking the input or this function will fail
  85804. * and return \c false. Furthermore, if the decoder state is
  85805. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  85806. * with FLAC__stream_decoder_flush() or reset with
  85807. * FLAC__stream_decoder_reset() before decoding can continue.
  85808. *
  85809. * \param decoder A decoder instance.
  85810. * \param sample The target sample number to seek to.
  85811. * \assert
  85812. * \code decoder != NULL \endcode
  85813. * \retval FLAC__bool
  85814. * \c true if successful, else \c false.
  85815. */
  85816. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  85817. /* \} */
  85818. #ifdef __cplusplus
  85819. }
  85820. #endif
  85821. #endif
  85822. /********* End of inlined file: stream_decoder.h *********/
  85823. /********* Start of inlined file: stream_encoder.h *********/
  85824. #ifndef FLAC__STREAM_ENCODER_H
  85825. #define FLAC__STREAM_ENCODER_H
  85826. #include <stdio.h> /* for FILE */
  85827. #ifdef __cplusplus
  85828. extern "C" {
  85829. #endif
  85830. /** \file include/FLAC/stream_encoder.h
  85831. *
  85832. * \brief
  85833. * This module contains the functions which implement the stream
  85834. * encoder.
  85835. *
  85836. * See the detailed documentation in the
  85837. * \link flac_stream_encoder stream encoder \endlink module.
  85838. */
  85839. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  85840. * \ingroup flac
  85841. *
  85842. * \brief
  85843. * This module describes the encoder layers provided by libFLAC.
  85844. *
  85845. * The stream encoder can be used to encode complete streams either to the
  85846. * client via callbacks, or directly to a file, depending on how it is
  85847. * initialized. When encoding via callbacks, the client provides a write
  85848. * callback which will be called whenever FLAC data is ready to be written.
  85849. * If the client also supplies a seek callback, the encoder will also
  85850. * automatically handle the writing back of metadata discovered while
  85851. * encoding, like stream info, seek points offsets, etc. When encoding to
  85852. * a file, the client needs only supply a filename or open \c FILE* and an
  85853. * optional progress callback for periodic notification of progress; the
  85854. * write and seek callbacks are supplied internally. For more info see the
  85855. * \link flac_stream_encoder stream encoder \endlink module.
  85856. */
  85857. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  85858. * \ingroup flac_encoder
  85859. *
  85860. * \brief
  85861. * This module contains the functions which implement the stream
  85862. * encoder.
  85863. *
  85864. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  85865. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  85866. *
  85867. * The basic usage of this encoder is as follows:
  85868. * - The program creates an instance of an encoder using
  85869. * FLAC__stream_encoder_new().
  85870. * - The program overrides the default settings using
  85871. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  85872. * functions should be called:
  85873. * - FLAC__stream_encoder_set_channels()
  85874. * - FLAC__stream_encoder_set_bits_per_sample()
  85875. * - FLAC__stream_encoder_set_sample_rate()
  85876. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  85877. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  85878. * - If the application wants to control the compression level or set its own
  85879. * metadata, then the following should also be called:
  85880. * - FLAC__stream_encoder_set_compression_level()
  85881. * - FLAC__stream_encoder_set_verify()
  85882. * - FLAC__stream_encoder_set_metadata()
  85883. * - The rest of the set functions should only be called if the client needs
  85884. * exact control over how the audio is compressed; thorough understanding
  85885. * of the FLAC format is necessary to achieve good results.
  85886. * - The program initializes the instance to validate the settings and
  85887. * prepare for encoding using
  85888. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  85889. * or FLAC__stream_encoder_init_file() for native FLAC
  85890. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  85891. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  85892. * - The program calls FLAC__stream_encoder_process() or
  85893. * FLAC__stream_encoder_process_interleaved() to encode data, which
  85894. * subsequently calls the callbacks when there is encoder data ready
  85895. * to be written.
  85896. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  85897. * which causes the encoder to encode any data still in its input pipe,
  85898. * update the metadata with the final encoding statistics if output
  85899. * seeking is possible, and finally reset the encoder to the
  85900. * uninitialized state.
  85901. * - The instance may be used again or deleted with
  85902. * FLAC__stream_encoder_delete().
  85903. *
  85904. * In more detail, the stream encoder functions similarly to the
  85905. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  85906. * callbacks and more options. Typically the client will create a new
  85907. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  85908. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  85909. * calling one of the FLAC__stream_encoder_init_*() functions.
  85910. *
  85911. * Unlike the decoders, the stream encoder has many options that can
  85912. * affect the speed and compression ratio. When setting these parameters
  85913. * you should have some basic knowledge of the format (see the
  85914. * <A HREF="../documentation.html#format">user-level documentation</A>
  85915. * or the <A HREF="../format.html">formal description</A>). The
  85916. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  85917. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  85918. * functions will do this, so make sure to pay attention to the state
  85919. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  85920. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  85921. * before FLAC__stream_encoder_init_*() will take on the defaults from
  85922. * the constructor.
  85923. *
  85924. * There are three initialization functions for native FLAC, one for
  85925. * setting up the encoder to encode FLAC data to the client via
  85926. * callbacks, and two for encoding directly to a file.
  85927. *
  85928. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  85929. * You must also supply a write callback which will be called anytime
  85930. * there is raw encoded data to write. If the client can seek the output
  85931. * it is best to also supply seek and tell callbacks, as this allows the
  85932. * encoder to go back after encoding is finished to write back
  85933. * information that was collected while encoding, like seek point offsets,
  85934. * frame sizes, etc.
  85935. *
  85936. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  85937. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  85938. * filename or open \c FILE*; the encoder will handle all the callbacks
  85939. * internally. You may also supply a progress callback for periodic
  85940. * notification of the encoding progress.
  85941. *
  85942. * There are three similarly-named init functions for encoding to Ogg
  85943. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85944. * library has been built with Ogg support.
  85945. *
  85946. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  85947. * call the write callback several times, once with the \c fLaC signature,
  85948. * and once for each encoded metadata block. Note that for Ogg FLAC
  85949. * encoding you will usually get at least twice the number of callbacks than
  85950. * with native FLAC, one for the Ogg page header and one for the page body.
  85951. *
  85952. * After initializing the instance, the client may feed audio data to the
  85953. * encoder in one of two ways:
  85954. *
  85955. * - Channel separate, through FLAC__stream_encoder_process() - The client
  85956. * will pass an array of pointers to buffers, one for each channel, to
  85957. * the encoder, each of the same length. The samples need not be
  85958. * block-aligned, but each channel should have the same number of samples.
  85959. * - Channel interleaved, through
  85960. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  85961. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  85962. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  85963. * Again, the samples need not be block-aligned but they must be
  85964. * sample-aligned, i.e. the first value should be channel0_sample0 and
  85965. * the last value channelN_sampleM.
  85966. *
  85967. * Note that for either process call, each sample in the buffers should be a
  85968. * signed integer, right-justified to the resolution set by
  85969. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  85970. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  85971. *
  85972. * When the client is finished encoding data, it calls
  85973. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  85974. * data still in its input pipe, and call the metadata callback with the
  85975. * final encoding statistics. Then the instance may be deleted with
  85976. * FLAC__stream_encoder_delete() or initialized again to encode another
  85977. * stream.
  85978. *
  85979. * For programs that write their own metadata, but that do not know the
  85980. * actual metadata until after encoding, it is advantageous to instruct
  85981. * the encoder to write a PADDING block of the correct size, so that
  85982. * instead of rewriting the whole stream after encoding, the program can
  85983. * just overwrite the PADDING block. If only the maximum size of the
  85984. * metadata is known, the program can write a slightly larger padding
  85985. * block, then split it after encoding.
  85986. *
  85987. * Make sure you understand how lengths are calculated. All FLAC metadata
  85988. * blocks have a 4 byte header which contains the type and length. This
  85989. * length does not include the 4 bytes of the header. See the format page
  85990. * for the specification of metadata blocks and their lengths.
  85991. *
  85992. * \note
  85993. * If you are writing the FLAC data to a file via callbacks, make sure it
  85994. * is open for update (e.g. mode "w+" for stdio streams). This is because
  85995. * after the first encoding pass, the encoder will try to seek back to the
  85996. * beginning of the stream, to the STREAMINFO block, to write some data
  85997. * there. (If using FLAC__stream_encoder_init*_file() or
  85998. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  85999. *
  86000. * \note
  86001. * The "set" functions may only be called when the encoder is in the
  86002. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  86003. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  86004. * before FLAC__stream_encoder_init_*(). If this is the case they will
  86005. * return \c true, otherwise \c false.
  86006. *
  86007. * \note
  86008. * FLAC__stream_encoder_finish() resets all settings to the constructor
  86009. * defaults.
  86010. *
  86011. * \{
  86012. */
  86013. /** State values for a FLAC__StreamEncoder.
  86014. *
  86015. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  86016. *
  86017. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  86018. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  86019. * must be deleted with FLAC__stream_encoder_delete().
  86020. */
  86021. typedef enum {
  86022. FLAC__STREAM_ENCODER_OK = 0,
  86023. /**< The encoder is in the normal OK state and samples can be processed. */
  86024. FLAC__STREAM_ENCODER_UNINITIALIZED,
  86025. /**< The encoder is in the uninitialized state; one of the
  86026. * FLAC__stream_encoder_init_*() functions must be called before samples
  86027. * can be processed.
  86028. */
  86029. FLAC__STREAM_ENCODER_OGG_ERROR,
  86030. /**< An error occurred in the underlying Ogg layer. */
  86031. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  86032. /**< An error occurred in the underlying verify stream decoder;
  86033. * check FLAC__stream_encoder_get_verify_decoder_state().
  86034. */
  86035. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  86036. /**< The verify decoder detected a mismatch between the original
  86037. * audio signal and the decoded audio signal.
  86038. */
  86039. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  86040. /**< One of the callbacks returned a fatal error. */
  86041. FLAC__STREAM_ENCODER_IO_ERROR,
  86042. /**< An I/O error occurred while opening/reading/writing a file.
  86043. * Check \c errno.
  86044. */
  86045. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  86046. /**< An error occurred while writing the stream; usually, the
  86047. * write_callback returned an error.
  86048. */
  86049. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  86050. /**< Memory allocation failed. */
  86051. } FLAC__StreamEncoderState;
  86052. /** Maps a FLAC__StreamEncoderState to a C string.
  86053. *
  86054. * Using a FLAC__StreamEncoderState as the index to this array
  86055. * will give the string equivalent. The contents should not be modified.
  86056. */
  86057. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  86058. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  86059. */
  86060. typedef enum {
  86061. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  86062. /**< Initialization was successful. */
  86063. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  86064. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  86065. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86066. /**< The library was not compiled with support for the given container
  86067. * format.
  86068. */
  86069. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  86070. /**< A required callback was not supplied. */
  86071. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  86072. /**< The encoder has an invalid setting for number of channels. */
  86073. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  86074. /**< The encoder has an invalid setting for bits-per-sample.
  86075. * FLAC supports 4-32 bps but the reference encoder currently supports
  86076. * only up to 24 bps.
  86077. */
  86078. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  86079. /**< The encoder has an invalid setting for the input sample rate. */
  86080. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  86081. /**< The encoder has an invalid setting for the block size. */
  86082. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  86083. /**< The encoder has an invalid setting for the maximum LPC order. */
  86084. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  86085. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  86086. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  86087. /**< The specified block size is less than the maximum LPC order. */
  86088. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  86089. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  86090. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  86091. /**< The metadata input to the encoder is invalid, in one of the following ways:
  86092. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  86093. * - One of the metadata blocks contains an undefined type
  86094. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  86095. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  86096. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  86097. */
  86098. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  86099. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  86100. * already initialized, usually because
  86101. * FLAC__stream_encoder_finish() was not called.
  86102. */
  86103. } FLAC__StreamEncoderInitStatus;
  86104. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  86105. *
  86106. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  86107. * will give the string equivalent. The contents should not be modified.
  86108. */
  86109. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  86110. /** Return values for the FLAC__StreamEncoder read callback.
  86111. */
  86112. typedef enum {
  86113. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  86114. /**< The read was OK and decoding can continue. */
  86115. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  86116. /**< The read was attempted at the end of the stream. */
  86117. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  86118. /**< An unrecoverable error occurred. */
  86119. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  86120. /**< Client does not support reading back from the output. */
  86121. } FLAC__StreamEncoderReadStatus;
  86122. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  86123. *
  86124. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  86125. * will give the string equivalent. The contents should not be modified.
  86126. */
  86127. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  86128. /** Return values for the FLAC__StreamEncoder write callback.
  86129. */
  86130. typedef enum {
  86131. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  86132. /**< The write was OK and encoding can continue. */
  86133. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  86134. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  86135. } FLAC__StreamEncoderWriteStatus;
  86136. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  86137. *
  86138. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  86139. * will give the string equivalent. The contents should not be modified.
  86140. */
  86141. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  86142. /** Return values for the FLAC__StreamEncoder seek callback.
  86143. */
  86144. typedef enum {
  86145. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  86146. /**< The seek was OK and encoding can continue. */
  86147. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  86148. /**< An unrecoverable error occurred. */
  86149. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86150. /**< Client does not support seeking. */
  86151. } FLAC__StreamEncoderSeekStatus;
  86152. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  86153. *
  86154. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  86155. * will give the string equivalent. The contents should not be modified.
  86156. */
  86157. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  86158. /** Return values for the FLAC__StreamEncoder tell callback.
  86159. */
  86160. typedef enum {
  86161. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  86162. /**< The tell was OK and encoding can continue. */
  86163. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  86164. /**< An unrecoverable error occurred. */
  86165. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86166. /**< Client does not support seeking. */
  86167. } FLAC__StreamEncoderTellStatus;
  86168. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  86169. *
  86170. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  86171. * will give the string equivalent. The contents should not be modified.
  86172. */
  86173. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  86174. /***********************************************************************
  86175. *
  86176. * class FLAC__StreamEncoder
  86177. *
  86178. ***********************************************************************/
  86179. struct FLAC__StreamEncoderProtected;
  86180. struct FLAC__StreamEncoderPrivate;
  86181. /** The opaque structure definition for the stream encoder type.
  86182. * See the \link flac_stream_encoder stream encoder module \endlink
  86183. * for a detailed description.
  86184. */
  86185. typedef struct {
  86186. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86187. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86188. } FLAC__StreamEncoder;
  86189. /** Signature for the read callback.
  86190. *
  86191. * A function pointer matching this signature must be passed to
  86192. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  86193. * The supplied function will be called when the encoder needs to read back
  86194. * encoded data. This happens during the metadata callback, when the encoder
  86195. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  86196. * while encoding. The address of the buffer to be filled is supplied, along
  86197. * with the number of bytes the buffer can hold. The callback may choose to
  86198. * supply less data and modify the byte count but must be careful not to
  86199. * overflow the buffer. The callback then returns a status code chosen from
  86200. * FLAC__StreamEncoderReadStatus.
  86201. *
  86202. * Here is an example of a read callback for stdio streams:
  86203. * \code
  86204. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86205. * {
  86206. * FILE *file = ((MyClientData*)client_data)->file;
  86207. * if(*bytes > 0) {
  86208. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86209. * if(ferror(file))
  86210. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86211. * else if(*bytes == 0)
  86212. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  86213. * else
  86214. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  86215. * }
  86216. * else
  86217. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86218. * }
  86219. * \endcode
  86220. *
  86221. * \note In general, FLAC__StreamEncoder functions which change the
  86222. * state should not be called on the \a encoder while in the callback.
  86223. *
  86224. * \param encoder The encoder instance calling the callback.
  86225. * \param buffer A pointer to a location for the callee to store
  86226. * data to be encoded.
  86227. * \param bytes A pointer to the size of the buffer. On entry
  86228. * to the callback, it contains the maximum number
  86229. * of bytes that may be stored in \a buffer. The
  86230. * callee must set it to the actual number of bytes
  86231. * stored (0 in case of error or end-of-stream) before
  86232. * returning.
  86233. * \param client_data The callee's client data set through
  86234. * FLAC__stream_encoder_set_client_data().
  86235. * \retval FLAC__StreamEncoderReadStatus
  86236. * The callee's return status.
  86237. */
  86238. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86239. /** Signature for the write callback.
  86240. *
  86241. * A function pointer matching this signature must be passed to
  86242. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86243. * by the encoder anytime there is raw encoded data ready to write. It may
  86244. * include metadata mixed with encoded audio frames and the data is not
  86245. * guaranteed to be aligned on frame or metadata block boundaries.
  86246. *
  86247. * The only duty of the callback is to write out the \a bytes worth of data
  86248. * in \a buffer to the current position in the output stream. The arguments
  86249. * \a samples and \a current_frame are purely informational. If \a samples
  86250. * is greater than \c 0, then \a current_frame will hold the current frame
  86251. * number that is being written; otherwise it indicates that the write
  86252. * callback is being called to write metadata.
  86253. *
  86254. * \note
  86255. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  86256. * write callback will be called twice when writing each audio
  86257. * frame; once for the page header, and once for the page body.
  86258. * When writing the page header, the \a samples argument to the
  86259. * write callback will be \c 0.
  86260. *
  86261. * \note In general, FLAC__StreamEncoder functions which change the
  86262. * state should not be called on the \a encoder while in the callback.
  86263. *
  86264. * \param encoder The encoder instance calling the callback.
  86265. * \param buffer An array of encoded data of length \a bytes.
  86266. * \param bytes The byte length of \a buffer.
  86267. * \param samples The number of samples encoded by \a buffer.
  86268. * \c 0 has a special meaning; see above.
  86269. * \param current_frame The number of the current frame being encoded.
  86270. * \param client_data The callee's client data set through
  86271. * FLAC__stream_encoder_init_*().
  86272. * \retval FLAC__StreamEncoderWriteStatus
  86273. * The callee's return status.
  86274. */
  86275. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  86276. /** Signature for the seek callback.
  86277. *
  86278. * A function pointer matching this signature may be passed to
  86279. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86280. * when the encoder needs to seek the output stream. The encoder will pass
  86281. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  86282. *
  86283. * Here is an example of a seek callback for stdio streams:
  86284. * \code
  86285. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86286. * {
  86287. * FILE *file = ((MyClientData*)client_data)->file;
  86288. * if(file == stdin)
  86289. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  86290. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86291. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  86292. * else
  86293. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  86294. * }
  86295. * \endcode
  86296. *
  86297. * \note In general, FLAC__StreamEncoder functions which change the
  86298. * state should not be called on the \a encoder while in the callback.
  86299. *
  86300. * \param encoder The encoder instance calling the callback.
  86301. * \param absolute_byte_offset The offset from the beginning of the stream
  86302. * to seek to.
  86303. * \param client_data The callee's client data set through
  86304. * FLAC__stream_encoder_init_*().
  86305. * \retval FLAC__StreamEncoderSeekStatus
  86306. * The callee's return status.
  86307. */
  86308. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86309. /** Signature for the tell callback.
  86310. *
  86311. * A function pointer matching this signature may be passed to
  86312. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86313. * when the encoder needs to know the current position of the output stream.
  86314. *
  86315. * \warning
  86316. * The callback must return the true current byte offset of the output to
  86317. * which the encoder is writing. If you are buffering the output, make
  86318. * sure and take this into account. If you are writing directly to a
  86319. * FILE* from your write callback, ftell() is sufficient. If you are
  86320. * writing directly to a file descriptor from your write callback, you
  86321. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  86322. * these points to rewrite metadata after encoding.
  86323. *
  86324. * Here is an example of a tell callback for stdio streams:
  86325. * \code
  86326. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86327. * {
  86328. * FILE *file = ((MyClientData*)client_data)->file;
  86329. * off_t pos;
  86330. * if(file == stdin)
  86331. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  86332. * else if((pos = ftello(file)) < 0)
  86333. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  86334. * else {
  86335. * *absolute_byte_offset = (FLAC__uint64)pos;
  86336. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  86337. * }
  86338. * }
  86339. * \endcode
  86340. *
  86341. * \note In general, FLAC__StreamEncoder functions which change the
  86342. * state should not be called on the \a encoder while in the callback.
  86343. *
  86344. * \param encoder The encoder instance calling the callback.
  86345. * \param absolute_byte_offset The address at which to store the current
  86346. * position of the output.
  86347. * \param client_data The callee's client data set through
  86348. * FLAC__stream_encoder_init_*().
  86349. * \retval FLAC__StreamEncoderTellStatus
  86350. * The callee's return status.
  86351. */
  86352. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  86353. /** Signature for the metadata callback.
  86354. *
  86355. * A function pointer matching this signature may be passed to
  86356. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86357. * once at the end of encoding with the populated STREAMINFO structure. This
  86358. * is so the client can seek back to the beginning of the file and write the
  86359. * STREAMINFO block with the correct statistics after encoding (like
  86360. * minimum/maximum frame size and total samples).
  86361. *
  86362. * \note In general, FLAC__StreamEncoder functions which change the
  86363. * state should not be called on the \a encoder while in the callback.
  86364. *
  86365. * \param encoder The encoder instance calling the callback.
  86366. * \param metadata The final populated STREAMINFO block.
  86367. * \param client_data The callee's client data set through
  86368. * FLAC__stream_encoder_init_*().
  86369. */
  86370. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  86371. /** Signature for the progress callback.
  86372. *
  86373. * A function pointer matching this signature may be passed to
  86374. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  86375. * The supplied function will be called when the encoder has finished
  86376. * writing a frame. The \c total_frames_estimate argument to the
  86377. * callback will be based on the value from
  86378. * FLAC__stream_encoder_set_total_samples_estimate().
  86379. *
  86380. * \note In general, FLAC__StreamEncoder functions which change the
  86381. * state should not be called on the \a encoder while in the callback.
  86382. *
  86383. * \param encoder The encoder instance calling the callback.
  86384. * \param bytes_written Bytes written so far.
  86385. * \param samples_written Samples written so far.
  86386. * \param frames_written Frames written so far.
  86387. * \param total_frames_estimate The estimate of the total number of
  86388. * frames to be written.
  86389. * \param client_data The callee's client data set through
  86390. * FLAC__stream_encoder_init_*().
  86391. */
  86392. 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);
  86393. /***********************************************************************
  86394. *
  86395. * Class constructor/destructor
  86396. *
  86397. ***********************************************************************/
  86398. /** Create a new stream encoder instance. The instance is created with
  86399. * default settings; see the individual FLAC__stream_encoder_set_*()
  86400. * functions for each setting's default.
  86401. *
  86402. * \retval FLAC__StreamEncoder*
  86403. * \c NULL if there was an error allocating memory, else the new instance.
  86404. */
  86405. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  86406. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  86407. *
  86408. * \param encoder A pointer to an existing encoder.
  86409. * \assert
  86410. * \code encoder != NULL \endcode
  86411. */
  86412. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  86413. /***********************************************************************
  86414. *
  86415. * Public class method prototypes
  86416. *
  86417. ***********************************************************************/
  86418. /** Set the serial number for the FLAC stream to use in the Ogg container.
  86419. *
  86420. * \note
  86421. * This does not need to be set for native FLAC encoding.
  86422. *
  86423. * \note
  86424. * It is recommended to set a serial number explicitly as the default of '0'
  86425. * may collide with other streams.
  86426. *
  86427. * \default \c 0
  86428. * \param encoder An encoder instance to set.
  86429. * \param serial_number See above.
  86430. * \assert
  86431. * \code encoder != NULL \endcode
  86432. * \retval FLAC__bool
  86433. * \c false if the encoder is already initialized, else \c true.
  86434. */
  86435. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  86436. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  86437. * encoded output by feeding it through an internal decoder and comparing
  86438. * the original signal against the decoded signal. If a mismatch occurs,
  86439. * the process call will return \c false. Note that this will slow the
  86440. * encoding process by the extra time required for decoding and comparison.
  86441. *
  86442. * \default \c false
  86443. * \param encoder An encoder instance to set.
  86444. * \param value Flag value (see above).
  86445. * \assert
  86446. * \code encoder != NULL \endcode
  86447. * \retval FLAC__bool
  86448. * \c false if the encoder is already initialized, else \c true.
  86449. */
  86450. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86451. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  86452. * the encoder will comply with the Subset and will check the
  86453. * settings during FLAC__stream_encoder_init_*() to see if all settings
  86454. * comply. If \c false, the settings may take advantage of the full
  86455. * range that the format allows.
  86456. *
  86457. * Make sure you know what it entails before setting this to \c false.
  86458. *
  86459. * \default \c true
  86460. * \param encoder An encoder instance to set.
  86461. * \param value Flag value (see above).
  86462. * \assert
  86463. * \code encoder != NULL \endcode
  86464. * \retval FLAC__bool
  86465. * \c false if the encoder is already initialized, else \c true.
  86466. */
  86467. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86468. /** Set the number of channels to be encoded.
  86469. *
  86470. * \default \c 2
  86471. * \param encoder An encoder instance to set.
  86472. * \param value See above.
  86473. * \assert
  86474. * \code encoder != NULL \endcode
  86475. * \retval FLAC__bool
  86476. * \c false if the encoder is already initialized, else \c true.
  86477. */
  86478. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  86479. /** Set the sample resolution of the input to be encoded.
  86480. *
  86481. * \warning
  86482. * Do not feed the encoder data that is wider than the value you
  86483. * set here or you will generate an invalid stream.
  86484. *
  86485. * \default \c 16
  86486. * \param encoder An encoder instance to set.
  86487. * \param value See above.
  86488. * \assert
  86489. * \code encoder != NULL \endcode
  86490. * \retval FLAC__bool
  86491. * \c false if the encoder is already initialized, else \c true.
  86492. */
  86493. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  86494. /** Set the sample rate (in Hz) of the input to be encoded.
  86495. *
  86496. * \default \c 44100
  86497. * \param encoder An encoder instance to set.
  86498. * \param value See above.
  86499. * \assert
  86500. * \code encoder != NULL \endcode
  86501. * \retval FLAC__bool
  86502. * \c false if the encoder is already initialized, else \c true.
  86503. */
  86504. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  86505. /** Set the compression level
  86506. *
  86507. * The compression level is roughly proportional to the amount of effort
  86508. * the encoder expends to compress the file. A higher level usually
  86509. * means more computation but higher compression. The default level is
  86510. * suitable for most applications.
  86511. *
  86512. * Currently the levels range from \c 0 (fastest, least compression) to
  86513. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  86514. * treated as \c 8.
  86515. *
  86516. * This function automatically calls the following other \c _set_
  86517. * functions with appropriate values, so the client does not need to
  86518. * unless it specifically wants to override them:
  86519. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  86520. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  86521. * - FLAC__stream_encoder_set_apodization()
  86522. * - FLAC__stream_encoder_set_max_lpc_order()
  86523. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  86524. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  86525. * - FLAC__stream_encoder_set_do_escape_coding()
  86526. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  86527. * - FLAC__stream_encoder_set_min_residual_partition_order()
  86528. * - FLAC__stream_encoder_set_max_residual_partition_order()
  86529. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  86530. *
  86531. * The actual values set for each level are:
  86532. * <table>
  86533. * <tr>
  86534. * <td><b>level</b><td>
  86535. * <td>do mid-side stereo<td>
  86536. * <td>loose mid-side stereo<td>
  86537. * <td>apodization<td>
  86538. * <td>max lpc order<td>
  86539. * <td>qlp coeff precision<td>
  86540. * <td>qlp coeff prec search<td>
  86541. * <td>escape coding<td>
  86542. * <td>exhaustive model search<td>
  86543. * <td>min residual partition order<td>
  86544. * <td>max residual partition order<td>
  86545. * <td>rice parameter search dist<td>
  86546. * </tr>
  86547. * <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>
  86548. * <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>
  86549. * <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>
  86550. * <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>
  86551. * <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>
  86552. * <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>
  86553. * <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>
  86554. * <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>
  86555. * <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>
  86556. * </table>
  86557. *
  86558. * \default \c 5
  86559. * \param encoder An encoder instance to set.
  86560. * \param value See above.
  86561. * \assert
  86562. * \code encoder != NULL \endcode
  86563. * \retval FLAC__bool
  86564. * \c false if the encoder is already initialized, else \c true.
  86565. */
  86566. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  86567. /** Set the blocksize to use while encoding.
  86568. *
  86569. * The number of samples to use per frame. Use \c 0 to let the encoder
  86570. * estimate a blocksize; this is usually best.
  86571. *
  86572. * \default \c 0
  86573. * \param encoder An encoder instance to set.
  86574. * \param value See above.
  86575. * \assert
  86576. * \code encoder != NULL \endcode
  86577. * \retval FLAC__bool
  86578. * \c false if the encoder is already initialized, else \c true.
  86579. */
  86580. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  86581. /** Set to \c true to enable mid-side encoding on stereo input. The
  86582. * number of channels must be 2 for this to have any effect. Set to
  86583. * \c false to use only independent channel coding.
  86584. *
  86585. * \default \c false
  86586. * \param encoder An encoder instance to set.
  86587. * \param value Flag value (see above).
  86588. * \assert
  86589. * \code encoder != NULL \endcode
  86590. * \retval FLAC__bool
  86591. * \c false if the encoder is already initialized, else \c true.
  86592. */
  86593. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86594. /** Set to \c true to enable adaptive switching between mid-side and
  86595. * left-right encoding on stereo input. Set to \c false to use
  86596. * exhaustive searching. Setting this to \c true requires
  86597. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  86598. * \c true in order to have any effect.
  86599. *
  86600. * \default \c false
  86601. * \param encoder An encoder instance to set.
  86602. * \param value Flag value (see above).
  86603. * \assert
  86604. * \code encoder != NULL \endcode
  86605. * \retval FLAC__bool
  86606. * \c false if the encoder is already initialized, else \c true.
  86607. */
  86608. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86609. /** Sets the apodization function(s) the encoder will use when windowing
  86610. * audio data for LPC analysis.
  86611. *
  86612. * The \a specification is a plain ASCII string which specifies exactly
  86613. * which functions to use. There may be more than one (up to 32),
  86614. * separated by \c ';' characters. Some functions take one or more
  86615. * comma-separated arguments in parentheses.
  86616. *
  86617. * The available functions are \c bartlett, \c bartlett_hann,
  86618. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  86619. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  86620. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  86621. *
  86622. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  86623. * (0<STDDEV<=0.5).
  86624. *
  86625. * For \c tukey(P), P specifies the fraction of the window that is
  86626. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  86627. * corresponds to \c hann.
  86628. *
  86629. * Example specifications are \c "blackman" or
  86630. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  86631. *
  86632. * Any function that is specified erroneously is silently dropped. Up
  86633. * to 32 functions are kept, the rest are dropped. If the specification
  86634. * is empty the encoder defaults to \c "tukey(0.5)".
  86635. *
  86636. * When more than one function is specified, then for every subframe the
  86637. * encoder will try each of them separately and choose the window that
  86638. * results in the smallest compressed subframe.
  86639. *
  86640. * Note that each function specified causes the encoder to occupy a
  86641. * floating point array in which to store the window.
  86642. *
  86643. * \default \c "tukey(0.5)"
  86644. * \param encoder An encoder instance to set.
  86645. * \param specification See above.
  86646. * \assert
  86647. * \code encoder != NULL \endcode
  86648. * \code specification != NULL \endcode
  86649. * \retval FLAC__bool
  86650. * \c false if the encoder is already initialized, else \c true.
  86651. */
  86652. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  86653. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  86654. *
  86655. * \default \c 0
  86656. * \param encoder An encoder instance to set.
  86657. * \param value See above.
  86658. * \assert
  86659. * \code encoder != NULL \endcode
  86660. * \retval FLAC__bool
  86661. * \c false if the encoder is already initialized, else \c true.
  86662. */
  86663. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  86664. /** Set the precision, in bits, of the quantized linear predictor
  86665. * coefficients, or \c 0 to let the encoder select it based on the
  86666. * blocksize.
  86667. *
  86668. * \note
  86669. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  86670. * be less than 32.
  86671. *
  86672. * \default \c 0
  86673. * \param encoder An encoder instance to set.
  86674. * \param value See above.
  86675. * \assert
  86676. * \code encoder != NULL \endcode
  86677. * \retval FLAC__bool
  86678. * \c false if the encoder is already initialized, else \c true.
  86679. */
  86680. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  86681. /** Set to \c false to use only the specified quantized linear predictor
  86682. * coefficient precision, or \c true to search neighboring precision
  86683. * values and use the best one.
  86684. *
  86685. * \default \c false
  86686. * \param encoder An encoder instance to set.
  86687. * \param value See above.
  86688. * \assert
  86689. * \code encoder != NULL \endcode
  86690. * \retval FLAC__bool
  86691. * \c false if the encoder is already initialized, else \c true.
  86692. */
  86693. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86694. /** Deprecated. Setting this value has no effect.
  86695. *
  86696. * \default \c false
  86697. * \param encoder An encoder instance to set.
  86698. * \param value See above.
  86699. * \assert
  86700. * \code encoder != NULL \endcode
  86701. * \retval FLAC__bool
  86702. * \c false if the encoder is already initialized, else \c true.
  86703. */
  86704. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86705. /** Set to \c false to let the encoder estimate the best model order
  86706. * based on the residual signal energy, or \c true to force the
  86707. * encoder to evaluate all order models and select the best.
  86708. *
  86709. * \default \c false
  86710. * \param encoder An encoder instance to set.
  86711. * \param value See above.
  86712. * \assert
  86713. * \code encoder != NULL \endcode
  86714. * \retval FLAC__bool
  86715. * \c false if the encoder is already initialized, else \c true.
  86716. */
  86717. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86718. /** Set the minimum partition order to search when coding the residual.
  86719. * This is used in tandem with
  86720. * FLAC__stream_encoder_set_max_residual_partition_order().
  86721. *
  86722. * The partition order determines the context size in the residual.
  86723. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  86724. *
  86725. * Set both min and max values to \c 0 to force a single context,
  86726. * whose Rice parameter is based on the residual signal variance.
  86727. * Otherwise, set a min and max order, and the encoder will search
  86728. * all orders, using the mean of each context for its Rice parameter,
  86729. * and use the best.
  86730. *
  86731. * \default \c 0
  86732. * \param encoder An encoder instance to set.
  86733. * \param value See above.
  86734. * \assert
  86735. * \code encoder != NULL \endcode
  86736. * \retval FLAC__bool
  86737. * \c false if the encoder is already initialized, else \c true.
  86738. */
  86739. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  86740. /** Set the maximum partition order to search when coding the residual.
  86741. * This is used in tandem with
  86742. * FLAC__stream_encoder_set_min_residual_partition_order().
  86743. *
  86744. * The partition order determines the context size in the residual.
  86745. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  86746. *
  86747. * Set both min and max values to \c 0 to force a single context,
  86748. * whose Rice parameter is based on the residual signal variance.
  86749. * Otherwise, set a min and max order, and the encoder will search
  86750. * all orders, using the mean of each context for its Rice parameter,
  86751. * and use the best.
  86752. *
  86753. * \default \c 0
  86754. * \param encoder An encoder instance to set.
  86755. * \param value See above.
  86756. * \assert
  86757. * \code encoder != NULL \endcode
  86758. * \retval FLAC__bool
  86759. * \c false if the encoder is already initialized, else \c true.
  86760. */
  86761. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  86762. /** Deprecated. Setting this value has no effect.
  86763. *
  86764. * \default \c 0
  86765. * \param encoder An encoder instance to set.
  86766. * \param value See above.
  86767. * \assert
  86768. * \code encoder != NULL \endcode
  86769. * \retval FLAC__bool
  86770. * \c false if the encoder is already initialized, else \c true.
  86771. */
  86772. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  86773. /** Set an estimate of the total samples that will be encoded.
  86774. * This is merely an estimate and may be set to \c 0 if unknown.
  86775. * This value will be written to the STREAMINFO block before encoding,
  86776. * and can remove the need for the caller to rewrite the value later
  86777. * if the value is known before encoding.
  86778. *
  86779. * \default \c 0
  86780. * \param encoder An encoder instance to set.
  86781. * \param value See above.
  86782. * \assert
  86783. * \code encoder != NULL \endcode
  86784. * \retval FLAC__bool
  86785. * \c false if the encoder is already initialized, else \c true.
  86786. */
  86787. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  86788. /** Set the metadata blocks to be emitted to the stream before encoding.
  86789. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  86790. * array of pointers to metadata blocks. The array is non-const since
  86791. * the encoder may need to change the \a is_last flag inside them, and
  86792. * in some cases update seek point offsets. Otherwise, the encoder will
  86793. * not modify or free the blocks. It is up to the caller to free the
  86794. * metadata blocks after encoding finishes.
  86795. *
  86796. * \note
  86797. * The encoder stores only copies of the pointers in the \a metadata array;
  86798. * the metadata blocks themselves must survive at least until after
  86799. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  86800. *
  86801. * \note
  86802. * The STREAMINFO block is always written and no STREAMINFO block may
  86803. * occur in the supplied array.
  86804. *
  86805. * \note
  86806. * By default the encoder does not create a SEEKTABLE. If one is supplied
  86807. * in the \a metadata array, but the client has specified that it does not
  86808. * support seeking, then the SEEKTABLE will be written verbatim. However
  86809. * by itself this is not very useful as the client will not know the stream
  86810. * offsets for the seekpoints ahead of time. In order to get a proper
  86811. * seektable the client must support seeking. See next note.
  86812. *
  86813. * \note
  86814. * SEEKTABLE blocks are handled specially. Since you will not know
  86815. * the values for the seek point stream offsets, you should pass in
  86816. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  86817. * required sample numbers (or placeholder points), with \c 0 for the
  86818. * \a frame_samples and \a stream_offset fields for each point. If the
  86819. * client has specified that it supports seeking by providing a seek
  86820. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  86821. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  86822. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  86823. * then while it is encoding the encoder will fill the stream offsets in
  86824. * for you and when encoding is finished, it will seek back and write the
  86825. * real values into the SEEKTABLE block in the stream. There are helper
  86826. * routines for manipulating seektable template blocks; see metadata.h:
  86827. * FLAC__metadata_object_seektable_template_*(). If the client does
  86828. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  86829. * will slow down or remove the ability to seek in the FLAC stream.
  86830. *
  86831. * \note
  86832. * The encoder instance \b will modify the first \c SEEKTABLE block
  86833. * as it transforms the template to a valid seektable while encoding,
  86834. * but it is still up to the caller to free all metadata blocks after
  86835. * encoding.
  86836. *
  86837. * \note
  86838. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  86839. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  86840. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  86841. * will simply write it's own into the stream. If no VORBIS_COMMENT
  86842. * block is present in the \a metadata array, libFLAC will write an
  86843. * empty one, containing only the vendor string.
  86844. *
  86845. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  86846. * the second metadata block of the stream. The encoder already supplies
  86847. * the STREAMINFO block automatically. If \a metadata does not contain a
  86848. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  86849. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  86850. * first, the init function will reorder \a metadata by moving the
  86851. * VORBIS_COMMENT block to the front; the relative ordering of the other
  86852. * blocks will remain as they were.
  86853. *
  86854. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  86855. * stream to \c 65535. If \a num_blocks exceeds this the function will
  86856. * return \c false.
  86857. *
  86858. * \default \c NULL, 0
  86859. * \param encoder An encoder instance to set.
  86860. * \param metadata See above.
  86861. * \param num_blocks See above.
  86862. * \assert
  86863. * \code encoder != NULL \endcode
  86864. * \retval FLAC__bool
  86865. * \c false if the encoder is already initialized, else \c true.
  86866. * \c false if the encoder is already initialized, or if
  86867. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  86868. */
  86869. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  86870. /** Get the current encoder state.
  86871. *
  86872. * \param encoder An encoder instance to query.
  86873. * \assert
  86874. * \code encoder != NULL \endcode
  86875. * \retval FLAC__StreamEncoderState
  86876. * The current encoder state.
  86877. */
  86878. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  86879. /** Get the state of the verify stream decoder.
  86880. * Useful when the stream encoder state is
  86881. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  86882. *
  86883. * \param encoder An encoder instance to query.
  86884. * \assert
  86885. * \code encoder != NULL \endcode
  86886. * \retval FLAC__StreamDecoderState
  86887. * The verify stream decoder state.
  86888. */
  86889. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  86890. /** Get the current encoder state as a C string.
  86891. * This version automatically resolves
  86892. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  86893. * verify decoder's state.
  86894. *
  86895. * \param encoder A encoder instance to query.
  86896. * \assert
  86897. * \code encoder != NULL \endcode
  86898. * \retval const char *
  86899. * The encoder state as a C string. Do not modify the contents.
  86900. */
  86901. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  86902. /** Get relevant values about the nature of a verify decoder error.
  86903. * Useful when the stream encoder state is
  86904. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  86905. * be addresses in which the stats will be returned, or NULL if value
  86906. * is not desired.
  86907. *
  86908. * \param encoder An encoder instance to query.
  86909. * \param absolute_sample The absolute sample number of the mismatch.
  86910. * \param frame_number The number of the frame in which the mismatch occurred.
  86911. * \param channel The channel in which the mismatch occurred.
  86912. * \param sample The number of the sample (relative to the frame) in
  86913. * which the mismatch occurred.
  86914. * \param expected The expected value for the sample in question.
  86915. * \param got The actual value returned by the decoder.
  86916. * \assert
  86917. * \code encoder != NULL \endcode
  86918. */
  86919. 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);
  86920. /** Get the "verify" flag.
  86921. *
  86922. * \param encoder An encoder instance to query.
  86923. * \assert
  86924. * \code encoder != NULL \endcode
  86925. * \retval FLAC__bool
  86926. * See FLAC__stream_encoder_set_verify().
  86927. */
  86928. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  86929. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  86930. *
  86931. * \param encoder An encoder instance to query.
  86932. * \assert
  86933. * \code encoder != NULL \endcode
  86934. * \retval FLAC__bool
  86935. * See FLAC__stream_encoder_set_streamable_subset().
  86936. */
  86937. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  86938. /** Get the number of input channels being processed.
  86939. *
  86940. * \param encoder An encoder instance to query.
  86941. * \assert
  86942. * \code encoder != NULL \endcode
  86943. * \retval unsigned
  86944. * See FLAC__stream_encoder_set_channels().
  86945. */
  86946. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  86947. /** Get the input sample resolution setting.
  86948. *
  86949. * \param encoder An encoder instance to query.
  86950. * \assert
  86951. * \code encoder != NULL \endcode
  86952. * \retval unsigned
  86953. * See FLAC__stream_encoder_set_bits_per_sample().
  86954. */
  86955. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  86956. /** Get the input sample rate setting.
  86957. *
  86958. * \param encoder An encoder instance to query.
  86959. * \assert
  86960. * \code encoder != NULL \endcode
  86961. * \retval unsigned
  86962. * See FLAC__stream_encoder_set_sample_rate().
  86963. */
  86964. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  86965. /** Get the blocksize setting.
  86966. *
  86967. * \param encoder An encoder instance to query.
  86968. * \assert
  86969. * \code encoder != NULL \endcode
  86970. * \retval unsigned
  86971. * See FLAC__stream_encoder_set_blocksize().
  86972. */
  86973. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  86974. /** Get the "mid/side stereo coding" flag.
  86975. *
  86976. * \param encoder An encoder instance to query.
  86977. * \assert
  86978. * \code encoder != NULL \endcode
  86979. * \retval FLAC__bool
  86980. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  86981. */
  86982. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  86983. /** Get the "adaptive mid/side switching" flag.
  86984. *
  86985. * \param encoder An encoder instance to query.
  86986. * \assert
  86987. * \code encoder != NULL \endcode
  86988. * \retval FLAC__bool
  86989. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  86990. */
  86991. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  86992. /** Get the maximum LPC order setting.
  86993. *
  86994. * \param encoder An encoder instance to query.
  86995. * \assert
  86996. * \code encoder != NULL \endcode
  86997. * \retval unsigned
  86998. * See FLAC__stream_encoder_set_max_lpc_order().
  86999. */
  87000. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  87001. /** Get the quantized linear predictor coefficient precision setting.
  87002. *
  87003. * \param encoder An encoder instance to query.
  87004. * \assert
  87005. * \code encoder != NULL \endcode
  87006. * \retval unsigned
  87007. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  87008. */
  87009. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  87010. /** Get the qlp coefficient precision search flag.
  87011. *
  87012. * \param encoder An encoder instance to query.
  87013. * \assert
  87014. * \code encoder != NULL \endcode
  87015. * \retval FLAC__bool
  87016. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  87017. */
  87018. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  87019. /** Get the "escape coding" flag.
  87020. *
  87021. * \param encoder An encoder instance to query.
  87022. * \assert
  87023. * \code encoder != NULL \endcode
  87024. * \retval FLAC__bool
  87025. * See FLAC__stream_encoder_set_do_escape_coding().
  87026. */
  87027. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  87028. /** Get the exhaustive model search flag.
  87029. *
  87030. * \param encoder An encoder instance to query.
  87031. * \assert
  87032. * \code encoder != NULL \endcode
  87033. * \retval FLAC__bool
  87034. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  87035. */
  87036. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  87037. /** Get the minimum residual partition order setting.
  87038. *
  87039. * \param encoder An encoder instance to query.
  87040. * \assert
  87041. * \code encoder != NULL \endcode
  87042. * \retval unsigned
  87043. * See FLAC__stream_encoder_set_min_residual_partition_order().
  87044. */
  87045. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87046. /** Get maximum residual partition order setting.
  87047. *
  87048. * \param encoder An encoder instance to query.
  87049. * \assert
  87050. * \code encoder != NULL \endcode
  87051. * \retval unsigned
  87052. * See FLAC__stream_encoder_set_max_residual_partition_order().
  87053. */
  87054. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87055. /** Get the Rice parameter search distance setting.
  87056. *
  87057. * \param encoder An encoder instance to query.
  87058. * \assert
  87059. * \code encoder != NULL \endcode
  87060. * \retval unsigned
  87061. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  87062. */
  87063. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  87064. /** Get the previously set estimate of the total samples to be encoded.
  87065. * The encoder merely mimics back the value given to
  87066. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  87067. * other way of knowing how many samples the client will encode.
  87068. *
  87069. * \param encoder An encoder instance to set.
  87070. * \assert
  87071. * \code encoder != NULL \endcode
  87072. * \retval FLAC__uint64
  87073. * See FLAC__stream_encoder_get_total_samples_estimate().
  87074. */
  87075. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  87076. /** Initialize the encoder instance to encode native FLAC streams.
  87077. *
  87078. * This flavor of initialization sets up the encoder to encode to a
  87079. * native FLAC stream. I/O is performed via callbacks to the client.
  87080. * For encoding to a plain file via filename or open \c FILE*,
  87081. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  87082. * provide a simpler interface.
  87083. *
  87084. * This function should be called after FLAC__stream_encoder_new() and
  87085. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87086. * or FLAC__stream_encoder_process_interleaved().
  87087. * initialization succeeded.
  87088. *
  87089. * The call to FLAC__stream_encoder_init_stream() currently will also
  87090. * immediately call the write callback several times, once with the \c fLaC
  87091. * signature, and once for each encoded metadata block.
  87092. *
  87093. * \param encoder An uninitialized encoder instance.
  87094. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87095. * pointer must not be \c NULL.
  87096. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87097. * pointer may be \c NULL if seeking is not
  87098. * supported. The encoder uses seeking to go back
  87099. * and write some some stream statistics to the
  87100. * STREAMINFO block; this is recommended but not
  87101. * necessary to create a valid FLAC stream. If
  87102. * \a seek_callback is not \c NULL then a
  87103. * \a tell_callback must also be supplied.
  87104. * Alternatively, a dummy seek callback that just
  87105. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87106. * may also be supplied, all though this is slightly
  87107. * less efficient for the encoder.
  87108. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87109. * pointer may be \c NULL if seeking is not
  87110. * supported. If \a seek_callback is \c NULL then
  87111. * this argument will be ignored. If
  87112. * \a seek_callback is not \c NULL then a
  87113. * \a tell_callback must also be supplied.
  87114. * Alternatively, a dummy tell callback that just
  87115. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87116. * may also be supplied, all though this is slightly
  87117. * less efficient for the encoder.
  87118. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87119. * pointer may be \c NULL if the callback is not
  87120. * desired. If the client provides a seek callback,
  87121. * this function is not necessary as the encoder
  87122. * will automatically seek back and update the
  87123. * STREAMINFO block. It may also be \c NULL if the
  87124. * client does not support seeking, since it will
  87125. * have no way of going back to update the
  87126. * STREAMINFO. However the client can still supply
  87127. * a callback if it would like to know the details
  87128. * from the STREAMINFO.
  87129. * \param client_data This value will be supplied to callbacks in their
  87130. * \a client_data argument.
  87131. * \assert
  87132. * \code encoder != NULL \endcode
  87133. * \retval FLAC__StreamEncoderInitStatus
  87134. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87135. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87136. */
  87137. 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);
  87138. /** Initialize the encoder instance to encode Ogg FLAC streams.
  87139. *
  87140. * This flavor of initialization sets up the encoder to encode to a FLAC
  87141. * stream in an Ogg container. I/O is performed via callbacks to the
  87142. * client. For encoding to a plain file via filename or open \c FILE*,
  87143. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  87144. * provide a simpler interface.
  87145. *
  87146. * This function should be called after FLAC__stream_encoder_new() and
  87147. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87148. * or FLAC__stream_encoder_process_interleaved().
  87149. * initialization succeeded.
  87150. *
  87151. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  87152. * immediately call the write callback several times to write the metadata
  87153. * packets.
  87154. *
  87155. * \param encoder An uninitialized encoder instance.
  87156. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  87157. * pointer must not be \c NULL if \a seek_callback
  87158. * is non-NULL since they are both needed to be
  87159. * able to write data back to the Ogg FLAC stream
  87160. * in the post-encode phase.
  87161. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87162. * pointer must not be \c NULL.
  87163. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87164. * pointer may be \c NULL if seeking is not
  87165. * supported. The encoder uses seeking to go back
  87166. * and write some some stream statistics to the
  87167. * STREAMINFO block; this is recommended but not
  87168. * necessary to create a valid FLAC stream. If
  87169. * \a seek_callback is not \c NULL then a
  87170. * \a tell_callback must also be supplied.
  87171. * Alternatively, a dummy seek callback that just
  87172. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87173. * may also be supplied, all though this is slightly
  87174. * less efficient for the encoder.
  87175. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87176. * pointer may be \c NULL if seeking is not
  87177. * supported. If \a seek_callback is \c NULL then
  87178. * this argument will be ignored. If
  87179. * \a seek_callback is not \c NULL then a
  87180. * \a tell_callback must also be supplied.
  87181. * Alternatively, a dummy tell callback that just
  87182. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87183. * may also be supplied, all though this is slightly
  87184. * less efficient for the encoder.
  87185. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87186. * pointer may be \c NULL if the callback is not
  87187. * desired. If the client provides a seek callback,
  87188. * this function is not necessary as the encoder
  87189. * will automatically seek back and update the
  87190. * STREAMINFO block. It may also be \c NULL if the
  87191. * client does not support seeking, since it will
  87192. * have no way of going back to update the
  87193. * STREAMINFO. However the client can still supply
  87194. * a callback if it would like to know the details
  87195. * from the STREAMINFO.
  87196. * \param client_data This value will be supplied to callbacks in their
  87197. * \a client_data argument.
  87198. * \assert
  87199. * \code encoder != NULL \endcode
  87200. * \retval FLAC__StreamEncoderInitStatus
  87201. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87202. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87203. */
  87204. 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);
  87205. /** Initialize the encoder instance to encode native FLAC files.
  87206. *
  87207. * This flavor of initialization sets up the encoder to encode to a
  87208. * plain native FLAC file. For non-stdio streams, you must use
  87209. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  87210. *
  87211. * This function should be called after FLAC__stream_encoder_new() and
  87212. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87213. * or FLAC__stream_encoder_process_interleaved().
  87214. * initialization succeeded.
  87215. *
  87216. * \param encoder An uninitialized encoder instance.
  87217. * \param file An open file. The file should have been opened
  87218. * with mode \c "w+b" and rewound. The file
  87219. * becomes owned by the encoder and should not be
  87220. * manipulated by the client while encoding.
  87221. * Unless \a file is \c stdout, it will be closed
  87222. * when FLAC__stream_encoder_finish() is called.
  87223. * Note however that a proper SEEKTABLE cannot be
  87224. * created when encoding to \c stdout since it is
  87225. * not seekable.
  87226. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87227. * pointer may be \c NULL if the callback is not
  87228. * desired.
  87229. * \param client_data This value will be supplied to callbacks in their
  87230. * \a client_data argument.
  87231. * \assert
  87232. * \code encoder != NULL \endcode
  87233. * \code file != NULL \endcode
  87234. * \retval FLAC__StreamEncoderInitStatus
  87235. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87236. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87237. */
  87238. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87239. /** Initialize the encoder instance to encode Ogg FLAC files.
  87240. *
  87241. * This flavor of initialization sets up the encoder to encode to a
  87242. * plain Ogg FLAC file. For non-stdio streams, you must use
  87243. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  87244. *
  87245. * This function should be called after FLAC__stream_encoder_new() and
  87246. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87247. * or FLAC__stream_encoder_process_interleaved().
  87248. * initialization succeeded.
  87249. *
  87250. * \param encoder An uninitialized encoder instance.
  87251. * \param file An open file. The file should have been opened
  87252. * with mode \c "w+b" and rewound. The file
  87253. * becomes owned by the encoder and should not be
  87254. * manipulated by the client while encoding.
  87255. * Unless \a file is \c stdout, it will be closed
  87256. * when FLAC__stream_encoder_finish() is called.
  87257. * Note however that a proper SEEKTABLE cannot be
  87258. * created when encoding to \c stdout since it is
  87259. * not seekable.
  87260. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87261. * pointer may be \c NULL if the callback is not
  87262. * desired.
  87263. * \param client_data This value will be supplied to callbacks in their
  87264. * \a client_data argument.
  87265. * \assert
  87266. * \code encoder != NULL \endcode
  87267. * \code file != NULL \endcode
  87268. * \retval FLAC__StreamEncoderInitStatus
  87269. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87270. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87271. */
  87272. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87273. /** Initialize the encoder instance to encode native FLAC files.
  87274. *
  87275. * This flavor of initialization sets up the encoder to encode to a plain
  87276. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87277. * with Unicode filenames on Windows), you must use
  87278. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  87279. * and provide callbacks for the I/O.
  87280. *
  87281. * This function should be called after FLAC__stream_encoder_new() and
  87282. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87283. * or FLAC__stream_encoder_process_interleaved().
  87284. * initialization succeeded.
  87285. *
  87286. * \param encoder An uninitialized encoder instance.
  87287. * \param filename The name of the file to encode to. The file will
  87288. * be opened with fopen(). Use \c NULL to encode to
  87289. * \c stdout. Note however that a proper SEEKTABLE
  87290. * cannot be created when encoding to \c stdout since
  87291. * it is not seekable.
  87292. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87293. * pointer may be \c NULL if the callback is not
  87294. * desired.
  87295. * \param client_data This value will be supplied to callbacks in their
  87296. * \a client_data argument.
  87297. * \assert
  87298. * \code encoder != NULL \endcode
  87299. * \retval FLAC__StreamEncoderInitStatus
  87300. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87301. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87302. */
  87303. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87304. /** Initialize the encoder instance to encode Ogg FLAC files.
  87305. *
  87306. * This flavor of initialization sets up the encoder to encode to a plain
  87307. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87308. * with Unicode filenames on Windows), you must use
  87309. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  87310. * and provide callbacks for the I/O.
  87311. *
  87312. * This function should be called after FLAC__stream_encoder_new() and
  87313. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87314. * or FLAC__stream_encoder_process_interleaved().
  87315. * initialization succeeded.
  87316. *
  87317. * \param encoder An uninitialized encoder instance.
  87318. * \param filename The name of the file to encode to. The file will
  87319. * be opened with fopen(). Use \c NULL to encode to
  87320. * \c stdout. Note however that a proper SEEKTABLE
  87321. * cannot be created when encoding to \c stdout since
  87322. * it is not seekable.
  87323. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87324. * pointer may be \c NULL if the callback is not
  87325. * desired.
  87326. * \param client_data This value will be supplied to callbacks in their
  87327. * \a client_data argument.
  87328. * \assert
  87329. * \code encoder != NULL \endcode
  87330. * \retval FLAC__StreamEncoderInitStatus
  87331. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87332. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87333. */
  87334. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87335. /** Finish the encoding process.
  87336. * Flushes the encoding buffer, releases resources, resets the encoder
  87337. * settings to their defaults, and returns the encoder state to
  87338. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  87339. * one or more write callbacks before returning, and will generate
  87340. * a metadata callback.
  87341. *
  87342. * Note that in the course of processing the last frame, errors can
  87343. * occur, so the caller should be sure to check the return value to
  87344. * ensure the file was encoded properly.
  87345. *
  87346. * In the event of a prematurely-terminated encode, it is not strictly
  87347. * necessary to call this immediately before FLAC__stream_encoder_delete()
  87348. * but it is good practice to match every FLAC__stream_encoder_init_*()
  87349. * with a FLAC__stream_encoder_finish().
  87350. *
  87351. * \param encoder An uninitialized encoder instance.
  87352. * \assert
  87353. * \code encoder != NULL \endcode
  87354. * \retval FLAC__bool
  87355. * \c false if an error occurred processing the last frame; or if verify
  87356. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  87357. * verify mismatch; else \c true. If \c false, caller should check the
  87358. * state with FLAC__stream_encoder_get_state() for more information
  87359. * about the error.
  87360. */
  87361. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  87362. /** Submit data for encoding.
  87363. * This version allows you to supply the input data via an array of
  87364. * pointers, each pointer pointing to an array of \a samples samples
  87365. * representing one channel. The samples need not be block-aligned,
  87366. * but each channel should have the same number of samples. Each sample
  87367. * should be a signed integer, right-justified to the resolution set by
  87368. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  87369. * resolution is 16 bits per sample, the samples should all be in the
  87370. * range [-32768,32767].
  87371. *
  87372. * For applications where channel order is important, channels must
  87373. * follow the order as described in the
  87374. * <A HREF="../format.html#frame_header">frame header</A>.
  87375. *
  87376. * \param encoder An initialized encoder instance in the OK state.
  87377. * \param buffer An array of pointers to each channel's signal.
  87378. * \param samples The number of samples in one channel.
  87379. * \assert
  87380. * \code encoder != NULL \endcode
  87381. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  87382. * \retval FLAC__bool
  87383. * \c true if successful, else \c false; in this case, check the
  87384. * encoder state with FLAC__stream_encoder_get_state() to see what
  87385. * went wrong.
  87386. */
  87387. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  87388. /** Submit data for encoding.
  87389. * This version allows you to supply the input data where the channels
  87390. * are interleaved into a single array (i.e. channel0_sample0,
  87391. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  87392. * The samples need not be block-aligned but they must be
  87393. * sample-aligned, i.e. the first value should be channel0_sample0
  87394. * and the last value channelN_sampleM. Each sample should be a signed
  87395. * integer, right-justified to the resolution set by
  87396. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  87397. * resolution is 16 bits per sample, the samples should all be in the
  87398. * range [-32768,32767].
  87399. *
  87400. * For applications where channel order is important, channels must
  87401. * follow the order as described in the
  87402. * <A HREF="../format.html#frame_header">frame header</A>.
  87403. *
  87404. * \param encoder An initialized encoder instance in the OK state.
  87405. * \param buffer An array of channel-interleaved data (see above).
  87406. * \param samples The number of samples in one channel, the same as for
  87407. * FLAC__stream_encoder_process(). For example, if
  87408. * encoding two channels, \c 1000 \a samples corresponds
  87409. * to a \a buffer of 2000 values.
  87410. * \assert
  87411. * \code encoder != NULL \endcode
  87412. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  87413. * \retval FLAC__bool
  87414. * \c true if successful, else \c false; in this case, check the
  87415. * encoder state with FLAC__stream_encoder_get_state() to see what
  87416. * went wrong.
  87417. */
  87418. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  87419. /* \} */
  87420. #ifdef __cplusplus
  87421. }
  87422. #endif
  87423. #endif
  87424. /********* End of inlined file: stream_encoder.h *********/
  87425. #ifdef _MSC_VER
  87426. /* OPT: an MSVC built-in would be better */
  87427. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  87428. {
  87429. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  87430. return (x>>16) | (x<<16);
  87431. }
  87432. #endif
  87433. #if defined(_MSC_VER) && defined(_X86_)
  87434. /* OPT: an MSVC built-in would be better */
  87435. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  87436. {
  87437. __asm {
  87438. mov edx, start
  87439. mov ecx, len
  87440. test ecx, ecx
  87441. loop1:
  87442. jz done1
  87443. mov eax, [edx]
  87444. bswap eax
  87445. mov [edx], eax
  87446. add edx, 4
  87447. dec ecx
  87448. jmp short loop1
  87449. done1:
  87450. }
  87451. }
  87452. #endif
  87453. /** \mainpage
  87454. *
  87455. * \section intro Introduction
  87456. *
  87457. * This is the documentation for the FLAC C and C++ APIs. It is
  87458. * highly interconnected; this introduction should give you a top
  87459. * level idea of the structure and how to find the information you
  87460. * need. As a prerequisite you should have at least a basic
  87461. * knowledge of the FLAC format, documented
  87462. * <A HREF="../format.html">here</A>.
  87463. *
  87464. * \section c_api FLAC C API
  87465. *
  87466. * The FLAC C API is the interface to libFLAC, a set of structures
  87467. * describing the components of FLAC streams, and functions for
  87468. * encoding and decoding streams, as well as manipulating FLAC
  87469. * metadata in files. The public include files will be installed
  87470. * in your include area (for example /usr/include/FLAC/...).
  87471. *
  87472. * By writing a little code and linking against libFLAC, it is
  87473. * relatively easy to add FLAC support to another program. The
  87474. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  87475. * Complete source code of libFLAC as well as the command-line
  87476. * encoder and plugins is available and is a useful source of
  87477. * examples.
  87478. *
  87479. * Aside from encoders and decoders, libFLAC provides a powerful
  87480. * metadata interface for manipulating metadata in FLAC files. It
  87481. * allows the user to add, delete, and modify FLAC metadata blocks
  87482. * and it can automatically take advantage of PADDING blocks to avoid
  87483. * rewriting the entire FLAC file when changing the size of the
  87484. * metadata.
  87485. *
  87486. * libFLAC usually only requires the standard C library and C math
  87487. * library. In particular, threading is not used so there is no
  87488. * dependency on a thread library. However, libFLAC does not use
  87489. * global variables and should be thread-safe.
  87490. *
  87491. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  87492. * However the metadata editing interfaces currently have limited
  87493. * read-only support for Ogg FLAC files.
  87494. *
  87495. * \section cpp_api FLAC C++ API
  87496. *
  87497. * The FLAC C++ API is a set of classes that encapsulate the
  87498. * structures and functions in libFLAC. They provide slightly more
  87499. * functionality with respect to metadata but are otherwise
  87500. * equivalent. For the most part, they share the same usage as
  87501. * their counterparts in libFLAC, and the FLAC C API documentation
  87502. * can be used as a supplement. The public include files
  87503. * for the C++ API will be installed in your include area (for
  87504. * example /usr/include/FLAC++/...).
  87505. *
  87506. * libFLAC++ is also licensed under
  87507. * <A HREF="../license.html">Xiph's BSD license</A>.
  87508. *
  87509. * \section getting_started Getting Started
  87510. *
  87511. * A good starting point for learning the API is to browse through
  87512. * the <A HREF="modules.html">modules</A>. Modules are logical
  87513. * groupings of related functions or classes, which correspond roughly
  87514. * to header files or sections of header files. Each module includes a
  87515. * detailed description of the general usage of its functions or
  87516. * classes.
  87517. *
  87518. * From there you can go on to look at the documentation of
  87519. * individual functions. You can see different views of the individual
  87520. * functions through the links in top bar across this page.
  87521. *
  87522. * If you prefer a more hands-on approach, you can jump right to some
  87523. * <A HREF="../documentation_example_code.html">example code</A>.
  87524. *
  87525. * \section porting_guide Porting Guide
  87526. *
  87527. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  87528. * has been introduced which gives detailed instructions on how to
  87529. * port your code to newer versions of FLAC.
  87530. *
  87531. * \section embedded_developers Embedded Developers
  87532. *
  87533. * libFLAC has grown larger over time as more functionality has been
  87534. * included, but much of it may be unnecessary for a particular embedded
  87535. * implementation. Unused parts may be pruned by some simple editing of
  87536. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  87537. * metadata interface are all independent from each other.
  87538. *
  87539. * It is easiest to just describe the dependencies:
  87540. *
  87541. * - All modules depend on the \link flac_format Format \endlink module.
  87542. * - The decoders and encoders depend on the bitbuffer.
  87543. * - The decoder is independent of the encoder. The encoder uses the
  87544. * decoder because of the verify feature, but this can be removed if
  87545. * not needed.
  87546. * - Parts of the metadata interface require the stream decoder (but not
  87547. * the encoder).
  87548. * - Ogg support is selectable through the compile time macro
  87549. * \c FLAC__HAS_OGG.
  87550. *
  87551. * For example, if your application only requires the stream decoder, no
  87552. * encoder, and no metadata interface, you can remove the stream encoder
  87553. * and the metadata interface, which will greatly reduce the size of the
  87554. * library.
  87555. *
  87556. * Also, there are several places in the libFLAC code with comments marked
  87557. * with "OPT:" where a #define can be changed to enable code that might be
  87558. * faster on a specific platform. Experimenting with these can yield faster
  87559. * binaries.
  87560. */
  87561. /** \defgroup porting Porting Guide for New Versions
  87562. *
  87563. * This module describes differences in the library interfaces from
  87564. * version to version. It assists in the porting of code that uses
  87565. * the libraries to newer versions of FLAC.
  87566. *
  87567. * One simple facility for making porting easier that has been added
  87568. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  87569. * library's includes (e.g. \c include/FLAC/export.h). The
  87570. * \c #defines mirror the libraries'
  87571. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  87572. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  87573. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  87574. * These can be used to support multiple versions of an API during the
  87575. * transition phase, e.g.
  87576. *
  87577. * \code
  87578. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  87579. * legacy code
  87580. * #else
  87581. * new code
  87582. * #endif
  87583. * \endcode
  87584. *
  87585. * The the source will work for multiple versions and the legacy code can
  87586. * easily be removed when the transition is complete.
  87587. *
  87588. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  87589. * include/FLAC/export.h), which can be used to determine whether or not
  87590. * the library has been compiled with support for Ogg FLAC. This is
  87591. * simpler than trying to call an Ogg init function and catching the
  87592. * error.
  87593. */
  87594. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  87595. * \ingroup porting
  87596. *
  87597. * \brief
  87598. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  87599. *
  87600. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  87601. * been simplified. First, libOggFLAC has been merged into libFLAC and
  87602. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  87603. * decoding layers and three encoding layers have been merged into a
  87604. * single stream decoder and stream encoder. That is, the functionality
  87605. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  87606. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  87607. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  87608. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  87609. * is there is now a single API that can be used to encode or decode
  87610. * streams to/from native FLAC or Ogg FLAC and the single API can work
  87611. * on both seekable and non-seekable streams.
  87612. *
  87613. * Instead of creating an encoder or decoder of a certain layer, now the
  87614. * client will always create a FLAC__StreamEncoder or
  87615. * FLAC__StreamDecoder. The old layers are now differentiated by the
  87616. * initialization function. For example, for the decoder,
  87617. * FLAC__stream_decoder_init() has been replaced by
  87618. * FLAC__stream_decoder_init_stream(). This init function takes
  87619. * callbacks for the I/O, and the seeking callbacks are optional. This
  87620. * allows the client to use the same object for seekable and
  87621. * non-seekable streams. For decoding a FLAC file directly, the client
  87622. * can use FLAC__stream_decoder_init_file() and pass just a filename
  87623. * and fewer callbacks; most of the other callbacks are supplied
  87624. * internally. For situations where fopen()ing by filename is not
  87625. * possible (e.g. Unicode filenames on Windows) the client can instead
  87626. * open the file itself and supply the FILE* to
  87627. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  87628. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  87629. * Since the callbacks and client data are now passed to the init
  87630. * function, the FLAC__stream_decoder_set_*_callback() functions and
  87631. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  87632. * rest of the calls to the decoder are the same as before.
  87633. *
  87634. * There are counterpart init functions for Ogg FLAC, e.g.
  87635. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  87636. * and callbacks are the same as for native FLAC.
  87637. *
  87638. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  87639. * been set up like so:
  87640. *
  87641. * \code
  87642. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  87643. * if(decoder == NULL) do_something;
  87644. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  87645. * [... other settings ...]
  87646. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  87647. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  87648. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  87649. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  87650. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  87651. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  87652. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  87653. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  87654. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  87655. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  87656. * \endcode
  87657. *
  87658. * In FLAC 1.1.3 it is like this:
  87659. *
  87660. * \code
  87661. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  87662. * if(decoder == NULL) do_something;
  87663. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  87664. * [... other settings ...]
  87665. * if(FLAC__stream_decoder_init_stream(
  87666. * decoder,
  87667. * my_read_callback,
  87668. * my_seek_callback, // or NULL
  87669. * my_tell_callback, // or NULL
  87670. * my_length_callback, // or NULL
  87671. * my_eof_callback, // or NULL
  87672. * my_write_callback,
  87673. * my_metadata_callback, // or NULL
  87674. * my_error_callback,
  87675. * my_client_data
  87676. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87677. * \endcode
  87678. *
  87679. * or you could do;
  87680. *
  87681. * \code
  87682. * [...]
  87683. * FILE *file = fopen("somefile.flac","rb");
  87684. * if(file == NULL) do_somthing;
  87685. * if(FLAC__stream_decoder_init_FILE(
  87686. * decoder,
  87687. * file,
  87688. * my_write_callback,
  87689. * my_metadata_callback, // or NULL
  87690. * my_error_callback,
  87691. * my_client_data
  87692. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87693. * \endcode
  87694. *
  87695. * or just:
  87696. *
  87697. * \code
  87698. * [...]
  87699. * if(FLAC__stream_decoder_init_file(
  87700. * decoder,
  87701. * "somefile.flac",
  87702. * my_write_callback,
  87703. * my_metadata_callback, // or NULL
  87704. * my_error_callback,
  87705. * my_client_data
  87706. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87707. * \endcode
  87708. *
  87709. * Another small change to the decoder is in how it handles unparseable
  87710. * streams. Before, when the decoder found an unparseable stream
  87711. * (reserved for when the decoder encounters a stream from a future
  87712. * encoder that it can't parse), it changed the state to
  87713. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  87714. * drops sync and calls the error callback with a new error code
  87715. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  87716. * more robust. If your error callback does not discriminate on the the
  87717. * error state, your code does not need to be changed.
  87718. *
  87719. * The encoder now has a new setting:
  87720. * FLAC__stream_encoder_set_apodization(). This is for setting the
  87721. * method used to window the data before LPC analysis. You only need to
  87722. * add a call to this function if the default is not suitable. There
  87723. * are also two new convenience functions that may be useful:
  87724. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  87725. * FLAC__metadata_get_cuesheet().
  87726. *
  87727. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  87728. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  87729. * is now \c size_t instead of \c unsigned.
  87730. */
  87731. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  87732. * \ingroup porting
  87733. *
  87734. * \brief
  87735. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  87736. *
  87737. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  87738. * There was a slight change in the implementation of
  87739. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  87740. * of the \a metadata array of pointers so the client no longer needs
  87741. * to maintain it after the call. The objects themselves that are
  87742. * pointed to by the array are still not copied though and must be
  87743. * maintained until the call to FLAC__stream_encoder_finish().
  87744. */
  87745. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  87746. * \ingroup porting
  87747. *
  87748. * \brief
  87749. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  87750. *
  87751. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  87752. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  87753. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  87754. *
  87755. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  87756. * has changed to reflect the conversion of one of the reserved bits
  87757. * into active use. It used to be \c 2 and now is \c 1. However the
  87758. * FLAC frame header length has not changed, so to skip the proper
  87759. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  87760. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  87761. */
  87762. /** \defgroup flac FLAC C API
  87763. *
  87764. * The FLAC C API is the interface to libFLAC, a set of structures
  87765. * describing the components of FLAC streams, and functions for
  87766. * encoding and decoding streams, as well as manipulating FLAC
  87767. * metadata in files.
  87768. *
  87769. * You should start with the format components as all other modules
  87770. * are dependent on it.
  87771. */
  87772. #endif
  87773. /********* End of inlined file: all.h *********/
  87774. /********* Start of inlined file: bitmath.c *********/
  87775. /********* Start of inlined file: juce_FlacHeader.h *********/
  87776. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  87777. // tasks..
  87778. #define VERSION "1.2.1"
  87779. #define FLAC__NO_DLL 1
  87780. #ifdef _MSC_VER
  87781. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  87782. #endif
  87783. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  87784. #define FLAC__SYS_DARWIN 1
  87785. #endif
  87786. /********* End of inlined file: juce_FlacHeader.h *********/
  87787. #if JUCE_USE_FLAC
  87788. #if HAVE_CONFIG_H
  87789. # include <config.h>
  87790. #endif
  87791. /********* Start of inlined file: bitmath.h *********/
  87792. #ifndef FLAC__PRIVATE__BITMATH_H
  87793. #define FLAC__PRIVATE__BITMATH_H
  87794. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  87795. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  87796. unsigned FLAC__bitmath_silog2(int v);
  87797. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  87798. #endif
  87799. /********* End of inlined file: bitmath.h *********/
  87800. /* An example of what FLAC__bitmath_ilog2() computes:
  87801. *
  87802. * ilog2( 0) = assertion failure
  87803. * ilog2( 1) = 0
  87804. * ilog2( 2) = 1
  87805. * ilog2( 3) = 1
  87806. * ilog2( 4) = 2
  87807. * ilog2( 5) = 2
  87808. * ilog2( 6) = 2
  87809. * ilog2( 7) = 2
  87810. * ilog2( 8) = 3
  87811. * ilog2( 9) = 3
  87812. * ilog2(10) = 3
  87813. * ilog2(11) = 3
  87814. * ilog2(12) = 3
  87815. * ilog2(13) = 3
  87816. * ilog2(14) = 3
  87817. * ilog2(15) = 3
  87818. * ilog2(16) = 4
  87819. * ilog2(17) = 4
  87820. * ilog2(18) = 4
  87821. */
  87822. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  87823. {
  87824. unsigned l = 0;
  87825. FLAC__ASSERT(v > 0);
  87826. while(v >>= 1)
  87827. l++;
  87828. return l;
  87829. }
  87830. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  87831. {
  87832. unsigned l = 0;
  87833. FLAC__ASSERT(v > 0);
  87834. while(v >>= 1)
  87835. l++;
  87836. return l;
  87837. }
  87838. /* An example of what FLAC__bitmath_silog2() computes:
  87839. *
  87840. * silog2(-10) = 5
  87841. * silog2(- 9) = 5
  87842. * silog2(- 8) = 4
  87843. * silog2(- 7) = 4
  87844. * silog2(- 6) = 4
  87845. * silog2(- 5) = 4
  87846. * silog2(- 4) = 3
  87847. * silog2(- 3) = 3
  87848. * silog2(- 2) = 2
  87849. * silog2(- 1) = 2
  87850. * silog2( 0) = 0
  87851. * silog2( 1) = 2
  87852. * silog2( 2) = 3
  87853. * silog2( 3) = 3
  87854. * silog2( 4) = 4
  87855. * silog2( 5) = 4
  87856. * silog2( 6) = 4
  87857. * silog2( 7) = 4
  87858. * silog2( 8) = 5
  87859. * silog2( 9) = 5
  87860. * silog2( 10) = 5
  87861. */
  87862. unsigned FLAC__bitmath_silog2(int v)
  87863. {
  87864. while(1) {
  87865. if(v == 0) {
  87866. return 0;
  87867. }
  87868. else if(v > 0) {
  87869. unsigned l = 0;
  87870. while(v) {
  87871. l++;
  87872. v >>= 1;
  87873. }
  87874. return l+1;
  87875. }
  87876. else if(v == -1) {
  87877. return 2;
  87878. }
  87879. else {
  87880. v++;
  87881. v = -v;
  87882. }
  87883. }
  87884. }
  87885. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  87886. {
  87887. while(1) {
  87888. if(v == 0) {
  87889. return 0;
  87890. }
  87891. else if(v > 0) {
  87892. unsigned l = 0;
  87893. while(v) {
  87894. l++;
  87895. v >>= 1;
  87896. }
  87897. return l+1;
  87898. }
  87899. else if(v == -1) {
  87900. return 2;
  87901. }
  87902. else {
  87903. v++;
  87904. v = -v;
  87905. }
  87906. }
  87907. }
  87908. #endif
  87909. /********* End of inlined file: bitmath.c *********/
  87910. /********* Start of inlined file: bitreader.c *********/
  87911. /********* Start of inlined file: juce_FlacHeader.h *********/
  87912. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  87913. // tasks..
  87914. #define VERSION "1.2.1"
  87915. #define FLAC__NO_DLL 1
  87916. #ifdef _MSC_VER
  87917. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  87918. #endif
  87919. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  87920. #define FLAC__SYS_DARWIN 1
  87921. #endif
  87922. /********* End of inlined file: juce_FlacHeader.h *********/
  87923. #if JUCE_USE_FLAC
  87924. #if HAVE_CONFIG_H
  87925. # include <config.h>
  87926. #endif
  87927. #include <stdlib.h> /* for malloc() */
  87928. #include <string.h> /* for memcpy(), memset() */
  87929. #ifdef _MSC_VER
  87930. #include <winsock.h> /* for ntohl() */
  87931. #elif defined FLAC__SYS_DARWIN
  87932. #include <machine/endian.h> /* for ntohl() */
  87933. #elif defined __MINGW32__
  87934. #include <winsock.h> /* for ntohl() */
  87935. #else
  87936. #include <netinet/in.h> /* for ntohl() */
  87937. #endif
  87938. /********* Start of inlined file: bitreader.h *********/
  87939. #ifndef FLAC__PRIVATE__BITREADER_H
  87940. #define FLAC__PRIVATE__BITREADER_H
  87941. #include <stdio.h> /* for FILE */
  87942. /********* Start of inlined file: cpu.h *********/
  87943. #ifndef FLAC__PRIVATE__CPU_H
  87944. #define FLAC__PRIVATE__CPU_H
  87945. #ifdef HAVE_CONFIG_H
  87946. #include <config.h>
  87947. #endif
  87948. typedef enum {
  87949. FLAC__CPUINFO_TYPE_IA32,
  87950. FLAC__CPUINFO_TYPE_PPC,
  87951. FLAC__CPUINFO_TYPE_UNKNOWN
  87952. } FLAC__CPUInfo_Type;
  87953. typedef struct {
  87954. FLAC__bool cpuid;
  87955. FLAC__bool bswap;
  87956. FLAC__bool cmov;
  87957. FLAC__bool mmx;
  87958. FLAC__bool fxsr;
  87959. FLAC__bool sse;
  87960. FLAC__bool sse2;
  87961. FLAC__bool sse3;
  87962. FLAC__bool ssse3;
  87963. FLAC__bool _3dnow;
  87964. FLAC__bool ext3dnow;
  87965. FLAC__bool extmmx;
  87966. } FLAC__CPUInfo_IA32;
  87967. typedef struct {
  87968. FLAC__bool altivec;
  87969. FLAC__bool ppc64;
  87970. } FLAC__CPUInfo_PPC;
  87971. typedef struct {
  87972. FLAC__bool use_asm;
  87973. FLAC__CPUInfo_Type type;
  87974. union {
  87975. FLAC__CPUInfo_IA32 ia32;
  87976. FLAC__CPUInfo_PPC ppc;
  87977. } data;
  87978. } FLAC__CPUInfo;
  87979. void FLAC__cpu_info(FLAC__CPUInfo *info);
  87980. #ifndef FLAC__NO_ASM
  87981. #ifdef FLAC__CPU_IA32
  87982. #ifdef FLAC__HAS_NASM
  87983. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  87984. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  87985. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  87986. #endif
  87987. #endif
  87988. #endif
  87989. #endif
  87990. /********* End of inlined file: cpu.h *********/
  87991. /*
  87992. * opaque structure definition
  87993. */
  87994. struct FLAC__BitReader;
  87995. typedef struct FLAC__BitReader FLAC__BitReader;
  87996. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  87997. /*
  87998. * construction, deletion, initialization, etc functions
  87999. */
  88000. FLAC__BitReader *FLAC__bitreader_new(void);
  88001. void FLAC__bitreader_delete(FLAC__BitReader *br);
  88002. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  88003. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  88004. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  88005. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  88006. /*
  88007. * CRC functions
  88008. */
  88009. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  88010. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  88011. /*
  88012. * info functions
  88013. */
  88014. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  88015. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  88016. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  88017. /*
  88018. * read functions
  88019. */
  88020. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  88021. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  88022. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  88023. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  88024. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  88025. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  88026. 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! */
  88027. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  88028. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88029. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88030. #ifndef FLAC__NO_ASM
  88031. # ifdef FLAC__CPU_IA32
  88032. # ifdef FLAC__HAS_NASM
  88033. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88034. # endif
  88035. # endif
  88036. #endif
  88037. #if 0 /* UNUSED */
  88038. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88039. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  88040. #endif
  88041. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  88042. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  88043. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  88044. #endif
  88045. /********* End of inlined file: bitreader.h *********/
  88046. /********* Start of inlined file: crc.h *********/
  88047. #ifndef FLAC__PRIVATE__CRC_H
  88048. #define FLAC__PRIVATE__CRC_H
  88049. /* 8 bit CRC generator, MSB shifted first
  88050. ** polynomial = x^8 + x^2 + x^1 + x^0
  88051. ** init = 0
  88052. */
  88053. extern FLAC__byte const FLAC__crc8_table[256];
  88054. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  88055. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  88056. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  88057. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  88058. /* 16 bit CRC generator, MSB shifted first
  88059. ** polynomial = x^16 + x^15 + x^2 + x^0
  88060. ** init = 0
  88061. */
  88062. extern unsigned FLAC__crc16_table[256];
  88063. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  88064. /* this alternate may be faster on some systems/compilers */
  88065. #if 0
  88066. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  88067. #endif
  88068. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  88069. #endif
  88070. /********* End of inlined file: crc.h *********/
  88071. /* Things should be fastest when this matches the machine word size */
  88072. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  88073. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  88074. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  88075. typedef FLAC__uint32 brword;
  88076. #define FLAC__BYTES_PER_WORD 4
  88077. #define FLAC__BITS_PER_WORD 32
  88078. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  88079. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  88080. #if WORDS_BIGENDIAN
  88081. #define SWAP_BE_WORD_TO_HOST(x) (x)
  88082. #else
  88083. #if defined (_MSC_VER) && defined (_X86_)
  88084. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  88085. #else
  88086. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  88087. #endif
  88088. #endif
  88089. /* counts the # of zero MSBs in a word */
  88090. #define COUNT_ZERO_MSBS(word) ( \
  88091. (word) <= 0xffff ? \
  88092. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  88093. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  88094. )
  88095. /* this alternate might be slightly faster on some systems/compilers: */
  88096. #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])) )
  88097. /*
  88098. * This should be at least twice as large as the largest number of words
  88099. * required to represent any 'number' (in any encoding) you are going to
  88100. * read. With FLAC this is on the order of maybe a few hundred bits.
  88101. * If the buffer is smaller than that, the decoder won't be able to read
  88102. * in a whole number that is in a variable length encoding (e.g. Rice).
  88103. * But to be practical it should be at least 1K bytes.
  88104. *
  88105. * Increase this number to decrease the number of read callbacks, at the
  88106. * expense of using more memory. Or decrease for the reverse effect,
  88107. * keeping in mind the limit from the first paragraph. The optimal size
  88108. * also depends on the CPU cache size and other factors; some twiddling
  88109. * may be necessary to squeeze out the best performance.
  88110. */
  88111. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  88112. static const unsigned char byte_to_unary_table[] = {
  88113. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  88114. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  88115. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88116. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88117. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88118. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88119. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88120. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  88129. };
  88130. #ifdef min
  88131. #undef min
  88132. #endif
  88133. #define min(x,y) ((x)<(y)?(x):(y))
  88134. #ifdef max
  88135. #undef max
  88136. #endif
  88137. #define max(x,y) ((x)>(y)?(x):(y))
  88138. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  88139. #ifdef _MSC_VER
  88140. #define FLAC__U64L(x) x
  88141. #else
  88142. #define FLAC__U64L(x) x##LLU
  88143. #endif
  88144. #ifndef FLaC__INLINE
  88145. #define FLaC__INLINE
  88146. #endif
  88147. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  88148. struct FLAC__BitReader {
  88149. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  88150. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  88151. brword *buffer;
  88152. unsigned capacity; /* in words */
  88153. unsigned words; /* # of completed words in buffer */
  88154. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  88155. unsigned consumed_words; /* #words ... */
  88156. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  88157. unsigned read_crc16; /* the running frame CRC */
  88158. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  88159. FLAC__BitReaderReadCallback read_callback;
  88160. void *client_data;
  88161. FLAC__CPUInfo cpu_info;
  88162. };
  88163. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  88164. {
  88165. register unsigned crc = br->read_crc16;
  88166. #if FLAC__BYTES_PER_WORD == 4
  88167. switch(br->crc16_align) {
  88168. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  88169. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88170. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88171. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88172. }
  88173. #elif FLAC__BYTES_PER_WORD == 8
  88174. switch(br->crc16_align) {
  88175. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  88176. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  88177. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  88178. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  88179. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  88180. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88181. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88182. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88183. }
  88184. #else
  88185. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  88186. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  88187. br->read_crc16 = crc;
  88188. #endif
  88189. br->crc16_align = 0;
  88190. }
  88191. /* would be static except it needs to be called by asm routines */
  88192. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  88193. {
  88194. unsigned start, end;
  88195. size_t bytes;
  88196. FLAC__byte *target;
  88197. /* first shift the unconsumed buffer data toward the front as much as possible */
  88198. if(br->consumed_words > 0) {
  88199. start = br->consumed_words;
  88200. end = br->words + (br->bytes? 1:0);
  88201. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  88202. br->words -= start;
  88203. br->consumed_words = 0;
  88204. }
  88205. /*
  88206. * set the target for reading, taking into account word alignment and endianness
  88207. */
  88208. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  88209. if(bytes == 0)
  88210. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  88211. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  88212. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  88213. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  88214. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  88215. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  88216. * ^^-------target, bytes=3
  88217. * on LE machines, have to byteswap the odd tail word so nothing is
  88218. * overwritten:
  88219. */
  88220. #if WORDS_BIGENDIAN
  88221. #else
  88222. if(br->bytes)
  88223. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  88224. #endif
  88225. /* now it looks like:
  88226. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  88227. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  88228. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  88229. * ^^-------target, bytes=3
  88230. */
  88231. /* read in the data; note that the callback may return a smaller number of bytes */
  88232. if(!br->read_callback(target, &bytes, br->client_data))
  88233. return false;
  88234. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  88235. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88236. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88237. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  88238. * now have to byteswap on LE machines:
  88239. */
  88240. #if WORDS_BIGENDIAN
  88241. #else
  88242. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  88243. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  88244. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  88245. start = br->words;
  88246. local_swap32_block_(br->buffer + start, end - start);
  88247. }
  88248. else
  88249. # endif
  88250. for(start = br->words; start < end; start++)
  88251. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  88252. #endif
  88253. /* now it looks like:
  88254. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88255. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88256. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  88257. * finally we'll update the reader values:
  88258. */
  88259. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  88260. br->words = end / FLAC__BYTES_PER_WORD;
  88261. br->bytes = end % FLAC__BYTES_PER_WORD;
  88262. return true;
  88263. }
  88264. /***********************************************************************
  88265. *
  88266. * Class constructor/destructor
  88267. *
  88268. ***********************************************************************/
  88269. FLAC__BitReader *FLAC__bitreader_new(void)
  88270. {
  88271. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  88272. /* calloc() implies:
  88273. memset(br, 0, sizeof(FLAC__BitReader));
  88274. br->buffer = 0;
  88275. br->capacity = 0;
  88276. br->words = br->bytes = 0;
  88277. br->consumed_words = br->consumed_bits = 0;
  88278. br->read_callback = 0;
  88279. br->client_data = 0;
  88280. */
  88281. return br;
  88282. }
  88283. void FLAC__bitreader_delete(FLAC__BitReader *br)
  88284. {
  88285. FLAC__ASSERT(0 != br);
  88286. FLAC__bitreader_free(br);
  88287. free(br);
  88288. }
  88289. /***********************************************************************
  88290. *
  88291. * Public class methods
  88292. *
  88293. ***********************************************************************/
  88294. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  88295. {
  88296. FLAC__ASSERT(0 != br);
  88297. br->words = br->bytes = 0;
  88298. br->consumed_words = br->consumed_bits = 0;
  88299. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  88300. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  88301. if(br->buffer == 0)
  88302. return false;
  88303. br->read_callback = rcb;
  88304. br->client_data = cd;
  88305. br->cpu_info = cpu;
  88306. return true;
  88307. }
  88308. void FLAC__bitreader_free(FLAC__BitReader *br)
  88309. {
  88310. FLAC__ASSERT(0 != br);
  88311. if(0 != br->buffer)
  88312. free(br->buffer);
  88313. br->buffer = 0;
  88314. br->capacity = 0;
  88315. br->words = br->bytes = 0;
  88316. br->consumed_words = br->consumed_bits = 0;
  88317. br->read_callback = 0;
  88318. br->client_data = 0;
  88319. }
  88320. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  88321. {
  88322. br->words = br->bytes = 0;
  88323. br->consumed_words = br->consumed_bits = 0;
  88324. return true;
  88325. }
  88326. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  88327. {
  88328. unsigned i, j;
  88329. if(br == 0) {
  88330. fprintf(out, "bitreader is NULL\n");
  88331. }
  88332. else {
  88333. 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);
  88334. for(i = 0; i < br->words; i++) {
  88335. fprintf(out, "%08X: ", i);
  88336. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88337. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88338. fprintf(out, ".");
  88339. else
  88340. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88341. fprintf(out, "\n");
  88342. }
  88343. if(br->bytes > 0) {
  88344. fprintf(out, "%08X: ", i);
  88345. for(j = 0; j < br->bytes*8; j++)
  88346. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88347. fprintf(out, ".");
  88348. else
  88349. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  88350. fprintf(out, "\n");
  88351. }
  88352. }
  88353. }
  88354. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  88355. {
  88356. FLAC__ASSERT(0 != br);
  88357. FLAC__ASSERT(0 != br->buffer);
  88358. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88359. br->read_crc16 = (unsigned)seed;
  88360. br->crc16_align = br->consumed_bits;
  88361. }
  88362. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  88363. {
  88364. FLAC__ASSERT(0 != br);
  88365. FLAC__ASSERT(0 != br->buffer);
  88366. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88367. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  88368. /* CRC any tail bytes in a partially-consumed word */
  88369. if(br->consumed_bits) {
  88370. const brword tail = br->buffer[br->consumed_words];
  88371. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  88372. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  88373. }
  88374. return br->read_crc16;
  88375. }
  88376. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  88377. {
  88378. return ((br->consumed_bits & 7) == 0);
  88379. }
  88380. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  88381. {
  88382. return 8 - (br->consumed_bits & 7);
  88383. }
  88384. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  88385. {
  88386. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  88387. }
  88388. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  88389. {
  88390. FLAC__ASSERT(0 != br);
  88391. FLAC__ASSERT(0 != br->buffer);
  88392. FLAC__ASSERT(bits <= 32);
  88393. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  88394. FLAC__ASSERT(br->consumed_words <= br->words);
  88395. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88396. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88397. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  88398. *val = 0;
  88399. return true;
  88400. }
  88401. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  88402. if(!bitreader_read_from_client_(br))
  88403. return false;
  88404. }
  88405. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  88406. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88407. if(br->consumed_bits) {
  88408. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88409. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  88410. const brword word = br->buffer[br->consumed_words];
  88411. if(bits < n) {
  88412. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  88413. br->consumed_bits += bits;
  88414. return true;
  88415. }
  88416. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  88417. bits -= n;
  88418. crc16_update_word_(br, word);
  88419. br->consumed_words++;
  88420. br->consumed_bits = 0;
  88421. 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 */
  88422. *val <<= bits;
  88423. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  88424. br->consumed_bits = bits;
  88425. }
  88426. return true;
  88427. }
  88428. else {
  88429. const brword word = br->buffer[br->consumed_words];
  88430. if(bits < FLAC__BITS_PER_WORD) {
  88431. *val = word >> (FLAC__BITS_PER_WORD-bits);
  88432. br->consumed_bits = bits;
  88433. return true;
  88434. }
  88435. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  88436. *val = word;
  88437. crc16_update_word_(br, word);
  88438. br->consumed_words++;
  88439. return true;
  88440. }
  88441. }
  88442. else {
  88443. /* in this case we're starting our read at a partial tail word;
  88444. * the reader has guaranteed that we have at least 'bits' bits
  88445. * available to read, which makes this case simpler.
  88446. */
  88447. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88448. if(br->consumed_bits) {
  88449. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88450. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  88451. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  88452. br->consumed_bits += bits;
  88453. return true;
  88454. }
  88455. else {
  88456. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  88457. br->consumed_bits += bits;
  88458. return true;
  88459. }
  88460. }
  88461. }
  88462. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  88463. {
  88464. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  88465. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  88466. return false;
  88467. /* sign-extend: */
  88468. *val <<= (32-bits);
  88469. *val >>= (32-bits);
  88470. return true;
  88471. }
  88472. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  88473. {
  88474. FLAC__uint32 hi, lo;
  88475. if(bits > 32) {
  88476. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  88477. return false;
  88478. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  88479. return false;
  88480. *val = hi;
  88481. *val <<= 32;
  88482. *val |= lo;
  88483. }
  88484. else {
  88485. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  88486. return false;
  88487. *val = lo;
  88488. }
  88489. return true;
  88490. }
  88491. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  88492. {
  88493. FLAC__uint32 x8, x32 = 0;
  88494. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88495. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  88496. return false;
  88497. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88498. return false;
  88499. x32 |= (x8 << 8);
  88500. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88501. return false;
  88502. x32 |= (x8 << 16);
  88503. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88504. return false;
  88505. x32 |= (x8 << 24);
  88506. *val = x32;
  88507. return true;
  88508. }
  88509. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  88510. {
  88511. /*
  88512. * OPT: a faster implementation is possible but probably not that useful
  88513. * since this is only called a couple of times in the metadata readers.
  88514. */
  88515. FLAC__ASSERT(0 != br);
  88516. FLAC__ASSERT(0 != br->buffer);
  88517. if(bits > 0) {
  88518. const unsigned n = br->consumed_bits & 7;
  88519. unsigned m;
  88520. FLAC__uint32 x;
  88521. if(n != 0) {
  88522. m = min(8-n, bits);
  88523. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  88524. return false;
  88525. bits -= m;
  88526. }
  88527. m = bits / 8;
  88528. if(m > 0) {
  88529. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  88530. return false;
  88531. bits %= 8;
  88532. }
  88533. if(bits > 0) {
  88534. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  88535. return false;
  88536. }
  88537. }
  88538. return true;
  88539. }
  88540. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  88541. {
  88542. FLAC__uint32 x;
  88543. FLAC__ASSERT(0 != br);
  88544. FLAC__ASSERT(0 != br->buffer);
  88545. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  88546. /* step 1: skip over partial head word to get word aligned */
  88547. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  88548. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88549. return false;
  88550. nvals--;
  88551. }
  88552. if(0 == nvals)
  88553. return true;
  88554. /* step 2: skip whole words in chunks */
  88555. while(nvals >= FLAC__BYTES_PER_WORD) {
  88556. if(br->consumed_words < br->words) {
  88557. br->consumed_words++;
  88558. nvals -= FLAC__BYTES_PER_WORD;
  88559. }
  88560. else if(!bitreader_read_from_client_(br))
  88561. return false;
  88562. }
  88563. /* step 3: skip any remainder from partial tail bytes */
  88564. while(nvals) {
  88565. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88566. return false;
  88567. nvals--;
  88568. }
  88569. return true;
  88570. }
  88571. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  88572. {
  88573. FLAC__uint32 x;
  88574. FLAC__ASSERT(0 != br);
  88575. FLAC__ASSERT(0 != br->buffer);
  88576. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  88577. /* step 1: read from partial head word to get word aligned */
  88578. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  88579. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88580. return false;
  88581. *val++ = (FLAC__byte)x;
  88582. nvals--;
  88583. }
  88584. if(0 == nvals)
  88585. return true;
  88586. /* step 2: read whole words in chunks */
  88587. while(nvals >= FLAC__BYTES_PER_WORD) {
  88588. if(br->consumed_words < br->words) {
  88589. const brword word = br->buffer[br->consumed_words++];
  88590. #if FLAC__BYTES_PER_WORD == 4
  88591. val[0] = (FLAC__byte)(word >> 24);
  88592. val[1] = (FLAC__byte)(word >> 16);
  88593. val[2] = (FLAC__byte)(word >> 8);
  88594. val[3] = (FLAC__byte)word;
  88595. #elif FLAC__BYTES_PER_WORD == 8
  88596. val[0] = (FLAC__byte)(word >> 56);
  88597. val[1] = (FLAC__byte)(word >> 48);
  88598. val[2] = (FLAC__byte)(word >> 40);
  88599. val[3] = (FLAC__byte)(word >> 32);
  88600. val[4] = (FLAC__byte)(word >> 24);
  88601. val[5] = (FLAC__byte)(word >> 16);
  88602. val[6] = (FLAC__byte)(word >> 8);
  88603. val[7] = (FLAC__byte)word;
  88604. #else
  88605. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  88606. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  88607. #endif
  88608. val += FLAC__BYTES_PER_WORD;
  88609. nvals -= FLAC__BYTES_PER_WORD;
  88610. }
  88611. else if(!bitreader_read_from_client_(br))
  88612. return false;
  88613. }
  88614. /* step 3: read any remainder from partial tail bytes */
  88615. while(nvals) {
  88616. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88617. return false;
  88618. *val++ = (FLAC__byte)x;
  88619. nvals--;
  88620. }
  88621. return true;
  88622. }
  88623. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  88624. #if 0 /* slow but readable version */
  88625. {
  88626. unsigned bit;
  88627. FLAC__ASSERT(0 != br);
  88628. FLAC__ASSERT(0 != br->buffer);
  88629. *val = 0;
  88630. while(1) {
  88631. if(!FLAC__bitreader_read_bit(br, &bit))
  88632. return false;
  88633. if(bit)
  88634. break;
  88635. else
  88636. *val++;
  88637. }
  88638. return true;
  88639. }
  88640. #else
  88641. {
  88642. unsigned i;
  88643. FLAC__ASSERT(0 != br);
  88644. FLAC__ASSERT(0 != br->buffer);
  88645. *val = 0;
  88646. while(1) {
  88647. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  88648. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  88649. if(b) {
  88650. i = COUNT_ZERO_MSBS(b);
  88651. *val += i;
  88652. i++;
  88653. br->consumed_bits += i;
  88654. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  88655. crc16_update_word_(br, br->buffer[br->consumed_words]);
  88656. br->consumed_words++;
  88657. br->consumed_bits = 0;
  88658. }
  88659. return true;
  88660. }
  88661. else {
  88662. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  88663. crc16_update_word_(br, br->buffer[br->consumed_words]);
  88664. br->consumed_words++;
  88665. br->consumed_bits = 0;
  88666. /* didn't find stop bit yet, have to keep going... */
  88667. }
  88668. }
  88669. /* at this point we've eaten up all the whole words; have to try
  88670. * reading through any tail bytes before calling the read callback.
  88671. * this is a repeat of the above logic adjusted for the fact we
  88672. * don't have a whole word. note though if the client is feeding
  88673. * us data a byte at a time (unlikely), br->consumed_bits may not
  88674. * be zero.
  88675. */
  88676. if(br->bytes) {
  88677. const unsigned end = br->bytes * 8;
  88678. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  88679. if(b) {
  88680. i = COUNT_ZERO_MSBS(b);
  88681. *val += i;
  88682. i++;
  88683. br->consumed_bits += i;
  88684. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  88685. return true;
  88686. }
  88687. else {
  88688. *val += end - br->consumed_bits;
  88689. br->consumed_bits += end;
  88690. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  88691. /* didn't find stop bit yet, have to keep going... */
  88692. }
  88693. }
  88694. if(!bitreader_read_from_client_(br))
  88695. return false;
  88696. }
  88697. }
  88698. #endif
  88699. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  88700. {
  88701. FLAC__uint32 lsbs = 0, msbs = 0;
  88702. unsigned uval;
  88703. FLAC__ASSERT(0 != br);
  88704. FLAC__ASSERT(0 != br->buffer);
  88705. FLAC__ASSERT(parameter <= 31);
  88706. /* read the unary MSBs and end bit */
  88707. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  88708. return false;
  88709. /* read the binary LSBs */
  88710. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  88711. return false;
  88712. /* compose the value */
  88713. uval = (msbs << parameter) | lsbs;
  88714. if(uval & 1)
  88715. *val = -((int)(uval >> 1)) - 1;
  88716. else
  88717. *val = (int)(uval >> 1);
  88718. return true;
  88719. }
  88720. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  88721. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  88722. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  88723. /* OPT: possibly faster version for use with MSVC */
  88724. #ifdef _MSC_VER
  88725. {
  88726. unsigned i;
  88727. unsigned uval = 0;
  88728. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  88729. /* try and get br->consumed_words and br->consumed_bits into register;
  88730. * must remember to flush them back to *br before calling other
  88731. * bitwriter functions that use them, and before returning */
  88732. register unsigned cwords;
  88733. register unsigned cbits;
  88734. FLAC__ASSERT(0 != br);
  88735. FLAC__ASSERT(0 != br->buffer);
  88736. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88737. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88738. FLAC__ASSERT(parameter < 32);
  88739. /* 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 */
  88740. if(nvals == 0)
  88741. return true;
  88742. cbits = br->consumed_bits;
  88743. cwords = br->consumed_words;
  88744. while(1) {
  88745. /* read unary part */
  88746. while(1) {
  88747. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88748. brword b = br->buffer[cwords] << cbits;
  88749. if(b) {
  88750. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  88751. __asm {
  88752. bsr eax, b
  88753. not eax
  88754. and eax, 31
  88755. mov i, eax
  88756. }
  88757. #else
  88758. i = COUNT_ZERO_MSBS(b);
  88759. #endif
  88760. uval += i;
  88761. bits = parameter;
  88762. i++;
  88763. cbits += i;
  88764. if(cbits == FLAC__BITS_PER_WORD) {
  88765. crc16_update_word_(br, br->buffer[cwords]);
  88766. cwords++;
  88767. cbits = 0;
  88768. }
  88769. goto break1;
  88770. }
  88771. else {
  88772. uval += FLAC__BITS_PER_WORD - cbits;
  88773. crc16_update_word_(br, br->buffer[cwords]);
  88774. cwords++;
  88775. cbits = 0;
  88776. /* didn't find stop bit yet, have to keep going... */
  88777. }
  88778. }
  88779. /* at this point we've eaten up all the whole words; have to try
  88780. * reading through any tail bytes before calling the read callback.
  88781. * this is a repeat of the above logic adjusted for the fact we
  88782. * don't have a whole word. note though if the client is feeding
  88783. * us data a byte at a time (unlikely), br->consumed_bits may not
  88784. * be zero.
  88785. */
  88786. if(br->bytes) {
  88787. const unsigned end = br->bytes * 8;
  88788. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  88789. if(b) {
  88790. i = COUNT_ZERO_MSBS(b);
  88791. uval += i;
  88792. bits = parameter;
  88793. i++;
  88794. cbits += i;
  88795. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88796. goto break1;
  88797. }
  88798. else {
  88799. uval += end - cbits;
  88800. cbits += end;
  88801. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88802. /* didn't find stop bit yet, have to keep going... */
  88803. }
  88804. }
  88805. /* flush registers and read; bitreader_read_from_client_() does
  88806. * not touch br->consumed_bits at all but we still need to set
  88807. * it in case it fails and we have to return false.
  88808. */
  88809. br->consumed_bits = cbits;
  88810. br->consumed_words = cwords;
  88811. if(!bitreader_read_from_client_(br))
  88812. return false;
  88813. cwords = br->consumed_words;
  88814. }
  88815. break1:
  88816. /* read binary part */
  88817. FLAC__ASSERT(cwords <= br->words);
  88818. if(bits) {
  88819. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  88820. /* flush registers and read; bitreader_read_from_client_() does
  88821. * not touch br->consumed_bits at all but we still need to set
  88822. * it in case it fails and we have to return false.
  88823. */
  88824. br->consumed_bits = cbits;
  88825. br->consumed_words = cwords;
  88826. if(!bitreader_read_from_client_(br))
  88827. return false;
  88828. cwords = br->consumed_words;
  88829. }
  88830. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88831. if(cbits) {
  88832. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88833. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  88834. const brword word = br->buffer[cwords];
  88835. if(bits < n) {
  88836. uval <<= bits;
  88837. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  88838. cbits += bits;
  88839. goto break2;
  88840. }
  88841. uval <<= n;
  88842. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  88843. bits -= n;
  88844. crc16_update_word_(br, word);
  88845. cwords++;
  88846. cbits = 0;
  88847. 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 */
  88848. uval <<= bits;
  88849. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  88850. cbits = bits;
  88851. }
  88852. goto break2;
  88853. }
  88854. else {
  88855. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  88856. uval <<= bits;
  88857. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  88858. cbits = bits;
  88859. goto break2;
  88860. }
  88861. }
  88862. else {
  88863. /* in this case we're starting our read at a partial tail word;
  88864. * the reader has guaranteed that we have at least 'bits' bits
  88865. * available to read, which makes this case simpler.
  88866. */
  88867. uval <<= bits;
  88868. if(cbits) {
  88869. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88870. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  88871. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  88872. cbits += bits;
  88873. goto break2;
  88874. }
  88875. else {
  88876. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  88877. cbits += bits;
  88878. goto break2;
  88879. }
  88880. }
  88881. }
  88882. break2:
  88883. /* compose the value */
  88884. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  88885. /* are we done? */
  88886. --nvals;
  88887. if(nvals == 0) {
  88888. br->consumed_bits = cbits;
  88889. br->consumed_words = cwords;
  88890. return true;
  88891. }
  88892. uval = 0;
  88893. ++vals;
  88894. }
  88895. }
  88896. #else
  88897. {
  88898. unsigned i;
  88899. unsigned uval = 0;
  88900. /* try and get br->consumed_words and br->consumed_bits into register;
  88901. * must remember to flush them back to *br before calling other
  88902. * bitwriter functions that use them, and before returning */
  88903. register unsigned cwords;
  88904. register unsigned cbits;
  88905. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  88906. FLAC__ASSERT(0 != br);
  88907. FLAC__ASSERT(0 != br->buffer);
  88908. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88909. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88910. FLAC__ASSERT(parameter < 32);
  88911. /* 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 */
  88912. if(nvals == 0)
  88913. return true;
  88914. cbits = br->consumed_bits;
  88915. cwords = br->consumed_words;
  88916. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  88917. while(1) {
  88918. /* read unary part */
  88919. while(1) {
  88920. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88921. brword b = br->buffer[cwords] << cbits;
  88922. if(b) {
  88923. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  88924. asm volatile (
  88925. "bsrl %1, %0;"
  88926. "notl %0;"
  88927. "andl $31, %0;"
  88928. : "=r"(i)
  88929. : "r"(b)
  88930. );
  88931. #else
  88932. i = COUNT_ZERO_MSBS(b);
  88933. #endif
  88934. uval += i;
  88935. cbits += i;
  88936. cbits++; /* skip over stop bit */
  88937. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  88938. crc16_update_word_(br, br->buffer[cwords]);
  88939. cwords++;
  88940. cbits = 0;
  88941. }
  88942. goto break1;
  88943. }
  88944. else {
  88945. uval += FLAC__BITS_PER_WORD - cbits;
  88946. crc16_update_word_(br, br->buffer[cwords]);
  88947. cwords++;
  88948. cbits = 0;
  88949. /* didn't find stop bit yet, have to keep going... */
  88950. }
  88951. }
  88952. /* at this point we've eaten up all the whole words; have to try
  88953. * reading through any tail bytes before calling the read callback.
  88954. * this is a repeat of the above logic adjusted for the fact we
  88955. * don't have a whole word. note though if the client is feeding
  88956. * us data a byte at a time (unlikely), br->consumed_bits may not
  88957. * be zero.
  88958. */
  88959. if(br->bytes) {
  88960. const unsigned end = br->bytes * 8;
  88961. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  88962. if(b) {
  88963. i = COUNT_ZERO_MSBS(b);
  88964. uval += i;
  88965. cbits += i;
  88966. cbits++; /* skip over stop bit */
  88967. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88968. goto break1;
  88969. }
  88970. else {
  88971. uval += end - cbits;
  88972. cbits += end;
  88973. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88974. /* didn't find stop bit yet, have to keep going... */
  88975. }
  88976. }
  88977. /* flush registers and read; bitreader_read_from_client_() does
  88978. * not touch br->consumed_bits at all but we still need to set
  88979. * it in case it fails and we have to return false.
  88980. */
  88981. br->consumed_bits = cbits;
  88982. br->consumed_words = cwords;
  88983. if(!bitreader_read_from_client_(br))
  88984. return false;
  88985. cwords = br->consumed_words;
  88986. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  88987. /* + uval to offset our count by the # of unary bits already
  88988. * consumed before the read, because we will add these back
  88989. * in all at once at break1
  88990. */
  88991. }
  88992. break1:
  88993. ucbits -= uval;
  88994. ucbits--; /* account for stop bit */
  88995. /* read binary part */
  88996. FLAC__ASSERT(cwords <= br->words);
  88997. if(parameter) {
  88998. while(ucbits < parameter) {
  88999. /* flush registers and read; bitreader_read_from_client_() does
  89000. * not touch br->consumed_bits at all but we still need to set
  89001. * it in case it fails and we have to return false.
  89002. */
  89003. br->consumed_bits = cbits;
  89004. br->consumed_words = cwords;
  89005. if(!bitreader_read_from_client_(br))
  89006. return false;
  89007. cwords = br->consumed_words;
  89008. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89009. }
  89010. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89011. if(cbits) {
  89012. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  89013. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89014. const brword word = br->buffer[cwords];
  89015. if(parameter < n) {
  89016. uval <<= parameter;
  89017. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  89018. cbits += parameter;
  89019. }
  89020. else {
  89021. uval <<= n;
  89022. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89023. crc16_update_word_(br, word);
  89024. cwords++;
  89025. cbits = parameter - n;
  89026. 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 */
  89027. uval <<= cbits;
  89028. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  89029. }
  89030. }
  89031. }
  89032. else {
  89033. cbits = parameter;
  89034. uval <<= parameter;
  89035. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89036. }
  89037. }
  89038. else {
  89039. /* in this case we're starting our read at a partial tail word;
  89040. * the reader has guaranteed that we have at least 'parameter'
  89041. * bits available to read, which makes this case simpler.
  89042. */
  89043. uval <<= parameter;
  89044. if(cbits) {
  89045. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89046. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  89047. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  89048. cbits += parameter;
  89049. }
  89050. else {
  89051. cbits = parameter;
  89052. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89053. }
  89054. }
  89055. }
  89056. ucbits -= parameter;
  89057. /* compose the value */
  89058. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89059. /* are we done? */
  89060. --nvals;
  89061. if(nvals == 0) {
  89062. br->consumed_bits = cbits;
  89063. br->consumed_words = cwords;
  89064. return true;
  89065. }
  89066. uval = 0;
  89067. ++vals;
  89068. }
  89069. }
  89070. #endif
  89071. #if 0 /* UNUSED */
  89072. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89073. {
  89074. FLAC__uint32 lsbs = 0, msbs = 0;
  89075. unsigned bit, uval, k;
  89076. FLAC__ASSERT(0 != br);
  89077. FLAC__ASSERT(0 != br->buffer);
  89078. k = FLAC__bitmath_ilog2(parameter);
  89079. /* read the unary MSBs and end bit */
  89080. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89081. return false;
  89082. /* read the binary LSBs */
  89083. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89084. return false;
  89085. if(parameter == 1u<<k) {
  89086. /* compose the value */
  89087. uval = (msbs << k) | lsbs;
  89088. }
  89089. else {
  89090. unsigned d = (1 << (k+1)) - parameter;
  89091. if(lsbs >= d) {
  89092. if(!FLAC__bitreader_read_bit(br, &bit))
  89093. return false;
  89094. lsbs <<= 1;
  89095. lsbs |= bit;
  89096. lsbs -= d;
  89097. }
  89098. /* compose the value */
  89099. uval = msbs * parameter + lsbs;
  89100. }
  89101. /* unfold unsigned to signed */
  89102. if(uval & 1)
  89103. *val = -((int)(uval >> 1)) - 1;
  89104. else
  89105. *val = (int)(uval >> 1);
  89106. return true;
  89107. }
  89108. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  89109. {
  89110. FLAC__uint32 lsbs, msbs = 0;
  89111. unsigned bit, k;
  89112. FLAC__ASSERT(0 != br);
  89113. FLAC__ASSERT(0 != br->buffer);
  89114. k = FLAC__bitmath_ilog2(parameter);
  89115. /* read the unary MSBs and end bit */
  89116. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89117. return false;
  89118. /* read the binary LSBs */
  89119. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89120. return false;
  89121. if(parameter == 1u<<k) {
  89122. /* compose the value */
  89123. *val = (msbs << k) | lsbs;
  89124. }
  89125. else {
  89126. unsigned d = (1 << (k+1)) - parameter;
  89127. if(lsbs >= d) {
  89128. if(!FLAC__bitreader_read_bit(br, &bit))
  89129. return false;
  89130. lsbs <<= 1;
  89131. lsbs |= bit;
  89132. lsbs -= d;
  89133. }
  89134. /* compose the value */
  89135. *val = msbs * parameter + lsbs;
  89136. }
  89137. return true;
  89138. }
  89139. #endif /* UNUSED */
  89140. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89141. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  89142. {
  89143. FLAC__uint32 v = 0;
  89144. FLAC__uint32 x;
  89145. unsigned i;
  89146. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89147. return false;
  89148. if(raw)
  89149. raw[(*rawlen)++] = (FLAC__byte)x;
  89150. if(!(x & 0x80)) { /* 0xxxxxxx */
  89151. v = x;
  89152. i = 0;
  89153. }
  89154. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89155. v = x & 0x1F;
  89156. i = 1;
  89157. }
  89158. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89159. v = x & 0x0F;
  89160. i = 2;
  89161. }
  89162. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89163. v = x & 0x07;
  89164. i = 3;
  89165. }
  89166. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89167. v = x & 0x03;
  89168. i = 4;
  89169. }
  89170. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89171. v = x & 0x01;
  89172. i = 5;
  89173. }
  89174. else {
  89175. *val = 0xffffffff;
  89176. return true;
  89177. }
  89178. for( ; i; i--) {
  89179. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89180. return false;
  89181. if(raw)
  89182. raw[(*rawlen)++] = (FLAC__byte)x;
  89183. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89184. *val = 0xffffffff;
  89185. return true;
  89186. }
  89187. v <<= 6;
  89188. v |= (x & 0x3F);
  89189. }
  89190. *val = v;
  89191. return true;
  89192. }
  89193. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89194. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  89195. {
  89196. FLAC__uint64 v = 0;
  89197. FLAC__uint32 x;
  89198. unsigned i;
  89199. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89200. return false;
  89201. if(raw)
  89202. raw[(*rawlen)++] = (FLAC__byte)x;
  89203. if(!(x & 0x80)) { /* 0xxxxxxx */
  89204. v = x;
  89205. i = 0;
  89206. }
  89207. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89208. v = x & 0x1F;
  89209. i = 1;
  89210. }
  89211. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89212. v = x & 0x0F;
  89213. i = 2;
  89214. }
  89215. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89216. v = x & 0x07;
  89217. i = 3;
  89218. }
  89219. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89220. v = x & 0x03;
  89221. i = 4;
  89222. }
  89223. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89224. v = x & 0x01;
  89225. i = 5;
  89226. }
  89227. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  89228. v = 0;
  89229. i = 6;
  89230. }
  89231. else {
  89232. *val = FLAC__U64L(0xffffffffffffffff);
  89233. return true;
  89234. }
  89235. for( ; i; i--) {
  89236. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89237. return false;
  89238. if(raw)
  89239. raw[(*rawlen)++] = (FLAC__byte)x;
  89240. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89241. *val = FLAC__U64L(0xffffffffffffffff);
  89242. return true;
  89243. }
  89244. v <<= 6;
  89245. v |= (x & 0x3F);
  89246. }
  89247. *val = v;
  89248. return true;
  89249. }
  89250. #endif
  89251. /********* End of inlined file: bitreader.c *********/
  89252. /********* Start of inlined file: bitwriter.c *********/
  89253. /********* Start of inlined file: juce_FlacHeader.h *********/
  89254. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89255. // tasks..
  89256. #define VERSION "1.2.1"
  89257. #define FLAC__NO_DLL 1
  89258. #ifdef _MSC_VER
  89259. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89260. #endif
  89261. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89262. #define FLAC__SYS_DARWIN 1
  89263. #endif
  89264. /********* End of inlined file: juce_FlacHeader.h *********/
  89265. #if JUCE_USE_FLAC
  89266. #if HAVE_CONFIG_H
  89267. # include <config.h>
  89268. #endif
  89269. #include <stdlib.h> /* for malloc() */
  89270. #include <string.h> /* for memcpy(), memset() */
  89271. #ifdef _MSC_VER
  89272. #include <winsock.h> /* for ntohl() */
  89273. #elif defined FLAC__SYS_DARWIN
  89274. #include <machine/endian.h> /* for ntohl() */
  89275. #elif defined __MINGW32__
  89276. #include <winsock.h> /* for ntohl() */
  89277. #else
  89278. #include <netinet/in.h> /* for ntohl() */
  89279. #endif
  89280. #if 0 /* UNUSED */
  89281. #endif
  89282. /********* Start of inlined file: bitwriter.h *********/
  89283. #ifndef FLAC__PRIVATE__BITWRITER_H
  89284. #define FLAC__PRIVATE__BITWRITER_H
  89285. #include <stdio.h> /* for FILE */
  89286. /*
  89287. * opaque structure definition
  89288. */
  89289. struct FLAC__BitWriter;
  89290. typedef struct FLAC__BitWriter FLAC__BitWriter;
  89291. /*
  89292. * construction, deletion, initialization, etc functions
  89293. */
  89294. FLAC__BitWriter *FLAC__bitwriter_new(void);
  89295. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  89296. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  89297. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  89298. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  89299. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  89300. /*
  89301. * CRC functions
  89302. *
  89303. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  89304. */
  89305. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  89306. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  89307. /*
  89308. * info functions
  89309. */
  89310. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  89311. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  89312. /*
  89313. * direct buffer access
  89314. *
  89315. * there may be no calls on the bitwriter between get and release.
  89316. * the bitwriter continues to own the returned buffer.
  89317. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  89318. */
  89319. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  89320. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  89321. /*
  89322. * write functions
  89323. */
  89324. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  89325. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  89326. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  89327. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  89328. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  89329. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  89330. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  89331. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  89332. #if 0 /* UNUSED */
  89333. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  89334. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  89335. #endif
  89336. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  89337. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  89338. #if 0 /* UNUSED */
  89339. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  89340. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  89341. #endif
  89342. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  89343. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  89344. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  89345. #endif
  89346. /********* End of inlined file: bitwriter.h *********/
  89347. /********* Start of inlined file: alloc.h *********/
  89348. #ifndef FLAC__SHARE__ALLOC_H
  89349. #define FLAC__SHARE__ALLOC_H
  89350. #if HAVE_CONFIG_H
  89351. # include <config.h>
  89352. #endif
  89353. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  89354. * before #including this file, otherwise SIZE_MAX might not be defined
  89355. */
  89356. #include <limits.h> /* for SIZE_MAX */
  89357. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  89358. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  89359. #endif
  89360. #include <stdlib.h> /* for size_t, malloc(), etc */
  89361. #ifndef SIZE_MAX
  89362. # ifndef SIZE_T_MAX
  89363. # ifdef _MSC_VER
  89364. # define SIZE_T_MAX UINT_MAX
  89365. # else
  89366. # error
  89367. # endif
  89368. # endif
  89369. # define SIZE_MAX SIZE_T_MAX
  89370. #endif
  89371. #ifndef FLaC__INLINE
  89372. #define FLaC__INLINE
  89373. #endif
  89374. /* avoid malloc()ing 0 bytes, see:
  89375. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  89376. */
  89377. static FLaC__INLINE void *safe_malloc_(size_t size)
  89378. {
  89379. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89380. if(!size)
  89381. size++;
  89382. return malloc(size);
  89383. }
  89384. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  89385. {
  89386. if(!nmemb || !size)
  89387. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89388. return calloc(nmemb, size);
  89389. }
  89390. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  89391. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  89392. {
  89393. size2 += size1;
  89394. if(size2 < size1)
  89395. return 0;
  89396. return safe_malloc_(size2);
  89397. }
  89398. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  89399. {
  89400. size2 += size1;
  89401. if(size2 < size1)
  89402. return 0;
  89403. size3 += size2;
  89404. if(size3 < size2)
  89405. return 0;
  89406. return safe_malloc_(size3);
  89407. }
  89408. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  89409. {
  89410. size2 += size1;
  89411. if(size2 < size1)
  89412. return 0;
  89413. size3 += size2;
  89414. if(size3 < size2)
  89415. return 0;
  89416. size4 += size3;
  89417. if(size4 < size3)
  89418. return 0;
  89419. return safe_malloc_(size4);
  89420. }
  89421. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  89422. #if 0
  89423. needs support for cases where sizeof(size_t) != 4
  89424. {
  89425. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  89426. if(sizeof(size_t) == 4) {
  89427. if ((double)size1 * (double)size2 < 4294967296.0)
  89428. return malloc(size1*size2);
  89429. }
  89430. return 0;
  89431. }
  89432. #else
  89433. /* better? */
  89434. {
  89435. if(!size1 || !size2)
  89436. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89437. if(size1 > SIZE_MAX / size2)
  89438. return 0;
  89439. return malloc(size1*size2);
  89440. }
  89441. #endif
  89442. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  89443. {
  89444. if(!size1 || !size2 || !size3)
  89445. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89446. if(size1 > SIZE_MAX / size2)
  89447. return 0;
  89448. size1 *= size2;
  89449. if(size1 > SIZE_MAX / size3)
  89450. return 0;
  89451. return malloc(size1*size3);
  89452. }
  89453. /* size1*size2 + size3 */
  89454. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  89455. {
  89456. if(!size1 || !size2)
  89457. return safe_malloc_(size3);
  89458. if(size1 > SIZE_MAX / size2)
  89459. return 0;
  89460. return safe_malloc_add_2op_(size1*size2, size3);
  89461. }
  89462. /* size1 * (size2 + size3) */
  89463. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  89464. {
  89465. if(!size1 || (!size2 && !size3))
  89466. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89467. size2 += size3;
  89468. if(size2 < size3)
  89469. return 0;
  89470. return safe_malloc_mul_2op_(size1, size2);
  89471. }
  89472. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  89473. {
  89474. size2 += size1;
  89475. if(size2 < size1)
  89476. return 0;
  89477. return realloc(ptr, size2);
  89478. }
  89479. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  89480. {
  89481. size2 += size1;
  89482. if(size2 < size1)
  89483. return 0;
  89484. size3 += size2;
  89485. if(size3 < size2)
  89486. return 0;
  89487. return realloc(ptr, size3);
  89488. }
  89489. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  89490. {
  89491. size2 += size1;
  89492. if(size2 < size1)
  89493. return 0;
  89494. size3 += size2;
  89495. if(size3 < size2)
  89496. return 0;
  89497. size4 += size3;
  89498. if(size4 < size3)
  89499. return 0;
  89500. return realloc(ptr, size4);
  89501. }
  89502. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  89503. {
  89504. if(!size1 || !size2)
  89505. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  89506. if(size1 > SIZE_MAX / size2)
  89507. return 0;
  89508. return realloc(ptr, size1*size2);
  89509. }
  89510. /* size1 * (size2 + size3) */
  89511. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  89512. {
  89513. if(!size1 || (!size2 && !size3))
  89514. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  89515. size2 += size3;
  89516. if(size2 < size3)
  89517. return 0;
  89518. return safe_realloc_mul_2op_(ptr, size1, size2);
  89519. }
  89520. #endif
  89521. /********* End of inlined file: alloc.h *********/
  89522. /* Things should be fastest when this matches the machine word size */
  89523. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  89524. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  89525. typedef FLAC__uint32 bwword;
  89526. #define FLAC__BYTES_PER_WORD 4
  89527. #define FLAC__BITS_PER_WORD 32
  89528. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  89529. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  89530. #if WORDS_BIGENDIAN
  89531. #define SWAP_BE_WORD_TO_HOST(x) (x)
  89532. #else
  89533. #ifdef _MSC_VER
  89534. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  89535. #else
  89536. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  89537. #endif
  89538. #endif
  89539. /*
  89540. * The default capacity here doesn't matter too much. The buffer always grows
  89541. * to hold whatever is written to it. Usually the encoder will stop adding at
  89542. * a frame or metadata block, then write that out and clear the buffer for the
  89543. * next one.
  89544. */
  89545. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  89546. /* When growing, increment 4K at a time */
  89547. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  89548. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  89549. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  89550. #ifdef min
  89551. #undef min
  89552. #endif
  89553. #define min(x,y) ((x)<(y)?(x):(y))
  89554. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89555. #ifdef _MSC_VER
  89556. #define FLAC__U64L(x) x
  89557. #else
  89558. #define FLAC__U64L(x) x##LLU
  89559. #endif
  89560. #ifndef FLaC__INLINE
  89561. #define FLaC__INLINE
  89562. #endif
  89563. struct FLAC__BitWriter {
  89564. bwword *buffer;
  89565. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  89566. unsigned capacity; /* capacity of buffer in words */
  89567. unsigned words; /* # of complete words in buffer */
  89568. unsigned bits; /* # of used bits in accum */
  89569. };
  89570. /* * WATCHOUT: The current implementation only grows the buffer. */
  89571. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  89572. {
  89573. unsigned new_capacity;
  89574. bwword *new_buffer;
  89575. FLAC__ASSERT(0 != bw);
  89576. FLAC__ASSERT(0 != bw->buffer);
  89577. /* calculate total words needed to store 'bits_to_add' additional bits */
  89578. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  89579. /* it's possible (due to pessimism in the growth estimation that
  89580. * leads to this call) that we don't actually need to grow
  89581. */
  89582. if(bw->capacity >= new_capacity)
  89583. return true;
  89584. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  89585. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  89586. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  89587. /* make sure we got everything right */
  89588. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  89589. FLAC__ASSERT(new_capacity > bw->capacity);
  89590. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  89591. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  89592. if(new_buffer == 0)
  89593. return false;
  89594. bw->buffer = new_buffer;
  89595. bw->capacity = new_capacity;
  89596. return true;
  89597. }
  89598. /***********************************************************************
  89599. *
  89600. * Class constructor/destructor
  89601. *
  89602. ***********************************************************************/
  89603. FLAC__BitWriter *FLAC__bitwriter_new(void)
  89604. {
  89605. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  89606. /* note that calloc() sets all members to 0 for us */
  89607. return bw;
  89608. }
  89609. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  89610. {
  89611. FLAC__ASSERT(0 != bw);
  89612. FLAC__bitwriter_free(bw);
  89613. free(bw);
  89614. }
  89615. /***********************************************************************
  89616. *
  89617. * Public class methods
  89618. *
  89619. ***********************************************************************/
  89620. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  89621. {
  89622. FLAC__ASSERT(0 != bw);
  89623. bw->words = bw->bits = 0;
  89624. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  89625. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  89626. if(bw->buffer == 0)
  89627. return false;
  89628. return true;
  89629. }
  89630. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  89631. {
  89632. FLAC__ASSERT(0 != bw);
  89633. if(0 != bw->buffer)
  89634. free(bw->buffer);
  89635. bw->buffer = 0;
  89636. bw->capacity = 0;
  89637. bw->words = bw->bits = 0;
  89638. }
  89639. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  89640. {
  89641. bw->words = bw->bits = 0;
  89642. }
  89643. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  89644. {
  89645. unsigned i, j;
  89646. if(bw == 0) {
  89647. fprintf(out, "bitwriter is NULL\n");
  89648. }
  89649. else {
  89650. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  89651. for(i = 0; i < bw->words; i++) {
  89652. fprintf(out, "%08X: ", i);
  89653. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  89654. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  89655. fprintf(out, "\n");
  89656. }
  89657. if(bw->bits > 0) {
  89658. fprintf(out, "%08X: ", i);
  89659. for(j = 0; j < bw->bits; j++)
  89660. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  89661. fprintf(out, "\n");
  89662. }
  89663. }
  89664. }
  89665. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  89666. {
  89667. const FLAC__byte *buffer;
  89668. size_t bytes;
  89669. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  89670. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  89671. return false;
  89672. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  89673. FLAC__bitwriter_release_buffer(bw);
  89674. return true;
  89675. }
  89676. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  89677. {
  89678. const FLAC__byte *buffer;
  89679. size_t bytes;
  89680. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  89681. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  89682. return false;
  89683. *crc = FLAC__crc8(buffer, bytes);
  89684. FLAC__bitwriter_release_buffer(bw);
  89685. return true;
  89686. }
  89687. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  89688. {
  89689. return ((bw->bits & 7) == 0);
  89690. }
  89691. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  89692. {
  89693. return FLAC__TOTAL_BITS(bw);
  89694. }
  89695. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  89696. {
  89697. FLAC__ASSERT((bw->bits & 7) == 0);
  89698. /* double protection */
  89699. if(bw->bits & 7)
  89700. return false;
  89701. /* if we have bits in the accumulator we have to flush those to the buffer first */
  89702. if(bw->bits) {
  89703. FLAC__ASSERT(bw->words <= bw->capacity);
  89704. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  89705. return false;
  89706. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  89707. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  89708. }
  89709. /* now we can just return what we have */
  89710. *buffer = (FLAC__byte*)bw->buffer;
  89711. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  89712. return true;
  89713. }
  89714. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  89715. {
  89716. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  89717. * get-mode' flag could be added everywhere and then cleared here
  89718. */
  89719. (void)bw;
  89720. }
  89721. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  89722. {
  89723. unsigned n;
  89724. FLAC__ASSERT(0 != bw);
  89725. FLAC__ASSERT(0 != bw->buffer);
  89726. if(bits == 0)
  89727. return true;
  89728. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89729. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  89730. return false;
  89731. /* first part gets to word alignment */
  89732. if(bw->bits) {
  89733. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  89734. bw->accum <<= n;
  89735. bits -= n;
  89736. bw->bits += n;
  89737. if(bw->bits == FLAC__BITS_PER_WORD) {
  89738. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89739. bw->bits = 0;
  89740. }
  89741. else
  89742. return true;
  89743. }
  89744. /* do whole words */
  89745. while(bits >= FLAC__BITS_PER_WORD) {
  89746. bw->buffer[bw->words++] = 0;
  89747. bits -= FLAC__BITS_PER_WORD;
  89748. }
  89749. /* do any leftovers */
  89750. if(bits > 0) {
  89751. bw->accum = 0;
  89752. bw->bits = bits;
  89753. }
  89754. return true;
  89755. }
  89756. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  89757. {
  89758. register unsigned left;
  89759. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89760. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89761. FLAC__ASSERT(0 != bw);
  89762. FLAC__ASSERT(0 != bw->buffer);
  89763. FLAC__ASSERT(bits <= 32);
  89764. if(bits == 0)
  89765. return true;
  89766. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89767. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  89768. return false;
  89769. left = FLAC__BITS_PER_WORD - bw->bits;
  89770. if(bits < left) {
  89771. bw->accum <<= bits;
  89772. bw->accum |= val;
  89773. bw->bits += bits;
  89774. }
  89775. 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 */
  89776. bw->accum <<= left;
  89777. bw->accum |= val >> (bw->bits = bits - left);
  89778. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89779. bw->accum = val;
  89780. }
  89781. else {
  89782. bw->accum = val;
  89783. bw->bits = 0;
  89784. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  89785. }
  89786. return true;
  89787. }
  89788. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  89789. {
  89790. /* zero-out unused bits */
  89791. if(bits < 32)
  89792. val &= (~(0xffffffff << bits));
  89793. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  89794. }
  89795. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  89796. {
  89797. /* this could be a little faster but it's not used for much */
  89798. if(bits > 32) {
  89799. return
  89800. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  89801. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  89802. }
  89803. else
  89804. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  89805. }
  89806. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  89807. {
  89808. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  89809. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  89810. return false;
  89811. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  89812. return false;
  89813. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  89814. return false;
  89815. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  89816. return false;
  89817. return true;
  89818. }
  89819. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  89820. {
  89821. unsigned i;
  89822. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  89823. for(i = 0; i < nvals; i++) {
  89824. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  89825. return false;
  89826. }
  89827. return true;
  89828. }
  89829. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  89830. {
  89831. if(val < 32)
  89832. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  89833. else
  89834. return
  89835. FLAC__bitwriter_write_zeroes(bw, val) &&
  89836. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  89837. }
  89838. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  89839. {
  89840. FLAC__uint32 uval;
  89841. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  89842. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89843. uval = (val<<1) ^ (val>>31);
  89844. return 1 + parameter + (uval >> parameter);
  89845. }
  89846. #if 0 /* UNUSED */
  89847. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  89848. {
  89849. unsigned bits, msbs, uval;
  89850. unsigned k;
  89851. FLAC__ASSERT(parameter > 0);
  89852. /* fold signed to unsigned */
  89853. if(val < 0)
  89854. uval = (unsigned)(((-(++val)) << 1) + 1);
  89855. else
  89856. uval = (unsigned)(val << 1);
  89857. k = FLAC__bitmath_ilog2(parameter);
  89858. if(parameter == 1u<<k) {
  89859. FLAC__ASSERT(k <= 30);
  89860. msbs = uval >> k;
  89861. bits = 1 + k + msbs;
  89862. }
  89863. else {
  89864. unsigned q, r, d;
  89865. d = (1 << (k+1)) - parameter;
  89866. q = uval / parameter;
  89867. r = uval - (q * parameter);
  89868. bits = 1 + q + k;
  89869. if(r >= d)
  89870. bits++;
  89871. }
  89872. return bits;
  89873. }
  89874. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  89875. {
  89876. unsigned bits, msbs;
  89877. unsigned k;
  89878. FLAC__ASSERT(parameter > 0);
  89879. k = FLAC__bitmath_ilog2(parameter);
  89880. if(parameter == 1u<<k) {
  89881. FLAC__ASSERT(k <= 30);
  89882. msbs = uval >> k;
  89883. bits = 1 + k + msbs;
  89884. }
  89885. else {
  89886. unsigned q, r, d;
  89887. d = (1 << (k+1)) - parameter;
  89888. q = uval / parameter;
  89889. r = uval - (q * parameter);
  89890. bits = 1 + q + k;
  89891. if(r >= d)
  89892. bits++;
  89893. }
  89894. return bits;
  89895. }
  89896. #endif /* UNUSED */
  89897. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  89898. {
  89899. unsigned total_bits, interesting_bits, msbs;
  89900. FLAC__uint32 uval, pattern;
  89901. FLAC__ASSERT(0 != bw);
  89902. FLAC__ASSERT(0 != bw->buffer);
  89903. FLAC__ASSERT(parameter < 8*sizeof(uval));
  89904. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89905. uval = (val<<1) ^ (val>>31);
  89906. msbs = uval >> parameter;
  89907. interesting_bits = 1 + parameter;
  89908. total_bits = interesting_bits + msbs;
  89909. pattern = 1 << parameter; /* the unary end bit */
  89910. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  89911. if(total_bits <= 32)
  89912. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  89913. else
  89914. return
  89915. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  89916. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  89917. }
  89918. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  89919. {
  89920. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  89921. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  89922. FLAC__uint32 uval;
  89923. unsigned left;
  89924. const unsigned lsbits = 1 + parameter;
  89925. unsigned msbits;
  89926. FLAC__ASSERT(0 != bw);
  89927. FLAC__ASSERT(0 != bw->buffer);
  89928. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  89929. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89930. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89931. while(nvals) {
  89932. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89933. uval = (*vals<<1) ^ (*vals>>31);
  89934. msbits = uval >> parameter;
  89935. #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) */
  89936. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  89937. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  89938. bw->bits = bw->bits + msbits + lsbits;
  89939. uval |= mask1; /* set stop bit */
  89940. uval &= mask2; /* mask off unused top bits */
  89941. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  89942. bw->accum <<= msbits;
  89943. bw->accum <<= lsbits;
  89944. bw->accum |= uval;
  89945. if(bw->bits == FLAC__BITS_PER_WORD) {
  89946. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89947. bw->bits = 0;
  89948. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  89949. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  89950. FLAC__ASSERT(bw->capacity == bw->words);
  89951. return false;
  89952. }
  89953. }
  89954. }
  89955. else {
  89956. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  89957. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  89958. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  89959. bw->bits = bw->bits + msbits + lsbits;
  89960. uval |= mask1; /* set stop bit */
  89961. uval &= mask2; /* mask off unused top bits */
  89962. bw->accum <<= msbits + lsbits;
  89963. bw->accum |= uval;
  89964. }
  89965. else {
  89966. #endif
  89967. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89968. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  89969. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  89970. return false;
  89971. if(msbits) {
  89972. /* first part gets to word alignment */
  89973. if(bw->bits) {
  89974. left = FLAC__BITS_PER_WORD - bw->bits;
  89975. if(msbits < left) {
  89976. bw->accum <<= msbits;
  89977. bw->bits += msbits;
  89978. goto break1;
  89979. }
  89980. else {
  89981. bw->accum <<= left;
  89982. msbits -= left;
  89983. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89984. bw->bits = 0;
  89985. }
  89986. }
  89987. /* do whole words */
  89988. while(msbits >= FLAC__BITS_PER_WORD) {
  89989. bw->buffer[bw->words++] = 0;
  89990. msbits -= FLAC__BITS_PER_WORD;
  89991. }
  89992. /* do any leftovers */
  89993. if(msbits > 0) {
  89994. bw->accum = 0;
  89995. bw->bits = msbits;
  89996. }
  89997. }
  89998. break1:
  89999. uval |= mask1; /* set stop bit */
  90000. uval &= mask2; /* mask off unused top bits */
  90001. left = FLAC__BITS_PER_WORD - bw->bits;
  90002. if(lsbits < left) {
  90003. bw->accum <<= lsbits;
  90004. bw->accum |= uval;
  90005. bw->bits += lsbits;
  90006. }
  90007. else {
  90008. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  90009. * be > lsbits (because of previous assertions) so it would have
  90010. * triggered the (lsbits<left) case above.
  90011. */
  90012. FLAC__ASSERT(bw->bits);
  90013. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  90014. bw->accum <<= left;
  90015. bw->accum |= uval >> (bw->bits = lsbits - left);
  90016. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90017. bw->accum = uval;
  90018. }
  90019. #if 1
  90020. }
  90021. #endif
  90022. vals++;
  90023. nvals--;
  90024. }
  90025. return true;
  90026. }
  90027. #if 0 /* UNUSED */
  90028. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  90029. {
  90030. unsigned total_bits, msbs, uval;
  90031. unsigned k;
  90032. FLAC__ASSERT(0 != bw);
  90033. FLAC__ASSERT(0 != bw->buffer);
  90034. FLAC__ASSERT(parameter > 0);
  90035. /* fold signed to unsigned */
  90036. if(val < 0)
  90037. uval = (unsigned)(((-(++val)) << 1) + 1);
  90038. else
  90039. uval = (unsigned)(val << 1);
  90040. k = FLAC__bitmath_ilog2(parameter);
  90041. if(parameter == 1u<<k) {
  90042. unsigned pattern;
  90043. FLAC__ASSERT(k <= 30);
  90044. msbs = uval >> k;
  90045. total_bits = 1 + k + msbs;
  90046. pattern = 1 << k; /* the unary end bit */
  90047. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90048. if(total_bits <= 32) {
  90049. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90050. return false;
  90051. }
  90052. else {
  90053. /* write the unary MSBs */
  90054. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90055. return false;
  90056. /* write the unary end bit and binary LSBs */
  90057. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90058. return false;
  90059. }
  90060. }
  90061. else {
  90062. unsigned q, r, d;
  90063. d = (1 << (k+1)) - parameter;
  90064. q = uval / parameter;
  90065. r = uval - (q * parameter);
  90066. /* write the unary MSBs */
  90067. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90068. return false;
  90069. /* write the unary end bit */
  90070. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90071. return false;
  90072. /* write the binary LSBs */
  90073. if(r >= d) {
  90074. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90075. return false;
  90076. }
  90077. else {
  90078. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90079. return false;
  90080. }
  90081. }
  90082. return true;
  90083. }
  90084. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  90085. {
  90086. unsigned total_bits, msbs;
  90087. unsigned k;
  90088. FLAC__ASSERT(0 != bw);
  90089. FLAC__ASSERT(0 != bw->buffer);
  90090. FLAC__ASSERT(parameter > 0);
  90091. k = FLAC__bitmath_ilog2(parameter);
  90092. if(parameter == 1u<<k) {
  90093. unsigned pattern;
  90094. FLAC__ASSERT(k <= 30);
  90095. msbs = uval >> k;
  90096. total_bits = 1 + k + msbs;
  90097. pattern = 1 << k; /* the unary end bit */
  90098. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90099. if(total_bits <= 32) {
  90100. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90101. return false;
  90102. }
  90103. else {
  90104. /* write the unary MSBs */
  90105. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90106. return false;
  90107. /* write the unary end bit and binary LSBs */
  90108. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90109. return false;
  90110. }
  90111. }
  90112. else {
  90113. unsigned q, r, d;
  90114. d = (1 << (k+1)) - parameter;
  90115. q = uval / parameter;
  90116. r = uval - (q * parameter);
  90117. /* write the unary MSBs */
  90118. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90119. return false;
  90120. /* write the unary end bit */
  90121. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90122. return false;
  90123. /* write the binary LSBs */
  90124. if(r >= d) {
  90125. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90126. return false;
  90127. }
  90128. else {
  90129. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90130. return false;
  90131. }
  90132. }
  90133. return true;
  90134. }
  90135. #endif /* UNUSED */
  90136. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  90137. {
  90138. FLAC__bool ok = 1;
  90139. FLAC__ASSERT(0 != bw);
  90140. FLAC__ASSERT(0 != bw->buffer);
  90141. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  90142. if(val < 0x80) {
  90143. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  90144. }
  90145. else if(val < 0x800) {
  90146. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  90147. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90148. }
  90149. else if(val < 0x10000) {
  90150. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  90151. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90152. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90153. }
  90154. else if(val < 0x200000) {
  90155. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  90156. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90157. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90158. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90159. }
  90160. else if(val < 0x4000000) {
  90161. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  90162. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90163. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90164. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90165. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90166. }
  90167. else {
  90168. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  90169. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  90170. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90171. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90172. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90173. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90174. }
  90175. return ok;
  90176. }
  90177. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  90178. {
  90179. FLAC__bool ok = 1;
  90180. FLAC__ASSERT(0 != bw);
  90181. FLAC__ASSERT(0 != bw->buffer);
  90182. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  90183. if(val < 0x80) {
  90184. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  90185. }
  90186. else if(val < 0x800) {
  90187. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  90188. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90189. }
  90190. else if(val < 0x10000) {
  90191. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  90192. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90193. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90194. }
  90195. else if(val < 0x200000) {
  90196. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  90197. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90198. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90199. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90200. }
  90201. else if(val < 0x4000000) {
  90202. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  90203. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90204. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90205. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90206. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90207. }
  90208. else if(val < 0x80000000) {
  90209. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  90210. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90211. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90212. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90213. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90214. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90215. }
  90216. else {
  90217. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  90218. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  90219. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90220. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90221. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90222. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90223. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90224. }
  90225. return ok;
  90226. }
  90227. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  90228. {
  90229. /* 0-pad to byte boundary */
  90230. if(bw->bits & 7u)
  90231. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  90232. else
  90233. return true;
  90234. }
  90235. #endif
  90236. /********* End of inlined file: bitwriter.c *********/
  90237. /********* Start of inlined file: cpu.c *********/
  90238. /********* Start of inlined file: juce_FlacHeader.h *********/
  90239. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90240. // tasks..
  90241. #define VERSION "1.2.1"
  90242. #define FLAC__NO_DLL 1
  90243. #ifdef _MSC_VER
  90244. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90245. #endif
  90246. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90247. #define FLAC__SYS_DARWIN 1
  90248. #endif
  90249. /********* End of inlined file: juce_FlacHeader.h *********/
  90250. #if JUCE_USE_FLAC
  90251. #if HAVE_CONFIG_H
  90252. # include <config.h>
  90253. #endif
  90254. #include <stdlib.h>
  90255. #include <stdio.h>
  90256. #if defined FLAC__CPU_IA32
  90257. # include <signal.h>
  90258. #elif defined FLAC__CPU_PPC
  90259. # if !defined FLAC__NO_ASM
  90260. # if defined FLAC__SYS_DARWIN
  90261. # include <sys/sysctl.h>
  90262. # include <mach/mach.h>
  90263. # include <mach/mach_host.h>
  90264. # include <mach/host_info.h>
  90265. # include <mach/machine.h>
  90266. # ifndef CPU_SUBTYPE_POWERPC_970
  90267. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  90268. # endif
  90269. # else /* FLAC__SYS_DARWIN */
  90270. # include <signal.h>
  90271. # include <setjmp.h>
  90272. static sigjmp_buf jmpbuf;
  90273. static volatile sig_atomic_t canjump = 0;
  90274. static void sigill_handler (int sig)
  90275. {
  90276. if (!canjump) {
  90277. signal (sig, SIG_DFL);
  90278. raise (sig);
  90279. }
  90280. canjump = 0;
  90281. siglongjmp (jmpbuf, 1);
  90282. }
  90283. # endif /* FLAC__SYS_DARWIN */
  90284. # endif /* FLAC__NO_ASM */
  90285. #endif /* FLAC__CPU_PPC */
  90286. #if defined (__NetBSD__) || defined(__OpenBSD__)
  90287. #include <sys/param.h>
  90288. #include <sys/sysctl.h>
  90289. #include <machine/cpu.h>
  90290. #endif
  90291. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  90292. #include <sys/types.h>
  90293. #include <sys/sysctl.h>
  90294. #endif
  90295. #if defined(__APPLE__)
  90296. /* how to get sysctlbyname()? */
  90297. #endif
  90298. /* these are flags in EDX of CPUID AX=00000001 */
  90299. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  90300. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  90301. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  90302. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  90303. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  90304. /* these are flags in ECX of CPUID AX=00000001 */
  90305. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  90306. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  90307. /* these are flags in EDX of CPUID AX=80000001 */
  90308. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  90309. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  90310. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  90311. /*
  90312. * Extra stuff needed for detection of OS support for SSE on IA-32
  90313. */
  90314. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  90315. # if defined(__linux__)
  90316. /*
  90317. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  90318. * modify the return address to jump over the offending SSE instruction
  90319. * and also the operation following it that indicates the instruction
  90320. * executed successfully. In this way we use no global variables and
  90321. * stay thread-safe.
  90322. *
  90323. * 3 + 3 + 6:
  90324. * 3 bytes for "xorps xmm0,xmm0"
  90325. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  90326. * 6 bytes extra in case our estimate is wrong
  90327. * 12 bytes puts us in the NOP "landing zone"
  90328. */
  90329. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  90330. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90331. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  90332. {
  90333. (void)signal;
  90334. sc.eip += 3 + 3 + 6;
  90335. }
  90336. # else
  90337. # include <sys/ucontext.h>
  90338. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  90339. {
  90340. (void)signal, (void)si;
  90341. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  90342. }
  90343. # endif
  90344. # elif defined(_MSC_VER)
  90345. # include <windows.h>
  90346. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  90347. # ifdef USE_TRY_CATCH_FLAVOR
  90348. # else
  90349. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  90350. {
  90351. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  90352. ep->ContextRecord->Eip += 3 + 3 + 6;
  90353. return EXCEPTION_CONTINUE_EXECUTION;
  90354. }
  90355. return EXCEPTION_CONTINUE_SEARCH;
  90356. }
  90357. # endif
  90358. # endif
  90359. #endif
  90360. void FLAC__cpu_info(FLAC__CPUInfo *info)
  90361. {
  90362. /*
  90363. * IA32-specific
  90364. */
  90365. #ifdef FLAC__CPU_IA32
  90366. info->type = FLAC__CPUINFO_TYPE_IA32;
  90367. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  90368. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  90369. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  90370. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  90371. info->data.ia32.cmov = false;
  90372. info->data.ia32.mmx = false;
  90373. info->data.ia32.fxsr = false;
  90374. info->data.ia32.sse = false;
  90375. info->data.ia32.sse2 = false;
  90376. info->data.ia32.sse3 = false;
  90377. info->data.ia32.ssse3 = false;
  90378. info->data.ia32._3dnow = false;
  90379. info->data.ia32.ext3dnow = false;
  90380. info->data.ia32.extmmx = false;
  90381. if(info->data.ia32.cpuid) {
  90382. /* http://www.sandpile.org/ia32/cpuid.htm */
  90383. FLAC__uint32 flags_edx, flags_ecx;
  90384. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  90385. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  90386. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  90387. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  90388. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  90389. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  90390. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  90391. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  90392. #ifdef FLAC__USE_3DNOW
  90393. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  90394. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  90395. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  90396. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  90397. #else
  90398. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  90399. #endif
  90400. #ifdef DEBUG
  90401. fprintf(stderr, "CPU info (IA-32):\n");
  90402. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  90403. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  90404. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  90405. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  90406. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  90407. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  90408. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  90409. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  90410. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  90411. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  90412. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  90413. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  90414. #endif
  90415. /*
  90416. * now have to check for OS support of SSE/SSE2
  90417. */
  90418. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  90419. #if defined FLAC__NO_SSE_OS
  90420. /* assume user knows better than us; turn it off */
  90421. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90422. #elif defined FLAC__SSE_OS
  90423. /* assume user knows better than us; leave as detected above */
  90424. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  90425. int sse = 0;
  90426. size_t len;
  90427. /* at least one of these must work: */
  90428. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  90429. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  90430. if(!sse)
  90431. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90432. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  90433. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  90434. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  90435. size_t len = sizeof(val);
  90436. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90437. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90438. else { /* double-check SSE2 */
  90439. mib[1] = CPU_SSE2;
  90440. len = sizeof(val);
  90441. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90442. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90443. }
  90444. # else
  90445. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90446. # endif
  90447. #elif defined(__linux__)
  90448. int sse = 0;
  90449. struct sigaction sigill_save;
  90450. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90451. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  90452. #else
  90453. struct sigaction sigill_sse;
  90454. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  90455. __sigemptyset(&sigill_sse.sa_mask);
  90456. 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 */
  90457. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  90458. #endif
  90459. {
  90460. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  90461. /* see sigill_handler_sse_os() for an explanation of the following: */
  90462. asm volatile (
  90463. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  90464. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  90465. "incl %0\n\t" /* SIGILL handler will jump over this */
  90466. /* landing zone */
  90467. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  90468. "nop\n\t"
  90469. "nop\n\t"
  90470. "nop\n\t"
  90471. "nop\n\t"
  90472. "nop\n\t"
  90473. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  90474. "nop\n\t"
  90475. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  90476. : "=r"(sse)
  90477. : "r"(sse)
  90478. );
  90479. sigaction(SIGILL, &sigill_save, NULL);
  90480. }
  90481. if(!sse)
  90482. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90483. #elif defined(_MSC_VER)
  90484. # ifdef USE_TRY_CATCH_FLAVOR
  90485. _try {
  90486. __asm {
  90487. # if _MSC_VER <= 1200
  90488. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  90489. _emit 0x0F
  90490. _emit 0x57
  90491. _emit 0xC0
  90492. # else
  90493. xorps xmm0,xmm0
  90494. # endif
  90495. }
  90496. }
  90497. _except(EXCEPTION_EXECUTE_HANDLER) {
  90498. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  90499. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90500. }
  90501. # else
  90502. int sse = 0;
  90503. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  90504. /* see GCC version above for explanation */
  90505. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  90506. /* http://www.codeproject.com/cpp/gccasm.asp */
  90507. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  90508. __asm {
  90509. # if _MSC_VER <= 1200
  90510. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  90511. _emit 0x0F
  90512. _emit 0x57
  90513. _emit 0xC0
  90514. # else
  90515. xorps xmm0,xmm0
  90516. # endif
  90517. inc sse
  90518. nop
  90519. nop
  90520. nop
  90521. nop
  90522. nop
  90523. nop
  90524. nop
  90525. nop
  90526. nop
  90527. }
  90528. SetUnhandledExceptionFilter(save);
  90529. if(!sse)
  90530. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90531. # endif
  90532. #else
  90533. /* no way to test, disable to be safe */
  90534. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90535. #endif
  90536. #ifdef DEBUG
  90537. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  90538. #endif
  90539. }
  90540. }
  90541. #else
  90542. info->use_asm = false;
  90543. #endif
  90544. /*
  90545. * PPC-specific
  90546. */
  90547. #elif defined FLAC__CPU_PPC
  90548. info->type = FLAC__CPUINFO_TYPE_PPC;
  90549. # if !defined FLAC__NO_ASM
  90550. info->use_asm = true;
  90551. # ifdef FLAC__USE_ALTIVEC
  90552. # if defined FLAC__SYS_DARWIN
  90553. {
  90554. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  90555. size_t len = sizeof(val);
  90556. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  90557. }
  90558. {
  90559. host_basic_info_data_t hostInfo;
  90560. mach_msg_type_number_t infoCount;
  90561. infoCount = HOST_BASIC_INFO_COUNT;
  90562. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  90563. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  90564. }
  90565. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  90566. {
  90567. /* no Darwin, do it the brute-force way */
  90568. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  90569. info->data.ppc.altivec = 0;
  90570. info->data.ppc.ppc64 = 0;
  90571. signal (SIGILL, sigill_handler);
  90572. canjump = 0;
  90573. if (!sigsetjmp (jmpbuf, 1)) {
  90574. canjump = 1;
  90575. asm volatile (
  90576. "mtspr 256, %0\n\t"
  90577. "vand %%v0, %%v0, %%v0"
  90578. :
  90579. : "r" (-1)
  90580. );
  90581. info->data.ppc.altivec = 1;
  90582. }
  90583. canjump = 0;
  90584. if (!sigsetjmp (jmpbuf, 1)) {
  90585. int x = 0;
  90586. canjump = 1;
  90587. /* PPC64 hardware implements the cntlzd instruction */
  90588. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  90589. info->data.ppc.ppc64 = 1;
  90590. }
  90591. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  90592. }
  90593. # endif
  90594. # else /* !FLAC__USE_ALTIVEC */
  90595. info->data.ppc.altivec = 0;
  90596. info->data.ppc.ppc64 = 0;
  90597. # endif
  90598. # else
  90599. info->use_asm = false;
  90600. # endif
  90601. /*
  90602. * unknown CPI
  90603. */
  90604. #else
  90605. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  90606. info->use_asm = false;
  90607. #endif
  90608. }
  90609. #endif
  90610. /********* End of inlined file: cpu.c *********/
  90611. /********* Start of inlined file: crc.c *********/
  90612. /********* Start of inlined file: juce_FlacHeader.h *********/
  90613. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90614. // tasks..
  90615. #define VERSION "1.2.1"
  90616. #define FLAC__NO_DLL 1
  90617. #ifdef _MSC_VER
  90618. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90619. #endif
  90620. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90621. #define FLAC__SYS_DARWIN 1
  90622. #endif
  90623. /********* End of inlined file: juce_FlacHeader.h *********/
  90624. #if JUCE_USE_FLAC
  90625. #if HAVE_CONFIG_H
  90626. # include <config.h>
  90627. #endif
  90628. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  90629. FLAC__byte const FLAC__crc8_table[256] = {
  90630. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  90631. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  90632. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  90633. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  90634. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  90635. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  90636. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  90637. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  90638. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  90639. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  90640. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  90641. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  90642. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  90643. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  90644. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  90645. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  90646. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  90647. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  90648. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  90649. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  90650. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  90651. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  90652. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  90653. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  90654. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  90655. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  90656. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  90657. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  90658. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  90659. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  90660. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  90661. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  90662. };
  90663. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  90664. unsigned FLAC__crc16_table[256] = {
  90665. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  90666. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  90667. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  90668. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  90669. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  90670. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  90671. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  90672. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  90673. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  90674. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  90675. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  90676. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  90677. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  90678. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  90679. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  90680. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  90681. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  90682. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  90683. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  90684. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  90685. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  90686. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  90687. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  90688. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  90689. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  90690. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  90691. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  90692. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  90693. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  90694. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  90695. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  90696. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  90697. };
  90698. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  90699. {
  90700. *crc = FLAC__crc8_table[*crc ^ data];
  90701. }
  90702. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  90703. {
  90704. while(len--)
  90705. *crc = FLAC__crc8_table[*crc ^ *data++];
  90706. }
  90707. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  90708. {
  90709. FLAC__uint8 crc = 0;
  90710. while(len--)
  90711. crc = FLAC__crc8_table[crc ^ *data++];
  90712. return crc;
  90713. }
  90714. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  90715. {
  90716. unsigned crc = 0;
  90717. while(len--)
  90718. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  90719. return crc;
  90720. }
  90721. #endif
  90722. /********* End of inlined file: crc.c *********/
  90723. /********* Start of inlined file: fixed.c *********/
  90724. /********* Start of inlined file: juce_FlacHeader.h *********/
  90725. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90726. // tasks..
  90727. #define VERSION "1.2.1"
  90728. #define FLAC__NO_DLL 1
  90729. #ifdef _MSC_VER
  90730. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90731. #endif
  90732. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90733. #define FLAC__SYS_DARWIN 1
  90734. #endif
  90735. /********* End of inlined file: juce_FlacHeader.h *********/
  90736. #if JUCE_USE_FLAC
  90737. #if HAVE_CONFIG_H
  90738. # include <config.h>
  90739. #endif
  90740. #include <math.h>
  90741. #include <string.h>
  90742. /********* Start of inlined file: fixed.h *********/
  90743. #ifndef FLAC__PRIVATE__FIXED_H
  90744. #define FLAC__PRIVATE__FIXED_H
  90745. #ifdef HAVE_CONFIG_H
  90746. #include <config.h>
  90747. #endif
  90748. /********* Start of inlined file: float.h *********/
  90749. #ifndef FLAC__PRIVATE__FLOAT_H
  90750. #define FLAC__PRIVATE__FLOAT_H
  90751. #ifdef HAVE_CONFIG_H
  90752. #include <config.h>
  90753. #endif
  90754. /*
  90755. * These typedefs make it easier to ensure that integer versions of
  90756. * the library really only contain integer operations. All the code
  90757. * in libFLAC should use FLAC__float and FLAC__double in place of
  90758. * float and double, and be protected by checks of the macro
  90759. * FLAC__INTEGER_ONLY_LIBRARY.
  90760. *
  90761. * FLAC__real is the basic floating point type used in LPC analysis.
  90762. */
  90763. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90764. typedef double FLAC__double;
  90765. typedef float FLAC__float;
  90766. /*
  90767. * WATCHOUT: changing FLAC__real will change the signatures of many
  90768. * functions that have assembly language equivalents and break them.
  90769. */
  90770. typedef float FLAC__real;
  90771. #else
  90772. /*
  90773. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  90774. * for the integer part and lower 16 bits for the fractional part.
  90775. */
  90776. typedef FLAC__int32 FLAC__fixedpoint;
  90777. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  90778. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  90779. extern const FLAC__fixedpoint FLAC__FP_ONE;
  90780. extern const FLAC__fixedpoint FLAC__FP_LN2;
  90781. extern const FLAC__fixedpoint FLAC__FP_E;
  90782. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  90783. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  90784. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  90785. /*
  90786. * FLAC__fixedpoint_log2()
  90787. * --------------------------------------------------------------------
  90788. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  90789. * algorithm by Knuth for x >= 1.0
  90790. *
  90791. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  90792. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  90793. *
  90794. * 'precision' roughly limits the number of iterations that are done;
  90795. * use (unsigned)(-1) for maximum precision.
  90796. *
  90797. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  90798. * function will punt and return 0.
  90799. *
  90800. * The return value will also have 'fracbits' fractional bits.
  90801. */
  90802. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  90803. #endif
  90804. #endif
  90805. /********* End of inlined file: float.h *********/
  90806. /********* Start of inlined file: format.h *********/
  90807. #ifndef FLAC__PRIVATE__FORMAT_H
  90808. #define FLAC__PRIVATE__FORMAT_H
  90809. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  90810. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  90811. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  90812. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  90813. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  90814. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  90815. #endif
  90816. /********* End of inlined file: format.h *********/
  90817. /*
  90818. * FLAC__fixed_compute_best_predictor()
  90819. * --------------------------------------------------------------------
  90820. * Compute the best fixed predictor and the expected bits-per-sample
  90821. * of the residual signal for each order. The _wide() version uses
  90822. * 64-bit integers which is statistically necessary when bits-per-
  90823. * sample + log2(blocksize) > 30
  90824. *
  90825. * IN data[0,data_len-1]
  90826. * IN data_len
  90827. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  90828. */
  90829. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90830. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  90831. # ifndef FLAC__NO_ASM
  90832. # ifdef FLAC__CPU_IA32
  90833. # ifdef FLAC__HAS_NASM
  90834. 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]);
  90835. # endif
  90836. # endif
  90837. # endif
  90838. 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]);
  90839. #else
  90840. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  90841. 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]);
  90842. #endif
  90843. /*
  90844. * FLAC__fixed_compute_residual()
  90845. * --------------------------------------------------------------------
  90846. * Compute the residual signal obtained from sutracting the predicted
  90847. * signal from the original.
  90848. *
  90849. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  90850. * IN data_len length of original signal
  90851. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  90852. * OUT residual[0,data_len-1] residual signal
  90853. */
  90854. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  90855. /*
  90856. * FLAC__fixed_restore_signal()
  90857. * --------------------------------------------------------------------
  90858. * Restore the original signal by summing the residual and the
  90859. * predictor.
  90860. *
  90861. * IN residual[0,data_len-1] residual signal
  90862. * IN data_len length of original signal
  90863. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  90864. * *** IMPORTANT: the caller must pass in the historical samples:
  90865. * IN data[-order,-1] previously-reconstructed historical samples
  90866. * OUT data[0,data_len-1] original signal
  90867. */
  90868. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  90869. #endif
  90870. /********* End of inlined file: fixed.h *********/
  90871. #ifndef M_LN2
  90872. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  90873. #define M_LN2 0.69314718055994530942
  90874. #endif
  90875. #ifdef min
  90876. #undef min
  90877. #endif
  90878. #define min(x,y) ((x) < (y)? (x) : (y))
  90879. #ifdef local_abs
  90880. #undef local_abs
  90881. #endif
  90882. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  90883. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  90884. /* rbps stands for residual bits per sample
  90885. *
  90886. * (ln(2) * err)
  90887. * rbps = log (-----------)
  90888. * 2 ( n )
  90889. */
  90890. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  90891. {
  90892. FLAC__uint32 rbps;
  90893. unsigned bits; /* the number of bits required to represent a number */
  90894. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  90895. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  90896. FLAC__ASSERT(err > 0);
  90897. FLAC__ASSERT(n > 0);
  90898. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  90899. if(err <= n)
  90900. return 0;
  90901. /*
  90902. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  90903. * These allow us later to know we won't lose too much precision in the
  90904. * fixed-point division (err<<fracbits)/n.
  90905. */
  90906. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  90907. err <<= fracbits;
  90908. err /= n;
  90909. /* err now holds err/n with fracbits fractional bits */
  90910. /*
  90911. * Whittle err down to 16 bits max. 16 significant bits is enough for
  90912. * our purposes.
  90913. */
  90914. FLAC__ASSERT(err > 0);
  90915. bits = FLAC__bitmath_ilog2(err)+1;
  90916. if(bits > 16) {
  90917. err >>= (bits-16);
  90918. fracbits -= (bits-16);
  90919. }
  90920. rbps = (FLAC__uint32)err;
  90921. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  90922. rbps *= FLAC__FP_LN2;
  90923. fracbits += 16;
  90924. FLAC__ASSERT(fracbits >= 0);
  90925. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  90926. {
  90927. const int f = fracbits & 3;
  90928. if(f) {
  90929. rbps >>= f;
  90930. fracbits -= f;
  90931. }
  90932. }
  90933. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  90934. if(rbps == 0)
  90935. return 0;
  90936. /*
  90937. * The return value must have 16 fractional bits. Since the whole part
  90938. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  90939. * must be >= -3, these assertion allows us to be able to shift rbps
  90940. * left if necessary to get 16 fracbits without losing any bits of the
  90941. * whole part of rbps.
  90942. *
  90943. * There is a slight chance due to accumulated error that the whole part
  90944. * will require 6 bits, so we use 6 in the assertion. Really though as
  90945. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  90946. */
  90947. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  90948. FLAC__ASSERT(fracbits >= -3);
  90949. /* now shift the decimal point into place */
  90950. if(fracbits < 16)
  90951. return rbps << (16-fracbits);
  90952. else if(fracbits > 16)
  90953. return rbps >> (fracbits-16);
  90954. else
  90955. return rbps;
  90956. }
  90957. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  90958. {
  90959. FLAC__uint32 rbps;
  90960. unsigned bits; /* the number of bits required to represent a number */
  90961. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  90962. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  90963. FLAC__ASSERT(err > 0);
  90964. FLAC__ASSERT(n > 0);
  90965. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  90966. if(err <= n)
  90967. return 0;
  90968. /*
  90969. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  90970. * These allow us later to know we won't lose too much precision in the
  90971. * fixed-point division (err<<fracbits)/n.
  90972. */
  90973. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  90974. err <<= fracbits;
  90975. err /= n;
  90976. /* err now holds err/n with fracbits fractional bits */
  90977. /*
  90978. * Whittle err down to 16 bits max. 16 significant bits is enough for
  90979. * our purposes.
  90980. */
  90981. FLAC__ASSERT(err > 0);
  90982. bits = FLAC__bitmath_ilog2_wide(err)+1;
  90983. if(bits > 16) {
  90984. err >>= (bits-16);
  90985. fracbits -= (bits-16);
  90986. }
  90987. rbps = (FLAC__uint32)err;
  90988. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  90989. rbps *= FLAC__FP_LN2;
  90990. fracbits += 16;
  90991. FLAC__ASSERT(fracbits >= 0);
  90992. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  90993. {
  90994. const int f = fracbits & 3;
  90995. if(f) {
  90996. rbps >>= f;
  90997. fracbits -= f;
  90998. }
  90999. }
  91000. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91001. if(rbps == 0)
  91002. return 0;
  91003. /*
  91004. * The return value must have 16 fractional bits. Since the whole part
  91005. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91006. * must be >= -3, these assertion allows us to be able to shift rbps
  91007. * left if necessary to get 16 fracbits without losing any bits of the
  91008. * whole part of rbps.
  91009. *
  91010. * There is a slight chance due to accumulated error that the whole part
  91011. * will require 6 bits, so we use 6 in the assertion. Really though as
  91012. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91013. */
  91014. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91015. FLAC__ASSERT(fracbits >= -3);
  91016. /* now shift the decimal point into place */
  91017. if(fracbits < 16)
  91018. return rbps << (16-fracbits);
  91019. else if(fracbits > 16)
  91020. return rbps >> (fracbits-16);
  91021. else
  91022. return rbps;
  91023. }
  91024. #endif
  91025. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91026. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91027. #else
  91028. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91029. #endif
  91030. {
  91031. FLAC__int32 last_error_0 = data[-1];
  91032. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91033. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91034. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91035. FLAC__int32 error, save;
  91036. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91037. unsigned i, order;
  91038. for(i = 0; i < data_len; i++) {
  91039. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91040. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91041. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91042. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91043. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91044. }
  91045. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91046. order = 0;
  91047. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91048. order = 1;
  91049. else if(total_error_2 < min(total_error_3, total_error_4))
  91050. order = 2;
  91051. else if(total_error_3 < total_error_4)
  91052. order = 3;
  91053. else
  91054. order = 4;
  91055. /* Estimate the expected number of bits per residual signal sample. */
  91056. /* 'total_error*' is linearly related to the variance of the residual */
  91057. /* signal, so we use it directly to compute E(|x|) */
  91058. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91059. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91060. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91061. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91062. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91063. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91064. 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);
  91065. 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);
  91066. 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);
  91067. 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);
  91068. 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);
  91069. #else
  91070. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  91071. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  91072. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  91073. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  91074. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  91075. #endif
  91076. return order;
  91077. }
  91078. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91079. 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])
  91080. #else
  91081. 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])
  91082. #endif
  91083. {
  91084. FLAC__int32 last_error_0 = data[-1];
  91085. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91086. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91087. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91088. FLAC__int32 error, save;
  91089. /* total_error_* are 64-bits to avoid overflow when encoding
  91090. * erratic signals when the bits-per-sample and blocksize are
  91091. * large.
  91092. */
  91093. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91094. unsigned i, order;
  91095. for(i = 0; i < data_len; i++) {
  91096. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91097. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91098. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91099. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91100. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91101. }
  91102. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91103. order = 0;
  91104. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91105. order = 1;
  91106. else if(total_error_2 < min(total_error_3, total_error_4))
  91107. order = 2;
  91108. else if(total_error_3 < total_error_4)
  91109. order = 3;
  91110. else
  91111. order = 4;
  91112. /* Estimate the expected number of bits per residual signal sample. */
  91113. /* 'total_error*' is linearly related to the variance of the residual */
  91114. /* signal, so we use it directly to compute E(|x|) */
  91115. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91116. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91117. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91118. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91119. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91120. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91121. #if defined _MSC_VER || defined __MINGW32__
  91122. /* with MSVC you have to spoon feed it the casting */
  91123. 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);
  91124. 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);
  91125. 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);
  91126. 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);
  91127. 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);
  91128. #else
  91129. 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);
  91130. 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);
  91131. 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);
  91132. 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);
  91133. 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);
  91134. #endif
  91135. #else
  91136. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  91137. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  91138. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  91139. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  91140. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  91141. #endif
  91142. return order;
  91143. }
  91144. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  91145. {
  91146. const int idata_len = (int)data_len;
  91147. int i;
  91148. switch(order) {
  91149. case 0:
  91150. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91151. memcpy(residual, data, sizeof(residual[0])*data_len);
  91152. break;
  91153. case 1:
  91154. for(i = 0; i < idata_len; i++)
  91155. residual[i] = data[i] - data[i-1];
  91156. break;
  91157. case 2:
  91158. for(i = 0; i < idata_len; i++)
  91159. #if 1 /* OPT: may be faster with some compilers on some systems */
  91160. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  91161. #else
  91162. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  91163. #endif
  91164. break;
  91165. case 3:
  91166. for(i = 0; i < idata_len; i++)
  91167. #if 1 /* OPT: may be faster with some compilers on some systems */
  91168. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  91169. #else
  91170. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  91171. #endif
  91172. break;
  91173. case 4:
  91174. for(i = 0; i < idata_len; i++)
  91175. #if 1 /* OPT: may be faster with some compilers on some systems */
  91176. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  91177. #else
  91178. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  91179. #endif
  91180. break;
  91181. default:
  91182. FLAC__ASSERT(0);
  91183. }
  91184. }
  91185. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  91186. {
  91187. int i, idata_len = (int)data_len;
  91188. switch(order) {
  91189. case 0:
  91190. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91191. memcpy(data, residual, sizeof(residual[0])*data_len);
  91192. break;
  91193. case 1:
  91194. for(i = 0; i < idata_len; i++)
  91195. data[i] = residual[i] + data[i-1];
  91196. break;
  91197. case 2:
  91198. for(i = 0; i < idata_len; i++)
  91199. #if 1 /* OPT: may be faster with some compilers on some systems */
  91200. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  91201. #else
  91202. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  91203. #endif
  91204. break;
  91205. case 3:
  91206. for(i = 0; i < idata_len; i++)
  91207. #if 1 /* OPT: may be faster with some compilers on some systems */
  91208. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  91209. #else
  91210. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  91211. #endif
  91212. break;
  91213. case 4:
  91214. for(i = 0; i < idata_len; i++)
  91215. #if 1 /* OPT: may be faster with some compilers on some systems */
  91216. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  91217. #else
  91218. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  91219. #endif
  91220. break;
  91221. default:
  91222. FLAC__ASSERT(0);
  91223. }
  91224. }
  91225. #endif
  91226. /********* End of inlined file: fixed.c *********/
  91227. /********* Start of inlined file: float.c *********/
  91228. /********* Start of inlined file: juce_FlacHeader.h *********/
  91229. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91230. // tasks..
  91231. #define VERSION "1.2.1"
  91232. #define FLAC__NO_DLL 1
  91233. #ifdef _MSC_VER
  91234. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91235. #endif
  91236. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91237. #define FLAC__SYS_DARWIN 1
  91238. #endif
  91239. /********* End of inlined file: juce_FlacHeader.h *********/
  91240. #if JUCE_USE_FLAC
  91241. #if HAVE_CONFIG_H
  91242. # include <config.h>
  91243. #endif
  91244. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91245. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91246. #ifdef _MSC_VER
  91247. #define FLAC__U64L(x) x
  91248. #else
  91249. #define FLAC__U64L(x) x##LLU
  91250. #endif
  91251. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  91252. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  91253. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  91254. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  91255. const FLAC__fixedpoint FLAC__FP_E = 178145;
  91256. /* Lookup tables for Knuth's logarithm algorithm */
  91257. #define LOG2_LOOKUP_PRECISION 16
  91258. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  91259. {
  91260. /*
  91261. * 0 fraction bits
  91262. */
  91263. /* undefined */ 0x00000000,
  91264. /* lg(2/1) = */ 0x00000001,
  91265. /* lg(4/3) = */ 0x00000000,
  91266. /* lg(8/7) = */ 0x00000000,
  91267. /* lg(16/15) = */ 0x00000000,
  91268. /* lg(32/31) = */ 0x00000000,
  91269. /* lg(64/63) = */ 0x00000000,
  91270. /* lg(128/127) = */ 0x00000000,
  91271. /* lg(256/255) = */ 0x00000000,
  91272. /* lg(512/511) = */ 0x00000000,
  91273. /* lg(1024/1023) = */ 0x00000000,
  91274. /* lg(2048/2047) = */ 0x00000000,
  91275. /* lg(4096/4095) = */ 0x00000000,
  91276. /* lg(8192/8191) = */ 0x00000000,
  91277. /* lg(16384/16383) = */ 0x00000000,
  91278. /* lg(32768/32767) = */ 0x00000000
  91279. },
  91280. {
  91281. /*
  91282. * 4 fraction bits
  91283. */
  91284. /* undefined */ 0x00000000,
  91285. /* lg(2/1) = */ 0x00000010,
  91286. /* lg(4/3) = */ 0x00000007,
  91287. /* lg(8/7) = */ 0x00000003,
  91288. /* lg(16/15) = */ 0x00000001,
  91289. /* lg(32/31) = */ 0x00000001,
  91290. /* lg(64/63) = */ 0x00000000,
  91291. /* lg(128/127) = */ 0x00000000,
  91292. /* lg(256/255) = */ 0x00000000,
  91293. /* lg(512/511) = */ 0x00000000,
  91294. /* lg(1024/1023) = */ 0x00000000,
  91295. /* lg(2048/2047) = */ 0x00000000,
  91296. /* lg(4096/4095) = */ 0x00000000,
  91297. /* lg(8192/8191) = */ 0x00000000,
  91298. /* lg(16384/16383) = */ 0x00000000,
  91299. /* lg(32768/32767) = */ 0x00000000
  91300. },
  91301. {
  91302. /*
  91303. * 8 fraction bits
  91304. */
  91305. /* undefined */ 0x00000000,
  91306. /* lg(2/1) = */ 0x00000100,
  91307. /* lg(4/3) = */ 0x0000006a,
  91308. /* lg(8/7) = */ 0x00000031,
  91309. /* lg(16/15) = */ 0x00000018,
  91310. /* lg(32/31) = */ 0x0000000c,
  91311. /* lg(64/63) = */ 0x00000006,
  91312. /* lg(128/127) = */ 0x00000003,
  91313. /* lg(256/255) = */ 0x00000001,
  91314. /* lg(512/511) = */ 0x00000001,
  91315. /* lg(1024/1023) = */ 0x00000000,
  91316. /* lg(2048/2047) = */ 0x00000000,
  91317. /* lg(4096/4095) = */ 0x00000000,
  91318. /* lg(8192/8191) = */ 0x00000000,
  91319. /* lg(16384/16383) = */ 0x00000000,
  91320. /* lg(32768/32767) = */ 0x00000000
  91321. },
  91322. {
  91323. /*
  91324. * 12 fraction bits
  91325. */
  91326. /* undefined */ 0x00000000,
  91327. /* lg(2/1) = */ 0x00001000,
  91328. /* lg(4/3) = */ 0x000006a4,
  91329. /* lg(8/7) = */ 0x00000315,
  91330. /* lg(16/15) = */ 0x0000017d,
  91331. /* lg(32/31) = */ 0x000000bc,
  91332. /* lg(64/63) = */ 0x0000005d,
  91333. /* lg(128/127) = */ 0x0000002e,
  91334. /* lg(256/255) = */ 0x00000017,
  91335. /* lg(512/511) = */ 0x0000000c,
  91336. /* lg(1024/1023) = */ 0x00000006,
  91337. /* lg(2048/2047) = */ 0x00000003,
  91338. /* lg(4096/4095) = */ 0x00000001,
  91339. /* lg(8192/8191) = */ 0x00000001,
  91340. /* lg(16384/16383) = */ 0x00000000,
  91341. /* lg(32768/32767) = */ 0x00000000
  91342. },
  91343. {
  91344. /*
  91345. * 16 fraction bits
  91346. */
  91347. /* undefined */ 0x00000000,
  91348. /* lg(2/1) = */ 0x00010000,
  91349. /* lg(4/3) = */ 0x00006a40,
  91350. /* lg(8/7) = */ 0x00003151,
  91351. /* lg(16/15) = */ 0x000017d6,
  91352. /* lg(32/31) = */ 0x00000bba,
  91353. /* lg(64/63) = */ 0x000005d1,
  91354. /* lg(128/127) = */ 0x000002e6,
  91355. /* lg(256/255) = */ 0x00000172,
  91356. /* lg(512/511) = */ 0x000000b9,
  91357. /* lg(1024/1023) = */ 0x0000005c,
  91358. /* lg(2048/2047) = */ 0x0000002e,
  91359. /* lg(4096/4095) = */ 0x00000017,
  91360. /* lg(8192/8191) = */ 0x0000000c,
  91361. /* lg(16384/16383) = */ 0x00000006,
  91362. /* lg(32768/32767) = */ 0x00000003
  91363. },
  91364. {
  91365. /*
  91366. * 20 fraction bits
  91367. */
  91368. /* undefined */ 0x00000000,
  91369. /* lg(2/1) = */ 0x00100000,
  91370. /* lg(4/3) = */ 0x0006a3fe,
  91371. /* lg(8/7) = */ 0x00031513,
  91372. /* lg(16/15) = */ 0x00017d60,
  91373. /* lg(32/31) = */ 0x0000bb9d,
  91374. /* lg(64/63) = */ 0x00005d10,
  91375. /* lg(128/127) = */ 0x00002e59,
  91376. /* lg(256/255) = */ 0x00001721,
  91377. /* lg(512/511) = */ 0x00000b8e,
  91378. /* lg(1024/1023) = */ 0x000005c6,
  91379. /* lg(2048/2047) = */ 0x000002e3,
  91380. /* lg(4096/4095) = */ 0x00000171,
  91381. /* lg(8192/8191) = */ 0x000000b9,
  91382. /* lg(16384/16383) = */ 0x0000005c,
  91383. /* lg(32768/32767) = */ 0x0000002e
  91384. },
  91385. {
  91386. /*
  91387. * 24 fraction bits
  91388. */
  91389. /* undefined */ 0x00000000,
  91390. /* lg(2/1) = */ 0x01000000,
  91391. /* lg(4/3) = */ 0x006a3fe6,
  91392. /* lg(8/7) = */ 0x00315130,
  91393. /* lg(16/15) = */ 0x0017d605,
  91394. /* lg(32/31) = */ 0x000bb9ca,
  91395. /* lg(64/63) = */ 0x0005d0fc,
  91396. /* lg(128/127) = */ 0x0002e58f,
  91397. /* lg(256/255) = */ 0x0001720e,
  91398. /* lg(512/511) = */ 0x0000b8d8,
  91399. /* lg(1024/1023) = */ 0x00005c61,
  91400. /* lg(2048/2047) = */ 0x00002e2d,
  91401. /* lg(4096/4095) = */ 0x00001716,
  91402. /* lg(8192/8191) = */ 0x00000b8b,
  91403. /* lg(16384/16383) = */ 0x000005c5,
  91404. /* lg(32768/32767) = */ 0x000002e3
  91405. },
  91406. {
  91407. /*
  91408. * 28 fraction bits
  91409. */
  91410. /* undefined */ 0x00000000,
  91411. /* lg(2/1) = */ 0x10000000,
  91412. /* lg(4/3) = */ 0x06a3fe5c,
  91413. /* lg(8/7) = */ 0x03151301,
  91414. /* lg(16/15) = */ 0x017d6049,
  91415. /* lg(32/31) = */ 0x00bb9ca6,
  91416. /* lg(64/63) = */ 0x005d0fba,
  91417. /* lg(128/127) = */ 0x002e58f7,
  91418. /* lg(256/255) = */ 0x001720da,
  91419. /* lg(512/511) = */ 0x000b8d87,
  91420. /* lg(1024/1023) = */ 0x0005c60b,
  91421. /* lg(2048/2047) = */ 0x0002e2d7,
  91422. /* lg(4096/4095) = */ 0x00017160,
  91423. /* lg(8192/8191) = */ 0x0000b8ad,
  91424. /* lg(16384/16383) = */ 0x00005c56,
  91425. /* lg(32768/32767) = */ 0x00002e2b
  91426. }
  91427. };
  91428. #if 0
  91429. static const FLAC__uint64 log2_lookup_wide[] = {
  91430. {
  91431. /*
  91432. * 32 fraction bits
  91433. */
  91434. /* undefined */ 0x00000000,
  91435. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  91436. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  91437. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  91438. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  91439. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  91440. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  91441. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  91442. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  91443. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  91444. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  91445. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  91446. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  91447. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  91448. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  91449. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  91450. },
  91451. {
  91452. /*
  91453. * 48 fraction bits
  91454. */
  91455. /* undefined */ 0x00000000,
  91456. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  91457. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  91458. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  91459. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  91460. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  91461. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  91462. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  91463. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  91464. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  91465. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  91466. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  91467. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  91468. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  91469. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  91470. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  91471. }
  91472. };
  91473. #endif
  91474. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  91475. {
  91476. const FLAC__uint32 ONE = (1u << fracbits);
  91477. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  91478. FLAC__ASSERT(fracbits < 32);
  91479. FLAC__ASSERT((fracbits & 0x3) == 0);
  91480. if(x < ONE)
  91481. return 0;
  91482. if(precision > LOG2_LOOKUP_PRECISION)
  91483. precision = LOG2_LOOKUP_PRECISION;
  91484. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  91485. {
  91486. FLAC__uint32 y = 0;
  91487. FLAC__uint32 z = x >> 1, k = 1;
  91488. while (x > ONE && k < precision) {
  91489. if (x - z >= ONE) {
  91490. x -= z;
  91491. z = x >> k;
  91492. y += table[k];
  91493. }
  91494. else {
  91495. z >>= 1;
  91496. k++;
  91497. }
  91498. }
  91499. return y;
  91500. }
  91501. }
  91502. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  91503. #endif
  91504. /********* End of inlined file: float.c *********/
  91505. /********* Start of inlined file: format.c *********/
  91506. /********* Start of inlined file: juce_FlacHeader.h *********/
  91507. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91508. // tasks..
  91509. #define VERSION "1.2.1"
  91510. #define FLAC__NO_DLL 1
  91511. #ifdef _MSC_VER
  91512. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91513. #endif
  91514. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91515. #define FLAC__SYS_DARWIN 1
  91516. #endif
  91517. /********* End of inlined file: juce_FlacHeader.h *********/
  91518. #if JUCE_USE_FLAC
  91519. #if HAVE_CONFIG_H
  91520. # include <config.h>
  91521. #endif
  91522. #include <stdio.h>
  91523. #include <stdlib.h> /* for qsort() */
  91524. #include <string.h> /* for memset() */
  91525. #ifndef FLaC__INLINE
  91526. #define FLaC__INLINE
  91527. #endif
  91528. #ifdef min
  91529. #undef min
  91530. #endif
  91531. #define min(a,b) ((a)<(b)?(a):(b))
  91532. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91533. #ifdef _MSC_VER
  91534. #define FLAC__U64L(x) x
  91535. #else
  91536. #define FLAC__U64L(x) x##LLU
  91537. #endif
  91538. /* VERSION should come from configure */
  91539. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  91540. ;
  91541. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  91542. /* yet one more hack because of MSVC6: */
  91543. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  91544. #else
  91545. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  91546. #endif
  91547. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  91548. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  91549. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  91550. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  91551. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  91552. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  91553. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  91554. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  91555. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  91556. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  91557. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  91558. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  91559. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  91560. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  91561. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  91562. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  91563. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  91564. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  91565. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  91566. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  91567. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  91568. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  91569. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  91570. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  91571. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  91572. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  91573. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  91574. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  91575. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  91576. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  91577. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  91578. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  91579. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  91580. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  91581. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  91582. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  91583. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  91584. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  91585. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  91586. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  91587. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  91588. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  91589. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  91590. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  91591. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  91592. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  91593. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  91594. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  91595. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  91596. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  91597. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  91598. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  91599. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  91600. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  91601. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  91602. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  91603. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  91604. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  91605. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  91606. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  91607. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  91608. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  91609. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  91610. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  91611. "PARTITIONED_RICE",
  91612. "PARTITIONED_RICE2"
  91613. };
  91614. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  91615. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  91616. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  91617. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  91618. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  91619. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  91620. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  91621. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  91622. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  91623. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  91624. "CONSTANT",
  91625. "VERBATIM",
  91626. "FIXED",
  91627. "LPC"
  91628. };
  91629. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  91630. "INDEPENDENT",
  91631. "LEFT_SIDE",
  91632. "RIGHT_SIDE",
  91633. "MID_SIDE"
  91634. };
  91635. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  91636. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  91637. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  91638. };
  91639. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  91640. "STREAMINFO",
  91641. "PADDING",
  91642. "APPLICATION",
  91643. "SEEKTABLE",
  91644. "VORBIS_COMMENT",
  91645. "CUESHEET",
  91646. "PICTURE"
  91647. };
  91648. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  91649. "Other",
  91650. "32x32 pixels 'file icon' (PNG only)",
  91651. "Other file icon",
  91652. "Cover (front)",
  91653. "Cover (back)",
  91654. "Leaflet page",
  91655. "Media (e.g. label side of CD)",
  91656. "Lead artist/lead performer/soloist",
  91657. "Artist/performer",
  91658. "Conductor",
  91659. "Band/Orchestra",
  91660. "Composer",
  91661. "Lyricist/text writer",
  91662. "Recording Location",
  91663. "During recording",
  91664. "During performance",
  91665. "Movie/video screen capture",
  91666. "A bright coloured fish",
  91667. "Illustration",
  91668. "Band/artist logotype",
  91669. "Publisher/Studio logotype"
  91670. };
  91671. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  91672. {
  91673. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  91674. return false;
  91675. }
  91676. else
  91677. return true;
  91678. }
  91679. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  91680. {
  91681. if(
  91682. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  91683. (
  91684. sample_rate >= (1u << 16) &&
  91685. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  91686. )
  91687. ) {
  91688. return false;
  91689. }
  91690. else
  91691. return true;
  91692. }
  91693. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  91694. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  91695. {
  91696. unsigned i;
  91697. FLAC__uint64 prev_sample_number = 0;
  91698. FLAC__bool got_prev = false;
  91699. FLAC__ASSERT(0 != seek_table);
  91700. for(i = 0; i < seek_table->num_points; i++) {
  91701. if(got_prev) {
  91702. if(
  91703. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  91704. seek_table->points[i].sample_number <= prev_sample_number
  91705. )
  91706. return false;
  91707. }
  91708. prev_sample_number = seek_table->points[i].sample_number;
  91709. got_prev = true;
  91710. }
  91711. return true;
  91712. }
  91713. /* used as the sort predicate for qsort() */
  91714. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  91715. {
  91716. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  91717. if(l->sample_number == r->sample_number)
  91718. return 0;
  91719. else if(l->sample_number < r->sample_number)
  91720. return -1;
  91721. else
  91722. return 1;
  91723. }
  91724. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  91725. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  91726. {
  91727. unsigned i, j;
  91728. FLAC__bool first;
  91729. FLAC__ASSERT(0 != seek_table);
  91730. /* sort the seekpoints */
  91731. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  91732. /* uniquify the seekpoints */
  91733. first = true;
  91734. for(i = j = 0; i < seek_table->num_points; i++) {
  91735. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  91736. if(!first) {
  91737. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  91738. continue;
  91739. }
  91740. }
  91741. first = false;
  91742. seek_table->points[j++] = seek_table->points[i];
  91743. }
  91744. for(i = j; i < seek_table->num_points; i++) {
  91745. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  91746. seek_table->points[i].stream_offset = 0;
  91747. seek_table->points[i].frame_samples = 0;
  91748. }
  91749. return j;
  91750. }
  91751. /*
  91752. * also disallows non-shortest-form encodings, c.f.
  91753. * http://www.unicode.org/versions/corrigendum1.html
  91754. * and a more clear explanation at the end of this section:
  91755. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  91756. */
  91757. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  91758. {
  91759. FLAC__ASSERT(0 != utf8);
  91760. if ((utf8[0] & 0x80) == 0) {
  91761. return 1;
  91762. }
  91763. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  91764. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  91765. return 0;
  91766. return 2;
  91767. }
  91768. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  91769. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  91770. return 0;
  91771. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  91772. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  91773. return 0;
  91774. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  91775. return 0;
  91776. return 3;
  91777. }
  91778. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  91779. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  91780. return 0;
  91781. return 4;
  91782. }
  91783. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  91784. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  91785. return 0;
  91786. return 5;
  91787. }
  91788. 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) {
  91789. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  91790. return 0;
  91791. return 6;
  91792. }
  91793. else {
  91794. return 0;
  91795. }
  91796. }
  91797. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  91798. {
  91799. char c;
  91800. for(c = *name; c; c = *(++name))
  91801. if(c < 0x20 || c == 0x3d || c > 0x7d)
  91802. return false;
  91803. return true;
  91804. }
  91805. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  91806. {
  91807. if(length == (unsigned)(-1)) {
  91808. while(*value) {
  91809. unsigned n = utf8len_(value);
  91810. if(n == 0)
  91811. return false;
  91812. value += n;
  91813. }
  91814. }
  91815. else {
  91816. const FLAC__byte *end = value + length;
  91817. while(value < end) {
  91818. unsigned n = utf8len_(value);
  91819. if(n == 0)
  91820. return false;
  91821. value += n;
  91822. }
  91823. if(value != end)
  91824. return false;
  91825. }
  91826. return true;
  91827. }
  91828. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  91829. {
  91830. const FLAC__byte *s, *end;
  91831. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  91832. if(*s < 0x20 || *s > 0x7D)
  91833. return false;
  91834. }
  91835. if(s == end)
  91836. return false;
  91837. s++; /* skip '=' */
  91838. while(s < end) {
  91839. unsigned n = utf8len_(s);
  91840. if(n == 0)
  91841. return false;
  91842. s += n;
  91843. }
  91844. if(s != end)
  91845. return false;
  91846. return true;
  91847. }
  91848. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  91849. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  91850. {
  91851. unsigned i, j;
  91852. if(check_cd_da_subset) {
  91853. if(cue_sheet->lead_in < 2 * 44100) {
  91854. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  91855. return false;
  91856. }
  91857. if(cue_sheet->lead_in % 588 != 0) {
  91858. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  91859. return false;
  91860. }
  91861. }
  91862. if(cue_sheet->num_tracks == 0) {
  91863. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  91864. return false;
  91865. }
  91866. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  91867. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  91868. return false;
  91869. }
  91870. for(i = 0; i < cue_sheet->num_tracks; i++) {
  91871. if(cue_sheet->tracks[i].number == 0) {
  91872. if(violation) *violation = "cue sheet may not have a track number 0";
  91873. return false;
  91874. }
  91875. if(check_cd_da_subset) {
  91876. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  91877. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  91878. return false;
  91879. }
  91880. }
  91881. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  91882. if(violation) {
  91883. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  91884. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  91885. else
  91886. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  91887. }
  91888. return false;
  91889. }
  91890. if(i < cue_sheet->num_tracks - 1) {
  91891. if(cue_sheet->tracks[i].num_indices == 0) {
  91892. if(violation) *violation = "cue sheet track must have at least one index point";
  91893. return false;
  91894. }
  91895. if(cue_sheet->tracks[i].indices[0].number > 1) {
  91896. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  91897. return false;
  91898. }
  91899. }
  91900. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  91901. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  91902. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  91903. return false;
  91904. }
  91905. if(j > 0) {
  91906. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  91907. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  91908. return false;
  91909. }
  91910. }
  91911. }
  91912. }
  91913. return true;
  91914. }
  91915. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  91916. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  91917. {
  91918. char *p;
  91919. FLAC__byte *b;
  91920. for(p = picture->mime_type; *p; p++) {
  91921. if(*p < 0x20 || *p > 0x7e) {
  91922. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  91923. return false;
  91924. }
  91925. }
  91926. for(b = picture->description; *b; ) {
  91927. unsigned n = utf8len_(b);
  91928. if(n == 0) {
  91929. if(violation) *violation = "description string must be valid UTF-8";
  91930. return false;
  91931. }
  91932. b += n;
  91933. }
  91934. return true;
  91935. }
  91936. /*
  91937. * These routines are private to libFLAC
  91938. */
  91939. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  91940. {
  91941. return
  91942. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  91943. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  91944. blocksize,
  91945. predictor_order
  91946. );
  91947. }
  91948. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  91949. {
  91950. unsigned max_rice_partition_order = 0;
  91951. while(!(blocksize & 1)) {
  91952. max_rice_partition_order++;
  91953. blocksize >>= 1;
  91954. }
  91955. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  91956. }
  91957. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  91958. {
  91959. unsigned max_rice_partition_order = limit;
  91960. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  91961. max_rice_partition_order--;
  91962. FLAC__ASSERT(
  91963. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  91964. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  91965. );
  91966. return max_rice_partition_order;
  91967. }
  91968. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  91969. {
  91970. FLAC__ASSERT(0 != object);
  91971. object->parameters = 0;
  91972. object->raw_bits = 0;
  91973. object->capacity_by_order = 0;
  91974. }
  91975. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  91976. {
  91977. FLAC__ASSERT(0 != object);
  91978. if(0 != object->parameters)
  91979. free(object->parameters);
  91980. if(0 != object->raw_bits)
  91981. free(object->raw_bits);
  91982. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  91983. }
  91984. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  91985. {
  91986. FLAC__ASSERT(0 != object);
  91987. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  91988. if(object->capacity_by_order < max_partition_order) {
  91989. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  91990. return false;
  91991. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  91992. return false;
  91993. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  91994. object->capacity_by_order = max_partition_order;
  91995. }
  91996. return true;
  91997. }
  91998. #endif
  91999. /********* End of inlined file: format.c *********/
  92000. /********* Start of inlined file: lpc_flac.c *********/
  92001. /********* Start of inlined file: juce_FlacHeader.h *********/
  92002. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92003. // tasks..
  92004. #define VERSION "1.2.1"
  92005. #define FLAC__NO_DLL 1
  92006. #ifdef _MSC_VER
  92007. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92008. #endif
  92009. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92010. #define FLAC__SYS_DARWIN 1
  92011. #endif
  92012. /********* End of inlined file: juce_FlacHeader.h *********/
  92013. #if JUCE_USE_FLAC
  92014. #if HAVE_CONFIG_H
  92015. # include <config.h>
  92016. #endif
  92017. #include <math.h>
  92018. /********* Start of inlined file: lpc.h *********/
  92019. #ifndef FLAC__PRIVATE__LPC_H
  92020. #define FLAC__PRIVATE__LPC_H
  92021. #ifdef HAVE_CONFIG_H
  92022. #include <config.h>
  92023. #endif
  92024. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92025. /*
  92026. * FLAC__lpc_window_data()
  92027. * --------------------------------------------------------------------
  92028. * Applies the given window to the data.
  92029. * OPT: asm implementation
  92030. *
  92031. * IN in[0,data_len-1]
  92032. * IN window[0,data_len-1]
  92033. * OUT out[0,lag-1]
  92034. * IN data_len
  92035. */
  92036. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  92037. /*
  92038. * FLAC__lpc_compute_autocorrelation()
  92039. * --------------------------------------------------------------------
  92040. * Compute the autocorrelation for lags between 0 and lag-1.
  92041. * Assumes data[] outside of [0,data_len-1] == 0.
  92042. * Asserts that lag > 0.
  92043. *
  92044. * IN data[0,data_len-1]
  92045. * IN data_len
  92046. * IN 0 < lag <= data_len
  92047. * OUT autoc[0,lag-1]
  92048. */
  92049. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92050. #ifndef FLAC__NO_ASM
  92051. # ifdef FLAC__CPU_IA32
  92052. # ifdef FLAC__HAS_NASM
  92053. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92054. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92055. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92056. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92057. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92058. # endif
  92059. # endif
  92060. #endif
  92061. /*
  92062. * FLAC__lpc_compute_lp_coefficients()
  92063. * --------------------------------------------------------------------
  92064. * Computes LP coefficients for orders 1..max_order.
  92065. * Do not call if autoc[0] == 0.0. This means the signal is zero
  92066. * and there is no point in calculating a predictor.
  92067. *
  92068. * IN autoc[0,max_order] autocorrelation values
  92069. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  92070. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  92071. * *** IMPORTANT:
  92072. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  92073. * OUT error[0,max_order-1] error for each order (more
  92074. * specifically, the variance of
  92075. * the error signal times # of
  92076. * samples in the signal)
  92077. *
  92078. * Example: if max_order is 9, the LP coefficients for order 9 will be
  92079. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  92080. * in lp_coeff[7][0,7], etc.
  92081. */
  92082. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  92083. /*
  92084. * FLAC__lpc_quantize_coefficients()
  92085. * --------------------------------------------------------------------
  92086. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  92087. * must be less than 32 (sizeof(FLAC__int32)*8).
  92088. *
  92089. * IN lp_coeff[0,order-1] LP coefficients
  92090. * IN order LP order
  92091. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  92092. * desired precision (in bits, including sign
  92093. * bit) of largest coefficient
  92094. * OUT qlp_coeff[0,order-1] quantized coefficients
  92095. * OUT shift # of bits to shift right to get approximated
  92096. * LP coefficients. NOTE: could be negative.
  92097. * RETURN 0 => quantization OK
  92098. * 1 => coefficients require too much shifting for *shift to
  92099. * fit in the LPC subframe header. 'shift' is unset.
  92100. * 2 => coefficients are all zero, which is bad. 'shift' is
  92101. * unset.
  92102. */
  92103. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  92104. /*
  92105. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  92106. * --------------------------------------------------------------------
  92107. * Compute the residual signal obtained from sutracting the predicted
  92108. * signal from the original.
  92109. *
  92110. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92111. * IN data_len length of original signal
  92112. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92113. * IN order > 0 LP order
  92114. * IN lp_quantization quantization of LP coefficients in bits
  92115. * OUT residual[0,data_len-1] residual signal
  92116. */
  92117. 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[]);
  92118. 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[]);
  92119. #ifndef FLAC__NO_ASM
  92120. # ifdef FLAC__CPU_IA32
  92121. # ifdef FLAC__HAS_NASM
  92122. 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[]);
  92123. 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[]);
  92124. # endif
  92125. # endif
  92126. #endif
  92127. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92128. /*
  92129. * FLAC__lpc_restore_signal()
  92130. * --------------------------------------------------------------------
  92131. * Restore the original signal by summing the residual and the
  92132. * predictor.
  92133. *
  92134. * IN residual[0,data_len-1] residual signal
  92135. * IN data_len length of original signal
  92136. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92137. * IN order > 0 LP order
  92138. * IN lp_quantization quantization of LP coefficients in bits
  92139. * *** IMPORTANT: the caller must pass in the historical samples:
  92140. * IN data[-order,-1] previously-reconstructed historical samples
  92141. * OUT data[0,data_len-1] original signal
  92142. */
  92143. 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[]);
  92144. 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[]);
  92145. #ifndef FLAC__NO_ASM
  92146. # ifdef FLAC__CPU_IA32
  92147. # ifdef FLAC__HAS_NASM
  92148. 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[]);
  92149. 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[]);
  92150. # endif /* FLAC__HAS_NASM */
  92151. # elif defined FLAC__CPU_PPC
  92152. 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[]);
  92153. 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[]);
  92154. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  92155. #endif /* FLAC__NO_ASM */
  92156. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92157. /*
  92158. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  92159. * --------------------------------------------------------------------
  92160. * Compute the expected number of bits per residual signal sample
  92161. * based on the LP error (which is related to the residual variance).
  92162. *
  92163. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  92164. * IN total_samples > 0 # of samples in residual signal
  92165. * RETURN expected bits per sample
  92166. */
  92167. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  92168. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  92169. /*
  92170. * FLAC__lpc_compute_best_order()
  92171. * --------------------------------------------------------------------
  92172. * Compute the best order from the array of signal errors returned
  92173. * during coefficient computation.
  92174. *
  92175. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  92176. * IN max_order > 0 max LP order
  92177. * IN total_samples > 0 # of samples in residual signal
  92178. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  92179. * (includes warmup sample size and quantized LP coefficient)
  92180. * RETURN [1,max_order] best order
  92181. */
  92182. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  92183. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92184. #endif
  92185. /********* End of inlined file: lpc.h *********/
  92186. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  92187. #include <stdio.h>
  92188. #endif
  92189. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92190. #ifndef M_LN2
  92191. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92192. #define M_LN2 0.69314718055994530942
  92193. #endif
  92194. /* OPT: #undef'ing this may improve the speed on some architectures */
  92195. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  92196. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  92197. {
  92198. unsigned i;
  92199. for(i = 0; i < data_len; i++)
  92200. out[i] = in[i] * window[i];
  92201. }
  92202. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  92203. {
  92204. /* a readable, but slower, version */
  92205. #if 0
  92206. FLAC__real d;
  92207. unsigned i;
  92208. FLAC__ASSERT(lag > 0);
  92209. FLAC__ASSERT(lag <= data_len);
  92210. /*
  92211. * Technically we should subtract the mean first like so:
  92212. * for(i = 0; i < data_len; i++)
  92213. * data[i] -= mean;
  92214. * but it appears not to make enough of a difference to matter, and
  92215. * most signals are already closely centered around zero
  92216. */
  92217. while(lag--) {
  92218. for(i = lag, d = 0.0; i < data_len; i++)
  92219. d += data[i] * data[i - lag];
  92220. autoc[lag] = d;
  92221. }
  92222. #endif
  92223. /*
  92224. * this version tends to run faster because of better data locality
  92225. * ('data_len' is usually much larger than 'lag')
  92226. */
  92227. FLAC__real d;
  92228. unsigned sample, coeff;
  92229. const unsigned limit = data_len - lag;
  92230. FLAC__ASSERT(lag > 0);
  92231. FLAC__ASSERT(lag <= data_len);
  92232. for(coeff = 0; coeff < lag; coeff++)
  92233. autoc[coeff] = 0.0;
  92234. for(sample = 0; sample <= limit; sample++) {
  92235. d = data[sample];
  92236. for(coeff = 0; coeff < lag; coeff++)
  92237. autoc[coeff] += d * data[sample+coeff];
  92238. }
  92239. for(; sample < data_len; sample++) {
  92240. d = data[sample];
  92241. for(coeff = 0; coeff < data_len - sample; coeff++)
  92242. autoc[coeff] += d * data[sample+coeff];
  92243. }
  92244. }
  92245. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  92246. {
  92247. unsigned i, j;
  92248. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  92249. FLAC__ASSERT(0 != max_order);
  92250. FLAC__ASSERT(0 < *max_order);
  92251. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  92252. FLAC__ASSERT(autoc[0] != 0.0);
  92253. err = autoc[0];
  92254. for(i = 0; i < *max_order; i++) {
  92255. /* Sum up this iteration's reflection coefficient. */
  92256. r = -autoc[i+1];
  92257. for(j = 0; j < i; j++)
  92258. r -= lpc[j] * autoc[i-j];
  92259. ref[i] = (r/=err);
  92260. /* Update LPC coefficients and total error. */
  92261. lpc[i]=r;
  92262. for(j = 0; j < (i>>1); j++) {
  92263. FLAC__double tmp = lpc[j];
  92264. lpc[j] += r * lpc[i-1-j];
  92265. lpc[i-1-j] += r * tmp;
  92266. }
  92267. if(i & 1)
  92268. lpc[j] += lpc[j] * r;
  92269. err *= (1.0 - r * r);
  92270. /* save this order */
  92271. for(j = 0; j <= i; j++)
  92272. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  92273. error[i] = err;
  92274. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  92275. if(err == 0.0) {
  92276. *max_order = i+1;
  92277. return;
  92278. }
  92279. }
  92280. }
  92281. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  92282. {
  92283. unsigned i;
  92284. FLAC__double cmax;
  92285. FLAC__int32 qmax, qmin;
  92286. FLAC__ASSERT(precision > 0);
  92287. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  92288. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  92289. precision--;
  92290. qmax = 1 << precision;
  92291. qmin = -qmax;
  92292. qmax--;
  92293. /* calc cmax = max( |lp_coeff[i]| ) */
  92294. cmax = 0.0;
  92295. for(i = 0; i < order; i++) {
  92296. const FLAC__double d = fabs(lp_coeff[i]);
  92297. if(d > cmax)
  92298. cmax = d;
  92299. }
  92300. if(cmax <= 0.0) {
  92301. /* => coefficients are all 0, which means our constant-detect didn't work */
  92302. return 2;
  92303. }
  92304. else {
  92305. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  92306. const int min_shiftlimit = -max_shiftlimit - 1;
  92307. int log2cmax;
  92308. (void)frexp(cmax, &log2cmax);
  92309. log2cmax--;
  92310. *shift = (int)precision - log2cmax - 1;
  92311. if(*shift > max_shiftlimit)
  92312. *shift = max_shiftlimit;
  92313. else if(*shift < min_shiftlimit)
  92314. return 1;
  92315. }
  92316. if(*shift >= 0) {
  92317. FLAC__double error = 0.0;
  92318. FLAC__int32 q;
  92319. for(i = 0; i < order; i++) {
  92320. error += lp_coeff[i] * (1 << *shift);
  92321. #if 1 /* unfortunately lround() is C99 */
  92322. if(error >= 0.0)
  92323. q = (FLAC__int32)(error + 0.5);
  92324. else
  92325. q = (FLAC__int32)(error - 0.5);
  92326. #else
  92327. q = lround(error);
  92328. #endif
  92329. #ifdef FLAC__OVERFLOW_DETECT
  92330. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92331. 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]);
  92332. else if(q < qmin)
  92333. 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]);
  92334. #endif
  92335. if(q > qmax)
  92336. q = qmax;
  92337. else if(q < qmin)
  92338. q = qmin;
  92339. error -= q;
  92340. qlp_coeff[i] = q;
  92341. }
  92342. }
  92343. /* negative shift is very rare but due to design flaw, negative shift is
  92344. * a NOP in the decoder, so it must be handled specially by scaling down
  92345. * coeffs
  92346. */
  92347. else {
  92348. const int nshift = -(*shift);
  92349. FLAC__double error = 0.0;
  92350. FLAC__int32 q;
  92351. #ifdef DEBUG
  92352. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  92353. #endif
  92354. for(i = 0; i < order; i++) {
  92355. error += lp_coeff[i] / (1 << nshift);
  92356. #if 1 /* unfortunately lround() is C99 */
  92357. if(error >= 0.0)
  92358. q = (FLAC__int32)(error + 0.5);
  92359. else
  92360. q = (FLAC__int32)(error - 0.5);
  92361. #else
  92362. q = lround(error);
  92363. #endif
  92364. #ifdef FLAC__OVERFLOW_DETECT
  92365. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92366. 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]);
  92367. else if(q < qmin)
  92368. 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]);
  92369. #endif
  92370. if(q > qmax)
  92371. q = qmax;
  92372. else if(q < qmin)
  92373. q = qmin;
  92374. error -= q;
  92375. qlp_coeff[i] = q;
  92376. }
  92377. *shift = 0;
  92378. }
  92379. return 0;
  92380. }
  92381. 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[])
  92382. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92383. {
  92384. FLAC__int64 sumo;
  92385. unsigned i, j;
  92386. FLAC__int32 sum;
  92387. const FLAC__int32 *history;
  92388. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92389. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92390. for(i=0;i<order;i++)
  92391. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92392. fprintf(stderr,"\n");
  92393. #endif
  92394. FLAC__ASSERT(order > 0);
  92395. for(i = 0; i < data_len; i++) {
  92396. sumo = 0;
  92397. sum = 0;
  92398. history = data;
  92399. for(j = 0; j < order; j++) {
  92400. sum += qlp_coeff[j] * (*(--history));
  92401. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  92402. #if defined _MSC_VER
  92403. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  92404. 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);
  92405. #else
  92406. if(sumo > 2147483647ll || sumo < -2147483648ll)
  92407. 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);
  92408. #endif
  92409. }
  92410. *(residual++) = *(data++) - (sum >> lp_quantization);
  92411. }
  92412. /* Here's a slower but clearer version:
  92413. for(i = 0; i < data_len; i++) {
  92414. sum = 0;
  92415. for(j = 0; j < order; j++)
  92416. sum += qlp_coeff[j] * data[i-j-1];
  92417. residual[i] = data[i] - (sum >> lp_quantization);
  92418. }
  92419. */
  92420. }
  92421. #else /* fully unrolled version for normal use */
  92422. {
  92423. int i;
  92424. FLAC__int32 sum;
  92425. FLAC__ASSERT(order > 0);
  92426. FLAC__ASSERT(order <= 32);
  92427. /*
  92428. * We do unique versions up to 12th order since that's the subset limit.
  92429. * Also they are roughly ordered to match frequency of occurrence to
  92430. * minimize branching.
  92431. */
  92432. if(order <= 12) {
  92433. if(order > 8) {
  92434. if(order > 10) {
  92435. if(order == 12) {
  92436. for(i = 0; i < (int)data_len; i++) {
  92437. sum = 0;
  92438. sum += qlp_coeff[11] * data[i-12];
  92439. sum += qlp_coeff[10] * data[i-11];
  92440. sum += qlp_coeff[9] * data[i-10];
  92441. sum += qlp_coeff[8] * data[i-9];
  92442. sum += qlp_coeff[7] * data[i-8];
  92443. sum += qlp_coeff[6] * data[i-7];
  92444. sum += qlp_coeff[5] * data[i-6];
  92445. sum += qlp_coeff[4] * data[i-5];
  92446. sum += qlp_coeff[3] * data[i-4];
  92447. sum += qlp_coeff[2] * data[i-3];
  92448. sum += qlp_coeff[1] * data[i-2];
  92449. sum += qlp_coeff[0] * data[i-1];
  92450. residual[i] = data[i] - (sum >> lp_quantization);
  92451. }
  92452. }
  92453. else { /* order == 11 */
  92454. for(i = 0; i < (int)data_len; i++) {
  92455. sum = 0;
  92456. sum += qlp_coeff[10] * data[i-11];
  92457. sum += qlp_coeff[9] * data[i-10];
  92458. sum += qlp_coeff[8] * data[i-9];
  92459. sum += qlp_coeff[7] * data[i-8];
  92460. sum += qlp_coeff[6] * data[i-7];
  92461. sum += qlp_coeff[5] * data[i-6];
  92462. sum += qlp_coeff[4] * data[i-5];
  92463. sum += qlp_coeff[3] * data[i-4];
  92464. sum += qlp_coeff[2] * data[i-3];
  92465. sum += qlp_coeff[1] * data[i-2];
  92466. sum += qlp_coeff[0] * data[i-1];
  92467. residual[i] = data[i] - (sum >> lp_quantization);
  92468. }
  92469. }
  92470. }
  92471. else {
  92472. if(order == 10) {
  92473. for(i = 0; i < (int)data_len; i++) {
  92474. sum = 0;
  92475. sum += qlp_coeff[9] * data[i-10];
  92476. sum += qlp_coeff[8] * data[i-9];
  92477. sum += qlp_coeff[7] * data[i-8];
  92478. sum += qlp_coeff[6] * data[i-7];
  92479. sum += qlp_coeff[5] * data[i-6];
  92480. sum += qlp_coeff[4] * data[i-5];
  92481. sum += qlp_coeff[3] * data[i-4];
  92482. sum += qlp_coeff[2] * data[i-3];
  92483. sum += qlp_coeff[1] * data[i-2];
  92484. sum += qlp_coeff[0] * data[i-1];
  92485. residual[i] = data[i] - (sum >> lp_quantization);
  92486. }
  92487. }
  92488. else { /* order == 9 */
  92489. for(i = 0; i < (int)data_len; i++) {
  92490. sum = 0;
  92491. sum += qlp_coeff[8] * data[i-9];
  92492. sum += qlp_coeff[7] * data[i-8];
  92493. sum += qlp_coeff[6] * data[i-7];
  92494. sum += qlp_coeff[5] * data[i-6];
  92495. sum += qlp_coeff[4] * data[i-5];
  92496. sum += qlp_coeff[3] * data[i-4];
  92497. sum += qlp_coeff[2] * data[i-3];
  92498. sum += qlp_coeff[1] * data[i-2];
  92499. sum += qlp_coeff[0] * data[i-1];
  92500. residual[i] = data[i] - (sum >> lp_quantization);
  92501. }
  92502. }
  92503. }
  92504. }
  92505. else if(order > 4) {
  92506. if(order > 6) {
  92507. if(order == 8) {
  92508. for(i = 0; i < (int)data_len; i++) {
  92509. sum = 0;
  92510. sum += qlp_coeff[7] * data[i-8];
  92511. sum += qlp_coeff[6] * data[i-7];
  92512. sum += qlp_coeff[5] * data[i-6];
  92513. sum += qlp_coeff[4] * data[i-5];
  92514. sum += qlp_coeff[3] * data[i-4];
  92515. sum += qlp_coeff[2] * data[i-3];
  92516. sum += qlp_coeff[1] * data[i-2];
  92517. sum += qlp_coeff[0] * data[i-1];
  92518. residual[i] = data[i] - (sum >> lp_quantization);
  92519. }
  92520. }
  92521. else { /* order == 7 */
  92522. for(i = 0; i < (int)data_len; i++) {
  92523. sum = 0;
  92524. sum += qlp_coeff[6] * data[i-7];
  92525. sum += qlp_coeff[5] * data[i-6];
  92526. sum += qlp_coeff[4] * data[i-5];
  92527. sum += qlp_coeff[3] * data[i-4];
  92528. sum += qlp_coeff[2] * data[i-3];
  92529. sum += qlp_coeff[1] * data[i-2];
  92530. sum += qlp_coeff[0] * data[i-1];
  92531. residual[i] = data[i] - (sum >> lp_quantization);
  92532. }
  92533. }
  92534. }
  92535. else {
  92536. if(order == 6) {
  92537. for(i = 0; i < (int)data_len; i++) {
  92538. sum = 0;
  92539. sum += qlp_coeff[5] * data[i-6];
  92540. sum += qlp_coeff[4] * data[i-5];
  92541. sum += qlp_coeff[3] * data[i-4];
  92542. sum += qlp_coeff[2] * data[i-3];
  92543. sum += qlp_coeff[1] * data[i-2];
  92544. sum += qlp_coeff[0] * data[i-1];
  92545. residual[i] = data[i] - (sum >> lp_quantization);
  92546. }
  92547. }
  92548. else { /* order == 5 */
  92549. for(i = 0; i < (int)data_len; i++) {
  92550. sum = 0;
  92551. sum += qlp_coeff[4] * data[i-5];
  92552. sum += qlp_coeff[3] * data[i-4];
  92553. sum += qlp_coeff[2] * data[i-3];
  92554. sum += qlp_coeff[1] * data[i-2];
  92555. sum += qlp_coeff[0] * data[i-1];
  92556. residual[i] = data[i] - (sum >> lp_quantization);
  92557. }
  92558. }
  92559. }
  92560. }
  92561. else {
  92562. if(order > 2) {
  92563. if(order == 4) {
  92564. for(i = 0; i < (int)data_len; i++) {
  92565. sum = 0;
  92566. sum += qlp_coeff[3] * data[i-4];
  92567. sum += qlp_coeff[2] * data[i-3];
  92568. sum += qlp_coeff[1] * data[i-2];
  92569. sum += qlp_coeff[0] * data[i-1];
  92570. residual[i] = data[i] - (sum >> lp_quantization);
  92571. }
  92572. }
  92573. else { /* order == 3 */
  92574. for(i = 0; i < (int)data_len; i++) {
  92575. sum = 0;
  92576. sum += qlp_coeff[2] * data[i-3];
  92577. sum += qlp_coeff[1] * data[i-2];
  92578. sum += qlp_coeff[0] * data[i-1];
  92579. residual[i] = data[i] - (sum >> lp_quantization);
  92580. }
  92581. }
  92582. }
  92583. else {
  92584. if(order == 2) {
  92585. for(i = 0; i < (int)data_len; i++) {
  92586. sum = 0;
  92587. sum += qlp_coeff[1] * data[i-2];
  92588. sum += qlp_coeff[0] * data[i-1];
  92589. residual[i] = data[i] - (sum >> lp_quantization);
  92590. }
  92591. }
  92592. else { /* order == 1 */
  92593. for(i = 0; i < (int)data_len; i++)
  92594. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  92595. }
  92596. }
  92597. }
  92598. }
  92599. else { /* order > 12 */
  92600. for(i = 0; i < (int)data_len; i++) {
  92601. sum = 0;
  92602. switch(order) {
  92603. case 32: sum += qlp_coeff[31] * data[i-32];
  92604. case 31: sum += qlp_coeff[30] * data[i-31];
  92605. case 30: sum += qlp_coeff[29] * data[i-30];
  92606. case 29: sum += qlp_coeff[28] * data[i-29];
  92607. case 28: sum += qlp_coeff[27] * data[i-28];
  92608. case 27: sum += qlp_coeff[26] * data[i-27];
  92609. case 26: sum += qlp_coeff[25] * data[i-26];
  92610. case 25: sum += qlp_coeff[24] * data[i-25];
  92611. case 24: sum += qlp_coeff[23] * data[i-24];
  92612. case 23: sum += qlp_coeff[22] * data[i-23];
  92613. case 22: sum += qlp_coeff[21] * data[i-22];
  92614. case 21: sum += qlp_coeff[20] * data[i-21];
  92615. case 20: sum += qlp_coeff[19] * data[i-20];
  92616. case 19: sum += qlp_coeff[18] * data[i-19];
  92617. case 18: sum += qlp_coeff[17] * data[i-18];
  92618. case 17: sum += qlp_coeff[16] * data[i-17];
  92619. case 16: sum += qlp_coeff[15] * data[i-16];
  92620. case 15: sum += qlp_coeff[14] * data[i-15];
  92621. case 14: sum += qlp_coeff[13] * data[i-14];
  92622. case 13: sum += qlp_coeff[12] * data[i-13];
  92623. sum += qlp_coeff[11] * data[i-12];
  92624. sum += qlp_coeff[10] * data[i-11];
  92625. sum += qlp_coeff[ 9] * data[i-10];
  92626. sum += qlp_coeff[ 8] * data[i- 9];
  92627. sum += qlp_coeff[ 7] * data[i- 8];
  92628. sum += qlp_coeff[ 6] * data[i- 7];
  92629. sum += qlp_coeff[ 5] * data[i- 6];
  92630. sum += qlp_coeff[ 4] * data[i- 5];
  92631. sum += qlp_coeff[ 3] * data[i- 4];
  92632. sum += qlp_coeff[ 2] * data[i- 3];
  92633. sum += qlp_coeff[ 1] * data[i- 2];
  92634. sum += qlp_coeff[ 0] * data[i- 1];
  92635. }
  92636. residual[i] = data[i] - (sum >> lp_quantization);
  92637. }
  92638. }
  92639. }
  92640. #endif
  92641. 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[])
  92642. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92643. {
  92644. unsigned i, j;
  92645. FLAC__int64 sum;
  92646. const FLAC__int32 *history;
  92647. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92648. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92649. for(i=0;i<order;i++)
  92650. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92651. fprintf(stderr,"\n");
  92652. #endif
  92653. FLAC__ASSERT(order > 0);
  92654. for(i = 0; i < data_len; i++) {
  92655. sum = 0;
  92656. history = data;
  92657. for(j = 0; j < order; j++)
  92658. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  92659. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  92660. #if defined _MSC_VER
  92661. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  92662. #else
  92663. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  92664. #endif
  92665. break;
  92666. }
  92667. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  92668. #if defined _MSC_VER
  92669. 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));
  92670. #else
  92671. 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)));
  92672. #endif
  92673. break;
  92674. }
  92675. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  92676. }
  92677. }
  92678. #else /* fully unrolled version for normal use */
  92679. {
  92680. int i;
  92681. FLAC__int64 sum;
  92682. FLAC__ASSERT(order > 0);
  92683. FLAC__ASSERT(order <= 32);
  92684. /*
  92685. * We do unique versions up to 12th order since that's the subset limit.
  92686. * Also they are roughly ordered to match frequency of occurrence to
  92687. * minimize branching.
  92688. */
  92689. if(order <= 12) {
  92690. if(order > 8) {
  92691. if(order > 10) {
  92692. if(order == 12) {
  92693. for(i = 0; i < (int)data_len; i++) {
  92694. sum = 0;
  92695. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92696. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92697. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92698. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92699. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92700. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92701. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92702. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92703. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92704. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92705. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92706. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92707. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92708. }
  92709. }
  92710. else { /* order == 11 */
  92711. for(i = 0; i < (int)data_len; i++) {
  92712. sum = 0;
  92713. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92714. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92715. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92716. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92717. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92718. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92719. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92720. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92721. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92722. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92723. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92724. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92725. }
  92726. }
  92727. }
  92728. else {
  92729. if(order == 10) {
  92730. for(i = 0; i < (int)data_len; i++) {
  92731. sum = 0;
  92732. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92733. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92734. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92735. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92736. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92737. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92738. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92739. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92740. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92741. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92742. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92743. }
  92744. }
  92745. else { /* order == 9 */
  92746. for(i = 0; i < (int)data_len; i++) {
  92747. sum = 0;
  92748. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92749. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92750. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92751. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92752. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92753. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92754. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92755. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92756. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92757. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92758. }
  92759. }
  92760. }
  92761. }
  92762. else if(order > 4) {
  92763. if(order > 6) {
  92764. if(order == 8) {
  92765. for(i = 0; i < (int)data_len; i++) {
  92766. sum = 0;
  92767. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92768. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92769. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92770. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92771. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92772. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92773. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92774. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92775. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92776. }
  92777. }
  92778. else { /* order == 7 */
  92779. for(i = 0; i < (int)data_len; i++) {
  92780. sum = 0;
  92781. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92782. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92783. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92784. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92785. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92786. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92787. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92788. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92789. }
  92790. }
  92791. }
  92792. else {
  92793. if(order == 6) {
  92794. for(i = 0; i < (int)data_len; i++) {
  92795. sum = 0;
  92796. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92797. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92798. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92799. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92800. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92801. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92802. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92803. }
  92804. }
  92805. else { /* order == 5 */
  92806. for(i = 0; i < (int)data_len; i++) {
  92807. sum = 0;
  92808. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92809. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92810. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92811. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92812. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92813. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92814. }
  92815. }
  92816. }
  92817. }
  92818. else {
  92819. if(order > 2) {
  92820. if(order == 4) {
  92821. for(i = 0; i < (int)data_len; i++) {
  92822. sum = 0;
  92823. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92824. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92825. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92826. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92827. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92828. }
  92829. }
  92830. else { /* order == 3 */
  92831. for(i = 0; i < (int)data_len; i++) {
  92832. sum = 0;
  92833. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92834. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92835. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92836. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92837. }
  92838. }
  92839. }
  92840. else {
  92841. if(order == 2) {
  92842. for(i = 0; i < (int)data_len; i++) {
  92843. sum = 0;
  92844. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92845. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92846. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92847. }
  92848. }
  92849. else { /* order == 1 */
  92850. for(i = 0; i < (int)data_len; i++)
  92851. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  92852. }
  92853. }
  92854. }
  92855. }
  92856. else { /* order > 12 */
  92857. for(i = 0; i < (int)data_len; i++) {
  92858. sum = 0;
  92859. switch(order) {
  92860. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  92861. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  92862. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  92863. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  92864. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  92865. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  92866. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  92867. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  92868. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  92869. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  92870. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  92871. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  92872. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  92873. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  92874. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  92875. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  92876. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  92877. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  92878. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  92879. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  92880. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92881. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92882. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  92883. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  92884. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  92885. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  92886. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  92887. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  92888. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  92889. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  92890. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  92891. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  92892. }
  92893. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92894. }
  92895. }
  92896. }
  92897. #endif
  92898. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92899. 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[])
  92900. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92901. {
  92902. FLAC__int64 sumo;
  92903. unsigned i, j;
  92904. FLAC__int32 sum;
  92905. const FLAC__int32 *r = residual, *history;
  92906. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92907. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92908. for(i=0;i<order;i++)
  92909. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92910. fprintf(stderr,"\n");
  92911. #endif
  92912. FLAC__ASSERT(order > 0);
  92913. for(i = 0; i < data_len; i++) {
  92914. sumo = 0;
  92915. sum = 0;
  92916. history = data;
  92917. for(j = 0; j < order; j++) {
  92918. sum += qlp_coeff[j] * (*(--history));
  92919. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  92920. #if defined _MSC_VER
  92921. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  92922. 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);
  92923. #else
  92924. if(sumo > 2147483647ll || sumo < -2147483648ll)
  92925. 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);
  92926. #endif
  92927. }
  92928. *(data++) = *(r++) + (sum >> lp_quantization);
  92929. }
  92930. /* Here's a slower but clearer version:
  92931. for(i = 0; i < data_len; i++) {
  92932. sum = 0;
  92933. for(j = 0; j < order; j++)
  92934. sum += qlp_coeff[j] * data[i-j-1];
  92935. data[i] = residual[i] + (sum >> lp_quantization);
  92936. }
  92937. */
  92938. }
  92939. #else /* fully unrolled version for normal use */
  92940. {
  92941. int i;
  92942. FLAC__int32 sum;
  92943. FLAC__ASSERT(order > 0);
  92944. FLAC__ASSERT(order <= 32);
  92945. /*
  92946. * We do unique versions up to 12th order since that's the subset limit.
  92947. * Also they are roughly ordered to match frequency of occurrence to
  92948. * minimize branching.
  92949. */
  92950. if(order <= 12) {
  92951. if(order > 8) {
  92952. if(order > 10) {
  92953. if(order == 12) {
  92954. for(i = 0; i < (int)data_len; i++) {
  92955. sum = 0;
  92956. sum += qlp_coeff[11] * data[i-12];
  92957. sum += qlp_coeff[10] * data[i-11];
  92958. sum += qlp_coeff[9] * data[i-10];
  92959. sum += qlp_coeff[8] * data[i-9];
  92960. sum += qlp_coeff[7] * data[i-8];
  92961. sum += qlp_coeff[6] * data[i-7];
  92962. sum += qlp_coeff[5] * data[i-6];
  92963. sum += qlp_coeff[4] * data[i-5];
  92964. sum += qlp_coeff[3] * data[i-4];
  92965. sum += qlp_coeff[2] * data[i-3];
  92966. sum += qlp_coeff[1] * data[i-2];
  92967. sum += qlp_coeff[0] * data[i-1];
  92968. data[i] = residual[i] + (sum >> lp_quantization);
  92969. }
  92970. }
  92971. else { /* order == 11 */
  92972. for(i = 0; i < (int)data_len; i++) {
  92973. sum = 0;
  92974. sum += qlp_coeff[10] * data[i-11];
  92975. sum += qlp_coeff[9] * data[i-10];
  92976. sum += qlp_coeff[8] * data[i-9];
  92977. sum += qlp_coeff[7] * data[i-8];
  92978. sum += qlp_coeff[6] * data[i-7];
  92979. sum += qlp_coeff[5] * data[i-6];
  92980. sum += qlp_coeff[4] * data[i-5];
  92981. sum += qlp_coeff[3] * data[i-4];
  92982. sum += qlp_coeff[2] * data[i-3];
  92983. sum += qlp_coeff[1] * data[i-2];
  92984. sum += qlp_coeff[0] * data[i-1];
  92985. data[i] = residual[i] + (sum >> lp_quantization);
  92986. }
  92987. }
  92988. }
  92989. else {
  92990. if(order == 10) {
  92991. for(i = 0; i < (int)data_len; i++) {
  92992. sum = 0;
  92993. sum += qlp_coeff[9] * data[i-10];
  92994. sum += qlp_coeff[8] * data[i-9];
  92995. sum += qlp_coeff[7] * data[i-8];
  92996. sum += qlp_coeff[6] * data[i-7];
  92997. sum += qlp_coeff[5] * data[i-6];
  92998. sum += qlp_coeff[4] * data[i-5];
  92999. sum += qlp_coeff[3] * data[i-4];
  93000. sum += qlp_coeff[2] * data[i-3];
  93001. sum += qlp_coeff[1] * data[i-2];
  93002. sum += qlp_coeff[0] * data[i-1];
  93003. data[i] = residual[i] + (sum >> lp_quantization);
  93004. }
  93005. }
  93006. else { /* order == 9 */
  93007. for(i = 0; i < (int)data_len; i++) {
  93008. sum = 0;
  93009. sum += qlp_coeff[8] * data[i-9];
  93010. sum += qlp_coeff[7] * data[i-8];
  93011. sum += qlp_coeff[6] * data[i-7];
  93012. sum += qlp_coeff[5] * data[i-6];
  93013. sum += qlp_coeff[4] * data[i-5];
  93014. sum += qlp_coeff[3] * data[i-4];
  93015. sum += qlp_coeff[2] * data[i-3];
  93016. sum += qlp_coeff[1] * data[i-2];
  93017. sum += qlp_coeff[0] * data[i-1];
  93018. data[i] = residual[i] + (sum >> lp_quantization);
  93019. }
  93020. }
  93021. }
  93022. }
  93023. else if(order > 4) {
  93024. if(order > 6) {
  93025. if(order == 8) {
  93026. for(i = 0; i < (int)data_len; i++) {
  93027. sum = 0;
  93028. sum += qlp_coeff[7] * data[i-8];
  93029. sum += qlp_coeff[6] * data[i-7];
  93030. sum += qlp_coeff[5] * data[i-6];
  93031. sum += qlp_coeff[4] * data[i-5];
  93032. sum += qlp_coeff[3] * data[i-4];
  93033. sum += qlp_coeff[2] * data[i-3];
  93034. sum += qlp_coeff[1] * data[i-2];
  93035. sum += qlp_coeff[0] * data[i-1];
  93036. data[i] = residual[i] + (sum >> lp_quantization);
  93037. }
  93038. }
  93039. else { /* order == 7 */
  93040. for(i = 0; i < (int)data_len; i++) {
  93041. sum = 0;
  93042. sum += qlp_coeff[6] * data[i-7];
  93043. sum += qlp_coeff[5] * data[i-6];
  93044. sum += qlp_coeff[4] * data[i-5];
  93045. sum += qlp_coeff[3] * data[i-4];
  93046. sum += qlp_coeff[2] * data[i-3];
  93047. sum += qlp_coeff[1] * data[i-2];
  93048. sum += qlp_coeff[0] * data[i-1];
  93049. data[i] = residual[i] + (sum >> lp_quantization);
  93050. }
  93051. }
  93052. }
  93053. else {
  93054. if(order == 6) {
  93055. for(i = 0; i < (int)data_len; i++) {
  93056. sum = 0;
  93057. sum += qlp_coeff[5] * data[i-6];
  93058. sum += qlp_coeff[4] * data[i-5];
  93059. sum += qlp_coeff[3] * data[i-4];
  93060. sum += qlp_coeff[2] * data[i-3];
  93061. sum += qlp_coeff[1] * data[i-2];
  93062. sum += qlp_coeff[0] * data[i-1];
  93063. data[i] = residual[i] + (sum >> lp_quantization);
  93064. }
  93065. }
  93066. else { /* order == 5 */
  93067. for(i = 0; i < (int)data_len; i++) {
  93068. sum = 0;
  93069. sum += qlp_coeff[4] * data[i-5];
  93070. sum += qlp_coeff[3] * data[i-4];
  93071. sum += qlp_coeff[2] * data[i-3];
  93072. sum += qlp_coeff[1] * data[i-2];
  93073. sum += qlp_coeff[0] * data[i-1];
  93074. data[i] = residual[i] + (sum >> lp_quantization);
  93075. }
  93076. }
  93077. }
  93078. }
  93079. else {
  93080. if(order > 2) {
  93081. if(order == 4) {
  93082. for(i = 0; i < (int)data_len; i++) {
  93083. sum = 0;
  93084. sum += qlp_coeff[3] * data[i-4];
  93085. sum += qlp_coeff[2] * data[i-3];
  93086. sum += qlp_coeff[1] * data[i-2];
  93087. sum += qlp_coeff[0] * data[i-1];
  93088. data[i] = residual[i] + (sum >> lp_quantization);
  93089. }
  93090. }
  93091. else { /* order == 3 */
  93092. for(i = 0; i < (int)data_len; i++) {
  93093. sum = 0;
  93094. sum += qlp_coeff[2] * data[i-3];
  93095. sum += qlp_coeff[1] * data[i-2];
  93096. sum += qlp_coeff[0] * data[i-1];
  93097. data[i] = residual[i] + (sum >> lp_quantization);
  93098. }
  93099. }
  93100. }
  93101. else {
  93102. if(order == 2) {
  93103. for(i = 0; i < (int)data_len; i++) {
  93104. sum = 0;
  93105. sum += qlp_coeff[1] * data[i-2];
  93106. sum += qlp_coeff[0] * data[i-1];
  93107. data[i] = residual[i] + (sum >> lp_quantization);
  93108. }
  93109. }
  93110. else { /* order == 1 */
  93111. for(i = 0; i < (int)data_len; i++)
  93112. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93113. }
  93114. }
  93115. }
  93116. }
  93117. else { /* order > 12 */
  93118. for(i = 0; i < (int)data_len; i++) {
  93119. sum = 0;
  93120. switch(order) {
  93121. case 32: sum += qlp_coeff[31] * data[i-32];
  93122. case 31: sum += qlp_coeff[30] * data[i-31];
  93123. case 30: sum += qlp_coeff[29] * data[i-30];
  93124. case 29: sum += qlp_coeff[28] * data[i-29];
  93125. case 28: sum += qlp_coeff[27] * data[i-28];
  93126. case 27: sum += qlp_coeff[26] * data[i-27];
  93127. case 26: sum += qlp_coeff[25] * data[i-26];
  93128. case 25: sum += qlp_coeff[24] * data[i-25];
  93129. case 24: sum += qlp_coeff[23] * data[i-24];
  93130. case 23: sum += qlp_coeff[22] * data[i-23];
  93131. case 22: sum += qlp_coeff[21] * data[i-22];
  93132. case 21: sum += qlp_coeff[20] * data[i-21];
  93133. case 20: sum += qlp_coeff[19] * data[i-20];
  93134. case 19: sum += qlp_coeff[18] * data[i-19];
  93135. case 18: sum += qlp_coeff[17] * data[i-18];
  93136. case 17: sum += qlp_coeff[16] * data[i-17];
  93137. case 16: sum += qlp_coeff[15] * data[i-16];
  93138. case 15: sum += qlp_coeff[14] * data[i-15];
  93139. case 14: sum += qlp_coeff[13] * data[i-14];
  93140. case 13: sum += qlp_coeff[12] * data[i-13];
  93141. sum += qlp_coeff[11] * data[i-12];
  93142. sum += qlp_coeff[10] * data[i-11];
  93143. sum += qlp_coeff[ 9] * data[i-10];
  93144. sum += qlp_coeff[ 8] * data[i- 9];
  93145. sum += qlp_coeff[ 7] * data[i- 8];
  93146. sum += qlp_coeff[ 6] * data[i- 7];
  93147. sum += qlp_coeff[ 5] * data[i- 6];
  93148. sum += qlp_coeff[ 4] * data[i- 5];
  93149. sum += qlp_coeff[ 3] * data[i- 4];
  93150. sum += qlp_coeff[ 2] * data[i- 3];
  93151. sum += qlp_coeff[ 1] * data[i- 2];
  93152. sum += qlp_coeff[ 0] * data[i- 1];
  93153. }
  93154. data[i] = residual[i] + (sum >> lp_quantization);
  93155. }
  93156. }
  93157. }
  93158. #endif
  93159. 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[])
  93160. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93161. {
  93162. unsigned i, j;
  93163. FLAC__int64 sum;
  93164. const FLAC__int32 *r = residual, *history;
  93165. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93166. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93167. for(i=0;i<order;i++)
  93168. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93169. fprintf(stderr,"\n");
  93170. #endif
  93171. FLAC__ASSERT(order > 0);
  93172. for(i = 0; i < data_len; i++) {
  93173. sum = 0;
  93174. history = data;
  93175. for(j = 0; j < order; j++)
  93176. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93177. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93178. #ifdef _MSC_VER
  93179. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93180. #else
  93181. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93182. #endif
  93183. break;
  93184. }
  93185. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  93186. #ifdef _MSC_VER
  93187. 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));
  93188. #else
  93189. 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)));
  93190. #endif
  93191. break;
  93192. }
  93193. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  93194. }
  93195. }
  93196. #else /* fully unrolled version for normal use */
  93197. {
  93198. int i;
  93199. FLAC__int64 sum;
  93200. FLAC__ASSERT(order > 0);
  93201. FLAC__ASSERT(order <= 32);
  93202. /*
  93203. * We do unique versions up to 12th order since that's the subset limit.
  93204. * Also they are roughly ordered to match frequency of occurrence to
  93205. * minimize branching.
  93206. */
  93207. if(order <= 12) {
  93208. if(order > 8) {
  93209. if(order > 10) {
  93210. if(order == 12) {
  93211. for(i = 0; i < (int)data_len; i++) {
  93212. sum = 0;
  93213. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93214. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93215. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93216. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93217. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93218. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93219. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93220. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93221. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93222. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93223. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93224. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93225. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93226. }
  93227. }
  93228. else { /* order == 11 */
  93229. for(i = 0; i < (int)data_len; i++) {
  93230. sum = 0;
  93231. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93232. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93233. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93234. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93235. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93236. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93237. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93238. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93239. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93240. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93241. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93242. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93243. }
  93244. }
  93245. }
  93246. else {
  93247. if(order == 10) {
  93248. for(i = 0; i < (int)data_len; i++) {
  93249. sum = 0;
  93250. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93251. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93252. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93253. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93254. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93255. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93256. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93257. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93258. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93259. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93260. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93261. }
  93262. }
  93263. else { /* order == 9 */
  93264. for(i = 0; i < (int)data_len; i++) {
  93265. sum = 0;
  93266. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93267. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93268. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93269. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93270. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93271. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93272. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93273. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93274. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93275. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93276. }
  93277. }
  93278. }
  93279. }
  93280. else if(order > 4) {
  93281. if(order > 6) {
  93282. if(order == 8) {
  93283. for(i = 0; i < (int)data_len; i++) {
  93284. sum = 0;
  93285. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93286. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93287. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93288. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93289. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93290. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93291. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93292. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93293. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93294. }
  93295. }
  93296. else { /* order == 7 */
  93297. for(i = 0; i < (int)data_len; i++) {
  93298. sum = 0;
  93299. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93300. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93301. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93302. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93303. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93304. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93305. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93306. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93307. }
  93308. }
  93309. }
  93310. else {
  93311. if(order == 6) {
  93312. for(i = 0; i < (int)data_len; i++) {
  93313. sum = 0;
  93314. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93315. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93316. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93317. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93318. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93319. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93320. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93321. }
  93322. }
  93323. else { /* order == 5 */
  93324. for(i = 0; i < (int)data_len; i++) {
  93325. sum = 0;
  93326. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93327. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93328. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93329. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93330. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93331. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93332. }
  93333. }
  93334. }
  93335. }
  93336. else {
  93337. if(order > 2) {
  93338. if(order == 4) {
  93339. for(i = 0; i < (int)data_len; i++) {
  93340. sum = 0;
  93341. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93342. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93343. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93344. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93345. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93346. }
  93347. }
  93348. else { /* order == 3 */
  93349. for(i = 0; i < (int)data_len; i++) {
  93350. sum = 0;
  93351. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93352. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93353. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93354. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93355. }
  93356. }
  93357. }
  93358. else {
  93359. if(order == 2) {
  93360. for(i = 0; i < (int)data_len; i++) {
  93361. sum = 0;
  93362. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93363. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93364. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93365. }
  93366. }
  93367. else { /* order == 1 */
  93368. for(i = 0; i < (int)data_len; i++)
  93369. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93370. }
  93371. }
  93372. }
  93373. }
  93374. else { /* order > 12 */
  93375. for(i = 0; i < (int)data_len; i++) {
  93376. sum = 0;
  93377. switch(order) {
  93378. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93379. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93380. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93381. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93382. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93383. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93384. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93385. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93386. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93387. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93388. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93389. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93390. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93391. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93392. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93393. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93394. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93395. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93396. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93397. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93398. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93399. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93400. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93401. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93402. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93403. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93404. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93405. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93406. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93407. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93408. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93409. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93410. }
  93411. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93412. }
  93413. }
  93414. }
  93415. #endif
  93416. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93417. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  93418. {
  93419. FLAC__double error_scale;
  93420. FLAC__ASSERT(total_samples > 0);
  93421. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  93422. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  93423. }
  93424. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  93425. {
  93426. if(lpc_error > 0.0) {
  93427. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  93428. if(bps >= 0.0)
  93429. return bps;
  93430. else
  93431. return 0.0;
  93432. }
  93433. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  93434. return 1e32;
  93435. }
  93436. else {
  93437. return 0.0;
  93438. }
  93439. }
  93440. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  93441. {
  93442. 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 */
  93443. FLAC__double bits, best_bits, error_scale;
  93444. FLAC__ASSERT(max_order > 0);
  93445. FLAC__ASSERT(total_samples > 0);
  93446. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  93447. best_index = 0;
  93448. best_bits = (unsigned)(-1);
  93449. for(index = 0, order = 1; index < max_order; index++, order++) {
  93450. 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);
  93451. if(bits < best_bits) {
  93452. best_index = index;
  93453. best_bits = bits;
  93454. }
  93455. }
  93456. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  93457. }
  93458. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93459. #endif
  93460. /********* End of inlined file: lpc_flac.c *********/
  93461. /********* Start of inlined file: md5.c *********/
  93462. /********* Start of inlined file: juce_FlacHeader.h *********/
  93463. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93464. // tasks..
  93465. #define VERSION "1.2.1"
  93466. #define FLAC__NO_DLL 1
  93467. #ifdef _MSC_VER
  93468. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93469. #endif
  93470. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93471. #define FLAC__SYS_DARWIN 1
  93472. #endif
  93473. /********* End of inlined file: juce_FlacHeader.h *********/
  93474. #if JUCE_USE_FLAC
  93475. #if HAVE_CONFIG_H
  93476. # include <config.h>
  93477. #endif
  93478. #include <stdlib.h> /* for malloc() */
  93479. #include <string.h> /* for memcpy() */
  93480. /********* Start of inlined file: md5.h *********/
  93481. #ifndef FLAC__PRIVATE__MD5_H
  93482. #define FLAC__PRIVATE__MD5_H
  93483. /*
  93484. * This is the header file for the MD5 message-digest algorithm.
  93485. * The algorithm is due to Ron Rivest. This code was
  93486. * written by Colin Plumb in 1993, no copyright is claimed.
  93487. * This code is in the public domain; do with it what you wish.
  93488. *
  93489. * Equivalent code is available from RSA Data Security, Inc.
  93490. * This code has been tested against that, and is equivalent,
  93491. * except that you don't need to include two pages of legalese
  93492. * with every copy.
  93493. *
  93494. * To compute the message digest of a chunk of bytes, declare an
  93495. * MD5Context structure, pass it to MD5Init, call MD5Update as
  93496. * needed on buffers full of bytes, and then call MD5Final, which
  93497. * will fill a supplied 16-byte array with the digest.
  93498. *
  93499. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  93500. * header definitions; now uses stuff from dpkg's config.h
  93501. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  93502. * Still in the public domain.
  93503. *
  93504. * Josh Coalson: made some changes to integrate with libFLAC.
  93505. * Still in the public domain, with no warranty.
  93506. */
  93507. typedef struct {
  93508. FLAC__uint32 in[16];
  93509. FLAC__uint32 buf[4];
  93510. FLAC__uint32 bytes[2];
  93511. FLAC__byte *internal_buf;
  93512. size_t capacity;
  93513. } FLAC__MD5Context;
  93514. void FLAC__MD5Init(FLAC__MD5Context *context);
  93515. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  93516. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  93517. #endif
  93518. /********* End of inlined file: md5.h *********/
  93519. #ifndef FLaC__INLINE
  93520. #define FLaC__INLINE
  93521. #endif
  93522. /*
  93523. * This code implements the MD5 message-digest algorithm.
  93524. * The algorithm is due to Ron Rivest. This code was
  93525. * written by Colin Plumb in 1993, no copyright is claimed.
  93526. * This code is in the public domain; do with it what you wish.
  93527. *
  93528. * Equivalent code is available from RSA Data Security, Inc.
  93529. * This code has been tested against that, and is equivalent,
  93530. * except that you don't need to include two pages of legalese
  93531. * with every copy.
  93532. *
  93533. * To compute the message digest of a chunk of bytes, declare an
  93534. * MD5Context structure, pass it to MD5Init, call MD5Update as
  93535. * needed on buffers full of bytes, and then call MD5Final, which
  93536. * will fill a supplied 16-byte array with the digest.
  93537. *
  93538. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  93539. * definitions; now uses stuff from dpkg's config.h.
  93540. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  93541. * Still in the public domain.
  93542. *
  93543. * Josh Coalson: made some changes to integrate with libFLAC.
  93544. * Still in the public domain.
  93545. */
  93546. /* The four core functions - F1 is optimized somewhat */
  93547. /* #define F1(x, y, z) (x & y | ~x & z) */
  93548. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  93549. #define F2(x, y, z) F1(z, x, y)
  93550. #define F3(x, y, z) (x ^ y ^ z)
  93551. #define F4(x, y, z) (y ^ (x | ~z))
  93552. /* This is the central step in the MD5 algorithm. */
  93553. #define MD5STEP(f,w,x,y,z,in,s) \
  93554. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  93555. /*
  93556. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  93557. * reflect the addition of 16 longwords of new data. MD5Update blocks
  93558. * the data and converts bytes into longwords for this routine.
  93559. */
  93560. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  93561. {
  93562. register FLAC__uint32 a, b, c, d;
  93563. a = buf[0];
  93564. b = buf[1];
  93565. c = buf[2];
  93566. d = buf[3];
  93567. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  93568. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  93569. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  93570. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  93571. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  93572. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  93573. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  93574. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  93575. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  93576. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  93577. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  93578. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  93579. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  93580. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  93581. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  93582. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  93583. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  93584. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  93585. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  93586. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  93587. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  93588. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  93589. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  93590. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  93591. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  93592. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  93593. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  93594. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  93595. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  93596. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  93597. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  93598. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  93599. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  93600. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  93601. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  93602. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  93603. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  93604. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  93605. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  93606. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  93607. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  93608. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  93609. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  93610. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  93611. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  93612. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  93613. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  93614. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  93615. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  93616. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  93617. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  93618. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  93619. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  93620. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  93621. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  93622. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  93623. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  93624. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  93625. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  93626. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  93627. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  93628. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  93629. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  93630. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  93631. buf[0] += a;
  93632. buf[1] += b;
  93633. buf[2] += c;
  93634. buf[3] += d;
  93635. }
  93636. #if WORDS_BIGENDIAN
  93637. //@@@@@@ OPT: use bswap/intrinsics
  93638. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  93639. {
  93640. register FLAC__uint32 x;
  93641. do {
  93642. x = *buf;
  93643. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  93644. *buf++ = (x >> 16) | (x << 16);
  93645. } while (--words);
  93646. }
  93647. static void byteSwapX16(FLAC__uint32 *buf)
  93648. {
  93649. register FLAC__uint32 x;
  93650. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93651. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93652. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93653. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93654. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93655. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93656. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93657. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93658. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93659. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93660. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93661. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93662. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93663. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93664. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93665. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  93666. }
  93667. #else
  93668. #define byteSwap(buf, words)
  93669. #define byteSwapX16(buf)
  93670. #endif
  93671. /*
  93672. * Update context to reflect the concatenation of another buffer full
  93673. * of bytes.
  93674. */
  93675. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  93676. {
  93677. FLAC__uint32 t;
  93678. /* Update byte count */
  93679. t = ctx->bytes[0];
  93680. if ((ctx->bytes[0] = t + len) < t)
  93681. ctx->bytes[1]++; /* Carry from low to high */
  93682. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  93683. if (t > len) {
  93684. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  93685. return;
  93686. }
  93687. /* First chunk is an odd size */
  93688. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  93689. byteSwapX16(ctx->in);
  93690. FLAC__MD5Transform(ctx->buf, ctx->in);
  93691. buf += t;
  93692. len -= t;
  93693. /* Process data in 64-byte chunks */
  93694. while (len >= 64) {
  93695. memcpy(ctx->in, buf, 64);
  93696. byteSwapX16(ctx->in);
  93697. FLAC__MD5Transform(ctx->buf, ctx->in);
  93698. buf += 64;
  93699. len -= 64;
  93700. }
  93701. /* Handle any remaining bytes of data. */
  93702. memcpy(ctx->in, buf, len);
  93703. }
  93704. /*
  93705. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  93706. * initialization constants.
  93707. */
  93708. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  93709. {
  93710. ctx->buf[0] = 0x67452301;
  93711. ctx->buf[1] = 0xefcdab89;
  93712. ctx->buf[2] = 0x98badcfe;
  93713. ctx->buf[3] = 0x10325476;
  93714. ctx->bytes[0] = 0;
  93715. ctx->bytes[1] = 0;
  93716. ctx->internal_buf = 0;
  93717. ctx->capacity = 0;
  93718. }
  93719. /*
  93720. * Final wrapup - pad to 64-byte boundary with the bit pattern
  93721. * 1 0* (64-bit count of bits processed, MSB-first)
  93722. */
  93723. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  93724. {
  93725. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  93726. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  93727. /* Set the first char of padding to 0x80. There is always room. */
  93728. *p++ = 0x80;
  93729. /* Bytes of padding needed to make 56 bytes (-8..55) */
  93730. count = 56 - 1 - count;
  93731. if (count < 0) { /* Padding forces an extra block */
  93732. memset(p, 0, count + 8);
  93733. byteSwapX16(ctx->in);
  93734. FLAC__MD5Transform(ctx->buf, ctx->in);
  93735. p = (FLAC__byte *)ctx->in;
  93736. count = 56;
  93737. }
  93738. memset(p, 0, count);
  93739. byteSwap(ctx->in, 14);
  93740. /* Append length in bits and transform */
  93741. ctx->in[14] = ctx->bytes[0] << 3;
  93742. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  93743. FLAC__MD5Transform(ctx->buf, ctx->in);
  93744. byteSwap(ctx->buf, 4);
  93745. memcpy(digest, ctx->buf, 16);
  93746. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  93747. if(0 != ctx->internal_buf) {
  93748. free(ctx->internal_buf);
  93749. ctx->internal_buf = 0;
  93750. ctx->capacity = 0;
  93751. }
  93752. }
  93753. /*
  93754. * Convert the incoming audio signal to a byte stream
  93755. */
  93756. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  93757. {
  93758. unsigned channel, sample;
  93759. register FLAC__int32 a_word;
  93760. register FLAC__byte *buf_ = buf;
  93761. #if WORDS_BIGENDIAN
  93762. #else
  93763. if(channels == 2 && bytes_per_sample == 2) {
  93764. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  93765. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  93766. for(sample = 0; sample < samples; sample++, buf1_+=2)
  93767. *buf1_ = (FLAC__int16)signal[1][sample];
  93768. }
  93769. else if(channels == 1 && bytes_per_sample == 2) {
  93770. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  93771. for(sample = 0; sample < samples; sample++)
  93772. *buf1_++ = (FLAC__int16)signal[0][sample];
  93773. }
  93774. else
  93775. #endif
  93776. if(bytes_per_sample == 2) {
  93777. if(channels == 2) {
  93778. for(sample = 0; sample < samples; sample++) {
  93779. a_word = signal[0][sample];
  93780. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93781. *buf_++ = (FLAC__byte)a_word;
  93782. a_word = signal[1][sample];
  93783. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93784. *buf_++ = (FLAC__byte)a_word;
  93785. }
  93786. }
  93787. else if(channels == 1) {
  93788. for(sample = 0; sample < samples; sample++) {
  93789. a_word = signal[0][sample];
  93790. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93791. *buf_++ = (FLAC__byte)a_word;
  93792. }
  93793. }
  93794. else {
  93795. for(sample = 0; sample < samples; sample++) {
  93796. for(channel = 0; channel < channels; channel++) {
  93797. a_word = signal[channel][sample];
  93798. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93799. *buf_++ = (FLAC__byte)a_word;
  93800. }
  93801. }
  93802. }
  93803. }
  93804. else if(bytes_per_sample == 3) {
  93805. if(channels == 2) {
  93806. for(sample = 0; sample < samples; sample++) {
  93807. a_word = signal[0][sample];
  93808. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93809. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93810. *buf_++ = (FLAC__byte)a_word;
  93811. a_word = signal[1][sample];
  93812. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93813. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93814. *buf_++ = (FLAC__byte)a_word;
  93815. }
  93816. }
  93817. else if(channels == 1) {
  93818. for(sample = 0; sample < samples; sample++) {
  93819. a_word = signal[0][sample];
  93820. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93821. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93822. *buf_++ = (FLAC__byte)a_word;
  93823. }
  93824. }
  93825. else {
  93826. for(sample = 0; sample < samples; sample++) {
  93827. for(channel = 0; channel < channels; channel++) {
  93828. a_word = signal[channel][sample];
  93829. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93830. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93831. *buf_++ = (FLAC__byte)a_word;
  93832. }
  93833. }
  93834. }
  93835. }
  93836. else if(bytes_per_sample == 1) {
  93837. if(channels == 2) {
  93838. for(sample = 0; sample < samples; sample++) {
  93839. a_word = signal[0][sample];
  93840. *buf_++ = (FLAC__byte)a_word;
  93841. a_word = signal[1][sample];
  93842. *buf_++ = (FLAC__byte)a_word;
  93843. }
  93844. }
  93845. else if(channels == 1) {
  93846. for(sample = 0; sample < samples; sample++) {
  93847. a_word = signal[0][sample];
  93848. *buf_++ = (FLAC__byte)a_word;
  93849. }
  93850. }
  93851. else {
  93852. for(sample = 0; sample < samples; sample++) {
  93853. for(channel = 0; channel < channels; channel++) {
  93854. a_word = signal[channel][sample];
  93855. *buf_++ = (FLAC__byte)a_word;
  93856. }
  93857. }
  93858. }
  93859. }
  93860. else { /* bytes_per_sample == 4, maybe optimize more later */
  93861. for(sample = 0; sample < samples; sample++) {
  93862. for(channel = 0; channel < channels; channel++) {
  93863. a_word = signal[channel][sample];
  93864. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93865. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93866. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93867. *buf_++ = (FLAC__byte)a_word;
  93868. }
  93869. }
  93870. }
  93871. }
  93872. /*
  93873. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  93874. */
  93875. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  93876. {
  93877. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  93878. /* overflow check */
  93879. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  93880. return false;
  93881. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  93882. return false;
  93883. if(ctx->capacity < bytes_needed) {
  93884. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  93885. if(0 == tmp) {
  93886. free(ctx->internal_buf);
  93887. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  93888. return false;
  93889. }
  93890. ctx->internal_buf = tmp;
  93891. ctx->capacity = bytes_needed;
  93892. }
  93893. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  93894. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  93895. return true;
  93896. }
  93897. #endif
  93898. /********* End of inlined file: md5.c *********/
  93899. /********* Start of inlined file: memory.c *********/
  93900. /********* Start of inlined file: juce_FlacHeader.h *********/
  93901. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93902. // tasks..
  93903. #define VERSION "1.2.1"
  93904. #define FLAC__NO_DLL 1
  93905. #ifdef _MSC_VER
  93906. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93907. #endif
  93908. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93909. #define FLAC__SYS_DARWIN 1
  93910. #endif
  93911. /********* End of inlined file: juce_FlacHeader.h *********/
  93912. #if JUCE_USE_FLAC
  93913. #if HAVE_CONFIG_H
  93914. # include <config.h>
  93915. #endif
  93916. /********* Start of inlined file: memory.h *********/
  93917. #ifndef FLAC__PRIVATE__MEMORY_H
  93918. #define FLAC__PRIVATE__MEMORY_H
  93919. #ifdef HAVE_CONFIG_H
  93920. #include <config.h>
  93921. #endif
  93922. #include <stdlib.h> /* for size_t */
  93923. /* Returns the unaligned address returned by malloc.
  93924. * Use free() on this address to deallocate.
  93925. */
  93926. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  93927. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  93928. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  93929. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  93930. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  93931. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93932. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  93933. #endif
  93934. #endif
  93935. /********* End of inlined file: memory.h *********/
  93936. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  93937. {
  93938. void *x;
  93939. FLAC__ASSERT(0 != aligned_address);
  93940. #ifdef FLAC__ALIGN_MALLOC_DATA
  93941. /* align on 32-byte (256-bit) boundary */
  93942. x = safe_malloc_add_2op_(bytes, /*+*/31);
  93943. #ifdef SIZEOF_VOIDP
  93944. #if SIZEOF_VOIDP == 4
  93945. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  93946. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  93947. #elif SIZEOF_VOIDP == 8
  93948. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  93949. #else
  93950. # error Unsupported sizeof(void*)
  93951. #endif
  93952. #else
  93953. /* there's got to be a better way to do this right for all archs */
  93954. if(sizeof(void*) == sizeof(unsigned))
  93955. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  93956. else if(sizeof(void*) == sizeof(FLAC__uint64))
  93957. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  93958. else
  93959. return 0;
  93960. #endif
  93961. #else
  93962. x = safe_malloc_(bytes);
  93963. *aligned_address = x;
  93964. #endif
  93965. return x;
  93966. }
  93967. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  93968. {
  93969. FLAC__int32 *pu; /* unaligned pointer */
  93970. union { /* union needed to comply with C99 pointer aliasing rules */
  93971. FLAC__int32 *pa; /* aligned pointer */
  93972. void *pv; /* aligned pointer alias */
  93973. } u;
  93974. FLAC__ASSERT(elements > 0);
  93975. FLAC__ASSERT(0 != unaligned_pointer);
  93976. FLAC__ASSERT(0 != aligned_pointer);
  93977. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93978. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93979. return false;
  93980. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  93981. if(0 == pu) {
  93982. return false;
  93983. }
  93984. else {
  93985. if(*unaligned_pointer != 0)
  93986. free(*unaligned_pointer);
  93987. *unaligned_pointer = pu;
  93988. *aligned_pointer = u.pa;
  93989. return true;
  93990. }
  93991. }
  93992. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  93993. {
  93994. FLAC__uint32 *pu; /* unaligned pointer */
  93995. union { /* union needed to comply with C99 pointer aliasing rules */
  93996. FLAC__uint32 *pa; /* aligned pointer */
  93997. void *pv; /* aligned pointer alias */
  93998. } u;
  93999. FLAC__ASSERT(elements > 0);
  94000. FLAC__ASSERT(0 != unaligned_pointer);
  94001. FLAC__ASSERT(0 != aligned_pointer);
  94002. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94003. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94004. return false;
  94005. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94006. if(0 == pu) {
  94007. return false;
  94008. }
  94009. else {
  94010. if(*unaligned_pointer != 0)
  94011. free(*unaligned_pointer);
  94012. *unaligned_pointer = pu;
  94013. *aligned_pointer = u.pa;
  94014. return true;
  94015. }
  94016. }
  94017. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  94018. {
  94019. FLAC__uint64 *pu; /* unaligned pointer */
  94020. union { /* union needed to comply with C99 pointer aliasing rules */
  94021. FLAC__uint64 *pa; /* aligned pointer */
  94022. void *pv; /* aligned pointer alias */
  94023. } u;
  94024. FLAC__ASSERT(elements > 0);
  94025. FLAC__ASSERT(0 != unaligned_pointer);
  94026. FLAC__ASSERT(0 != aligned_pointer);
  94027. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94028. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94029. return false;
  94030. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94031. if(0 == pu) {
  94032. return false;
  94033. }
  94034. else {
  94035. if(*unaligned_pointer != 0)
  94036. free(*unaligned_pointer);
  94037. *unaligned_pointer = pu;
  94038. *aligned_pointer = u.pa;
  94039. return true;
  94040. }
  94041. }
  94042. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  94043. {
  94044. unsigned *pu; /* unaligned pointer */
  94045. union { /* union needed to comply with C99 pointer aliasing rules */
  94046. unsigned *pa; /* aligned pointer */
  94047. void *pv; /* aligned pointer alias */
  94048. } u;
  94049. FLAC__ASSERT(elements > 0);
  94050. FLAC__ASSERT(0 != unaligned_pointer);
  94051. FLAC__ASSERT(0 != aligned_pointer);
  94052. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94053. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94054. return false;
  94055. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94056. if(0 == pu) {
  94057. return false;
  94058. }
  94059. else {
  94060. if(*unaligned_pointer != 0)
  94061. free(*unaligned_pointer);
  94062. *unaligned_pointer = pu;
  94063. *aligned_pointer = u.pa;
  94064. return true;
  94065. }
  94066. }
  94067. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94068. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  94069. {
  94070. FLAC__real *pu; /* unaligned pointer */
  94071. union { /* union needed to comply with C99 pointer aliasing rules */
  94072. FLAC__real *pa; /* aligned pointer */
  94073. void *pv; /* aligned pointer alias */
  94074. } u;
  94075. FLAC__ASSERT(elements > 0);
  94076. FLAC__ASSERT(0 != unaligned_pointer);
  94077. FLAC__ASSERT(0 != aligned_pointer);
  94078. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94079. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94080. return false;
  94081. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94082. if(0 == pu) {
  94083. return false;
  94084. }
  94085. else {
  94086. if(*unaligned_pointer != 0)
  94087. free(*unaligned_pointer);
  94088. *unaligned_pointer = pu;
  94089. *aligned_pointer = u.pa;
  94090. return true;
  94091. }
  94092. }
  94093. #endif
  94094. #endif
  94095. /********* End of inlined file: memory.c *********/
  94096. /********* Start of inlined file: stream_decoder.c *********/
  94097. /********* Start of inlined file: juce_FlacHeader.h *********/
  94098. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94099. // tasks..
  94100. #define VERSION "1.2.1"
  94101. #define FLAC__NO_DLL 1
  94102. #ifdef _MSC_VER
  94103. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94104. #endif
  94105. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  94106. #define FLAC__SYS_DARWIN 1
  94107. #endif
  94108. /********* End of inlined file: juce_FlacHeader.h *********/
  94109. #if JUCE_USE_FLAC
  94110. #if HAVE_CONFIG_H
  94111. # include <config.h>
  94112. #endif
  94113. #if defined _MSC_VER || defined __MINGW32__
  94114. #include <io.h> /* for _setmode() */
  94115. #include <fcntl.h> /* for _O_BINARY */
  94116. #endif
  94117. #if defined __CYGWIN__ || defined __EMX__
  94118. #include <io.h> /* for setmode(), O_BINARY */
  94119. #include <fcntl.h> /* for _O_BINARY */
  94120. #endif
  94121. #include <stdio.h>
  94122. #include <stdlib.h> /* for malloc() */
  94123. #include <string.h> /* for memset/memcpy() */
  94124. #include <sys/stat.h> /* for stat() */
  94125. #include <sys/types.h> /* for off_t */
  94126. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  94127. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  94128. #define fseeko fseek
  94129. #define ftello ftell
  94130. #endif
  94131. #endif
  94132. /********* Start of inlined file: stream_decoder.h *********/
  94133. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  94134. #define FLAC__PROTECTED__STREAM_DECODER_H
  94135. #if FLAC__HAS_OGG
  94136. #include "include/private/ogg_decoder_aspect.h"
  94137. #endif
  94138. typedef struct FLAC__StreamDecoderProtected {
  94139. FLAC__StreamDecoderState state;
  94140. unsigned channels;
  94141. FLAC__ChannelAssignment channel_assignment;
  94142. unsigned bits_per_sample;
  94143. unsigned sample_rate; /* in Hz */
  94144. unsigned blocksize; /* in samples (per channel) */
  94145. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  94146. #if FLAC__HAS_OGG
  94147. FLAC__OggDecoderAspect ogg_decoder_aspect;
  94148. #endif
  94149. } FLAC__StreamDecoderProtected;
  94150. /*
  94151. * return the number of input bytes consumed
  94152. */
  94153. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  94154. #endif
  94155. /********* End of inlined file: stream_decoder.h *********/
  94156. #ifdef max
  94157. #undef max
  94158. #endif
  94159. #define max(a,b) ((a)>(b)?(a):(b))
  94160. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94161. #ifdef _MSC_VER
  94162. #define FLAC__U64L(x) x
  94163. #else
  94164. #define FLAC__U64L(x) x##LLU
  94165. #endif
  94166. /* technically this should be in an "export.c" but this is convenient enough */
  94167. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  94168. #if FLAC__HAS_OGG
  94169. 1
  94170. #else
  94171. 0
  94172. #endif
  94173. ;
  94174. /***********************************************************************
  94175. *
  94176. * Private static data
  94177. *
  94178. ***********************************************************************/
  94179. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  94180. /***********************************************************************
  94181. *
  94182. * Private class method prototypes
  94183. *
  94184. ***********************************************************************/
  94185. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  94186. static FILE *get_binary_stdin_(void);
  94187. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  94188. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  94189. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  94190. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  94191. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94192. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94193. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  94194. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  94195. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  94196. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  94197. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  94198. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  94199. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  94200. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94201. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94202. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94203. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94204. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94205. 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);
  94206. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  94207. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  94208. #if FLAC__HAS_OGG
  94209. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  94210. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94211. #endif
  94212. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  94213. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  94214. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94215. #if FLAC__HAS_OGG
  94216. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94217. #endif
  94218. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94219. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  94220. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  94221. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  94222. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  94223. /***********************************************************************
  94224. *
  94225. * Private class data
  94226. *
  94227. ***********************************************************************/
  94228. typedef struct FLAC__StreamDecoderPrivate {
  94229. #if FLAC__HAS_OGG
  94230. FLAC__bool is_ogg;
  94231. #endif
  94232. FLAC__StreamDecoderReadCallback read_callback;
  94233. FLAC__StreamDecoderSeekCallback seek_callback;
  94234. FLAC__StreamDecoderTellCallback tell_callback;
  94235. FLAC__StreamDecoderLengthCallback length_callback;
  94236. FLAC__StreamDecoderEofCallback eof_callback;
  94237. FLAC__StreamDecoderWriteCallback write_callback;
  94238. FLAC__StreamDecoderMetadataCallback metadata_callback;
  94239. FLAC__StreamDecoderErrorCallback error_callback;
  94240. /* generic 32-bit datapath: */
  94241. 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[]);
  94242. /* generic 64-bit datapath: */
  94243. 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[]);
  94244. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  94245. 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[]);
  94246. /* 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: */
  94247. 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[]);
  94248. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  94249. void *client_data;
  94250. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  94251. FLAC__BitReader *input;
  94252. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  94253. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  94254. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  94255. unsigned output_capacity, output_channels;
  94256. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  94257. FLAC__uint64 samples_decoded;
  94258. FLAC__bool has_stream_info, has_seek_table;
  94259. FLAC__StreamMetadata stream_info;
  94260. FLAC__StreamMetadata seek_table;
  94261. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  94262. FLAC__byte *metadata_filter_ids;
  94263. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  94264. FLAC__Frame frame;
  94265. FLAC__bool cached; /* true if there is a byte in lookahead */
  94266. FLAC__CPUInfo cpuinfo;
  94267. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  94268. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  94269. /* unaligned (original) pointers to allocated data */
  94270. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  94271. 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 */
  94272. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  94273. FLAC__bool is_seeking;
  94274. FLAC__MD5Context md5context;
  94275. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  94276. /* (the rest of these are only used for seeking) */
  94277. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  94278. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  94279. FLAC__uint64 target_sample;
  94280. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  94281. #if FLAC__HAS_OGG
  94282. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  94283. #endif
  94284. } FLAC__StreamDecoderPrivate;
  94285. /***********************************************************************
  94286. *
  94287. * Public static class data
  94288. *
  94289. ***********************************************************************/
  94290. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  94291. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  94292. "FLAC__STREAM_DECODER_READ_METADATA",
  94293. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  94294. "FLAC__STREAM_DECODER_READ_FRAME",
  94295. "FLAC__STREAM_DECODER_END_OF_STREAM",
  94296. "FLAC__STREAM_DECODER_OGG_ERROR",
  94297. "FLAC__STREAM_DECODER_SEEK_ERROR",
  94298. "FLAC__STREAM_DECODER_ABORTED",
  94299. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  94300. "FLAC__STREAM_DECODER_UNINITIALIZED"
  94301. };
  94302. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  94303. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  94304. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  94305. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  94306. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  94307. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  94308. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  94309. };
  94310. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  94311. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  94312. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  94313. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  94314. };
  94315. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  94316. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  94317. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  94318. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  94319. };
  94320. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  94321. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  94322. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  94323. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  94324. };
  94325. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  94326. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  94327. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  94328. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  94329. };
  94330. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  94331. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  94332. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  94333. };
  94334. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  94335. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  94336. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  94337. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  94338. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  94339. };
  94340. /***********************************************************************
  94341. *
  94342. * Class constructor/destructor
  94343. *
  94344. ***********************************************************************/
  94345. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  94346. {
  94347. FLAC__StreamDecoder *decoder;
  94348. unsigned i;
  94349. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  94350. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  94351. if(decoder == 0) {
  94352. return 0;
  94353. }
  94354. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  94355. if(decoder->protected_ == 0) {
  94356. free(decoder);
  94357. return 0;
  94358. }
  94359. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  94360. if(decoder->private_ == 0) {
  94361. free(decoder->protected_);
  94362. free(decoder);
  94363. return 0;
  94364. }
  94365. decoder->private_->input = FLAC__bitreader_new();
  94366. if(decoder->private_->input == 0) {
  94367. free(decoder->private_);
  94368. free(decoder->protected_);
  94369. free(decoder);
  94370. return 0;
  94371. }
  94372. decoder->private_->metadata_filter_ids_capacity = 16;
  94373. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  94374. FLAC__bitreader_delete(decoder->private_->input);
  94375. free(decoder->private_);
  94376. free(decoder->protected_);
  94377. free(decoder);
  94378. return 0;
  94379. }
  94380. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94381. decoder->private_->output[i] = 0;
  94382. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94383. }
  94384. decoder->private_->output_capacity = 0;
  94385. decoder->private_->output_channels = 0;
  94386. decoder->private_->has_seek_table = false;
  94387. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  94388. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  94389. decoder->private_->file = 0;
  94390. set_defaults_dec(decoder);
  94391. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  94392. return decoder;
  94393. }
  94394. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  94395. {
  94396. unsigned i;
  94397. FLAC__ASSERT(0 != decoder);
  94398. FLAC__ASSERT(0 != decoder->protected_);
  94399. FLAC__ASSERT(0 != decoder->private_);
  94400. FLAC__ASSERT(0 != decoder->private_->input);
  94401. (void)FLAC__stream_decoder_finish(decoder);
  94402. if(0 != decoder->private_->metadata_filter_ids)
  94403. free(decoder->private_->metadata_filter_ids);
  94404. FLAC__bitreader_delete(decoder->private_->input);
  94405. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  94406. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  94407. free(decoder->private_);
  94408. free(decoder->protected_);
  94409. free(decoder);
  94410. }
  94411. /***********************************************************************
  94412. *
  94413. * Public class methods
  94414. *
  94415. ***********************************************************************/
  94416. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  94417. FLAC__StreamDecoder *decoder,
  94418. FLAC__StreamDecoderReadCallback read_callback,
  94419. FLAC__StreamDecoderSeekCallback seek_callback,
  94420. FLAC__StreamDecoderTellCallback tell_callback,
  94421. FLAC__StreamDecoderLengthCallback length_callback,
  94422. FLAC__StreamDecoderEofCallback eof_callback,
  94423. FLAC__StreamDecoderWriteCallback write_callback,
  94424. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94425. FLAC__StreamDecoderErrorCallback error_callback,
  94426. void *client_data,
  94427. FLAC__bool is_ogg
  94428. )
  94429. {
  94430. FLAC__ASSERT(0 != decoder);
  94431. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94432. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  94433. #if !FLAC__HAS_OGG
  94434. if(is_ogg)
  94435. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  94436. #endif
  94437. if(
  94438. 0 == read_callback ||
  94439. 0 == write_callback ||
  94440. 0 == error_callback ||
  94441. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  94442. )
  94443. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  94444. #if FLAC__HAS_OGG
  94445. decoder->private_->is_ogg = is_ogg;
  94446. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  94447. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  94448. #endif
  94449. /*
  94450. * get the CPU info and set the function pointers
  94451. */
  94452. FLAC__cpu_info(&decoder->private_->cpuinfo);
  94453. /* first default to the non-asm routines */
  94454. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  94455. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  94456. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  94457. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  94458. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  94459. /* now override with asm where appropriate */
  94460. #ifndef FLAC__NO_ASM
  94461. if(decoder->private_->cpuinfo.use_asm) {
  94462. #ifdef FLAC__CPU_IA32
  94463. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  94464. #ifdef FLAC__HAS_NASM
  94465. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  94466. if(decoder->private_->cpuinfo.data.ia32.bswap)
  94467. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  94468. #endif
  94469. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  94470. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  94471. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  94472. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  94473. }
  94474. else {
  94475. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  94476. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  94477. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  94478. }
  94479. #endif
  94480. #elif defined FLAC__CPU_PPC
  94481. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  94482. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  94483. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  94484. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  94485. }
  94486. #endif
  94487. }
  94488. #endif
  94489. /* from here on, errors are fatal */
  94490. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  94491. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94492. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  94493. }
  94494. decoder->private_->read_callback = read_callback;
  94495. decoder->private_->seek_callback = seek_callback;
  94496. decoder->private_->tell_callback = tell_callback;
  94497. decoder->private_->length_callback = length_callback;
  94498. decoder->private_->eof_callback = eof_callback;
  94499. decoder->private_->write_callback = write_callback;
  94500. decoder->private_->metadata_callback = metadata_callback;
  94501. decoder->private_->error_callback = error_callback;
  94502. decoder->private_->client_data = client_data;
  94503. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  94504. decoder->private_->samples_decoded = 0;
  94505. decoder->private_->has_stream_info = false;
  94506. decoder->private_->cached = false;
  94507. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  94508. decoder->private_->is_seeking = false;
  94509. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  94510. if(!FLAC__stream_decoder_reset(decoder)) {
  94511. /* above call sets the state for us */
  94512. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  94513. }
  94514. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  94515. }
  94516. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  94517. FLAC__StreamDecoder *decoder,
  94518. FLAC__StreamDecoderReadCallback read_callback,
  94519. FLAC__StreamDecoderSeekCallback seek_callback,
  94520. FLAC__StreamDecoderTellCallback tell_callback,
  94521. FLAC__StreamDecoderLengthCallback length_callback,
  94522. FLAC__StreamDecoderEofCallback eof_callback,
  94523. FLAC__StreamDecoderWriteCallback write_callback,
  94524. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94525. FLAC__StreamDecoderErrorCallback error_callback,
  94526. void *client_data
  94527. )
  94528. {
  94529. return init_stream_internal_dec(
  94530. decoder,
  94531. read_callback,
  94532. seek_callback,
  94533. tell_callback,
  94534. length_callback,
  94535. eof_callback,
  94536. write_callback,
  94537. metadata_callback,
  94538. error_callback,
  94539. client_data,
  94540. /*is_ogg=*/false
  94541. );
  94542. }
  94543. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  94544. FLAC__StreamDecoder *decoder,
  94545. FLAC__StreamDecoderReadCallback read_callback,
  94546. FLAC__StreamDecoderSeekCallback seek_callback,
  94547. FLAC__StreamDecoderTellCallback tell_callback,
  94548. FLAC__StreamDecoderLengthCallback length_callback,
  94549. FLAC__StreamDecoderEofCallback eof_callback,
  94550. FLAC__StreamDecoderWriteCallback write_callback,
  94551. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94552. FLAC__StreamDecoderErrorCallback error_callback,
  94553. void *client_data
  94554. )
  94555. {
  94556. return init_stream_internal_dec(
  94557. decoder,
  94558. read_callback,
  94559. seek_callback,
  94560. tell_callback,
  94561. length_callback,
  94562. eof_callback,
  94563. write_callback,
  94564. metadata_callback,
  94565. error_callback,
  94566. client_data,
  94567. /*is_ogg=*/true
  94568. );
  94569. }
  94570. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  94571. FLAC__StreamDecoder *decoder,
  94572. FILE *file,
  94573. FLAC__StreamDecoderWriteCallback write_callback,
  94574. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94575. FLAC__StreamDecoderErrorCallback error_callback,
  94576. void *client_data,
  94577. FLAC__bool is_ogg
  94578. )
  94579. {
  94580. FLAC__ASSERT(0 != decoder);
  94581. FLAC__ASSERT(0 != file);
  94582. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94583. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  94584. if(0 == write_callback || 0 == error_callback)
  94585. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  94586. /*
  94587. * To make sure that our file does not go unclosed after an error, we
  94588. * must assign the FILE pointer before any further error can occur in
  94589. * this routine.
  94590. */
  94591. if(file == stdin)
  94592. file = get_binary_stdin_(); /* just to be safe */
  94593. decoder->private_->file = file;
  94594. return init_stream_internal_dec(
  94595. decoder,
  94596. file_read_callback_dec,
  94597. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  94598. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  94599. decoder->private_->file == stdin? 0: file_length_callback_,
  94600. file_eof_callback_,
  94601. write_callback,
  94602. metadata_callback,
  94603. error_callback,
  94604. client_data,
  94605. is_ogg
  94606. );
  94607. }
  94608. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  94609. FLAC__StreamDecoder *decoder,
  94610. FILE *file,
  94611. FLAC__StreamDecoderWriteCallback write_callback,
  94612. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94613. FLAC__StreamDecoderErrorCallback error_callback,
  94614. void *client_data
  94615. )
  94616. {
  94617. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  94618. }
  94619. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  94620. FLAC__StreamDecoder *decoder,
  94621. FILE *file,
  94622. FLAC__StreamDecoderWriteCallback write_callback,
  94623. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94624. FLAC__StreamDecoderErrorCallback error_callback,
  94625. void *client_data
  94626. )
  94627. {
  94628. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  94629. }
  94630. static FLAC__StreamDecoderInitStatus init_file_internal_(
  94631. FLAC__StreamDecoder *decoder,
  94632. const char *filename,
  94633. FLAC__StreamDecoderWriteCallback write_callback,
  94634. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94635. FLAC__StreamDecoderErrorCallback error_callback,
  94636. void *client_data,
  94637. FLAC__bool is_ogg
  94638. )
  94639. {
  94640. FILE *file;
  94641. FLAC__ASSERT(0 != decoder);
  94642. /*
  94643. * To make sure that our file does not go unclosed after an error, we
  94644. * have to do the same entrance checks here that are later performed
  94645. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  94646. */
  94647. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94648. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  94649. if(0 == write_callback || 0 == error_callback)
  94650. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  94651. file = filename? fopen(filename, "rb") : stdin;
  94652. if(0 == file)
  94653. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  94654. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  94655. }
  94656. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  94657. FLAC__StreamDecoder *decoder,
  94658. const char *filename,
  94659. FLAC__StreamDecoderWriteCallback write_callback,
  94660. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94661. FLAC__StreamDecoderErrorCallback error_callback,
  94662. void *client_data
  94663. )
  94664. {
  94665. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  94666. }
  94667. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  94668. FLAC__StreamDecoder *decoder,
  94669. const char *filename,
  94670. FLAC__StreamDecoderWriteCallback write_callback,
  94671. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94672. FLAC__StreamDecoderErrorCallback error_callback,
  94673. void *client_data
  94674. )
  94675. {
  94676. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  94677. }
  94678. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  94679. {
  94680. FLAC__bool md5_failed = false;
  94681. unsigned i;
  94682. FLAC__ASSERT(0 != decoder);
  94683. FLAC__ASSERT(0 != decoder->private_);
  94684. FLAC__ASSERT(0 != decoder->protected_);
  94685. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  94686. return true;
  94687. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  94688. * always call FLAC__MD5Final()
  94689. */
  94690. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  94691. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  94692. free(decoder->private_->seek_table.data.seek_table.points);
  94693. decoder->private_->seek_table.data.seek_table.points = 0;
  94694. decoder->private_->has_seek_table = false;
  94695. }
  94696. FLAC__bitreader_free(decoder->private_->input);
  94697. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94698. /* WATCHOUT:
  94699. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  94700. * output arrays have a buffer of up to 3 zeroes in front
  94701. * (at negative indices) for alignment purposes; we use 4
  94702. * to keep the data well-aligned.
  94703. */
  94704. if(0 != decoder->private_->output[i]) {
  94705. free(decoder->private_->output[i]-4);
  94706. decoder->private_->output[i] = 0;
  94707. }
  94708. if(0 != decoder->private_->residual_unaligned[i]) {
  94709. free(decoder->private_->residual_unaligned[i]);
  94710. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94711. }
  94712. }
  94713. decoder->private_->output_capacity = 0;
  94714. decoder->private_->output_channels = 0;
  94715. #if FLAC__HAS_OGG
  94716. if(decoder->private_->is_ogg)
  94717. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  94718. #endif
  94719. if(0 != decoder->private_->file) {
  94720. if(decoder->private_->file != stdin)
  94721. fclose(decoder->private_->file);
  94722. decoder->private_->file = 0;
  94723. }
  94724. if(decoder->private_->do_md5_checking) {
  94725. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  94726. md5_failed = true;
  94727. }
  94728. decoder->private_->is_seeking = false;
  94729. set_defaults_dec(decoder);
  94730. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  94731. return !md5_failed;
  94732. }
  94733. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  94734. {
  94735. FLAC__ASSERT(0 != decoder);
  94736. FLAC__ASSERT(0 != decoder->private_);
  94737. FLAC__ASSERT(0 != decoder->protected_);
  94738. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94739. return false;
  94740. #if FLAC__HAS_OGG
  94741. /* can't check decoder->private_->is_ogg since that's not set until init time */
  94742. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  94743. return true;
  94744. #else
  94745. (void)value;
  94746. return false;
  94747. #endif
  94748. }
  94749. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  94750. {
  94751. FLAC__ASSERT(0 != decoder);
  94752. FLAC__ASSERT(0 != decoder->protected_);
  94753. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94754. return false;
  94755. decoder->protected_->md5_checking = value;
  94756. return true;
  94757. }
  94758. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  94759. {
  94760. FLAC__ASSERT(0 != decoder);
  94761. FLAC__ASSERT(0 != decoder->private_);
  94762. FLAC__ASSERT(0 != decoder->protected_);
  94763. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  94764. /* double protection */
  94765. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  94766. return false;
  94767. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94768. return false;
  94769. decoder->private_->metadata_filter[type] = true;
  94770. if(type == FLAC__METADATA_TYPE_APPLICATION)
  94771. decoder->private_->metadata_filter_ids_count = 0;
  94772. return true;
  94773. }
  94774. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  94775. {
  94776. FLAC__ASSERT(0 != decoder);
  94777. FLAC__ASSERT(0 != decoder->private_);
  94778. FLAC__ASSERT(0 != decoder->protected_);
  94779. FLAC__ASSERT(0 != id);
  94780. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94781. return false;
  94782. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  94783. return true;
  94784. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  94785. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  94786. 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))) {
  94787. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94788. return false;
  94789. }
  94790. decoder->private_->metadata_filter_ids_capacity *= 2;
  94791. }
  94792. 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));
  94793. decoder->private_->metadata_filter_ids_count++;
  94794. return true;
  94795. }
  94796. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  94797. {
  94798. unsigned i;
  94799. FLAC__ASSERT(0 != decoder);
  94800. FLAC__ASSERT(0 != decoder->private_);
  94801. FLAC__ASSERT(0 != decoder->protected_);
  94802. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94803. return false;
  94804. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  94805. decoder->private_->metadata_filter[i] = true;
  94806. decoder->private_->metadata_filter_ids_count = 0;
  94807. return true;
  94808. }
  94809. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  94810. {
  94811. FLAC__ASSERT(0 != decoder);
  94812. FLAC__ASSERT(0 != decoder->private_);
  94813. FLAC__ASSERT(0 != decoder->protected_);
  94814. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  94815. /* double protection */
  94816. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  94817. return false;
  94818. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94819. return false;
  94820. decoder->private_->metadata_filter[type] = false;
  94821. if(type == FLAC__METADATA_TYPE_APPLICATION)
  94822. decoder->private_->metadata_filter_ids_count = 0;
  94823. return true;
  94824. }
  94825. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  94826. {
  94827. FLAC__ASSERT(0 != decoder);
  94828. FLAC__ASSERT(0 != decoder->private_);
  94829. FLAC__ASSERT(0 != decoder->protected_);
  94830. FLAC__ASSERT(0 != id);
  94831. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94832. return false;
  94833. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  94834. return true;
  94835. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  94836. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  94837. 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))) {
  94838. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94839. return false;
  94840. }
  94841. decoder->private_->metadata_filter_ids_capacity *= 2;
  94842. }
  94843. 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));
  94844. decoder->private_->metadata_filter_ids_count++;
  94845. return true;
  94846. }
  94847. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  94848. {
  94849. FLAC__ASSERT(0 != decoder);
  94850. FLAC__ASSERT(0 != decoder->private_);
  94851. FLAC__ASSERT(0 != decoder->protected_);
  94852. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94853. return false;
  94854. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  94855. decoder->private_->metadata_filter_ids_count = 0;
  94856. return true;
  94857. }
  94858. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  94859. {
  94860. FLAC__ASSERT(0 != decoder);
  94861. FLAC__ASSERT(0 != decoder->protected_);
  94862. return decoder->protected_->state;
  94863. }
  94864. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  94865. {
  94866. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  94867. }
  94868. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  94869. {
  94870. FLAC__ASSERT(0 != decoder);
  94871. FLAC__ASSERT(0 != decoder->protected_);
  94872. return decoder->protected_->md5_checking;
  94873. }
  94874. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  94875. {
  94876. FLAC__ASSERT(0 != decoder);
  94877. FLAC__ASSERT(0 != decoder->protected_);
  94878. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  94879. }
  94880. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  94881. {
  94882. FLAC__ASSERT(0 != decoder);
  94883. FLAC__ASSERT(0 != decoder->protected_);
  94884. return decoder->protected_->channels;
  94885. }
  94886. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  94887. {
  94888. FLAC__ASSERT(0 != decoder);
  94889. FLAC__ASSERT(0 != decoder->protected_);
  94890. return decoder->protected_->channel_assignment;
  94891. }
  94892. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  94893. {
  94894. FLAC__ASSERT(0 != decoder);
  94895. FLAC__ASSERT(0 != decoder->protected_);
  94896. return decoder->protected_->bits_per_sample;
  94897. }
  94898. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  94899. {
  94900. FLAC__ASSERT(0 != decoder);
  94901. FLAC__ASSERT(0 != decoder->protected_);
  94902. return decoder->protected_->sample_rate;
  94903. }
  94904. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  94905. {
  94906. FLAC__ASSERT(0 != decoder);
  94907. FLAC__ASSERT(0 != decoder->protected_);
  94908. return decoder->protected_->blocksize;
  94909. }
  94910. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  94911. {
  94912. FLAC__ASSERT(0 != decoder);
  94913. FLAC__ASSERT(0 != decoder->private_);
  94914. FLAC__ASSERT(0 != position);
  94915. #if FLAC__HAS_OGG
  94916. if(decoder->private_->is_ogg)
  94917. return false;
  94918. #endif
  94919. if(0 == decoder->private_->tell_callback)
  94920. return false;
  94921. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  94922. return false;
  94923. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  94924. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  94925. return false;
  94926. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  94927. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  94928. return true;
  94929. }
  94930. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  94931. {
  94932. FLAC__ASSERT(0 != decoder);
  94933. FLAC__ASSERT(0 != decoder->private_);
  94934. FLAC__ASSERT(0 != decoder->protected_);
  94935. decoder->private_->samples_decoded = 0;
  94936. decoder->private_->do_md5_checking = false;
  94937. #if FLAC__HAS_OGG
  94938. if(decoder->private_->is_ogg)
  94939. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  94940. #endif
  94941. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  94942. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94943. return false;
  94944. }
  94945. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94946. return true;
  94947. }
  94948. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  94949. {
  94950. FLAC__ASSERT(0 != decoder);
  94951. FLAC__ASSERT(0 != decoder->private_);
  94952. FLAC__ASSERT(0 != decoder->protected_);
  94953. if(!FLAC__stream_decoder_flush(decoder)) {
  94954. /* above call sets the state for us */
  94955. return false;
  94956. }
  94957. #if FLAC__HAS_OGG
  94958. /*@@@ could go in !internal_reset_hack block below */
  94959. if(decoder->private_->is_ogg)
  94960. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  94961. #endif
  94962. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  94963. * (internal_reset_hack) don't try to rewind since we are already at
  94964. * the beginning of the stream and don't want to fail if the input is
  94965. * not seekable.
  94966. */
  94967. if(!decoder->private_->internal_reset_hack) {
  94968. if(decoder->private_->file == stdin)
  94969. return false; /* can't rewind stdin, reset fails */
  94970. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  94971. return false; /* seekable and seek fails, reset fails */
  94972. }
  94973. else
  94974. decoder->private_->internal_reset_hack = false;
  94975. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  94976. decoder->private_->has_stream_info = false;
  94977. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  94978. free(decoder->private_->seek_table.data.seek_table.points);
  94979. decoder->private_->seek_table.data.seek_table.points = 0;
  94980. decoder->private_->has_seek_table = false;
  94981. }
  94982. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  94983. /*
  94984. * This goes in reset() and not flush() because according to the spec, a
  94985. * fixed-blocksize stream must stay that way through the whole stream.
  94986. */
  94987. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  94988. /* We initialize the FLAC__MD5Context even though we may never use it. This
  94989. * is because md5 checking may be turned on to start and then turned off if
  94990. * a seek occurs. So we init the context here and finalize it in
  94991. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  94992. * properly.
  94993. */
  94994. FLAC__MD5Init(&decoder->private_->md5context);
  94995. decoder->private_->first_frame_offset = 0;
  94996. decoder->private_->unparseable_frame_count = 0;
  94997. return true;
  94998. }
  94999. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  95000. {
  95001. FLAC__bool got_a_frame;
  95002. FLAC__ASSERT(0 != decoder);
  95003. FLAC__ASSERT(0 != decoder->protected_);
  95004. while(1) {
  95005. switch(decoder->protected_->state) {
  95006. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95007. if(!find_metadata_(decoder))
  95008. return false; /* above function sets the status for us */
  95009. break;
  95010. case FLAC__STREAM_DECODER_READ_METADATA:
  95011. if(!read_metadata_(decoder))
  95012. return false; /* above function sets the status for us */
  95013. else
  95014. return true;
  95015. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95016. if(!frame_sync_(decoder))
  95017. return true; /* above function sets the status for us */
  95018. break;
  95019. case FLAC__STREAM_DECODER_READ_FRAME:
  95020. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  95021. return false; /* above function sets the status for us */
  95022. if(got_a_frame)
  95023. return true; /* above function sets the status for us */
  95024. break;
  95025. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95026. case FLAC__STREAM_DECODER_ABORTED:
  95027. return true;
  95028. default:
  95029. FLAC__ASSERT(0);
  95030. return false;
  95031. }
  95032. }
  95033. }
  95034. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  95035. {
  95036. FLAC__ASSERT(0 != decoder);
  95037. FLAC__ASSERT(0 != decoder->protected_);
  95038. while(1) {
  95039. switch(decoder->protected_->state) {
  95040. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95041. if(!find_metadata_(decoder))
  95042. return false; /* above function sets the status for us */
  95043. break;
  95044. case FLAC__STREAM_DECODER_READ_METADATA:
  95045. if(!read_metadata_(decoder))
  95046. return false; /* above function sets the status for us */
  95047. break;
  95048. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95049. case FLAC__STREAM_DECODER_READ_FRAME:
  95050. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95051. case FLAC__STREAM_DECODER_ABORTED:
  95052. return true;
  95053. default:
  95054. FLAC__ASSERT(0);
  95055. return false;
  95056. }
  95057. }
  95058. }
  95059. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  95060. {
  95061. FLAC__bool dummy;
  95062. FLAC__ASSERT(0 != decoder);
  95063. FLAC__ASSERT(0 != decoder->protected_);
  95064. while(1) {
  95065. switch(decoder->protected_->state) {
  95066. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95067. if(!find_metadata_(decoder))
  95068. return false; /* above function sets the status for us */
  95069. break;
  95070. case FLAC__STREAM_DECODER_READ_METADATA:
  95071. if(!read_metadata_(decoder))
  95072. return false; /* above function sets the status for us */
  95073. break;
  95074. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95075. if(!frame_sync_(decoder))
  95076. return true; /* above function sets the status for us */
  95077. break;
  95078. case FLAC__STREAM_DECODER_READ_FRAME:
  95079. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  95080. return false; /* above function sets the status for us */
  95081. break;
  95082. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95083. case FLAC__STREAM_DECODER_ABORTED:
  95084. return true;
  95085. default:
  95086. FLAC__ASSERT(0);
  95087. return false;
  95088. }
  95089. }
  95090. }
  95091. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  95092. {
  95093. FLAC__bool got_a_frame;
  95094. FLAC__ASSERT(0 != decoder);
  95095. FLAC__ASSERT(0 != decoder->protected_);
  95096. while(1) {
  95097. switch(decoder->protected_->state) {
  95098. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95099. case FLAC__STREAM_DECODER_READ_METADATA:
  95100. return false; /* above function sets the status for us */
  95101. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95102. if(!frame_sync_(decoder))
  95103. return true; /* above function sets the status for us */
  95104. break;
  95105. case FLAC__STREAM_DECODER_READ_FRAME:
  95106. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  95107. return false; /* above function sets the status for us */
  95108. if(got_a_frame)
  95109. return true; /* above function sets the status for us */
  95110. break;
  95111. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95112. case FLAC__STREAM_DECODER_ABORTED:
  95113. return true;
  95114. default:
  95115. FLAC__ASSERT(0);
  95116. return false;
  95117. }
  95118. }
  95119. }
  95120. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  95121. {
  95122. FLAC__uint64 length;
  95123. FLAC__ASSERT(0 != decoder);
  95124. if(
  95125. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  95126. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  95127. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  95128. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  95129. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  95130. )
  95131. return false;
  95132. if(0 == decoder->private_->seek_callback)
  95133. return false;
  95134. FLAC__ASSERT(decoder->private_->seek_callback);
  95135. FLAC__ASSERT(decoder->private_->tell_callback);
  95136. FLAC__ASSERT(decoder->private_->length_callback);
  95137. FLAC__ASSERT(decoder->private_->eof_callback);
  95138. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  95139. return false;
  95140. decoder->private_->is_seeking = true;
  95141. /* turn off md5 checking if a seek is attempted */
  95142. decoder->private_->do_md5_checking = false;
  95143. /* 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) */
  95144. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  95145. decoder->private_->is_seeking = false;
  95146. return false;
  95147. }
  95148. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  95149. if(
  95150. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  95151. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  95152. ) {
  95153. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  95154. /* above call sets the state for us */
  95155. decoder->private_->is_seeking = false;
  95156. return false;
  95157. }
  95158. /* check this again in case we didn't know total_samples the first time */
  95159. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  95160. decoder->private_->is_seeking = false;
  95161. return false;
  95162. }
  95163. }
  95164. {
  95165. const FLAC__bool ok =
  95166. #if FLAC__HAS_OGG
  95167. decoder->private_->is_ogg?
  95168. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  95169. #endif
  95170. seek_to_absolute_sample_(decoder, length, sample)
  95171. ;
  95172. decoder->private_->is_seeking = false;
  95173. return ok;
  95174. }
  95175. }
  95176. /***********************************************************************
  95177. *
  95178. * Protected class methods
  95179. *
  95180. ***********************************************************************/
  95181. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  95182. {
  95183. FLAC__ASSERT(0 != decoder);
  95184. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95185. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  95186. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  95187. }
  95188. /***********************************************************************
  95189. *
  95190. * Private class methods
  95191. *
  95192. ***********************************************************************/
  95193. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  95194. {
  95195. #if FLAC__HAS_OGG
  95196. decoder->private_->is_ogg = false;
  95197. #endif
  95198. decoder->private_->read_callback = 0;
  95199. decoder->private_->seek_callback = 0;
  95200. decoder->private_->tell_callback = 0;
  95201. decoder->private_->length_callback = 0;
  95202. decoder->private_->eof_callback = 0;
  95203. decoder->private_->write_callback = 0;
  95204. decoder->private_->metadata_callback = 0;
  95205. decoder->private_->error_callback = 0;
  95206. decoder->private_->client_data = 0;
  95207. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95208. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  95209. decoder->private_->metadata_filter_ids_count = 0;
  95210. decoder->protected_->md5_checking = false;
  95211. #if FLAC__HAS_OGG
  95212. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  95213. #endif
  95214. }
  95215. /*
  95216. * This will forcibly set stdin to binary mode (for OSes that require it)
  95217. */
  95218. FILE *get_binary_stdin_(void)
  95219. {
  95220. /* if something breaks here it is probably due to the presence or
  95221. * absence of an underscore before the identifiers 'setmode',
  95222. * 'fileno', and/or 'O_BINARY'; check your system header files.
  95223. */
  95224. #if defined _MSC_VER || defined __MINGW32__
  95225. _setmode(_fileno(stdin), _O_BINARY);
  95226. #elif defined __CYGWIN__
  95227. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  95228. setmode(_fileno(stdin), _O_BINARY);
  95229. #elif defined __EMX__
  95230. setmode(fileno(stdin), O_BINARY);
  95231. #endif
  95232. return stdin;
  95233. }
  95234. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  95235. {
  95236. unsigned i;
  95237. FLAC__int32 *tmp;
  95238. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  95239. return true;
  95240. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  95241. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95242. if(0 != decoder->private_->output[i]) {
  95243. free(decoder->private_->output[i]-4);
  95244. decoder->private_->output[i] = 0;
  95245. }
  95246. if(0 != decoder->private_->residual_unaligned[i]) {
  95247. free(decoder->private_->residual_unaligned[i]);
  95248. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95249. }
  95250. }
  95251. for(i = 0; i < channels; i++) {
  95252. /* WATCHOUT:
  95253. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95254. * output arrays have a buffer of up to 3 zeroes in front
  95255. * (at negative indices) for alignment purposes; we use 4
  95256. * to keep the data well-aligned.
  95257. */
  95258. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  95259. if(tmp == 0) {
  95260. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95261. return false;
  95262. }
  95263. memset(tmp, 0, sizeof(FLAC__int32)*4);
  95264. decoder->private_->output[i] = tmp + 4;
  95265. /* WATCHOUT:
  95266. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  95267. */
  95268. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  95269. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95270. return false;
  95271. }
  95272. }
  95273. decoder->private_->output_capacity = size;
  95274. decoder->private_->output_channels = channels;
  95275. return true;
  95276. }
  95277. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  95278. {
  95279. size_t i;
  95280. FLAC__ASSERT(0 != decoder);
  95281. FLAC__ASSERT(0 != decoder->private_);
  95282. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  95283. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  95284. return true;
  95285. return false;
  95286. }
  95287. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  95288. {
  95289. FLAC__uint32 x;
  95290. unsigned i, id_;
  95291. FLAC__bool first = true;
  95292. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95293. for(i = id_ = 0; i < 4; ) {
  95294. if(decoder->private_->cached) {
  95295. x = (FLAC__uint32)decoder->private_->lookahead;
  95296. decoder->private_->cached = false;
  95297. }
  95298. else {
  95299. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95300. return false; /* read_callback_ sets the state for us */
  95301. }
  95302. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  95303. first = true;
  95304. i++;
  95305. id_ = 0;
  95306. continue;
  95307. }
  95308. if(x == ID3V2_TAG_[id_]) {
  95309. id_++;
  95310. i = 0;
  95311. if(id_ == 3) {
  95312. if(!skip_id3v2_tag_(decoder))
  95313. return false; /* skip_id3v2_tag_ sets the state for us */
  95314. }
  95315. continue;
  95316. }
  95317. id_ = 0;
  95318. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95319. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  95320. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95321. return false; /* read_callback_ sets the state for us */
  95322. /* 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 */
  95323. /* else we have to check if the second byte is the end of a sync code */
  95324. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95325. decoder->private_->lookahead = (FLAC__byte)x;
  95326. decoder->private_->cached = true;
  95327. }
  95328. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  95329. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  95330. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  95331. return true;
  95332. }
  95333. }
  95334. i = 0;
  95335. if(first) {
  95336. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95337. first = false;
  95338. }
  95339. }
  95340. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  95341. return true;
  95342. }
  95343. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  95344. {
  95345. FLAC__bool is_last;
  95346. FLAC__uint32 i, x, type, length;
  95347. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95348. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  95349. return false; /* read_callback_ sets the state for us */
  95350. is_last = x? true : false;
  95351. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  95352. return false; /* read_callback_ sets the state for us */
  95353. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  95354. return false; /* read_callback_ sets the state for us */
  95355. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  95356. if(!read_metadata_streaminfo_(decoder, is_last, length))
  95357. return false;
  95358. decoder->private_->has_stream_info = true;
  95359. 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))
  95360. decoder->private_->do_md5_checking = false;
  95361. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  95362. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  95363. }
  95364. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  95365. if(!read_metadata_seektable_(decoder, is_last, length))
  95366. return false;
  95367. decoder->private_->has_seek_table = true;
  95368. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  95369. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  95370. }
  95371. else {
  95372. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  95373. unsigned real_length = length;
  95374. FLAC__StreamMetadata block;
  95375. block.is_last = is_last;
  95376. block.type = (FLAC__MetadataType)type;
  95377. block.length = length;
  95378. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  95379. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  95380. return false; /* read_callback_ sets the state for us */
  95381. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  95382. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  95383. return false;
  95384. }
  95385. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  95386. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  95387. skip_it = !skip_it;
  95388. }
  95389. if(skip_it) {
  95390. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  95391. return false; /* read_callback_ sets the state for us */
  95392. }
  95393. else {
  95394. switch(type) {
  95395. case FLAC__METADATA_TYPE_PADDING:
  95396. /* skip the padding bytes */
  95397. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  95398. return false; /* read_callback_ sets the state for us */
  95399. break;
  95400. case FLAC__METADATA_TYPE_APPLICATION:
  95401. /* remember, we read the ID already */
  95402. if(real_length > 0) {
  95403. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  95404. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95405. return false;
  95406. }
  95407. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  95408. return false; /* read_callback_ sets the state for us */
  95409. }
  95410. else
  95411. block.data.application.data = 0;
  95412. break;
  95413. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  95414. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  95415. return false;
  95416. break;
  95417. case FLAC__METADATA_TYPE_CUESHEET:
  95418. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  95419. return false;
  95420. break;
  95421. case FLAC__METADATA_TYPE_PICTURE:
  95422. if(!read_metadata_picture_(decoder, &block.data.picture))
  95423. return false;
  95424. break;
  95425. case FLAC__METADATA_TYPE_STREAMINFO:
  95426. case FLAC__METADATA_TYPE_SEEKTABLE:
  95427. FLAC__ASSERT(0);
  95428. break;
  95429. default:
  95430. if(real_length > 0) {
  95431. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  95432. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95433. return false;
  95434. }
  95435. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  95436. return false; /* read_callback_ sets the state for us */
  95437. }
  95438. else
  95439. block.data.unknown.data = 0;
  95440. break;
  95441. }
  95442. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  95443. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  95444. /* now we have to free any malloc()ed data in the block */
  95445. switch(type) {
  95446. case FLAC__METADATA_TYPE_PADDING:
  95447. break;
  95448. case FLAC__METADATA_TYPE_APPLICATION:
  95449. if(0 != block.data.application.data)
  95450. free(block.data.application.data);
  95451. break;
  95452. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  95453. if(0 != block.data.vorbis_comment.vendor_string.entry)
  95454. free(block.data.vorbis_comment.vendor_string.entry);
  95455. if(block.data.vorbis_comment.num_comments > 0)
  95456. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  95457. if(0 != block.data.vorbis_comment.comments[i].entry)
  95458. free(block.data.vorbis_comment.comments[i].entry);
  95459. if(0 != block.data.vorbis_comment.comments)
  95460. free(block.data.vorbis_comment.comments);
  95461. break;
  95462. case FLAC__METADATA_TYPE_CUESHEET:
  95463. if(block.data.cue_sheet.num_tracks > 0)
  95464. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  95465. if(0 != block.data.cue_sheet.tracks[i].indices)
  95466. free(block.data.cue_sheet.tracks[i].indices);
  95467. if(0 != block.data.cue_sheet.tracks)
  95468. free(block.data.cue_sheet.tracks);
  95469. break;
  95470. case FLAC__METADATA_TYPE_PICTURE:
  95471. if(0 != block.data.picture.mime_type)
  95472. free(block.data.picture.mime_type);
  95473. if(0 != block.data.picture.description)
  95474. free(block.data.picture.description);
  95475. if(0 != block.data.picture.data)
  95476. free(block.data.picture.data);
  95477. break;
  95478. case FLAC__METADATA_TYPE_STREAMINFO:
  95479. case FLAC__METADATA_TYPE_SEEKTABLE:
  95480. FLAC__ASSERT(0);
  95481. default:
  95482. if(0 != block.data.unknown.data)
  95483. free(block.data.unknown.data);
  95484. break;
  95485. }
  95486. }
  95487. }
  95488. if(is_last) {
  95489. /* if this fails, it's OK, it's just a hint for the seek routine */
  95490. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  95491. decoder->private_->first_frame_offset = 0;
  95492. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95493. }
  95494. return true;
  95495. }
  95496. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  95497. {
  95498. FLAC__uint32 x;
  95499. unsigned bits, used_bits = 0;
  95500. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95501. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  95502. decoder->private_->stream_info.is_last = is_last;
  95503. decoder->private_->stream_info.length = length;
  95504. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  95505. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  95506. return false; /* read_callback_ sets the state for us */
  95507. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  95508. used_bits += bits;
  95509. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  95510. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  95511. return false; /* read_callback_ sets the state for us */
  95512. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  95513. used_bits += bits;
  95514. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  95515. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  95516. return false; /* read_callback_ sets the state for us */
  95517. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  95518. used_bits += bits;
  95519. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  95520. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  95521. return false; /* read_callback_ sets the state for us */
  95522. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  95523. used_bits += bits;
  95524. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  95525. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  95526. return false; /* read_callback_ sets the state for us */
  95527. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  95528. used_bits += bits;
  95529. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  95530. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  95531. return false; /* read_callback_ sets the state for us */
  95532. decoder->private_->stream_info.data.stream_info.channels = x+1;
  95533. used_bits += bits;
  95534. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  95535. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  95536. return false; /* read_callback_ sets the state for us */
  95537. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  95538. used_bits += bits;
  95539. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  95540. 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))
  95541. return false; /* read_callback_ sets the state for us */
  95542. used_bits += bits;
  95543. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  95544. return false; /* read_callback_ sets the state for us */
  95545. used_bits += 16*8;
  95546. /* skip the rest of the block */
  95547. FLAC__ASSERT(used_bits % 8 == 0);
  95548. length -= (used_bits / 8);
  95549. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  95550. return false; /* read_callback_ sets the state for us */
  95551. return true;
  95552. }
  95553. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  95554. {
  95555. FLAC__uint32 i, x;
  95556. FLAC__uint64 xx;
  95557. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95558. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  95559. decoder->private_->seek_table.is_last = is_last;
  95560. decoder->private_->seek_table.length = length;
  95561. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  95562. /* use realloc since we may pass through here several times (e.g. after seeking) */
  95563. 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)))) {
  95564. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95565. return false;
  95566. }
  95567. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  95568. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  95569. return false; /* read_callback_ sets the state for us */
  95570. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  95571. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  95572. return false; /* read_callback_ sets the state for us */
  95573. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  95574. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  95575. return false; /* read_callback_ sets the state for us */
  95576. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  95577. }
  95578. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  95579. /* if there is a partial point left, skip over it */
  95580. if(length > 0) {
  95581. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  95582. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  95583. return false; /* read_callback_ sets the state for us */
  95584. }
  95585. return true;
  95586. }
  95587. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  95588. {
  95589. FLAC__uint32 i;
  95590. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95591. /* read vendor string */
  95592. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  95593. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  95594. return false; /* read_callback_ sets the state for us */
  95595. if(obj->vendor_string.length > 0) {
  95596. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  95597. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95598. return false;
  95599. }
  95600. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  95601. return false; /* read_callback_ sets the state for us */
  95602. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  95603. }
  95604. else
  95605. obj->vendor_string.entry = 0;
  95606. /* read num comments */
  95607. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  95608. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  95609. return false; /* read_callback_ sets the state for us */
  95610. /* read comments */
  95611. if(obj->num_comments > 0) {
  95612. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  95613. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95614. return false;
  95615. }
  95616. for(i = 0; i < obj->num_comments; i++) {
  95617. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  95618. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  95619. return false; /* read_callback_ sets the state for us */
  95620. if(obj->comments[i].length > 0) {
  95621. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  95622. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95623. return false;
  95624. }
  95625. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  95626. return false; /* read_callback_ sets the state for us */
  95627. obj->comments[i].entry[obj->comments[i].length] = '\0';
  95628. }
  95629. else
  95630. obj->comments[i].entry = 0;
  95631. }
  95632. }
  95633. else {
  95634. obj->comments = 0;
  95635. }
  95636. return true;
  95637. }
  95638. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  95639. {
  95640. FLAC__uint32 i, j, x;
  95641. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95642. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  95643. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  95644. 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))
  95645. return false; /* read_callback_ sets the state for us */
  95646. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  95647. return false; /* read_callback_ sets the state for us */
  95648. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  95649. return false; /* read_callback_ sets the state for us */
  95650. obj->is_cd = x? true : false;
  95651. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  95652. return false; /* read_callback_ sets the state for us */
  95653. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  95654. return false; /* read_callback_ sets the state for us */
  95655. obj->num_tracks = x;
  95656. if(obj->num_tracks > 0) {
  95657. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  95658. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95659. return false;
  95660. }
  95661. for(i = 0; i < obj->num_tracks; i++) {
  95662. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  95663. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  95664. return false; /* read_callback_ sets the state for us */
  95665. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  95666. return false; /* read_callback_ sets the state for us */
  95667. track->number = (FLAC__byte)x;
  95668. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  95669. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  95670. return false; /* read_callback_ sets the state for us */
  95671. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  95672. return false; /* read_callback_ sets the state for us */
  95673. track->type = x;
  95674. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  95675. return false; /* read_callback_ sets the state for us */
  95676. track->pre_emphasis = x;
  95677. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  95678. return false; /* read_callback_ sets the state for us */
  95679. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  95680. return false; /* read_callback_ sets the state for us */
  95681. track->num_indices = (FLAC__byte)x;
  95682. if(track->num_indices > 0) {
  95683. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  95684. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95685. return false;
  95686. }
  95687. for(j = 0; j < track->num_indices; j++) {
  95688. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  95689. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  95690. return false; /* read_callback_ sets the state for us */
  95691. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  95692. return false; /* read_callback_ sets the state for us */
  95693. index->number = (FLAC__byte)x;
  95694. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  95695. return false; /* read_callback_ sets the state for us */
  95696. }
  95697. }
  95698. }
  95699. }
  95700. return true;
  95701. }
  95702. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  95703. {
  95704. FLAC__uint32 x;
  95705. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95706. /* read type */
  95707. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  95708. return false; /* read_callback_ sets the state for us */
  95709. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  95710. /* read MIME type */
  95711. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  95712. return false; /* read_callback_ sets the state for us */
  95713. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  95714. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95715. return false;
  95716. }
  95717. if(x > 0) {
  95718. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  95719. return false; /* read_callback_ sets the state for us */
  95720. }
  95721. obj->mime_type[x] = '\0';
  95722. /* read description */
  95723. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  95724. return false; /* read_callback_ sets the state for us */
  95725. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  95726. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95727. return false;
  95728. }
  95729. if(x > 0) {
  95730. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  95731. return false; /* read_callback_ sets the state for us */
  95732. }
  95733. obj->description[x] = '\0';
  95734. /* read width */
  95735. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  95736. return false; /* read_callback_ sets the state for us */
  95737. /* read height */
  95738. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  95739. return false; /* read_callback_ sets the state for us */
  95740. /* read depth */
  95741. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  95742. return false; /* read_callback_ sets the state for us */
  95743. /* read colors */
  95744. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  95745. return false; /* read_callback_ sets the state for us */
  95746. /* read data */
  95747. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  95748. return false; /* read_callback_ sets the state for us */
  95749. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  95750. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95751. return false;
  95752. }
  95753. if(obj->data_length > 0) {
  95754. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  95755. return false; /* read_callback_ sets the state for us */
  95756. }
  95757. return true;
  95758. }
  95759. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  95760. {
  95761. FLAC__uint32 x;
  95762. unsigned i, skip;
  95763. /* skip the version and flags bytes */
  95764. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  95765. return false; /* read_callback_ sets the state for us */
  95766. /* get the size (in bytes) to skip */
  95767. skip = 0;
  95768. for(i = 0; i < 4; i++) {
  95769. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95770. return false; /* read_callback_ sets the state for us */
  95771. skip <<= 7;
  95772. skip |= (x & 0x7f);
  95773. }
  95774. /* skip the rest of the tag */
  95775. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  95776. return false; /* read_callback_ sets the state for us */
  95777. return true;
  95778. }
  95779. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  95780. {
  95781. FLAC__uint32 x;
  95782. FLAC__bool first = true;
  95783. /* If we know the total number of samples in the stream, stop if we've read that many. */
  95784. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  95785. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  95786. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  95787. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  95788. return true;
  95789. }
  95790. }
  95791. /* make sure we're byte aligned */
  95792. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  95793. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  95794. return false; /* read_callback_ sets the state for us */
  95795. }
  95796. while(1) {
  95797. if(decoder->private_->cached) {
  95798. x = (FLAC__uint32)decoder->private_->lookahead;
  95799. decoder->private_->cached = false;
  95800. }
  95801. else {
  95802. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95803. return false; /* read_callback_ sets the state for us */
  95804. }
  95805. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95806. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  95807. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95808. return false; /* read_callback_ sets the state for us */
  95809. /* 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 */
  95810. /* else we have to check if the second byte is the end of a sync code */
  95811. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95812. decoder->private_->lookahead = (FLAC__byte)x;
  95813. decoder->private_->cached = true;
  95814. }
  95815. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  95816. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  95817. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  95818. return true;
  95819. }
  95820. }
  95821. if(first) {
  95822. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95823. first = false;
  95824. }
  95825. }
  95826. return true;
  95827. }
  95828. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  95829. {
  95830. unsigned channel;
  95831. unsigned i;
  95832. FLAC__int32 mid, side;
  95833. unsigned frame_crc; /* the one we calculate from the input stream */
  95834. FLAC__uint32 x;
  95835. *got_a_frame = false;
  95836. /* init the CRC */
  95837. frame_crc = 0;
  95838. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  95839. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  95840. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  95841. if(!read_frame_header_(decoder))
  95842. return false;
  95843. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  95844. return true;
  95845. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  95846. return false;
  95847. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  95848. /*
  95849. * first figure the correct bits-per-sample of the subframe
  95850. */
  95851. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  95852. switch(decoder->private_->frame.header.channel_assignment) {
  95853. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  95854. /* no adjustment needed */
  95855. break;
  95856. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  95857. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95858. if(channel == 1)
  95859. bps++;
  95860. break;
  95861. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  95862. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95863. if(channel == 0)
  95864. bps++;
  95865. break;
  95866. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  95867. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95868. if(channel == 1)
  95869. bps++;
  95870. break;
  95871. default:
  95872. FLAC__ASSERT(0);
  95873. }
  95874. /*
  95875. * now read it
  95876. */
  95877. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  95878. return false;
  95879. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  95880. return true;
  95881. }
  95882. if(!read_zero_padding_(decoder))
  95883. return false;
  95884. 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) */
  95885. return true;
  95886. /*
  95887. * Read the frame CRC-16 from the footer and check
  95888. */
  95889. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  95890. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  95891. return false; /* read_callback_ sets the state for us */
  95892. if(frame_crc == x) {
  95893. if(do_full_decode) {
  95894. /* Undo any special channel coding */
  95895. switch(decoder->private_->frame.header.channel_assignment) {
  95896. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  95897. /* do nothing */
  95898. break;
  95899. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  95900. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95901. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95902. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  95903. break;
  95904. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  95905. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95906. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95907. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  95908. break;
  95909. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  95910. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95911. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  95912. #if 1
  95913. mid = decoder->private_->output[0][i];
  95914. side = decoder->private_->output[1][i];
  95915. mid <<= 1;
  95916. mid |= (side & 1); /* i.e. if 'side' is odd... */
  95917. decoder->private_->output[0][i] = (mid + side) >> 1;
  95918. decoder->private_->output[1][i] = (mid - side) >> 1;
  95919. #else
  95920. /* OPT: without 'side' temp variable */
  95921. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  95922. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  95923. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  95924. #endif
  95925. }
  95926. break;
  95927. default:
  95928. FLAC__ASSERT(0);
  95929. break;
  95930. }
  95931. }
  95932. }
  95933. else {
  95934. /* Bad frame, emit error and zero the output signal */
  95935. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  95936. if(do_full_decode) {
  95937. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  95938. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  95939. }
  95940. }
  95941. }
  95942. *got_a_frame = true;
  95943. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  95944. if(decoder->private_->next_fixed_block_size)
  95945. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  95946. /* put the latest values into the public section of the decoder instance */
  95947. decoder->protected_->channels = decoder->private_->frame.header.channels;
  95948. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  95949. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  95950. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  95951. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  95952. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95953. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  95954. /* write it */
  95955. if(do_full_decode) {
  95956. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  95957. return false;
  95958. }
  95959. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95960. return true;
  95961. }
  95962. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  95963. {
  95964. FLAC__uint32 x;
  95965. FLAC__uint64 xx;
  95966. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  95967. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  95968. unsigned raw_header_len;
  95969. FLAC__bool is_unparseable = false;
  95970. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95971. /* init the raw header with the saved bits from synchronization */
  95972. raw_header[0] = decoder->private_->header_warmup[0];
  95973. raw_header[1] = decoder->private_->header_warmup[1];
  95974. raw_header_len = 2;
  95975. /* check to make sure that reserved bit is 0 */
  95976. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  95977. is_unparseable = true;
  95978. /*
  95979. * Note that along the way as we read the header, we look for a sync
  95980. * code inside. If we find one it would indicate that our original
  95981. * sync was bad since there cannot be a sync code in a valid header.
  95982. *
  95983. * Three kinds of things can go wrong when reading the frame header:
  95984. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  95985. * If we don't find a sync code, it can end up looking like we read
  95986. * a valid but unparseable header, until getting to the frame header
  95987. * CRC. Even then we could get a false positive on the CRC.
  95988. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  95989. * future encoder).
  95990. * 3) We may be on a damaged frame which appears valid but unparseable.
  95991. *
  95992. * For all these reasons, we try and read a complete frame header as
  95993. * long as it seems valid, even if unparseable, up until the frame
  95994. * header CRC.
  95995. */
  95996. /*
  95997. * read in the raw header as bytes so we can CRC it, and parse it on the way
  95998. */
  95999. for(i = 0; i < 2; i++) {
  96000. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96001. return false; /* read_callback_ sets the state for us */
  96002. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96003. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  96004. decoder->private_->lookahead = (FLAC__byte)x;
  96005. decoder->private_->cached = true;
  96006. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96007. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96008. return true;
  96009. }
  96010. raw_header[raw_header_len++] = (FLAC__byte)x;
  96011. }
  96012. switch(x = raw_header[2] >> 4) {
  96013. case 0:
  96014. is_unparseable = true;
  96015. break;
  96016. case 1:
  96017. decoder->private_->frame.header.blocksize = 192;
  96018. break;
  96019. case 2:
  96020. case 3:
  96021. case 4:
  96022. case 5:
  96023. decoder->private_->frame.header.blocksize = 576 << (x-2);
  96024. break;
  96025. case 6:
  96026. case 7:
  96027. blocksize_hint = x;
  96028. break;
  96029. case 8:
  96030. case 9:
  96031. case 10:
  96032. case 11:
  96033. case 12:
  96034. case 13:
  96035. case 14:
  96036. case 15:
  96037. decoder->private_->frame.header.blocksize = 256 << (x-8);
  96038. break;
  96039. default:
  96040. FLAC__ASSERT(0);
  96041. break;
  96042. }
  96043. switch(x = raw_header[2] & 0x0f) {
  96044. case 0:
  96045. if(decoder->private_->has_stream_info)
  96046. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  96047. else
  96048. is_unparseable = true;
  96049. break;
  96050. case 1:
  96051. decoder->private_->frame.header.sample_rate = 88200;
  96052. break;
  96053. case 2:
  96054. decoder->private_->frame.header.sample_rate = 176400;
  96055. break;
  96056. case 3:
  96057. decoder->private_->frame.header.sample_rate = 192000;
  96058. break;
  96059. case 4:
  96060. decoder->private_->frame.header.sample_rate = 8000;
  96061. break;
  96062. case 5:
  96063. decoder->private_->frame.header.sample_rate = 16000;
  96064. break;
  96065. case 6:
  96066. decoder->private_->frame.header.sample_rate = 22050;
  96067. break;
  96068. case 7:
  96069. decoder->private_->frame.header.sample_rate = 24000;
  96070. break;
  96071. case 8:
  96072. decoder->private_->frame.header.sample_rate = 32000;
  96073. break;
  96074. case 9:
  96075. decoder->private_->frame.header.sample_rate = 44100;
  96076. break;
  96077. case 10:
  96078. decoder->private_->frame.header.sample_rate = 48000;
  96079. break;
  96080. case 11:
  96081. decoder->private_->frame.header.sample_rate = 96000;
  96082. break;
  96083. case 12:
  96084. case 13:
  96085. case 14:
  96086. sample_rate_hint = x;
  96087. break;
  96088. case 15:
  96089. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96090. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96091. return true;
  96092. default:
  96093. FLAC__ASSERT(0);
  96094. }
  96095. x = (unsigned)(raw_header[3] >> 4);
  96096. if(x & 8) {
  96097. decoder->private_->frame.header.channels = 2;
  96098. switch(x & 7) {
  96099. case 0:
  96100. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  96101. break;
  96102. case 1:
  96103. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  96104. break;
  96105. case 2:
  96106. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  96107. break;
  96108. default:
  96109. is_unparseable = true;
  96110. break;
  96111. }
  96112. }
  96113. else {
  96114. decoder->private_->frame.header.channels = (unsigned)x + 1;
  96115. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  96116. }
  96117. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  96118. case 0:
  96119. if(decoder->private_->has_stream_info)
  96120. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  96121. else
  96122. is_unparseable = true;
  96123. break;
  96124. case 1:
  96125. decoder->private_->frame.header.bits_per_sample = 8;
  96126. break;
  96127. case 2:
  96128. decoder->private_->frame.header.bits_per_sample = 12;
  96129. break;
  96130. case 4:
  96131. decoder->private_->frame.header.bits_per_sample = 16;
  96132. break;
  96133. case 5:
  96134. decoder->private_->frame.header.bits_per_sample = 20;
  96135. break;
  96136. case 6:
  96137. decoder->private_->frame.header.bits_per_sample = 24;
  96138. break;
  96139. case 3:
  96140. case 7:
  96141. is_unparseable = true;
  96142. break;
  96143. default:
  96144. FLAC__ASSERT(0);
  96145. break;
  96146. }
  96147. /* check to make sure that reserved bit is 0 */
  96148. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  96149. is_unparseable = true;
  96150. /* read the frame's starting sample number (or frame number as the case may be) */
  96151. if(
  96152. raw_header[1] & 0x01 ||
  96153. /*@@@ 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 */
  96154. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  96155. ) { /* variable blocksize */
  96156. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  96157. return false; /* read_callback_ sets the state for us */
  96158. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  96159. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96160. decoder->private_->cached = true;
  96161. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96162. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96163. return true;
  96164. }
  96165. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96166. decoder->private_->frame.header.number.sample_number = xx;
  96167. }
  96168. else { /* fixed blocksize */
  96169. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  96170. return false; /* read_callback_ sets the state for us */
  96171. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  96172. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96173. decoder->private_->cached = true;
  96174. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96175. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96176. return true;
  96177. }
  96178. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  96179. decoder->private_->frame.header.number.frame_number = x;
  96180. }
  96181. if(blocksize_hint) {
  96182. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96183. return false; /* read_callback_ sets the state for us */
  96184. raw_header[raw_header_len++] = (FLAC__byte)x;
  96185. if(blocksize_hint == 7) {
  96186. FLAC__uint32 _x;
  96187. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96188. return false; /* read_callback_ sets the state for us */
  96189. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96190. x = (x << 8) | _x;
  96191. }
  96192. decoder->private_->frame.header.blocksize = x+1;
  96193. }
  96194. if(sample_rate_hint) {
  96195. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96196. return false; /* read_callback_ sets the state for us */
  96197. raw_header[raw_header_len++] = (FLAC__byte)x;
  96198. if(sample_rate_hint != 12) {
  96199. FLAC__uint32 _x;
  96200. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96201. return false; /* read_callback_ sets the state for us */
  96202. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96203. x = (x << 8) | _x;
  96204. }
  96205. if(sample_rate_hint == 12)
  96206. decoder->private_->frame.header.sample_rate = x*1000;
  96207. else if(sample_rate_hint == 13)
  96208. decoder->private_->frame.header.sample_rate = x;
  96209. else
  96210. decoder->private_->frame.header.sample_rate = x*10;
  96211. }
  96212. /* read the CRC-8 byte */
  96213. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96214. return false; /* read_callback_ sets the state for us */
  96215. crc8 = (FLAC__byte)x;
  96216. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  96217. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96218. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96219. return true;
  96220. }
  96221. /* calculate the sample number from the frame number if needed */
  96222. decoder->private_->next_fixed_block_size = 0;
  96223. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  96224. x = decoder->private_->frame.header.number.frame_number;
  96225. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96226. if(decoder->private_->fixed_block_size)
  96227. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  96228. else if(decoder->private_->has_stream_info) {
  96229. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  96230. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  96231. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  96232. }
  96233. else
  96234. is_unparseable = true;
  96235. }
  96236. else if(x == 0) {
  96237. decoder->private_->frame.header.number.sample_number = 0;
  96238. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  96239. }
  96240. else {
  96241. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  96242. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  96243. }
  96244. }
  96245. if(is_unparseable) {
  96246. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96247. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96248. return true;
  96249. }
  96250. return true;
  96251. }
  96252. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96253. {
  96254. FLAC__uint32 x;
  96255. FLAC__bool wasted_bits;
  96256. unsigned i;
  96257. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  96258. return false; /* read_callback_ sets the state for us */
  96259. wasted_bits = (x & 1);
  96260. x &= 0xfe;
  96261. if(wasted_bits) {
  96262. unsigned u;
  96263. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  96264. return false; /* read_callback_ sets the state for us */
  96265. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  96266. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  96267. }
  96268. else
  96269. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  96270. /*
  96271. * Lots of magic numbers here
  96272. */
  96273. if(x & 0x80) {
  96274. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96275. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96276. return true;
  96277. }
  96278. else if(x == 0) {
  96279. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  96280. return false;
  96281. }
  96282. else if(x == 2) {
  96283. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  96284. return false;
  96285. }
  96286. else if(x < 16) {
  96287. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96288. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96289. return true;
  96290. }
  96291. else if(x <= 24) {
  96292. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  96293. return false;
  96294. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96295. return true;
  96296. }
  96297. else if(x < 64) {
  96298. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96299. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96300. return true;
  96301. }
  96302. else {
  96303. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  96304. return false;
  96305. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96306. return true;
  96307. }
  96308. if(wasted_bits && do_full_decode) {
  96309. x = decoder->private_->frame.subframes[channel].wasted_bits;
  96310. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96311. decoder->private_->output[channel][i] <<= x;
  96312. }
  96313. return true;
  96314. }
  96315. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96316. {
  96317. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  96318. FLAC__int32 x;
  96319. unsigned i;
  96320. FLAC__int32 *output = decoder->private_->output[channel];
  96321. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  96322. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96323. return false; /* read_callback_ sets the state for us */
  96324. subframe->value = x;
  96325. /* decode the subframe */
  96326. if(do_full_decode) {
  96327. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96328. output[i] = x;
  96329. }
  96330. return true;
  96331. }
  96332. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96333. {
  96334. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  96335. FLAC__int32 i32;
  96336. FLAC__uint32 u32;
  96337. unsigned u;
  96338. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  96339. subframe->residual = decoder->private_->residual[channel];
  96340. subframe->order = order;
  96341. /* read warm-up samples */
  96342. for(u = 0; u < order; u++) {
  96343. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96344. return false; /* read_callback_ sets the state for us */
  96345. subframe->warmup[u] = i32;
  96346. }
  96347. /* read entropy coding method info */
  96348. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  96349. return false; /* read_callback_ sets the state for us */
  96350. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  96351. switch(subframe->entropy_coding_method.type) {
  96352. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96353. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96354. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96355. return false; /* read_callback_ sets the state for us */
  96356. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  96357. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  96358. break;
  96359. default:
  96360. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96361. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96362. return true;
  96363. }
  96364. /* read residual */
  96365. switch(subframe->entropy_coding_method.type) {
  96366. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96367. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96368. 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))
  96369. return false;
  96370. break;
  96371. default:
  96372. FLAC__ASSERT(0);
  96373. }
  96374. /* decode the subframe */
  96375. if(do_full_decode) {
  96376. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  96377. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  96378. }
  96379. return true;
  96380. }
  96381. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96382. {
  96383. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  96384. FLAC__int32 i32;
  96385. FLAC__uint32 u32;
  96386. unsigned u;
  96387. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  96388. subframe->residual = decoder->private_->residual[channel];
  96389. subframe->order = order;
  96390. /* read warm-up samples */
  96391. for(u = 0; u < order; u++) {
  96392. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96393. return false; /* read_callback_ sets the state for us */
  96394. subframe->warmup[u] = i32;
  96395. }
  96396. /* read qlp coeff precision */
  96397. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  96398. return false; /* read_callback_ sets the state for us */
  96399. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  96400. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96401. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96402. return true;
  96403. }
  96404. subframe->qlp_coeff_precision = u32+1;
  96405. /* read qlp shift */
  96406. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  96407. return false; /* read_callback_ sets the state for us */
  96408. subframe->quantization_level = i32;
  96409. /* read quantized lp coefficiencts */
  96410. for(u = 0; u < order; u++) {
  96411. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  96412. return false; /* read_callback_ sets the state for us */
  96413. subframe->qlp_coeff[u] = i32;
  96414. }
  96415. /* read entropy coding method info */
  96416. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  96417. return false; /* read_callback_ sets the state for us */
  96418. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  96419. switch(subframe->entropy_coding_method.type) {
  96420. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96421. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96422. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96423. return false; /* read_callback_ sets the state for us */
  96424. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  96425. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  96426. break;
  96427. default:
  96428. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96429. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96430. return true;
  96431. }
  96432. /* read residual */
  96433. switch(subframe->entropy_coding_method.type) {
  96434. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96435. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96436. 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))
  96437. return false;
  96438. break;
  96439. default:
  96440. FLAC__ASSERT(0);
  96441. }
  96442. /* decode the subframe */
  96443. if(do_full_decode) {
  96444. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  96445. /*@@@@@@ technically not pessimistic enough, should be more like
  96446. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  96447. */
  96448. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  96449. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  96450. if(order <= 8)
  96451. 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);
  96452. else
  96453. 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);
  96454. }
  96455. else
  96456. 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);
  96457. else
  96458. 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);
  96459. }
  96460. return true;
  96461. }
  96462. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96463. {
  96464. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  96465. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  96466. unsigned i;
  96467. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  96468. subframe->data = residual;
  96469. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  96470. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96471. return false; /* read_callback_ sets the state for us */
  96472. residual[i] = x;
  96473. }
  96474. /* decode the subframe */
  96475. if(do_full_decode)
  96476. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  96477. return true;
  96478. }
  96479. 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)
  96480. {
  96481. FLAC__uint32 rice_parameter;
  96482. int i;
  96483. unsigned partition, sample, u;
  96484. const unsigned partitions = 1u << partition_order;
  96485. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  96486. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  96487. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  96488. /* sanity checks */
  96489. if(partition_order == 0) {
  96490. if(decoder->private_->frame.header.blocksize < predictor_order) {
  96491. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96492. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96493. return true;
  96494. }
  96495. }
  96496. else {
  96497. if(partition_samples < predictor_order) {
  96498. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96499. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96500. return true;
  96501. }
  96502. }
  96503. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  96504. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96505. return false;
  96506. }
  96507. sample = 0;
  96508. for(partition = 0; partition < partitions; partition++) {
  96509. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  96510. return false; /* read_callback_ sets the state for us */
  96511. partitioned_rice_contents->parameters[partition] = rice_parameter;
  96512. if(rice_parameter < pesc) {
  96513. partitioned_rice_contents->raw_bits[partition] = 0;
  96514. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  96515. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  96516. return false; /* read_callback_ sets the state for us */
  96517. sample += u;
  96518. }
  96519. else {
  96520. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  96521. return false; /* read_callback_ sets the state for us */
  96522. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  96523. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  96524. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  96525. return false; /* read_callback_ sets the state for us */
  96526. residual[sample] = i;
  96527. }
  96528. }
  96529. }
  96530. return true;
  96531. }
  96532. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  96533. {
  96534. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  96535. FLAC__uint32 zero = 0;
  96536. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  96537. return false; /* read_callback_ sets the state for us */
  96538. if(zero != 0) {
  96539. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96540. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96541. }
  96542. }
  96543. return true;
  96544. }
  96545. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  96546. {
  96547. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  96548. if(
  96549. #if FLAC__HAS_OGG
  96550. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  96551. !decoder->private_->is_ogg &&
  96552. #endif
  96553. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  96554. ) {
  96555. *bytes = 0;
  96556. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  96557. return false;
  96558. }
  96559. else if(*bytes > 0) {
  96560. /* While seeking, it is possible for our seek to land in the
  96561. * middle of audio data that looks exactly like a frame header
  96562. * from a future version of an encoder. When that happens, our
  96563. * error callback will get an
  96564. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  96565. * unparseable_frame_count. But there is a remote possibility
  96566. * that it is properly synced at such a "future-codec frame",
  96567. * so to make sure, we wait to see many "unparseable" errors in
  96568. * a row before bailing out.
  96569. */
  96570. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  96571. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  96572. return false;
  96573. }
  96574. else {
  96575. const FLAC__StreamDecoderReadStatus status =
  96576. #if FLAC__HAS_OGG
  96577. decoder->private_->is_ogg?
  96578. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  96579. #endif
  96580. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  96581. ;
  96582. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  96583. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  96584. return false;
  96585. }
  96586. else if(*bytes == 0) {
  96587. if(
  96588. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  96589. (
  96590. #if FLAC__HAS_OGG
  96591. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  96592. !decoder->private_->is_ogg &&
  96593. #endif
  96594. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  96595. )
  96596. ) {
  96597. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  96598. return false;
  96599. }
  96600. else
  96601. return true;
  96602. }
  96603. else
  96604. return true;
  96605. }
  96606. }
  96607. else {
  96608. /* abort to avoid a deadlock */
  96609. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  96610. return false;
  96611. }
  96612. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  96613. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  96614. * and at the same time hit the end of the stream (for example, seeking
  96615. * to a point that is after the beginning of the last Ogg page). There
  96616. * is no way to report an Ogg sync loss through the callbacks (see note
  96617. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  96618. * So to keep the decoder from stopping at this point we gate the call
  96619. * to the eof_callback and let the Ogg decoder aspect set the
  96620. * end-of-stream state when it is needed.
  96621. */
  96622. }
  96623. #if FLAC__HAS_OGG
  96624. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  96625. {
  96626. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  96627. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  96628. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  96629. /* we don't really have a way to handle lost sync via read
  96630. * callback so we'll let it pass and let the underlying
  96631. * FLAC decoder catch the error
  96632. */
  96633. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  96634. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  96635. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  96636. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  96637. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  96638. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  96639. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  96640. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  96641. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  96642. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  96643. default:
  96644. FLAC__ASSERT(0);
  96645. /* double protection */
  96646. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  96647. }
  96648. }
  96649. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  96650. {
  96651. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  96652. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  96653. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  96654. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  96655. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  96656. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  96657. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  96658. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  96659. default:
  96660. /* double protection: */
  96661. FLAC__ASSERT(0);
  96662. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  96663. }
  96664. }
  96665. #endif
  96666. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  96667. {
  96668. if(decoder->private_->is_seeking) {
  96669. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  96670. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  96671. FLAC__uint64 target_sample = decoder->private_->target_sample;
  96672. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96673. #if FLAC__HAS_OGG
  96674. decoder->private_->got_a_frame = true;
  96675. #endif
  96676. decoder->private_->last_frame = *frame; /* save the frame */
  96677. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  96678. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  96679. /* kick out of seek mode */
  96680. decoder->private_->is_seeking = false;
  96681. /* shift out the samples before target_sample */
  96682. if(delta > 0) {
  96683. unsigned channel;
  96684. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  96685. for(channel = 0; channel < frame->header.channels; channel++)
  96686. newbuffer[channel] = buffer[channel] + delta;
  96687. decoder->private_->last_frame.header.blocksize -= delta;
  96688. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  96689. /* write the relevant samples */
  96690. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  96691. }
  96692. else {
  96693. /* write the relevant samples */
  96694. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  96695. }
  96696. }
  96697. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  96698. }
  96699. /*
  96700. * If we never got STREAMINFO, turn off MD5 checking to save
  96701. * cycles since we don't have a sum to compare to anyway
  96702. */
  96703. if(!decoder->private_->has_stream_info)
  96704. decoder->private_->do_md5_checking = false;
  96705. if(decoder->private_->do_md5_checking) {
  96706. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  96707. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  96708. }
  96709. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  96710. }
  96711. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  96712. {
  96713. if(!decoder->private_->is_seeking)
  96714. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  96715. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  96716. decoder->private_->unparseable_frame_count++;
  96717. }
  96718. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  96719. {
  96720. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  96721. FLAC__int64 pos = -1;
  96722. int i;
  96723. unsigned approx_bytes_per_frame;
  96724. FLAC__bool first_seek = true;
  96725. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  96726. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  96727. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  96728. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  96729. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  96730. /* take these from the current frame in case they've changed mid-stream */
  96731. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  96732. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  96733. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  96734. /* use values from stream info if we didn't decode a frame */
  96735. if(channels == 0)
  96736. channels = decoder->private_->stream_info.data.stream_info.channels;
  96737. if(bps == 0)
  96738. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  96739. /* we are just guessing here */
  96740. if(max_framesize > 0)
  96741. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  96742. /*
  96743. * Check if it's a known fixed-blocksize stream. Note that though
  96744. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  96745. * never get a STREAMINFO block when decoding so the value of
  96746. * min_blocksize might be zero.
  96747. */
  96748. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  96749. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  96750. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  96751. }
  96752. else
  96753. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  96754. /*
  96755. * First, we set an upper and lower bound on where in the
  96756. * stream we will search. For now we assume the worst case
  96757. * scenario, which is our best guess at the beginning of
  96758. * the first frame and end of the stream.
  96759. */
  96760. lower_bound = first_frame_offset;
  96761. lower_bound_sample = 0;
  96762. upper_bound = stream_length;
  96763. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  96764. /*
  96765. * Now we refine the bounds if we have a seektable with
  96766. * suitable points. Note that according to the spec they
  96767. * must be ordered by ascending sample number.
  96768. *
  96769. * Note: to protect against invalid seek tables we will ignore points
  96770. * that have frame_samples==0 or sample_number>=total_samples
  96771. */
  96772. if(seek_table) {
  96773. FLAC__uint64 new_lower_bound = lower_bound;
  96774. FLAC__uint64 new_upper_bound = upper_bound;
  96775. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  96776. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  96777. /* find the closest seek point <= target_sample, if it exists */
  96778. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  96779. if(
  96780. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96781. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  96782. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  96783. seek_table->points[i].sample_number <= target_sample
  96784. )
  96785. break;
  96786. }
  96787. if(i >= 0) { /* i.e. we found a suitable seek point... */
  96788. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  96789. new_lower_bound_sample = seek_table->points[i].sample_number;
  96790. }
  96791. /* find the closest seek point > target_sample, if it exists */
  96792. for(i = 0; i < (int)seek_table->num_points; i++) {
  96793. if(
  96794. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96795. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  96796. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  96797. seek_table->points[i].sample_number > target_sample
  96798. )
  96799. break;
  96800. }
  96801. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  96802. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  96803. new_upper_bound_sample = seek_table->points[i].sample_number;
  96804. }
  96805. /* final protection against unsorted seek tables; keep original values if bogus */
  96806. if(new_upper_bound >= new_lower_bound) {
  96807. lower_bound = new_lower_bound;
  96808. upper_bound = new_upper_bound;
  96809. lower_bound_sample = new_lower_bound_sample;
  96810. upper_bound_sample = new_upper_bound_sample;
  96811. }
  96812. }
  96813. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  96814. /* there are 2 insidious ways that the following equality occurs, which
  96815. * we need to fix:
  96816. * 1) total_samples is 0 (unknown) and target_sample is 0
  96817. * 2) total_samples is 0 (unknown) and target_sample happens to be
  96818. * exactly equal to the last seek point in the seek table; this
  96819. * means there is no seek point above it, and upper_bound_samples
  96820. * remains equal to the estimate (of target_samples) we made above
  96821. * in either case it does not hurt to move upper_bound_sample up by 1
  96822. */
  96823. if(upper_bound_sample == lower_bound_sample)
  96824. upper_bound_sample++;
  96825. decoder->private_->target_sample = target_sample;
  96826. while(1) {
  96827. /* check if the bounds are still ok */
  96828. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  96829. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96830. return false;
  96831. }
  96832. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96833. #if defined _MSC_VER || defined __MINGW32__
  96834. /* with VC++ you have to spoon feed it the casting */
  96835. 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;
  96836. #else
  96837. 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;
  96838. #endif
  96839. #else
  96840. /* a little less accurate: */
  96841. if(upper_bound - lower_bound < 0xffffffff)
  96842. 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;
  96843. else /* @@@ WATCHOUT, ~2TB limit */
  96844. 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;
  96845. #endif
  96846. if(pos >= (FLAC__int64)upper_bound)
  96847. pos = (FLAC__int64)upper_bound - 1;
  96848. if(pos < (FLAC__int64)lower_bound)
  96849. pos = (FLAC__int64)lower_bound;
  96850. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  96851. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96852. return false;
  96853. }
  96854. if(!FLAC__stream_decoder_flush(decoder)) {
  96855. /* above call sets the state for us */
  96856. return false;
  96857. }
  96858. /* Now we need to get a frame. First we need to reset our
  96859. * unparseable_frame_count; if we get too many unparseable
  96860. * frames in a row, the read callback will return
  96861. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  96862. * FLAC__stream_decoder_process_single() to return false.
  96863. */
  96864. decoder->private_->unparseable_frame_count = 0;
  96865. if(!FLAC__stream_decoder_process_single(decoder)) {
  96866. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96867. return false;
  96868. }
  96869. /* our write callback will change the state when it gets to the target frame */
  96870. /* 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 */
  96871. #if 0
  96872. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  96873. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  96874. break;
  96875. #endif
  96876. if(!decoder->private_->is_seeking)
  96877. break;
  96878. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96879. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  96880. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  96881. if (pos == (FLAC__int64)lower_bound) {
  96882. /* can't move back any more than the first frame, something is fatally wrong */
  96883. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96884. return false;
  96885. }
  96886. /* our last move backwards wasn't big enough, try again */
  96887. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  96888. continue;
  96889. }
  96890. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  96891. first_seek = false;
  96892. /* make sure we are not seeking in corrupted stream */
  96893. if (this_frame_sample < lower_bound_sample) {
  96894. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96895. return false;
  96896. }
  96897. /* we need to narrow the search */
  96898. if(target_sample < this_frame_sample) {
  96899. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  96900. /*@@@@@@ what will decode position be if at end of stream? */
  96901. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  96902. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96903. return false;
  96904. }
  96905. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  96906. }
  96907. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  96908. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  96909. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  96910. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96911. return false;
  96912. }
  96913. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  96914. }
  96915. }
  96916. return true;
  96917. }
  96918. #if FLAC__HAS_OGG
  96919. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  96920. {
  96921. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  96922. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  96923. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  96924. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  96925. FLAC__bool did_a_seek;
  96926. unsigned iteration = 0;
  96927. /* In the first iterations, we will calculate the target byte position
  96928. * by the distance from the target sample to left_sample and
  96929. * right_sample (let's call it "proportional search"). After that, we
  96930. * will switch to binary search.
  96931. */
  96932. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  96933. /* We will switch to a linear search once our current sample is less
  96934. * than this number of samples ahead of the target sample
  96935. */
  96936. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  96937. /* If the total number of samples is unknown, use a large value, and
  96938. * force binary search immediately.
  96939. */
  96940. if(right_sample == 0) {
  96941. right_sample = (FLAC__uint64)(-1);
  96942. BINARY_SEARCH_AFTER_ITERATION = 0;
  96943. }
  96944. decoder->private_->target_sample = target_sample;
  96945. for( ; ; iteration++) {
  96946. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  96947. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  96948. pos = (right_pos + left_pos) / 2;
  96949. }
  96950. else {
  96951. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96952. #if defined _MSC_VER || defined __MINGW32__
  96953. /* with MSVC you have to spoon feed it the casting */
  96954. 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));
  96955. #else
  96956. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  96957. #endif
  96958. #else
  96959. /* a little less accurate: */
  96960. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  96961. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  96962. else /* @@@ WATCHOUT, ~2TB limit */
  96963. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  96964. #endif
  96965. /* @@@ TODO: might want to limit pos to some distance
  96966. * before EOF, to make sure we land before the last frame,
  96967. * thereby getting a this_frame_sample and so having a better
  96968. * estimate.
  96969. */
  96970. }
  96971. /* physical seek */
  96972. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  96973. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96974. return false;
  96975. }
  96976. if(!FLAC__stream_decoder_flush(decoder)) {
  96977. /* above call sets the state for us */
  96978. return false;
  96979. }
  96980. did_a_seek = true;
  96981. }
  96982. else
  96983. did_a_seek = false;
  96984. decoder->private_->got_a_frame = false;
  96985. if(!FLAC__stream_decoder_process_single(decoder)) {
  96986. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96987. return false;
  96988. }
  96989. if(!decoder->private_->got_a_frame) {
  96990. if(did_a_seek) {
  96991. /* this can happen if we seek to a point after the last frame; we drop
  96992. * to binary search right away in this case to avoid any wasted
  96993. * iterations of proportional search.
  96994. */
  96995. right_pos = pos;
  96996. BINARY_SEARCH_AFTER_ITERATION = 0;
  96997. }
  96998. else {
  96999. /* this can probably only happen if total_samples is unknown and the
  97000. * target_sample is past the end of the stream
  97001. */
  97002. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97003. return false;
  97004. }
  97005. }
  97006. /* our write callback will change the state when it gets to the target frame */
  97007. else if(!decoder->private_->is_seeking) {
  97008. break;
  97009. }
  97010. else {
  97011. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97012. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97013. if (did_a_seek) {
  97014. if (this_frame_sample <= target_sample) {
  97015. /* The 'equal' case should not happen, since
  97016. * FLAC__stream_decoder_process_single()
  97017. * should recognize that it has hit the
  97018. * target sample and we would exit through
  97019. * the 'break' above.
  97020. */
  97021. FLAC__ASSERT(this_frame_sample != target_sample);
  97022. left_sample = this_frame_sample;
  97023. /* sanity check to avoid infinite loop */
  97024. if (left_pos == pos) {
  97025. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97026. return false;
  97027. }
  97028. left_pos = pos;
  97029. }
  97030. else if(this_frame_sample > target_sample) {
  97031. right_sample = this_frame_sample;
  97032. /* sanity check to avoid infinite loop */
  97033. if (right_pos == pos) {
  97034. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97035. return false;
  97036. }
  97037. right_pos = pos;
  97038. }
  97039. }
  97040. }
  97041. }
  97042. return true;
  97043. }
  97044. #endif
  97045. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97046. {
  97047. (void)client_data;
  97048. if(*bytes > 0) {
  97049. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  97050. if(ferror(decoder->private_->file))
  97051. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97052. else if(*bytes == 0)
  97053. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97054. else
  97055. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97056. }
  97057. else
  97058. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  97059. }
  97060. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  97061. {
  97062. (void)client_data;
  97063. if(decoder->private_->file == stdin)
  97064. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  97065. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  97066. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  97067. else
  97068. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  97069. }
  97070. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  97071. {
  97072. off_t pos;
  97073. (void)client_data;
  97074. if(decoder->private_->file == stdin)
  97075. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  97076. else if((pos = ftello(decoder->private_->file)) < 0)
  97077. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  97078. else {
  97079. *absolute_byte_offset = (FLAC__uint64)pos;
  97080. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  97081. }
  97082. }
  97083. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  97084. {
  97085. struct stat filestats;
  97086. (void)client_data;
  97087. if(decoder->private_->file == stdin)
  97088. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  97089. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  97090. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  97091. else {
  97092. *stream_length = (FLAC__uint64)filestats.st_size;
  97093. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  97094. }
  97095. }
  97096. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  97097. {
  97098. (void)client_data;
  97099. return feof(decoder->private_->file)? true : false;
  97100. }
  97101. #endif
  97102. /********* End of inlined file: stream_decoder.c *********/
  97103. /********* Start of inlined file: stream_encoder.c *********/
  97104. /********* Start of inlined file: juce_FlacHeader.h *********/
  97105. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97106. // tasks..
  97107. #define VERSION "1.2.1"
  97108. #define FLAC__NO_DLL 1
  97109. #ifdef _MSC_VER
  97110. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97111. #endif
  97112. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  97113. #define FLAC__SYS_DARWIN 1
  97114. #endif
  97115. /********* End of inlined file: juce_FlacHeader.h *********/
  97116. #if JUCE_USE_FLAC
  97117. #if HAVE_CONFIG_H
  97118. # include <config.h>
  97119. #endif
  97120. #if defined _MSC_VER || defined __MINGW32__
  97121. #include <io.h> /* for _setmode() */
  97122. #include <fcntl.h> /* for _O_BINARY */
  97123. #endif
  97124. #if defined __CYGWIN__ || defined __EMX__
  97125. #include <io.h> /* for setmode(), O_BINARY */
  97126. #include <fcntl.h> /* for _O_BINARY */
  97127. #endif
  97128. #include <limits.h>
  97129. #include <stdio.h>
  97130. #include <stdlib.h> /* for malloc() */
  97131. #include <string.h> /* for memcpy() */
  97132. #include <sys/types.h> /* for off_t */
  97133. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  97134. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  97135. #define fseeko fseek
  97136. #define ftello ftell
  97137. #endif
  97138. #endif
  97139. /********* Start of inlined file: stream_encoder.h *********/
  97140. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  97141. #define FLAC__PROTECTED__STREAM_ENCODER_H
  97142. #if FLAC__HAS_OGG
  97143. #include "private/ogg_encoder_aspect.h"
  97144. #endif
  97145. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97146. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  97147. typedef enum {
  97148. FLAC__APODIZATION_BARTLETT,
  97149. FLAC__APODIZATION_BARTLETT_HANN,
  97150. FLAC__APODIZATION_BLACKMAN,
  97151. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  97152. FLAC__APODIZATION_CONNES,
  97153. FLAC__APODIZATION_FLATTOP,
  97154. FLAC__APODIZATION_GAUSS,
  97155. FLAC__APODIZATION_HAMMING,
  97156. FLAC__APODIZATION_HANN,
  97157. FLAC__APODIZATION_KAISER_BESSEL,
  97158. FLAC__APODIZATION_NUTTALL,
  97159. FLAC__APODIZATION_RECTANGLE,
  97160. FLAC__APODIZATION_TRIANGLE,
  97161. FLAC__APODIZATION_TUKEY,
  97162. FLAC__APODIZATION_WELCH
  97163. } FLAC__ApodizationFunction;
  97164. typedef struct {
  97165. FLAC__ApodizationFunction type;
  97166. union {
  97167. struct {
  97168. FLAC__real stddev;
  97169. } gauss;
  97170. struct {
  97171. FLAC__real p;
  97172. } tukey;
  97173. } parameters;
  97174. } FLAC__ApodizationSpecification;
  97175. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97176. typedef struct FLAC__StreamEncoderProtected {
  97177. FLAC__StreamEncoderState state;
  97178. FLAC__bool verify;
  97179. FLAC__bool streamable_subset;
  97180. FLAC__bool do_md5;
  97181. FLAC__bool do_mid_side_stereo;
  97182. FLAC__bool loose_mid_side_stereo;
  97183. unsigned channels;
  97184. unsigned bits_per_sample;
  97185. unsigned sample_rate;
  97186. unsigned blocksize;
  97187. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97188. unsigned num_apodizations;
  97189. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  97190. #endif
  97191. unsigned max_lpc_order;
  97192. unsigned qlp_coeff_precision;
  97193. FLAC__bool do_qlp_coeff_prec_search;
  97194. FLAC__bool do_exhaustive_model_search;
  97195. FLAC__bool do_escape_coding;
  97196. unsigned min_residual_partition_order;
  97197. unsigned max_residual_partition_order;
  97198. unsigned rice_parameter_search_dist;
  97199. FLAC__uint64 total_samples_estimate;
  97200. FLAC__StreamMetadata **metadata;
  97201. unsigned num_metadata_blocks;
  97202. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  97203. #if FLAC__HAS_OGG
  97204. FLAC__OggEncoderAspect ogg_encoder_aspect;
  97205. #endif
  97206. } FLAC__StreamEncoderProtected;
  97207. #endif
  97208. /********* End of inlined file: stream_encoder.h *********/
  97209. #if FLAC__HAS_OGG
  97210. #include "include/private/ogg_helper.h"
  97211. #include "include/private/ogg_mapping.h"
  97212. #endif
  97213. /********* Start of inlined file: stream_encoder_framing.h *********/
  97214. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97215. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97216. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  97217. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  97218. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97219. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97220. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97221. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97222. #endif
  97223. /********* End of inlined file: stream_encoder_framing.h *********/
  97224. /********* Start of inlined file: window.h *********/
  97225. #ifndef FLAC__PRIVATE__WINDOW_H
  97226. #define FLAC__PRIVATE__WINDOW_H
  97227. #ifdef HAVE_CONFIG_H
  97228. #include <config.h>
  97229. #endif
  97230. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97231. /*
  97232. * FLAC__window_*()
  97233. * --------------------------------------------------------------------
  97234. * Calculates window coefficients according to different apodization
  97235. * functions.
  97236. *
  97237. * OUT window[0,L-1]
  97238. * IN L (number of points in window)
  97239. */
  97240. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  97241. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  97242. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  97243. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  97244. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  97245. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  97246. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  97247. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  97248. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  97249. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  97250. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  97251. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  97252. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  97253. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  97254. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  97255. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97256. #endif
  97257. /********* End of inlined file: window.h *********/
  97258. #ifndef FLaC__INLINE
  97259. #define FLaC__INLINE
  97260. #endif
  97261. #ifdef min
  97262. #undef min
  97263. #endif
  97264. #define min(x,y) ((x)<(y)?(x):(y))
  97265. #ifdef max
  97266. #undef max
  97267. #endif
  97268. #define max(x,y) ((x)>(y)?(x):(y))
  97269. /* Exact Rice codeword length calculation is off by default. The simple
  97270. * (and fast) estimation (of how many bits a residual value will be
  97271. * encoded with) in this encoder is very good, almost always yielding
  97272. * compression within 0.1% of exact calculation.
  97273. */
  97274. #undef EXACT_RICE_BITS_CALCULATION
  97275. /* Rice parameter searching is off by default. The simple (and fast)
  97276. * parameter estimation in this encoder is very good, almost always
  97277. * yielding compression within 0.1% of the optimal parameters.
  97278. */
  97279. #undef ENABLE_RICE_PARAMETER_SEARCH
  97280. typedef struct {
  97281. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  97282. unsigned size; /* of each data[] in samples */
  97283. unsigned tail;
  97284. } verify_input_fifo;
  97285. typedef struct {
  97286. const FLAC__byte *data;
  97287. unsigned capacity;
  97288. unsigned bytes;
  97289. } verify_output;
  97290. typedef enum {
  97291. ENCODER_IN_MAGIC = 0,
  97292. ENCODER_IN_METADATA = 1,
  97293. ENCODER_IN_AUDIO = 2
  97294. } EncoderStateHint;
  97295. static struct CompressionLevels {
  97296. FLAC__bool do_mid_side_stereo;
  97297. FLAC__bool loose_mid_side_stereo;
  97298. unsigned max_lpc_order;
  97299. unsigned qlp_coeff_precision;
  97300. FLAC__bool do_qlp_coeff_prec_search;
  97301. FLAC__bool do_escape_coding;
  97302. FLAC__bool do_exhaustive_model_search;
  97303. unsigned min_residual_partition_order;
  97304. unsigned max_residual_partition_order;
  97305. unsigned rice_parameter_search_dist;
  97306. } compression_levels_[] = {
  97307. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  97308. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  97309. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  97310. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  97311. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  97312. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  97313. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  97314. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  97315. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  97316. };
  97317. /***********************************************************************
  97318. *
  97319. * Private class method prototypes
  97320. *
  97321. ***********************************************************************/
  97322. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  97323. static void free_(FLAC__StreamEncoder *encoder);
  97324. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  97325. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  97326. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  97327. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  97328. #if FLAC__HAS_OGG
  97329. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  97330. #endif
  97331. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  97332. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  97333. static FLAC__bool process_subframe_(
  97334. FLAC__StreamEncoder *encoder,
  97335. unsigned min_partition_order,
  97336. unsigned max_partition_order,
  97337. const FLAC__FrameHeader *frame_header,
  97338. unsigned subframe_bps,
  97339. const FLAC__int32 integer_signal[],
  97340. FLAC__Subframe *subframe[2],
  97341. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  97342. FLAC__int32 *residual[2],
  97343. unsigned *best_subframe,
  97344. unsigned *best_bits
  97345. );
  97346. static FLAC__bool add_subframe_(
  97347. FLAC__StreamEncoder *encoder,
  97348. unsigned blocksize,
  97349. unsigned subframe_bps,
  97350. const FLAC__Subframe *subframe,
  97351. FLAC__BitWriter *frame
  97352. );
  97353. static unsigned evaluate_constant_subframe_(
  97354. FLAC__StreamEncoder *encoder,
  97355. const FLAC__int32 signal,
  97356. unsigned blocksize,
  97357. unsigned subframe_bps,
  97358. FLAC__Subframe *subframe
  97359. );
  97360. static unsigned evaluate_fixed_subframe_(
  97361. FLAC__StreamEncoder *encoder,
  97362. const FLAC__int32 signal[],
  97363. FLAC__int32 residual[],
  97364. FLAC__uint64 abs_residual_partition_sums[],
  97365. unsigned raw_bits_per_partition[],
  97366. unsigned blocksize,
  97367. unsigned subframe_bps,
  97368. unsigned order,
  97369. unsigned rice_parameter,
  97370. unsigned rice_parameter_limit,
  97371. unsigned min_partition_order,
  97372. unsigned max_partition_order,
  97373. FLAC__bool do_escape_coding,
  97374. unsigned rice_parameter_search_dist,
  97375. FLAC__Subframe *subframe,
  97376. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  97377. );
  97378. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97379. static unsigned evaluate_lpc_subframe_(
  97380. FLAC__StreamEncoder *encoder,
  97381. const FLAC__int32 signal[],
  97382. FLAC__int32 residual[],
  97383. FLAC__uint64 abs_residual_partition_sums[],
  97384. unsigned raw_bits_per_partition[],
  97385. const FLAC__real lp_coeff[],
  97386. unsigned blocksize,
  97387. unsigned subframe_bps,
  97388. unsigned order,
  97389. unsigned qlp_coeff_precision,
  97390. unsigned rice_parameter,
  97391. unsigned rice_parameter_limit,
  97392. unsigned min_partition_order,
  97393. unsigned max_partition_order,
  97394. FLAC__bool do_escape_coding,
  97395. unsigned rice_parameter_search_dist,
  97396. FLAC__Subframe *subframe,
  97397. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  97398. );
  97399. #endif
  97400. static unsigned evaluate_verbatim_subframe_(
  97401. FLAC__StreamEncoder *encoder,
  97402. const FLAC__int32 signal[],
  97403. unsigned blocksize,
  97404. unsigned subframe_bps,
  97405. FLAC__Subframe *subframe
  97406. );
  97407. static unsigned find_best_partition_order_(
  97408. struct FLAC__StreamEncoderPrivate *private_,
  97409. const FLAC__int32 residual[],
  97410. FLAC__uint64 abs_residual_partition_sums[],
  97411. unsigned raw_bits_per_partition[],
  97412. unsigned residual_samples,
  97413. unsigned predictor_order,
  97414. unsigned rice_parameter,
  97415. unsigned rice_parameter_limit,
  97416. unsigned min_partition_order,
  97417. unsigned max_partition_order,
  97418. unsigned bps,
  97419. FLAC__bool do_escape_coding,
  97420. unsigned rice_parameter_search_dist,
  97421. FLAC__EntropyCodingMethod *best_ecm
  97422. );
  97423. static void precompute_partition_info_sums_(
  97424. const FLAC__int32 residual[],
  97425. FLAC__uint64 abs_residual_partition_sums[],
  97426. unsigned residual_samples,
  97427. unsigned predictor_order,
  97428. unsigned min_partition_order,
  97429. unsigned max_partition_order,
  97430. unsigned bps
  97431. );
  97432. static void precompute_partition_info_escapes_(
  97433. const FLAC__int32 residual[],
  97434. unsigned raw_bits_per_partition[],
  97435. unsigned residual_samples,
  97436. unsigned predictor_order,
  97437. unsigned min_partition_order,
  97438. unsigned max_partition_order
  97439. );
  97440. static FLAC__bool set_partitioned_rice_(
  97441. #ifdef EXACT_RICE_BITS_CALCULATION
  97442. const FLAC__int32 residual[],
  97443. #endif
  97444. const FLAC__uint64 abs_residual_partition_sums[],
  97445. const unsigned raw_bits_per_partition[],
  97446. const unsigned residual_samples,
  97447. const unsigned predictor_order,
  97448. const unsigned suggested_rice_parameter,
  97449. const unsigned rice_parameter_limit,
  97450. const unsigned rice_parameter_search_dist,
  97451. const unsigned partition_order,
  97452. const FLAC__bool search_for_escapes,
  97453. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  97454. unsigned *bits
  97455. );
  97456. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  97457. /* verify-related routines: */
  97458. static void append_to_verify_fifo_(
  97459. verify_input_fifo *fifo,
  97460. const FLAC__int32 * const input[],
  97461. unsigned input_offset,
  97462. unsigned channels,
  97463. unsigned wide_samples
  97464. );
  97465. static void append_to_verify_fifo_interleaved_(
  97466. verify_input_fifo *fifo,
  97467. const FLAC__int32 input[],
  97468. unsigned input_offset,
  97469. unsigned channels,
  97470. unsigned wide_samples
  97471. );
  97472. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97473. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  97474. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  97475. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  97476. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97477. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  97478. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  97479. 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);
  97480. static FILE *get_binary_stdout_(void);
  97481. /***********************************************************************
  97482. *
  97483. * Private class data
  97484. *
  97485. ***********************************************************************/
  97486. typedef struct FLAC__StreamEncoderPrivate {
  97487. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  97488. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  97489. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  97490. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97491. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  97492. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  97493. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  97494. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  97495. #endif
  97496. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  97497. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  97498. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  97499. FLAC__int32 *residual_workspace_mid_side[2][2];
  97500. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  97501. FLAC__Subframe subframe_workspace_mid_side[2][2];
  97502. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  97503. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  97504. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  97505. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  97506. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  97507. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  97508. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  97509. unsigned best_subframe_mid_side[2];
  97510. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  97511. unsigned best_subframe_bits_mid_side[2];
  97512. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  97513. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  97514. FLAC__BitWriter *frame; /* the current frame being worked on */
  97515. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  97516. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  97517. FLAC__ChannelAssignment last_channel_assignment;
  97518. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  97519. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  97520. unsigned current_sample_number;
  97521. unsigned current_frame_number;
  97522. FLAC__MD5Context md5context;
  97523. FLAC__CPUInfo cpuinfo;
  97524. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97525. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  97526. #else
  97527. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  97528. #endif
  97529. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97530. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97531. 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[]);
  97532. 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[]);
  97533. 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[]);
  97534. #endif
  97535. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  97536. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  97537. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  97538. FLAC__bool disable_constant_subframes;
  97539. FLAC__bool disable_fixed_subframes;
  97540. FLAC__bool disable_verbatim_subframes;
  97541. #if FLAC__HAS_OGG
  97542. FLAC__bool is_ogg;
  97543. #endif
  97544. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  97545. FLAC__StreamEncoderSeekCallback seek_callback;
  97546. FLAC__StreamEncoderTellCallback tell_callback;
  97547. FLAC__StreamEncoderWriteCallback write_callback;
  97548. FLAC__StreamEncoderMetadataCallback metadata_callback;
  97549. FLAC__StreamEncoderProgressCallback progress_callback;
  97550. void *client_data;
  97551. unsigned first_seekpoint_to_check;
  97552. FILE *file; /* only used when encoding to a file */
  97553. FLAC__uint64 bytes_written;
  97554. FLAC__uint64 samples_written;
  97555. unsigned frames_written;
  97556. unsigned total_frames_estimate;
  97557. /* unaligned (original) pointers to allocated data */
  97558. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  97559. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  97560. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97561. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  97562. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  97563. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  97564. FLAC__real *windowed_signal_unaligned;
  97565. #endif
  97566. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  97567. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  97568. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  97569. unsigned *raw_bits_per_partition_unaligned;
  97570. /*
  97571. * These fields have been moved here from private function local
  97572. * declarations merely to save stack space during encoding.
  97573. */
  97574. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97575. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  97576. #endif
  97577. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  97578. /*
  97579. * The data for the verify section
  97580. */
  97581. struct {
  97582. FLAC__StreamDecoder *decoder;
  97583. EncoderStateHint state_hint;
  97584. FLAC__bool needs_magic_hack;
  97585. verify_input_fifo input_fifo;
  97586. verify_output output;
  97587. struct {
  97588. FLAC__uint64 absolute_sample;
  97589. unsigned frame_number;
  97590. unsigned channel;
  97591. unsigned sample;
  97592. FLAC__int32 expected;
  97593. FLAC__int32 got;
  97594. } error_stats;
  97595. } verify;
  97596. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  97597. } FLAC__StreamEncoderPrivate;
  97598. /***********************************************************************
  97599. *
  97600. * Public static class data
  97601. *
  97602. ***********************************************************************/
  97603. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  97604. "FLAC__STREAM_ENCODER_OK",
  97605. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  97606. "FLAC__STREAM_ENCODER_OGG_ERROR",
  97607. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  97608. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  97609. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  97610. "FLAC__STREAM_ENCODER_IO_ERROR",
  97611. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  97612. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  97613. };
  97614. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  97615. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  97616. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  97617. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  97618. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  97619. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  97620. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  97621. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  97622. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  97623. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  97624. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  97625. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  97626. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  97627. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  97628. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  97629. };
  97630. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  97631. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  97632. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  97633. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  97634. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  97635. };
  97636. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  97637. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  97638. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  97639. };
  97640. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  97641. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  97642. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  97643. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  97644. };
  97645. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  97646. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  97647. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  97648. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  97649. };
  97650. /* Number of samples that will be overread to watch for end of stream. By
  97651. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  97652. * always try to read blocksize+1 samples before encoding a block, so that
  97653. * even if the stream has a total sample count that is an integral multiple
  97654. * of the blocksize, we will still notice when we are encoding the last
  97655. * block. This is needed, for example, to correctly set the end-of-stream
  97656. * marker in Ogg FLAC.
  97657. *
  97658. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  97659. * not really any reason to change it.
  97660. */
  97661. static const unsigned OVERREAD_ = 1;
  97662. /***********************************************************************
  97663. *
  97664. * Class constructor/destructor
  97665. *
  97666. */
  97667. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  97668. {
  97669. FLAC__StreamEncoder *encoder;
  97670. unsigned i;
  97671. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  97672. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  97673. if(encoder == 0) {
  97674. return 0;
  97675. }
  97676. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  97677. if(encoder->protected_ == 0) {
  97678. free(encoder);
  97679. return 0;
  97680. }
  97681. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  97682. if(encoder->private_ == 0) {
  97683. free(encoder->protected_);
  97684. free(encoder);
  97685. return 0;
  97686. }
  97687. encoder->private_->frame = FLAC__bitwriter_new();
  97688. if(encoder->private_->frame == 0) {
  97689. free(encoder->private_);
  97690. free(encoder->protected_);
  97691. free(encoder);
  97692. return 0;
  97693. }
  97694. encoder->private_->file = 0;
  97695. set_defaults_enc(encoder);
  97696. encoder->private_->is_being_deleted = false;
  97697. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97698. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  97699. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  97700. }
  97701. for(i = 0; i < 2; i++) {
  97702. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  97703. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  97704. }
  97705. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97706. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  97707. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  97708. }
  97709. for(i = 0; i < 2; i++) {
  97710. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  97711. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  97712. }
  97713. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97714. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  97715. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  97716. }
  97717. for(i = 0; i < 2; i++) {
  97718. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  97719. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  97720. }
  97721. for(i = 0; i < 2; i++)
  97722. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  97723. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  97724. return encoder;
  97725. }
  97726. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  97727. {
  97728. unsigned i;
  97729. FLAC__ASSERT(0 != encoder);
  97730. FLAC__ASSERT(0 != encoder->protected_);
  97731. FLAC__ASSERT(0 != encoder->private_);
  97732. FLAC__ASSERT(0 != encoder->private_->frame);
  97733. encoder->private_->is_being_deleted = true;
  97734. (void)FLAC__stream_encoder_finish(encoder);
  97735. if(0 != encoder->private_->verify.decoder)
  97736. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  97737. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97738. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  97739. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  97740. }
  97741. for(i = 0; i < 2; i++) {
  97742. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  97743. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  97744. }
  97745. for(i = 0; i < 2; i++)
  97746. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  97747. FLAC__bitwriter_delete(encoder->private_->frame);
  97748. free(encoder->private_);
  97749. free(encoder->protected_);
  97750. free(encoder);
  97751. }
  97752. /***********************************************************************
  97753. *
  97754. * Public class methods
  97755. *
  97756. ***********************************************************************/
  97757. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  97758. FLAC__StreamEncoder *encoder,
  97759. FLAC__StreamEncoderReadCallback read_callback,
  97760. FLAC__StreamEncoderWriteCallback write_callback,
  97761. FLAC__StreamEncoderSeekCallback seek_callback,
  97762. FLAC__StreamEncoderTellCallback tell_callback,
  97763. FLAC__StreamEncoderMetadataCallback metadata_callback,
  97764. void *client_data,
  97765. FLAC__bool is_ogg
  97766. )
  97767. {
  97768. unsigned i;
  97769. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  97770. FLAC__ASSERT(0 != encoder);
  97771. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97772. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  97773. #if !FLAC__HAS_OGG
  97774. if(is_ogg)
  97775. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  97776. #endif
  97777. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  97778. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  97779. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  97780. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  97781. if(encoder->protected_->channels != 2) {
  97782. encoder->protected_->do_mid_side_stereo = false;
  97783. encoder->protected_->loose_mid_side_stereo = false;
  97784. }
  97785. else if(!encoder->protected_->do_mid_side_stereo)
  97786. encoder->protected_->loose_mid_side_stereo = false;
  97787. if(encoder->protected_->bits_per_sample >= 32)
  97788. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  97789. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  97790. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  97791. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  97792. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  97793. if(encoder->protected_->blocksize == 0) {
  97794. if(encoder->protected_->max_lpc_order == 0)
  97795. encoder->protected_->blocksize = 1152;
  97796. else
  97797. encoder->protected_->blocksize = 4096;
  97798. }
  97799. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  97800. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  97801. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  97802. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  97803. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  97804. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  97805. if(encoder->protected_->qlp_coeff_precision == 0) {
  97806. if(encoder->protected_->bits_per_sample < 16) {
  97807. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  97808. /* @@@ until then we'll make a guess */
  97809. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  97810. }
  97811. else if(encoder->protected_->bits_per_sample == 16) {
  97812. if(encoder->protected_->blocksize <= 192)
  97813. encoder->protected_->qlp_coeff_precision = 7;
  97814. else if(encoder->protected_->blocksize <= 384)
  97815. encoder->protected_->qlp_coeff_precision = 8;
  97816. else if(encoder->protected_->blocksize <= 576)
  97817. encoder->protected_->qlp_coeff_precision = 9;
  97818. else if(encoder->protected_->blocksize <= 1152)
  97819. encoder->protected_->qlp_coeff_precision = 10;
  97820. else if(encoder->protected_->blocksize <= 2304)
  97821. encoder->protected_->qlp_coeff_precision = 11;
  97822. else if(encoder->protected_->blocksize <= 4608)
  97823. encoder->protected_->qlp_coeff_precision = 12;
  97824. else
  97825. encoder->protected_->qlp_coeff_precision = 13;
  97826. }
  97827. else {
  97828. if(encoder->protected_->blocksize <= 384)
  97829. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  97830. else if(encoder->protected_->blocksize <= 1152)
  97831. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  97832. else
  97833. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  97834. }
  97835. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  97836. }
  97837. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  97838. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  97839. if(encoder->protected_->streamable_subset) {
  97840. if(
  97841. encoder->protected_->blocksize != 192 &&
  97842. encoder->protected_->blocksize != 576 &&
  97843. encoder->protected_->blocksize != 1152 &&
  97844. encoder->protected_->blocksize != 2304 &&
  97845. encoder->protected_->blocksize != 4608 &&
  97846. encoder->protected_->blocksize != 256 &&
  97847. encoder->protected_->blocksize != 512 &&
  97848. encoder->protected_->blocksize != 1024 &&
  97849. encoder->protected_->blocksize != 2048 &&
  97850. encoder->protected_->blocksize != 4096 &&
  97851. encoder->protected_->blocksize != 8192 &&
  97852. encoder->protected_->blocksize != 16384
  97853. )
  97854. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97855. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  97856. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97857. if(
  97858. encoder->protected_->bits_per_sample != 8 &&
  97859. encoder->protected_->bits_per_sample != 12 &&
  97860. encoder->protected_->bits_per_sample != 16 &&
  97861. encoder->protected_->bits_per_sample != 20 &&
  97862. encoder->protected_->bits_per_sample != 24
  97863. )
  97864. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97865. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  97866. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97867. if(
  97868. encoder->protected_->sample_rate <= 48000 &&
  97869. (
  97870. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  97871. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  97872. )
  97873. ) {
  97874. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97875. }
  97876. }
  97877. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97878. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  97879. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  97880. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  97881. #if FLAC__HAS_OGG
  97882. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  97883. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  97884. unsigned i;
  97885. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  97886. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  97887. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  97888. for( ; i > 0; i--)
  97889. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  97890. encoder->protected_->metadata[0] = vc;
  97891. break;
  97892. }
  97893. }
  97894. }
  97895. #endif
  97896. /* keep track of any SEEKTABLE block */
  97897. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  97898. unsigned i;
  97899. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  97900. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  97901. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  97902. break; /* take only the first one */
  97903. }
  97904. }
  97905. }
  97906. /* validate metadata */
  97907. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  97908. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97909. metadata_has_seektable = false;
  97910. metadata_has_vorbis_comment = false;
  97911. metadata_picture_has_type1 = false;
  97912. metadata_picture_has_type2 = false;
  97913. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  97914. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  97915. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  97916. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97917. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  97918. if(metadata_has_seektable) /* only one is allowed */
  97919. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97920. metadata_has_seektable = true;
  97921. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  97922. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97923. }
  97924. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  97925. if(metadata_has_vorbis_comment) /* only one is allowed */
  97926. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97927. metadata_has_vorbis_comment = true;
  97928. }
  97929. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  97930. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  97931. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97932. }
  97933. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  97934. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  97935. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97936. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  97937. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  97938. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97939. metadata_picture_has_type1 = true;
  97940. /* standard icon must be 32x32 pixel PNG */
  97941. if(
  97942. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  97943. (
  97944. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  97945. m->data.picture.width != 32 ||
  97946. m->data.picture.height != 32
  97947. )
  97948. )
  97949. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97950. }
  97951. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  97952. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  97953. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97954. metadata_picture_has_type2 = true;
  97955. }
  97956. }
  97957. }
  97958. encoder->private_->input_capacity = 0;
  97959. for(i = 0; i < encoder->protected_->channels; i++) {
  97960. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  97961. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97962. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  97963. #endif
  97964. }
  97965. for(i = 0; i < 2; i++) {
  97966. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  97967. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97968. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  97969. #endif
  97970. }
  97971. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97972. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  97973. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  97974. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  97975. #endif
  97976. for(i = 0; i < encoder->protected_->channels; i++) {
  97977. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  97978. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  97979. encoder->private_->best_subframe[i] = 0;
  97980. }
  97981. for(i = 0; i < 2; i++) {
  97982. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  97983. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  97984. encoder->private_->best_subframe_mid_side[i] = 0;
  97985. }
  97986. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  97987. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  97988. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97989. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  97990. #else
  97991. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  97992. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  97993. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  97994. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  97995. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  97996. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  97997. 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);
  97998. #endif
  97999. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  98000. encoder->private_->loose_mid_side_stereo_frames = 1;
  98001. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  98002. encoder->private_->current_sample_number = 0;
  98003. encoder->private_->current_frame_number = 0;
  98004. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  98005. 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? */
  98006. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  98007. /*
  98008. * get the CPU info and set the function pointers
  98009. */
  98010. FLAC__cpu_info(&encoder->private_->cpuinfo);
  98011. /* first default to the non-asm routines */
  98012. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98013. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  98014. #endif
  98015. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  98016. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98017. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98018. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  98019. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98020. #endif
  98021. /* now override with asm where appropriate */
  98022. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98023. # ifndef FLAC__NO_ASM
  98024. if(encoder->private_->cpuinfo.use_asm) {
  98025. # ifdef FLAC__CPU_IA32
  98026. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98027. # ifdef FLAC__HAS_NASM
  98028. if(encoder->private_->cpuinfo.data.ia32.sse) {
  98029. if(encoder->protected_->max_lpc_order < 4)
  98030. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  98031. else if(encoder->protected_->max_lpc_order < 8)
  98032. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  98033. else if(encoder->protected_->max_lpc_order < 12)
  98034. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  98035. else
  98036. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98037. }
  98038. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  98039. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  98040. else
  98041. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98042. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  98043. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98044. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  98045. }
  98046. else {
  98047. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98048. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98049. }
  98050. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  98051. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  98052. # endif /* FLAC__HAS_NASM */
  98053. # endif /* FLAC__CPU_IA32 */
  98054. }
  98055. # endif /* !FLAC__NO_ASM */
  98056. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  98057. /* finally override based on wide-ness if necessary */
  98058. if(encoder->private_->use_wide_by_block) {
  98059. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  98060. }
  98061. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  98062. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  98063. #if FLAC__HAS_OGG
  98064. encoder->private_->is_ogg = is_ogg;
  98065. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  98066. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98067. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98068. }
  98069. #endif
  98070. encoder->private_->read_callback = read_callback;
  98071. encoder->private_->write_callback = write_callback;
  98072. encoder->private_->seek_callback = seek_callback;
  98073. encoder->private_->tell_callback = tell_callback;
  98074. encoder->private_->metadata_callback = metadata_callback;
  98075. encoder->private_->client_data = client_data;
  98076. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  98077. /* the above function sets the state for us in case of an error */
  98078. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98079. }
  98080. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  98081. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98082. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98083. }
  98084. /*
  98085. * Set up the verify stuff if necessary
  98086. */
  98087. if(encoder->protected_->verify) {
  98088. /*
  98089. * First, set up the fifo which will hold the
  98090. * original signal to compare against
  98091. */
  98092. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  98093. for(i = 0; i < encoder->protected_->channels; i++) {
  98094. 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))) {
  98095. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98096. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98097. }
  98098. }
  98099. encoder->private_->verify.input_fifo.tail = 0;
  98100. /*
  98101. * Now set up a stream decoder for verification
  98102. */
  98103. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  98104. if(0 == encoder->private_->verify.decoder) {
  98105. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98106. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98107. }
  98108. 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) {
  98109. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98110. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98111. }
  98112. }
  98113. encoder->private_->verify.error_stats.absolute_sample = 0;
  98114. encoder->private_->verify.error_stats.frame_number = 0;
  98115. encoder->private_->verify.error_stats.channel = 0;
  98116. encoder->private_->verify.error_stats.sample = 0;
  98117. encoder->private_->verify.error_stats.expected = 0;
  98118. encoder->private_->verify.error_stats.got = 0;
  98119. /*
  98120. * These must be done before we write any metadata, because that
  98121. * calls the write_callback, which uses these values.
  98122. */
  98123. encoder->private_->first_seekpoint_to_check = 0;
  98124. encoder->private_->samples_written = 0;
  98125. encoder->protected_->streaminfo_offset = 0;
  98126. encoder->protected_->seektable_offset = 0;
  98127. encoder->protected_->audio_offset = 0;
  98128. /*
  98129. * write the stream header
  98130. */
  98131. if(encoder->protected_->verify)
  98132. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  98133. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  98134. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98135. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98136. }
  98137. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98138. /* the above function sets the state for us in case of an error */
  98139. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98140. }
  98141. /*
  98142. * write the STREAMINFO metadata block
  98143. */
  98144. if(encoder->protected_->verify)
  98145. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  98146. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  98147. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  98148. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  98149. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  98150. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  98151. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  98152. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  98153. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  98154. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  98155. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  98156. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  98157. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  98158. if(encoder->protected_->do_md5)
  98159. FLAC__MD5Init(&encoder->private_->md5context);
  98160. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  98161. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98162. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98163. }
  98164. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98165. /* the above function sets the state for us in case of an error */
  98166. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98167. }
  98168. /*
  98169. * Now that the STREAMINFO block is written, we can init this to an
  98170. * absurdly-high value...
  98171. */
  98172. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  98173. /* ... and clear this to 0 */
  98174. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  98175. /*
  98176. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  98177. * if not, we will write an empty one (FLAC__add_metadata_block()
  98178. * automatically supplies the vendor string).
  98179. *
  98180. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  98181. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  98182. * true it will have already insured that the metadata list is properly
  98183. * ordered.)
  98184. */
  98185. if(!metadata_has_vorbis_comment) {
  98186. FLAC__StreamMetadata vorbis_comment;
  98187. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  98188. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  98189. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  98190. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  98191. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  98192. vorbis_comment.data.vorbis_comment.num_comments = 0;
  98193. vorbis_comment.data.vorbis_comment.comments = 0;
  98194. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  98195. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98196. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98197. }
  98198. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98199. /* the above function sets the state for us in case of an error */
  98200. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98201. }
  98202. }
  98203. /*
  98204. * write the user's metadata blocks
  98205. */
  98206. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98207. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  98208. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  98209. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98210. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98211. }
  98212. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98213. /* the above function sets the state for us in case of an error */
  98214. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98215. }
  98216. }
  98217. /* now that all the metadata is written, we save the stream offset */
  98218. 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 */
  98219. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98220. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98221. }
  98222. if(encoder->protected_->verify)
  98223. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  98224. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  98225. }
  98226. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  98227. FLAC__StreamEncoder *encoder,
  98228. FLAC__StreamEncoderWriteCallback write_callback,
  98229. FLAC__StreamEncoderSeekCallback seek_callback,
  98230. FLAC__StreamEncoderTellCallback tell_callback,
  98231. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98232. void *client_data
  98233. )
  98234. {
  98235. return init_stream_internal_enc(
  98236. encoder,
  98237. /*read_callback=*/0,
  98238. write_callback,
  98239. seek_callback,
  98240. tell_callback,
  98241. metadata_callback,
  98242. client_data,
  98243. /*is_ogg=*/false
  98244. );
  98245. }
  98246. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  98247. FLAC__StreamEncoder *encoder,
  98248. FLAC__StreamEncoderReadCallback read_callback,
  98249. FLAC__StreamEncoderWriteCallback write_callback,
  98250. FLAC__StreamEncoderSeekCallback seek_callback,
  98251. FLAC__StreamEncoderTellCallback tell_callback,
  98252. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98253. void *client_data
  98254. )
  98255. {
  98256. return init_stream_internal_enc(
  98257. encoder,
  98258. read_callback,
  98259. write_callback,
  98260. seek_callback,
  98261. tell_callback,
  98262. metadata_callback,
  98263. client_data,
  98264. /*is_ogg=*/true
  98265. );
  98266. }
  98267. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  98268. FLAC__StreamEncoder *encoder,
  98269. FILE *file,
  98270. FLAC__StreamEncoderProgressCallback progress_callback,
  98271. void *client_data,
  98272. FLAC__bool is_ogg
  98273. )
  98274. {
  98275. FLAC__StreamEncoderInitStatus init_status;
  98276. FLAC__ASSERT(0 != encoder);
  98277. FLAC__ASSERT(0 != file);
  98278. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98279. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98280. /* double protection */
  98281. if(file == 0) {
  98282. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98283. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98284. }
  98285. /*
  98286. * To make sure that our file does not go unclosed after an error, we
  98287. * must assign the FILE pointer before any further error can occur in
  98288. * this routine.
  98289. */
  98290. if(file == stdout)
  98291. file = get_binary_stdout_(); /* just to be safe */
  98292. encoder->private_->file = file;
  98293. encoder->private_->progress_callback = progress_callback;
  98294. encoder->private_->bytes_written = 0;
  98295. encoder->private_->samples_written = 0;
  98296. encoder->private_->frames_written = 0;
  98297. init_status = init_stream_internal_enc(
  98298. encoder,
  98299. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  98300. file_write_callback_,
  98301. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  98302. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  98303. /*metadata_callback=*/0,
  98304. client_data,
  98305. is_ogg
  98306. );
  98307. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  98308. /* the above function sets the state for us in case of an error */
  98309. return init_status;
  98310. }
  98311. {
  98312. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  98313. FLAC__ASSERT(blocksize != 0);
  98314. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  98315. }
  98316. return init_status;
  98317. }
  98318. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  98319. FLAC__StreamEncoder *encoder,
  98320. FILE *file,
  98321. FLAC__StreamEncoderProgressCallback progress_callback,
  98322. void *client_data
  98323. )
  98324. {
  98325. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  98326. }
  98327. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  98328. FLAC__StreamEncoder *encoder,
  98329. FILE *file,
  98330. FLAC__StreamEncoderProgressCallback progress_callback,
  98331. void *client_data
  98332. )
  98333. {
  98334. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  98335. }
  98336. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  98337. FLAC__StreamEncoder *encoder,
  98338. const char *filename,
  98339. FLAC__StreamEncoderProgressCallback progress_callback,
  98340. void *client_data,
  98341. FLAC__bool is_ogg
  98342. )
  98343. {
  98344. FILE *file;
  98345. FLAC__ASSERT(0 != encoder);
  98346. /*
  98347. * To make sure that our file does not go unclosed after an error, we
  98348. * have to do the same entrance checks here that are later performed
  98349. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  98350. */
  98351. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98352. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98353. file = filename? fopen(filename, "w+b") : stdout;
  98354. if(file == 0) {
  98355. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98356. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98357. }
  98358. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  98359. }
  98360. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  98361. FLAC__StreamEncoder *encoder,
  98362. const char *filename,
  98363. FLAC__StreamEncoderProgressCallback progress_callback,
  98364. void *client_data
  98365. )
  98366. {
  98367. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  98368. }
  98369. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  98370. FLAC__StreamEncoder *encoder,
  98371. const char *filename,
  98372. FLAC__StreamEncoderProgressCallback progress_callback,
  98373. void *client_data
  98374. )
  98375. {
  98376. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  98377. }
  98378. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  98379. {
  98380. FLAC__bool error = false;
  98381. FLAC__ASSERT(0 != encoder);
  98382. FLAC__ASSERT(0 != encoder->private_);
  98383. FLAC__ASSERT(0 != encoder->protected_);
  98384. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  98385. return true;
  98386. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  98387. if(encoder->private_->current_sample_number != 0) {
  98388. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  98389. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  98390. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  98391. error = true;
  98392. }
  98393. }
  98394. if(encoder->protected_->do_md5)
  98395. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  98396. if(!encoder->private_->is_being_deleted) {
  98397. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  98398. if(encoder->private_->seek_callback) {
  98399. #if FLAC__HAS_OGG
  98400. if(encoder->private_->is_ogg)
  98401. update_ogg_metadata_(encoder);
  98402. else
  98403. #endif
  98404. update_metadata_(encoder);
  98405. /* check if an error occurred while updating metadata */
  98406. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  98407. error = true;
  98408. }
  98409. if(encoder->private_->metadata_callback)
  98410. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  98411. }
  98412. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  98413. if(!error)
  98414. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  98415. error = true;
  98416. }
  98417. }
  98418. if(0 != encoder->private_->file) {
  98419. if(encoder->private_->file != stdout)
  98420. fclose(encoder->private_->file);
  98421. encoder->private_->file = 0;
  98422. }
  98423. #if FLAC__HAS_OGG
  98424. if(encoder->private_->is_ogg)
  98425. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  98426. #endif
  98427. free_(encoder);
  98428. set_defaults_enc(encoder);
  98429. if(!error)
  98430. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  98431. return !error;
  98432. }
  98433. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  98434. {
  98435. FLAC__ASSERT(0 != encoder);
  98436. FLAC__ASSERT(0 != encoder->private_);
  98437. FLAC__ASSERT(0 != encoder->protected_);
  98438. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98439. return false;
  98440. #if FLAC__HAS_OGG
  98441. /* can't check encoder->private_->is_ogg since that's not set until init time */
  98442. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  98443. return true;
  98444. #else
  98445. (void)value;
  98446. return false;
  98447. #endif
  98448. }
  98449. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98450. {
  98451. FLAC__ASSERT(0 != encoder);
  98452. FLAC__ASSERT(0 != encoder->private_);
  98453. FLAC__ASSERT(0 != encoder->protected_);
  98454. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98455. return false;
  98456. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  98457. encoder->protected_->verify = value;
  98458. #endif
  98459. return true;
  98460. }
  98461. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98462. {
  98463. FLAC__ASSERT(0 != encoder);
  98464. FLAC__ASSERT(0 != encoder->private_);
  98465. FLAC__ASSERT(0 != encoder->protected_);
  98466. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98467. return false;
  98468. encoder->protected_->streamable_subset = value;
  98469. return true;
  98470. }
  98471. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98472. {
  98473. FLAC__ASSERT(0 != encoder);
  98474. FLAC__ASSERT(0 != encoder->private_);
  98475. FLAC__ASSERT(0 != encoder->protected_);
  98476. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98477. return false;
  98478. encoder->protected_->do_md5 = value;
  98479. return true;
  98480. }
  98481. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  98482. {
  98483. FLAC__ASSERT(0 != encoder);
  98484. FLAC__ASSERT(0 != encoder->private_);
  98485. FLAC__ASSERT(0 != encoder->protected_);
  98486. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98487. return false;
  98488. encoder->protected_->channels = value;
  98489. return true;
  98490. }
  98491. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  98492. {
  98493. FLAC__ASSERT(0 != encoder);
  98494. FLAC__ASSERT(0 != encoder->private_);
  98495. FLAC__ASSERT(0 != encoder->protected_);
  98496. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98497. return false;
  98498. encoder->protected_->bits_per_sample = value;
  98499. return true;
  98500. }
  98501. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  98502. {
  98503. FLAC__ASSERT(0 != encoder);
  98504. FLAC__ASSERT(0 != encoder->private_);
  98505. FLAC__ASSERT(0 != encoder->protected_);
  98506. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98507. return false;
  98508. encoder->protected_->sample_rate = value;
  98509. return true;
  98510. }
  98511. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  98512. {
  98513. FLAC__bool ok = true;
  98514. FLAC__ASSERT(0 != encoder);
  98515. FLAC__ASSERT(0 != encoder->private_);
  98516. FLAC__ASSERT(0 != encoder->protected_);
  98517. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98518. return false;
  98519. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  98520. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  98521. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  98522. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  98523. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98524. #if 0
  98525. /* was: */
  98526. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  98527. /* but it's too hard to specify the string in a locale-specific way */
  98528. #else
  98529. encoder->protected_->num_apodizations = 1;
  98530. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  98531. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  98532. #endif
  98533. #endif
  98534. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  98535. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  98536. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  98537. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  98538. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  98539. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  98540. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  98541. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  98542. return ok;
  98543. }
  98544. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  98545. {
  98546. FLAC__ASSERT(0 != encoder);
  98547. FLAC__ASSERT(0 != encoder->private_);
  98548. FLAC__ASSERT(0 != encoder->protected_);
  98549. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98550. return false;
  98551. encoder->protected_->blocksize = value;
  98552. return true;
  98553. }
  98554. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98555. {
  98556. FLAC__ASSERT(0 != encoder);
  98557. FLAC__ASSERT(0 != encoder->private_);
  98558. FLAC__ASSERT(0 != encoder->protected_);
  98559. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98560. return false;
  98561. encoder->protected_->do_mid_side_stereo = value;
  98562. return true;
  98563. }
  98564. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98565. {
  98566. FLAC__ASSERT(0 != encoder);
  98567. FLAC__ASSERT(0 != encoder->private_);
  98568. FLAC__ASSERT(0 != encoder->protected_);
  98569. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98570. return false;
  98571. encoder->protected_->loose_mid_side_stereo = value;
  98572. return true;
  98573. }
  98574. /*@@@@add to tests*/
  98575. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  98576. {
  98577. FLAC__ASSERT(0 != encoder);
  98578. FLAC__ASSERT(0 != encoder->private_);
  98579. FLAC__ASSERT(0 != encoder->protected_);
  98580. FLAC__ASSERT(0 != specification);
  98581. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98582. return false;
  98583. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  98584. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  98585. #else
  98586. encoder->protected_->num_apodizations = 0;
  98587. while(1) {
  98588. const char *s = strchr(specification, ';');
  98589. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  98590. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  98591. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  98592. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  98593. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  98594. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  98595. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  98596. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  98597. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  98598. else if(n==6 && 0 == strncmp("connes" , specification, n))
  98599. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  98600. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  98601. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  98602. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  98603. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  98604. if (stddev > 0.0 && stddev <= 0.5) {
  98605. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  98606. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  98607. }
  98608. }
  98609. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  98610. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  98611. else if(n==4 && 0 == strncmp("hann" , specification, n))
  98612. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  98613. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  98614. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  98615. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  98616. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  98617. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  98618. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  98619. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  98620. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  98621. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  98622. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  98623. if (p >= 0.0 && p <= 1.0) {
  98624. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  98625. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  98626. }
  98627. }
  98628. else if(n==5 && 0 == strncmp("welch" , specification, n))
  98629. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  98630. if (encoder->protected_->num_apodizations == 32)
  98631. break;
  98632. if (s)
  98633. specification = s+1;
  98634. else
  98635. break;
  98636. }
  98637. if(encoder->protected_->num_apodizations == 0) {
  98638. encoder->protected_->num_apodizations = 1;
  98639. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  98640. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  98641. }
  98642. #endif
  98643. return true;
  98644. }
  98645. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  98646. {
  98647. FLAC__ASSERT(0 != encoder);
  98648. FLAC__ASSERT(0 != encoder->private_);
  98649. FLAC__ASSERT(0 != encoder->protected_);
  98650. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98651. return false;
  98652. encoder->protected_->max_lpc_order = value;
  98653. return true;
  98654. }
  98655. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  98656. {
  98657. FLAC__ASSERT(0 != encoder);
  98658. FLAC__ASSERT(0 != encoder->private_);
  98659. FLAC__ASSERT(0 != encoder->protected_);
  98660. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98661. return false;
  98662. encoder->protected_->qlp_coeff_precision = value;
  98663. return true;
  98664. }
  98665. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98666. {
  98667. FLAC__ASSERT(0 != encoder);
  98668. FLAC__ASSERT(0 != encoder->private_);
  98669. FLAC__ASSERT(0 != encoder->protected_);
  98670. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98671. return false;
  98672. encoder->protected_->do_qlp_coeff_prec_search = value;
  98673. return true;
  98674. }
  98675. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98676. {
  98677. FLAC__ASSERT(0 != encoder);
  98678. FLAC__ASSERT(0 != encoder->private_);
  98679. FLAC__ASSERT(0 != encoder->protected_);
  98680. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98681. return false;
  98682. #if 0
  98683. /*@@@ deprecated: */
  98684. encoder->protected_->do_escape_coding = value;
  98685. #else
  98686. (void)value;
  98687. #endif
  98688. return true;
  98689. }
  98690. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98691. {
  98692. FLAC__ASSERT(0 != encoder);
  98693. FLAC__ASSERT(0 != encoder->private_);
  98694. FLAC__ASSERT(0 != encoder->protected_);
  98695. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98696. return false;
  98697. encoder->protected_->do_exhaustive_model_search = value;
  98698. return true;
  98699. }
  98700. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  98701. {
  98702. FLAC__ASSERT(0 != encoder);
  98703. FLAC__ASSERT(0 != encoder->private_);
  98704. FLAC__ASSERT(0 != encoder->protected_);
  98705. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98706. return false;
  98707. encoder->protected_->min_residual_partition_order = value;
  98708. return true;
  98709. }
  98710. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  98711. {
  98712. FLAC__ASSERT(0 != encoder);
  98713. FLAC__ASSERT(0 != encoder->private_);
  98714. FLAC__ASSERT(0 != encoder->protected_);
  98715. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98716. return false;
  98717. encoder->protected_->max_residual_partition_order = value;
  98718. return true;
  98719. }
  98720. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  98721. {
  98722. FLAC__ASSERT(0 != encoder);
  98723. FLAC__ASSERT(0 != encoder->private_);
  98724. FLAC__ASSERT(0 != encoder->protected_);
  98725. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98726. return false;
  98727. #if 0
  98728. /*@@@ deprecated: */
  98729. encoder->protected_->rice_parameter_search_dist = value;
  98730. #else
  98731. (void)value;
  98732. #endif
  98733. return true;
  98734. }
  98735. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  98736. {
  98737. FLAC__ASSERT(0 != encoder);
  98738. FLAC__ASSERT(0 != encoder->private_);
  98739. FLAC__ASSERT(0 != encoder->protected_);
  98740. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98741. return false;
  98742. encoder->protected_->total_samples_estimate = value;
  98743. return true;
  98744. }
  98745. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  98746. {
  98747. FLAC__ASSERT(0 != encoder);
  98748. FLAC__ASSERT(0 != encoder->private_);
  98749. FLAC__ASSERT(0 != encoder->protected_);
  98750. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98751. return false;
  98752. if(0 == metadata)
  98753. num_blocks = 0;
  98754. if(0 == num_blocks)
  98755. metadata = 0;
  98756. /* realloc() does not do exactly what we want so... */
  98757. if(encoder->protected_->metadata) {
  98758. free(encoder->protected_->metadata);
  98759. encoder->protected_->metadata = 0;
  98760. encoder->protected_->num_metadata_blocks = 0;
  98761. }
  98762. if(num_blocks) {
  98763. FLAC__StreamMetadata **m;
  98764. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  98765. return false;
  98766. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  98767. encoder->protected_->metadata = m;
  98768. encoder->protected_->num_metadata_blocks = num_blocks;
  98769. }
  98770. #if FLAC__HAS_OGG
  98771. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  98772. return false;
  98773. #endif
  98774. return true;
  98775. }
  98776. /*
  98777. * These three functions are not static, but not publically exposed in
  98778. * include/FLAC/ either. They are used by the test suite.
  98779. */
  98780. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98781. {
  98782. FLAC__ASSERT(0 != encoder);
  98783. FLAC__ASSERT(0 != encoder->private_);
  98784. FLAC__ASSERT(0 != encoder->protected_);
  98785. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98786. return false;
  98787. encoder->private_->disable_constant_subframes = value;
  98788. return true;
  98789. }
  98790. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98791. {
  98792. FLAC__ASSERT(0 != encoder);
  98793. FLAC__ASSERT(0 != encoder->private_);
  98794. FLAC__ASSERT(0 != encoder->protected_);
  98795. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98796. return false;
  98797. encoder->private_->disable_fixed_subframes = value;
  98798. return true;
  98799. }
  98800. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98801. {
  98802. FLAC__ASSERT(0 != encoder);
  98803. FLAC__ASSERT(0 != encoder->private_);
  98804. FLAC__ASSERT(0 != encoder->protected_);
  98805. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98806. return false;
  98807. encoder->private_->disable_verbatim_subframes = value;
  98808. return true;
  98809. }
  98810. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  98811. {
  98812. FLAC__ASSERT(0 != encoder);
  98813. FLAC__ASSERT(0 != encoder->private_);
  98814. FLAC__ASSERT(0 != encoder->protected_);
  98815. return encoder->protected_->state;
  98816. }
  98817. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  98818. {
  98819. FLAC__ASSERT(0 != encoder);
  98820. FLAC__ASSERT(0 != encoder->private_);
  98821. FLAC__ASSERT(0 != encoder->protected_);
  98822. if(encoder->protected_->verify)
  98823. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  98824. else
  98825. return FLAC__STREAM_DECODER_UNINITIALIZED;
  98826. }
  98827. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  98828. {
  98829. FLAC__ASSERT(0 != encoder);
  98830. FLAC__ASSERT(0 != encoder->private_);
  98831. FLAC__ASSERT(0 != encoder->protected_);
  98832. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  98833. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  98834. else
  98835. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  98836. }
  98837. 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)
  98838. {
  98839. FLAC__ASSERT(0 != encoder);
  98840. FLAC__ASSERT(0 != encoder->private_);
  98841. FLAC__ASSERT(0 != encoder->protected_);
  98842. if(0 != absolute_sample)
  98843. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  98844. if(0 != frame_number)
  98845. *frame_number = encoder->private_->verify.error_stats.frame_number;
  98846. if(0 != channel)
  98847. *channel = encoder->private_->verify.error_stats.channel;
  98848. if(0 != sample)
  98849. *sample = encoder->private_->verify.error_stats.sample;
  98850. if(0 != expected)
  98851. *expected = encoder->private_->verify.error_stats.expected;
  98852. if(0 != got)
  98853. *got = encoder->private_->verify.error_stats.got;
  98854. }
  98855. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  98856. {
  98857. FLAC__ASSERT(0 != encoder);
  98858. FLAC__ASSERT(0 != encoder->private_);
  98859. FLAC__ASSERT(0 != encoder->protected_);
  98860. return encoder->protected_->verify;
  98861. }
  98862. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  98863. {
  98864. FLAC__ASSERT(0 != encoder);
  98865. FLAC__ASSERT(0 != encoder->private_);
  98866. FLAC__ASSERT(0 != encoder->protected_);
  98867. return encoder->protected_->streamable_subset;
  98868. }
  98869. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  98870. {
  98871. FLAC__ASSERT(0 != encoder);
  98872. FLAC__ASSERT(0 != encoder->private_);
  98873. FLAC__ASSERT(0 != encoder->protected_);
  98874. return encoder->protected_->do_md5;
  98875. }
  98876. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  98877. {
  98878. FLAC__ASSERT(0 != encoder);
  98879. FLAC__ASSERT(0 != encoder->private_);
  98880. FLAC__ASSERT(0 != encoder->protected_);
  98881. return encoder->protected_->channels;
  98882. }
  98883. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  98884. {
  98885. FLAC__ASSERT(0 != encoder);
  98886. FLAC__ASSERT(0 != encoder->private_);
  98887. FLAC__ASSERT(0 != encoder->protected_);
  98888. return encoder->protected_->bits_per_sample;
  98889. }
  98890. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  98891. {
  98892. FLAC__ASSERT(0 != encoder);
  98893. FLAC__ASSERT(0 != encoder->private_);
  98894. FLAC__ASSERT(0 != encoder->protected_);
  98895. return encoder->protected_->sample_rate;
  98896. }
  98897. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  98898. {
  98899. FLAC__ASSERT(0 != encoder);
  98900. FLAC__ASSERT(0 != encoder->private_);
  98901. FLAC__ASSERT(0 != encoder->protected_);
  98902. return encoder->protected_->blocksize;
  98903. }
  98904. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  98905. {
  98906. FLAC__ASSERT(0 != encoder);
  98907. FLAC__ASSERT(0 != encoder->private_);
  98908. FLAC__ASSERT(0 != encoder->protected_);
  98909. return encoder->protected_->do_mid_side_stereo;
  98910. }
  98911. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  98912. {
  98913. FLAC__ASSERT(0 != encoder);
  98914. FLAC__ASSERT(0 != encoder->private_);
  98915. FLAC__ASSERT(0 != encoder->protected_);
  98916. return encoder->protected_->loose_mid_side_stereo;
  98917. }
  98918. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  98919. {
  98920. FLAC__ASSERT(0 != encoder);
  98921. FLAC__ASSERT(0 != encoder->private_);
  98922. FLAC__ASSERT(0 != encoder->protected_);
  98923. return encoder->protected_->max_lpc_order;
  98924. }
  98925. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  98926. {
  98927. FLAC__ASSERT(0 != encoder);
  98928. FLAC__ASSERT(0 != encoder->private_);
  98929. FLAC__ASSERT(0 != encoder->protected_);
  98930. return encoder->protected_->qlp_coeff_precision;
  98931. }
  98932. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  98933. {
  98934. FLAC__ASSERT(0 != encoder);
  98935. FLAC__ASSERT(0 != encoder->private_);
  98936. FLAC__ASSERT(0 != encoder->protected_);
  98937. return encoder->protected_->do_qlp_coeff_prec_search;
  98938. }
  98939. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  98940. {
  98941. FLAC__ASSERT(0 != encoder);
  98942. FLAC__ASSERT(0 != encoder->private_);
  98943. FLAC__ASSERT(0 != encoder->protected_);
  98944. return encoder->protected_->do_escape_coding;
  98945. }
  98946. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  98947. {
  98948. FLAC__ASSERT(0 != encoder);
  98949. FLAC__ASSERT(0 != encoder->private_);
  98950. FLAC__ASSERT(0 != encoder->protected_);
  98951. return encoder->protected_->do_exhaustive_model_search;
  98952. }
  98953. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  98954. {
  98955. FLAC__ASSERT(0 != encoder);
  98956. FLAC__ASSERT(0 != encoder->private_);
  98957. FLAC__ASSERT(0 != encoder->protected_);
  98958. return encoder->protected_->min_residual_partition_order;
  98959. }
  98960. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  98961. {
  98962. FLAC__ASSERT(0 != encoder);
  98963. FLAC__ASSERT(0 != encoder->private_);
  98964. FLAC__ASSERT(0 != encoder->protected_);
  98965. return encoder->protected_->max_residual_partition_order;
  98966. }
  98967. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  98968. {
  98969. FLAC__ASSERT(0 != encoder);
  98970. FLAC__ASSERT(0 != encoder->private_);
  98971. FLAC__ASSERT(0 != encoder->protected_);
  98972. return encoder->protected_->rice_parameter_search_dist;
  98973. }
  98974. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  98975. {
  98976. FLAC__ASSERT(0 != encoder);
  98977. FLAC__ASSERT(0 != encoder->private_);
  98978. FLAC__ASSERT(0 != encoder->protected_);
  98979. return encoder->protected_->total_samples_estimate;
  98980. }
  98981. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  98982. {
  98983. unsigned i, j = 0, channel;
  98984. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  98985. FLAC__ASSERT(0 != encoder);
  98986. FLAC__ASSERT(0 != encoder->private_);
  98987. FLAC__ASSERT(0 != encoder->protected_);
  98988. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98989. do {
  98990. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  98991. if(encoder->protected_->verify)
  98992. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  98993. for(channel = 0; channel < channels; channel++)
  98994. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  98995. if(encoder->protected_->do_mid_side_stereo) {
  98996. FLAC__ASSERT(channels == 2);
  98997. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98998. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98999. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  99000. 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' ! */
  99001. }
  99002. }
  99003. else
  99004. j += n;
  99005. encoder->private_->current_sample_number += n;
  99006. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99007. if(encoder->private_->current_sample_number > blocksize) {
  99008. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  99009. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99010. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99011. return false;
  99012. /* move unprocessed overread samples to beginnings of arrays */
  99013. for(channel = 0; channel < channels; channel++)
  99014. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99015. if(encoder->protected_->do_mid_side_stereo) {
  99016. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99017. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99018. }
  99019. encoder->private_->current_sample_number = 1;
  99020. }
  99021. } while(j < samples);
  99022. return true;
  99023. }
  99024. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  99025. {
  99026. unsigned i, j, k, channel;
  99027. FLAC__int32 x, mid, side;
  99028. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99029. FLAC__ASSERT(0 != encoder);
  99030. FLAC__ASSERT(0 != encoder->private_);
  99031. FLAC__ASSERT(0 != encoder->protected_);
  99032. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99033. j = k = 0;
  99034. /*
  99035. * we have several flavors of the same basic loop, optimized for
  99036. * different conditions:
  99037. */
  99038. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  99039. /*
  99040. * stereo coding: unroll channel loop
  99041. */
  99042. do {
  99043. if(encoder->protected_->verify)
  99044. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99045. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99046. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99047. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  99048. x = buffer[k++];
  99049. encoder->private_->integer_signal[1][i] = x;
  99050. mid += x;
  99051. side -= x;
  99052. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  99053. encoder->private_->integer_signal_mid_side[1][i] = side;
  99054. encoder->private_->integer_signal_mid_side[0][i] = mid;
  99055. }
  99056. encoder->private_->current_sample_number = i;
  99057. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99058. if(i > blocksize) {
  99059. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99060. return false;
  99061. /* move unprocessed overread samples to beginnings of arrays */
  99062. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99063. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99064. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  99065. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  99066. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99067. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99068. encoder->private_->current_sample_number = 1;
  99069. }
  99070. } while(j < samples);
  99071. }
  99072. else {
  99073. /*
  99074. * independent channel coding: buffer each channel in inner loop
  99075. */
  99076. do {
  99077. if(encoder->protected_->verify)
  99078. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99079. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99080. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99081. for(channel = 0; channel < channels; channel++)
  99082. encoder->private_->integer_signal[channel][i] = buffer[k++];
  99083. }
  99084. encoder->private_->current_sample_number = i;
  99085. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99086. if(i > blocksize) {
  99087. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99088. return false;
  99089. /* move unprocessed overread samples to beginnings of arrays */
  99090. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99091. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99092. for(channel = 0; channel < channels; channel++)
  99093. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99094. encoder->private_->current_sample_number = 1;
  99095. }
  99096. } while(j < samples);
  99097. }
  99098. return true;
  99099. }
  99100. /***********************************************************************
  99101. *
  99102. * Private class methods
  99103. *
  99104. ***********************************************************************/
  99105. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  99106. {
  99107. FLAC__ASSERT(0 != encoder);
  99108. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99109. encoder->protected_->verify = true;
  99110. #else
  99111. encoder->protected_->verify = false;
  99112. #endif
  99113. encoder->protected_->streamable_subset = true;
  99114. encoder->protected_->do_md5 = true;
  99115. encoder->protected_->do_mid_side_stereo = false;
  99116. encoder->protected_->loose_mid_side_stereo = false;
  99117. encoder->protected_->channels = 2;
  99118. encoder->protected_->bits_per_sample = 16;
  99119. encoder->protected_->sample_rate = 44100;
  99120. encoder->protected_->blocksize = 0;
  99121. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99122. encoder->protected_->num_apodizations = 1;
  99123. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99124. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99125. #endif
  99126. encoder->protected_->max_lpc_order = 0;
  99127. encoder->protected_->qlp_coeff_precision = 0;
  99128. encoder->protected_->do_qlp_coeff_prec_search = false;
  99129. encoder->protected_->do_exhaustive_model_search = false;
  99130. encoder->protected_->do_escape_coding = false;
  99131. encoder->protected_->min_residual_partition_order = 0;
  99132. encoder->protected_->max_residual_partition_order = 0;
  99133. encoder->protected_->rice_parameter_search_dist = 0;
  99134. encoder->protected_->total_samples_estimate = 0;
  99135. encoder->protected_->metadata = 0;
  99136. encoder->protected_->num_metadata_blocks = 0;
  99137. encoder->private_->seek_table = 0;
  99138. encoder->private_->disable_constant_subframes = false;
  99139. encoder->private_->disable_fixed_subframes = false;
  99140. encoder->private_->disable_verbatim_subframes = false;
  99141. #if FLAC__HAS_OGG
  99142. encoder->private_->is_ogg = false;
  99143. #endif
  99144. encoder->private_->read_callback = 0;
  99145. encoder->private_->write_callback = 0;
  99146. encoder->private_->seek_callback = 0;
  99147. encoder->private_->tell_callback = 0;
  99148. encoder->private_->metadata_callback = 0;
  99149. encoder->private_->progress_callback = 0;
  99150. encoder->private_->client_data = 0;
  99151. #if FLAC__HAS_OGG
  99152. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  99153. #endif
  99154. }
  99155. void free_(FLAC__StreamEncoder *encoder)
  99156. {
  99157. unsigned i, channel;
  99158. FLAC__ASSERT(0 != encoder);
  99159. if(encoder->protected_->metadata) {
  99160. free(encoder->protected_->metadata);
  99161. encoder->protected_->metadata = 0;
  99162. encoder->protected_->num_metadata_blocks = 0;
  99163. }
  99164. for(i = 0; i < encoder->protected_->channels; i++) {
  99165. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  99166. free(encoder->private_->integer_signal_unaligned[i]);
  99167. encoder->private_->integer_signal_unaligned[i] = 0;
  99168. }
  99169. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99170. if(0 != encoder->private_->real_signal_unaligned[i]) {
  99171. free(encoder->private_->real_signal_unaligned[i]);
  99172. encoder->private_->real_signal_unaligned[i] = 0;
  99173. }
  99174. #endif
  99175. }
  99176. for(i = 0; i < 2; i++) {
  99177. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  99178. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  99179. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  99180. }
  99181. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99182. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  99183. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  99184. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  99185. }
  99186. #endif
  99187. }
  99188. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99189. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  99190. if(0 != encoder->private_->window_unaligned[i]) {
  99191. free(encoder->private_->window_unaligned[i]);
  99192. encoder->private_->window_unaligned[i] = 0;
  99193. }
  99194. }
  99195. if(0 != encoder->private_->windowed_signal_unaligned) {
  99196. free(encoder->private_->windowed_signal_unaligned);
  99197. encoder->private_->windowed_signal_unaligned = 0;
  99198. }
  99199. #endif
  99200. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99201. for(i = 0; i < 2; i++) {
  99202. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  99203. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  99204. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  99205. }
  99206. }
  99207. }
  99208. for(channel = 0; channel < 2; channel++) {
  99209. for(i = 0; i < 2; i++) {
  99210. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  99211. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  99212. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  99213. }
  99214. }
  99215. }
  99216. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  99217. free(encoder->private_->abs_residual_partition_sums_unaligned);
  99218. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  99219. }
  99220. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  99221. free(encoder->private_->raw_bits_per_partition_unaligned);
  99222. encoder->private_->raw_bits_per_partition_unaligned = 0;
  99223. }
  99224. if(encoder->protected_->verify) {
  99225. for(i = 0; i < encoder->protected_->channels; i++) {
  99226. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  99227. free(encoder->private_->verify.input_fifo.data[i]);
  99228. encoder->private_->verify.input_fifo.data[i] = 0;
  99229. }
  99230. }
  99231. }
  99232. FLAC__bitwriter_free(encoder->private_->frame);
  99233. }
  99234. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  99235. {
  99236. FLAC__bool ok;
  99237. unsigned i, channel;
  99238. FLAC__ASSERT(new_blocksize > 0);
  99239. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99240. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  99241. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  99242. if(new_blocksize <= encoder->private_->input_capacity)
  99243. return true;
  99244. ok = true;
  99245. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  99246. * requires that the input arrays (in our case the integer signals)
  99247. * have a buffer of up to 3 zeroes in front (at negative indices) for
  99248. * alignment purposes; we use 4 in front to keep the data well-aligned.
  99249. */
  99250. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  99251. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  99252. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  99253. encoder->private_->integer_signal[i] += 4;
  99254. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99255. #if 0 /* @@@ currently unused */
  99256. if(encoder->protected_->max_lpc_order > 0)
  99257. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  99258. #endif
  99259. #endif
  99260. }
  99261. for(i = 0; ok && i < 2; i++) {
  99262. 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]);
  99263. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  99264. encoder->private_->integer_signal_mid_side[i] += 4;
  99265. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99266. #if 0 /* @@@ currently unused */
  99267. if(encoder->protected_->max_lpc_order > 0)
  99268. 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]);
  99269. #endif
  99270. #endif
  99271. }
  99272. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99273. if(ok && encoder->protected_->max_lpc_order > 0) {
  99274. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  99275. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  99276. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  99277. }
  99278. #endif
  99279. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  99280. for(i = 0; ok && i < 2; i++) {
  99281. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  99282. }
  99283. }
  99284. for(channel = 0; ok && channel < 2; channel++) {
  99285. for(i = 0; ok && i < 2; i++) {
  99286. 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]);
  99287. }
  99288. }
  99289. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  99290. /*@@@ 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) */
  99291. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  99292. if(encoder->protected_->do_escape_coding)
  99293. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  99294. /* now adjust the windows if the blocksize has changed */
  99295. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99296. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  99297. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  99298. switch(encoder->protected_->apodizations[i].type) {
  99299. case FLAC__APODIZATION_BARTLETT:
  99300. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  99301. break;
  99302. case FLAC__APODIZATION_BARTLETT_HANN:
  99303. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  99304. break;
  99305. case FLAC__APODIZATION_BLACKMAN:
  99306. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  99307. break;
  99308. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  99309. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  99310. break;
  99311. case FLAC__APODIZATION_CONNES:
  99312. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  99313. break;
  99314. case FLAC__APODIZATION_FLATTOP:
  99315. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  99316. break;
  99317. case FLAC__APODIZATION_GAUSS:
  99318. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  99319. break;
  99320. case FLAC__APODIZATION_HAMMING:
  99321. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  99322. break;
  99323. case FLAC__APODIZATION_HANN:
  99324. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99325. break;
  99326. case FLAC__APODIZATION_KAISER_BESSEL:
  99327. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  99328. break;
  99329. case FLAC__APODIZATION_NUTTALL:
  99330. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  99331. break;
  99332. case FLAC__APODIZATION_RECTANGLE:
  99333. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  99334. break;
  99335. case FLAC__APODIZATION_TRIANGLE:
  99336. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  99337. break;
  99338. case FLAC__APODIZATION_TUKEY:
  99339. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  99340. break;
  99341. case FLAC__APODIZATION_WELCH:
  99342. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  99343. break;
  99344. default:
  99345. FLAC__ASSERT(0);
  99346. /* double protection */
  99347. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99348. break;
  99349. }
  99350. }
  99351. }
  99352. #endif
  99353. if(ok)
  99354. encoder->private_->input_capacity = new_blocksize;
  99355. else
  99356. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99357. return ok;
  99358. }
  99359. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  99360. {
  99361. const FLAC__byte *buffer;
  99362. size_t bytes;
  99363. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  99364. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  99365. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99366. return false;
  99367. }
  99368. if(encoder->protected_->verify) {
  99369. encoder->private_->verify.output.data = buffer;
  99370. encoder->private_->verify.output.bytes = bytes;
  99371. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  99372. encoder->private_->verify.needs_magic_hack = true;
  99373. }
  99374. else {
  99375. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  99376. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99377. FLAC__bitwriter_clear(encoder->private_->frame);
  99378. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  99379. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99380. return false;
  99381. }
  99382. }
  99383. }
  99384. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99385. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99386. FLAC__bitwriter_clear(encoder->private_->frame);
  99387. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99388. return false;
  99389. }
  99390. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99391. FLAC__bitwriter_clear(encoder->private_->frame);
  99392. if(samples > 0) {
  99393. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  99394. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  99395. }
  99396. return true;
  99397. }
  99398. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  99399. {
  99400. FLAC__StreamEncoderWriteStatus status;
  99401. FLAC__uint64 output_position = 0;
  99402. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  99403. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  99404. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99405. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  99406. }
  99407. /*
  99408. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  99409. */
  99410. if(samples == 0) {
  99411. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  99412. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  99413. encoder->protected_->streaminfo_offset = output_position;
  99414. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  99415. encoder->protected_->seektable_offset = output_position;
  99416. }
  99417. /*
  99418. * Mark the current seek point if hit (if audio_offset == 0 that
  99419. * means we're still writing metadata and haven't hit the first
  99420. * frame yet)
  99421. */
  99422. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  99423. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  99424. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  99425. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  99426. FLAC__uint64 test_sample;
  99427. unsigned i;
  99428. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  99429. test_sample = encoder->private_->seek_table->points[i].sample_number;
  99430. if(test_sample > frame_last_sample) {
  99431. break;
  99432. }
  99433. else if(test_sample >= frame_first_sample) {
  99434. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  99435. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  99436. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  99437. encoder->private_->first_seekpoint_to_check++;
  99438. /* DO NOT: "break;" and here's why:
  99439. * The seektable template may contain more than one target
  99440. * sample for any given frame; we will keep looping, generating
  99441. * duplicate seekpoints for them, and we'll clean it up later,
  99442. * just before writing the seektable back to the metadata.
  99443. */
  99444. }
  99445. else {
  99446. encoder->private_->first_seekpoint_to_check++;
  99447. }
  99448. }
  99449. }
  99450. #if FLAC__HAS_OGG
  99451. if(encoder->private_->is_ogg) {
  99452. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  99453. &encoder->protected_->ogg_encoder_aspect,
  99454. buffer,
  99455. bytes,
  99456. samples,
  99457. encoder->private_->current_frame_number,
  99458. is_last_block,
  99459. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  99460. encoder,
  99461. encoder->private_->client_data
  99462. );
  99463. }
  99464. else
  99465. #endif
  99466. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  99467. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99468. encoder->private_->bytes_written += bytes;
  99469. encoder->private_->samples_written += samples;
  99470. /* we keep a high watermark on the number of frames written because
  99471. * when the encoder goes back to write metadata, 'current_frame'
  99472. * will drop back to 0.
  99473. */
  99474. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  99475. }
  99476. else
  99477. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99478. return status;
  99479. }
  99480. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  99481. void update_metadata_(const FLAC__StreamEncoder *encoder)
  99482. {
  99483. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  99484. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  99485. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  99486. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  99487. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  99488. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  99489. FLAC__StreamEncoderSeekStatus seek_status;
  99490. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  99491. /* All this is based on intimate knowledge of the stream header
  99492. * layout, but a change to the header format that would break this
  99493. * would also break all streams encoded in the previous format.
  99494. */
  99495. /*
  99496. * Write MD5 signature
  99497. */
  99498. {
  99499. const unsigned md5_offset =
  99500. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99501. (
  99502. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99503. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  99504. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  99505. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  99506. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  99507. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  99508. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  99509. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  99510. ) / 8;
  99511. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  99512. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  99513. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99514. return;
  99515. }
  99516. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99517. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99518. return;
  99519. }
  99520. }
  99521. /*
  99522. * Write total samples
  99523. */
  99524. {
  99525. const unsigned total_samples_byte_offset =
  99526. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99527. (
  99528. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99529. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  99530. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  99531. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  99532. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  99533. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  99534. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  99535. - 4
  99536. ) / 8;
  99537. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  99538. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  99539. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  99540. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  99541. b[4] = (FLAC__byte)(samples & 0xFF);
  99542. 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) {
  99543. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  99544. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99545. return;
  99546. }
  99547. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99548. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99549. return;
  99550. }
  99551. }
  99552. /*
  99553. * Write min/max framesize
  99554. */
  99555. {
  99556. const unsigned min_framesize_offset =
  99557. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99558. (
  99559. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99560. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  99561. ) / 8;
  99562. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  99563. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  99564. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  99565. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  99566. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  99567. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  99568. 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) {
  99569. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  99570. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99571. return;
  99572. }
  99573. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99574. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99575. return;
  99576. }
  99577. }
  99578. /*
  99579. * Write seektable
  99580. */
  99581. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  99582. unsigned i;
  99583. FLAC__format_seektable_sort(encoder->private_->seek_table);
  99584. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  99585. 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) {
  99586. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  99587. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99588. return;
  99589. }
  99590. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  99591. FLAC__uint64 xx;
  99592. unsigned x;
  99593. xx = encoder->private_->seek_table->points[i].sample_number;
  99594. b[7] = (FLAC__byte)xx; xx >>= 8;
  99595. b[6] = (FLAC__byte)xx; xx >>= 8;
  99596. b[5] = (FLAC__byte)xx; xx >>= 8;
  99597. b[4] = (FLAC__byte)xx; xx >>= 8;
  99598. b[3] = (FLAC__byte)xx; xx >>= 8;
  99599. b[2] = (FLAC__byte)xx; xx >>= 8;
  99600. b[1] = (FLAC__byte)xx; xx >>= 8;
  99601. b[0] = (FLAC__byte)xx; xx >>= 8;
  99602. xx = encoder->private_->seek_table->points[i].stream_offset;
  99603. b[15] = (FLAC__byte)xx; xx >>= 8;
  99604. b[14] = (FLAC__byte)xx; xx >>= 8;
  99605. b[13] = (FLAC__byte)xx; xx >>= 8;
  99606. b[12] = (FLAC__byte)xx; xx >>= 8;
  99607. b[11] = (FLAC__byte)xx; xx >>= 8;
  99608. b[10] = (FLAC__byte)xx; xx >>= 8;
  99609. b[9] = (FLAC__byte)xx; xx >>= 8;
  99610. b[8] = (FLAC__byte)xx; xx >>= 8;
  99611. x = encoder->private_->seek_table->points[i].frame_samples;
  99612. b[17] = (FLAC__byte)x; x >>= 8;
  99613. b[16] = (FLAC__byte)x; x >>= 8;
  99614. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99615. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99616. return;
  99617. }
  99618. }
  99619. }
  99620. }
  99621. #if FLAC__HAS_OGG
  99622. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  99623. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  99624. {
  99625. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  99626. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  99627. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  99628. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  99629. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  99630. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  99631. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  99632. FLAC__STREAM_SYNC_LENGTH
  99633. ;
  99634. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  99635. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  99636. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  99637. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  99638. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  99639. ogg_page page;
  99640. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  99641. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  99642. /* Pre-check that client supports seeking, since we don't want the
  99643. * ogg_helper code to ever have to deal with this condition.
  99644. */
  99645. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  99646. return;
  99647. /* All this is based on intimate knowledge of the stream header
  99648. * layout, but a change to the header format that would break this
  99649. * would also break all streams encoded in the previous format.
  99650. */
  99651. /**
  99652. ** Write STREAMINFO stats
  99653. **/
  99654. simple_ogg_page__init(&page);
  99655. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  99656. simple_ogg_page__clear(&page);
  99657. return; /* state already set */
  99658. }
  99659. /*
  99660. * Write MD5 signature
  99661. */
  99662. {
  99663. const unsigned md5_offset =
  99664. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  99665. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99666. (
  99667. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99668. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  99669. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  99670. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  99671. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  99672. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  99673. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  99674. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  99675. ) / 8;
  99676. if(md5_offset + 16 > (unsigned)page.body_len) {
  99677. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99678. simple_ogg_page__clear(&page);
  99679. return;
  99680. }
  99681. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  99682. }
  99683. /*
  99684. * Write total samples
  99685. */
  99686. {
  99687. const unsigned total_samples_byte_offset =
  99688. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  99689. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99690. (
  99691. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99692. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  99693. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  99694. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  99695. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  99696. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  99697. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  99698. - 4
  99699. ) / 8;
  99700. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  99701. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99702. simple_ogg_page__clear(&page);
  99703. return;
  99704. }
  99705. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  99706. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  99707. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  99708. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  99709. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  99710. b[4] = (FLAC__byte)(samples & 0xFF);
  99711. memcpy(page.body + total_samples_byte_offset, b, 5);
  99712. }
  99713. /*
  99714. * Write min/max framesize
  99715. */
  99716. {
  99717. const unsigned min_framesize_offset =
  99718. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  99719. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99720. (
  99721. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99722. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  99723. ) / 8;
  99724. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  99725. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99726. simple_ogg_page__clear(&page);
  99727. return;
  99728. }
  99729. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  99730. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  99731. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  99732. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  99733. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  99734. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  99735. memcpy(page.body + min_framesize_offset, b, 6);
  99736. }
  99737. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  99738. simple_ogg_page__clear(&page);
  99739. return; /* state already set */
  99740. }
  99741. simple_ogg_page__clear(&page);
  99742. /*
  99743. * Write seektable
  99744. */
  99745. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  99746. unsigned i;
  99747. FLAC__byte *p;
  99748. FLAC__format_seektable_sort(encoder->private_->seek_table);
  99749. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  99750. simple_ogg_page__init(&page);
  99751. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  99752. simple_ogg_page__clear(&page);
  99753. return; /* state already set */
  99754. }
  99755. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  99756. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99757. simple_ogg_page__clear(&page);
  99758. return;
  99759. }
  99760. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  99761. FLAC__uint64 xx;
  99762. unsigned x;
  99763. xx = encoder->private_->seek_table->points[i].sample_number;
  99764. b[7] = (FLAC__byte)xx; xx >>= 8;
  99765. b[6] = (FLAC__byte)xx; xx >>= 8;
  99766. b[5] = (FLAC__byte)xx; xx >>= 8;
  99767. b[4] = (FLAC__byte)xx; xx >>= 8;
  99768. b[3] = (FLAC__byte)xx; xx >>= 8;
  99769. b[2] = (FLAC__byte)xx; xx >>= 8;
  99770. b[1] = (FLAC__byte)xx; xx >>= 8;
  99771. b[0] = (FLAC__byte)xx; xx >>= 8;
  99772. xx = encoder->private_->seek_table->points[i].stream_offset;
  99773. b[15] = (FLAC__byte)xx; xx >>= 8;
  99774. b[14] = (FLAC__byte)xx; xx >>= 8;
  99775. b[13] = (FLAC__byte)xx; xx >>= 8;
  99776. b[12] = (FLAC__byte)xx; xx >>= 8;
  99777. b[11] = (FLAC__byte)xx; xx >>= 8;
  99778. b[10] = (FLAC__byte)xx; xx >>= 8;
  99779. b[9] = (FLAC__byte)xx; xx >>= 8;
  99780. b[8] = (FLAC__byte)xx; xx >>= 8;
  99781. x = encoder->private_->seek_table->points[i].frame_samples;
  99782. b[17] = (FLAC__byte)x; x >>= 8;
  99783. b[16] = (FLAC__byte)x; x >>= 8;
  99784. memcpy(p, b, 18);
  99785. }
  99786. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  99787. simple_ogg_page__clear(&page);
  99788. return; /* state already set */
  99789. }
  99790. simple_ogg_page__clear(&page);
  99791. }
  99792. }
  99793. #endif
  99794. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  99795. {
  99796. FLAC__uint16 crc;
  99797. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99798. /*
  99799. * Accumulate raw signal to the MD5 signature
  99800. */
  99801. 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)) {
  99802. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99803. return false;
  99804. }
  99805. /*
  99806. * Process the frame header and subframes into the frame bitbuffer
  99807. */
  99808. if(!process_subframes_(encoder, is_fractional_block)) {
  99809. /* the above function sets the state for us in case of an error */
  99810. return false;
  99811. }
  99812. /*
  99813. * Zero-pad the frame to a byte_boundary
  99814. */
  99815. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  99816. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99817. return false;
  99818. }
  99819. /*
  99820. * CRC-16 the whole thing
  99821. */
  99822. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  99823. if(
  99824. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  99825. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  99826. ) {
  99827. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99828. return false;
  99829. }
  99830. /*
  99831. * Write it
  99832. */
  99833. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  99834. /* the above function sets the state for us in case of an error */
  99835. return false;
  99836. }
  99837. /*
  99838. * Get ready for the next frame
  99839. */
  99840. encoder->private_->current_sample_number = 0;
  99841. encoder->private_->current_frame_number++;
  99842. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  99843. return true;
  99844. }
  99845. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  99846. {
  99847. FLAC__FrameHeader frame_header;
  99848. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  99849. FLAC__bool do_independent, do_mid_side;
  99850. /*
  99851. * Calculate the min,max Rice partition orders
  99852. */
  99853. if(is_fractional_block) {
  99854. max_partition_order = 0;
  99855. }
  99856. else {
  99857. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  99858. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  99859. }
  99860. min_partition_order = min(min_partition_order, max_partition_order);
  99861. /*
  99862. * Setup the frame
  99863. */
  99864. frame_header.blocksize = encoder->protected_->blocksize;
  99865. frame_header.sample_rate = encoder->protected_->sample_rate;
  99866. frame_header.channels = encoder->protected_->channels;
  99867. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  99868. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  99869. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  99870. frame_header.number.frame_number = encoder->private_->current_frame_number;
  99871. /*
  99872. * Figure out what channel assignments to try
  99873. */
  99874. if(encoder->protected_->do_mid_side_stereo) {
  99875. if(encoder->protected_->loose_mid_side_stereo) {
  99876. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  99877. do_independent = true;
  99878. do_mid_side = true;
  99879. }
  99880. else {
  99881. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  99882. do_mid_side = !do_independent;
  99883. }
  99884. }
  99885. else {
  99886. do_independent = true;
  99887. do_mid_side = true;
  99888. }
  99889. }
  99890. else {
  99891. do_independent = true;
  99892. do_mid_side = false;
  99893. }
  99894. FLAC__ASSERT(do_independent || do_mid_side);
  99895. /*
  99896. * Check for wasted bits; set effective bps for each subframe
  99897. */
  99898. if(do_independent) {
  99899. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99900. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  99901. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  99902. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  99903. }
  99904. }
  99905. if(do_mid_side) {
  99906. FLAC__ASSERT(encoder->protected_->channels == 2);
  99907. for(channel = 0; channel < 2; channel++) {
  99908. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  99909. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  99910. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  99911. }
  99912. }
  99913. /*
  99914. * First do a normal encoding pass of each independent channel
  99915. */
  99916. if(do_independent) {
  99917. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99918. if(!
  99919. process_subframe_(
  99920. encoder,
  99921. min_partition_order,
  99922. max_partition_order,
  99923. &frame_header,
  99924. encoder->private_->subframe_bps[channel],
  99925. encoder->private_->integer_signal[channel],
  99926. encoder->private_->subframe_workspace_ptr[channel],
  99927. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  99928. encoder->private_->residual_workspace[channel],
  99929. encoder->private_->best_subframe+channel,
  99930. encoder->private_->best_subframe_bits+channel
  99931. )
  99932. )
  99933. return false;
  99934. }
  99935. }
  99936. /*
  99937. * Now do mid and side channels if requested
  99938. */
  99939. if(do_mid_side) {
  99940. FLAC__ASSERT(encoder->protected_->channels == 2);
  99941. for(channel = 0; channel < 2; channel++) {
  99942. if(!
  99943. process_subframe_(
  99944. encoder,
  99945. min_partition_order,
  99946. max_partition_order,
  99947. &frame_header,
  99948. encoder->private_->subframe_bps_mid_side[channel],
  99949. encoder->private_->integer_signal_mid_side[channel],
  99950. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  99951. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  99952. encoder->private_->residual_workspace_mid_side[channel],
  99953. encoder->private_->best_subframe_mid_side+channel,
  99954. encoder->private_->best_subframe_bits_mid_side+channel
  99955. )
  99956. )
  99957. return false;
  99958. }
  99959. }
  99960. /*
  99961. * Compose the frame bitbuffer
  99962. */
  99963. if(do_mid_side) {
  99964. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  99965. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  99966. FLAC__ChannelAssignment channel_assignment;
  99967. FLAC__ASSERT(encoder->protected_->channels == 2);
  99968. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  99969. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  99970. }
  99971. else {
  99972. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  99973. unsigned min_bits;
  99974. int ca;
  99975. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  99976. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  99977. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  99978. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  99979. FLAC__ASSERT(do_independent && do_mid_side);
  99980. /* We have to figure out which channel assignent results in the smallest frame */
  99981. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  99982. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  99983. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  99984. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  99985. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  99986. min_bits = bits[channel_assignment];
  99987. for(ca = 1; ca <= 3; ca++) {
  99988. if(bits[ca] < min_bits) {
  99989. min_bits = bits[ca];
  99990. channel_assignment = (FLAC__ChannelAssignment)ca;
  99991. }
  99992. }
  99993. }
  99994. frame_header.channel_assignment = channel_assignment;
  99995. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  99996. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99997. return false;
  99998. }
  99999. switch(channel_assignment) {
  100000. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100001. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100002. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100003. break;
  100004. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100005. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100006. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100007. break;
  100008. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100009. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100010. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100011. break;
  100012. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100013. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  100014. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100015. break;
  100016. default:
  100017. FLAC__ASSERT(0);
  100018. }
  100019. switch(channel_assignment) {
  100020. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100021. left_bps = encoder->private_->subframe_bps [0];
  100022. right_bps = encoder->private_->subframe_bps [1];
  100023. break;
  100024. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100025. left_bps = encoder->private_->subframe_bps [0];
  100026. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100027. break;
  100028. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100029. left_bps = encoder->private_->subframe_bps_mid_side[1];
  100030. right_bps = encoder->private_->subframe_bps [1];
  100031. break;
  100032. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100033. left_bps = encoder->private_->subframe_bps_mid_side[0];
  100034. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100035. break;
  100036. default:
  100037. FLAC__ASSERT(0);
  100038. }
  100039. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  100040. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  100041. return false;
  100042. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  100043. return false;
  100044. }
  100045. else {
  100046. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100047. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100048. return false;
  100049. }
  100050. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100051. 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)) {
  100052. /* the above function sets the state for us in case of an error */
  100053. return false;
  100054. }
  100055. }
  100056. }
  100057. if(encoder->protected_->loose_mid_side_stereo) {
  100058. encoder->private_->loose_mid_side_stereo_frame_count++;
  100059. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  100060. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  100061. }
  100062. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  100063. return true;
  100064. }
  100065. FLAC__bool process_subframe_(
  100066. FLAC__StreamEncoder *encoder,
  100067. unsigned min_partition_order,
  100068. unsigned max_partition_order,
  100069. const FLAC__FrameHeader *frame_header,
  100070. unsigned subframe_bps,
  100071. const FLAC__int32 integer_signal[],
  100072. FLAC__Subframe *subframe[2],
  100073. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  100074. FLAC__int32 *residual[2],
  100075. unsigned *best_subframe,
  100076. unsigned *best_bits
  100077. )
  100078. {
  100079. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100080. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100081. #else
  100082. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100083. #endif
  100084. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100085. FLAC__double lpc_residual_bits_per_sample;
  100086. 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 */
  100087. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  100088. unsigned min_lpc_order, max_lpc_order, lpc_order;
  100089. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  100090. #endif
  100091. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  100092. unsigned rice_parameter;
  100093. unsigned _candidate_bits, _best_bits;
  100094. unsigned _best_subframe;
  100095. /* only use RICE2 partitions if stream bps > 16 */
  100096. 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;
  100097. FLAC__ASSERT(frame_header->blocksize > 0);
  100098. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  100099. _best_subframe = 0;
  100100. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  100101. _best_bits = UINT_MAX;
  100102. else
  100103. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100104. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  100105. unsigned signal_is_constant = false;
  100106. 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);
  100107. /* check for constant subframe */
  100108. if(
  100109. !encoder->private_->disable_constant_subframes &&
  100110. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100111. fixed_residual_bits_per_sample[1] == 0.0
  100112. #else
  100113. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  100114. #endif
  100115. ) {
  100116. /* the above means it's possible all samples are the same value; now double-check it: */
  100117. unsigned i;
  100118. signal_is_constant = true;
  100119. for(i = 1; i < frame_header->blocksize; i++) {
  100120. if(integer_signal[0] != integer_signal[i]) {
  100121. signal_is_constant = false;
  100122. break;
  100123. }
  100124. }
  100125. }
  100126. if(signal_is_constant) {
  100127. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  100128. if(_candidate_bits < _best_bits) {
  100129. _best_subframe = !_best_subframe;
  100130. _best_bits = _candidate_bits;
  100131. }
  100132. }
  100133. else {
  100134. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  100135. /* encode fixed */
  100136. if(encoder->protected_->do_exhaustive_model_search) {
  100137. min_fixed_order = 0;
  100138. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  100139. }
  100140. else {
  100141. min_fixed_order = max_fixed_order = guess_fixed_order;
  100142. }
  100143. if(max_fixed_order >= frame_header->blocksize)
  100144. max_fixed_order = frame_header->blocksize - 1;
  100145. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  100146. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100147. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  100148. continue; /* don't even try */
  100149. 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 */
  100150. #else
  100151. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  100152. continue; /* don't even try */
  100153. 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 */
  100154. #endif
  100155. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100156. if(rice_parameter >= rice_parameter_limit) {
  100157. #ifdef DEBUG_VERBOSE
  100158. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  100159. #endif
  100160. rice_parameter = rice_parameter_limit - 1;
  100161. }
  100162. _candidate_bits =
  100163. evaluate_fixed_subframe_(
  100164. encoder,
  100165. integer_signal,
  100166. residual[!_best_subframe],
  100167. encoder->private_->abs_residual_partition_sums,
  100168. encoder->private_->raw_bits_per_partition,
  100169. frame_header->blocksize,
  100170. subframe_bps,
  100171. fixed_order,
  100172. rice_parameter,
  100173. rice_parameter_limit,
  100174. min_partition_order,
  100175. max_partition_order,
  100176. encoder->protected_->do_escape_coding,
  100177. encoder->protected_->rice_parameter_search_dist,
  100178. subframe[!_best_subframe],
  100179. partitioned_rice_contents[!_best_subframe]
  100180. );
  100181. if(_candidate_bits < _best_bits) {
  100182. _best_subframe = !_best_subframe;
  100183. _best_bits = _candidate_bits;
  100184. }
  100185. }
  100186. }
  100187. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100188. /* encode lpc */
  100189. if(encoder->protected_->max_lpc_order > 0) {
  100190. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  100191. max_lpc_order = frame_header->blocksize-1;
  100192. else
  100193. max_lpc_order = encoder->protected_->max_lpc_order;
  100194. if(max_lpc_order > 0) {
  100195. unsigned a;
  100196. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  100197. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  100198. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  100199. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  100200. if(autoc[0] != 0.0) {
  100201. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  100202. if(encoder->protected_->do_exhaustive_model_search) {
  100203. min_lpc_order = 1;
  100204. }
  100205. else {
  100206. const unsigned guess_lpc_order =
  100207. FLAC__lpc_compute_best_order(
  100208. lpc_error,
  100209. max_lpc_order,
  100210. frame_header->blocksize,
  100211. subframe_bps + (
  100212. encoder->protected_->do_qlp_coeff_prec_search?
  100213. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  100214. encoder->protected_->qlp_coeff_precision
  100215. )
  100216. );
  100217. min_lpc_order = max_lpc_order = guess_lpc_order;
  100218. }
  100219. if(max_lpc_order >= frame_header->blocksize)
  100220. max_lpc_order = frame_header->blocksize - 1;
  100221. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  100222. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  100223. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  100224. continue; /* don't even try */
  100225. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  100226. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100227. if(rice_parameter >= rice_parameter_limit) {
  100228. #ifdef DEBUG_VERBOSE
  100229. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  100230. #endif
  100231. rice_parameter = rice_parameter_limit - 1;
  100232. }
  100233. if(encoder->protected_->do_qlp_coeff_prec_search) {
  100234. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  100235. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  100236. if(subframe_bps <= 17) {
  100237. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  100238. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  100239. }
  100240. else
  100241. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  100242. }
  100243. else {
  100244. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  100245. }
  100246. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  100247. _candidate_bits =
  100248. evaluate_lpc_subframe_(
  100249. encoder,
  100250. integer_signal,
  100251. residual[!_best_subframe],
  100252. encoder->private_->abs_residual_partition_sums,
  100253. encoder->private_->raw_bits_per_partition,
  100254. encoder->private_->lp_coeff[lpc_order-1],
  100255. frame_header->blocksize,
  100256. subframe_bps,
  100257. lpc_order,
  100258. qlp_coeff_precision,
  100259. rice_parameter,
  100260. rice_parameter_limit,
  100261. min_partition_order,
  100262. max_partition_order,
  100263. encoder->protected_->do_escape_coding,
  100264. encoder->protected_->rice_parameter_search_dist,
  100265. subframe[!_best_subframe],
  100266. partitioned_rice_contents[!_best_subframe]
  100267. );
  100268. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  100269. if(_candidate_bits < _best_bits) {
  100270. _best_subframe = !_best_subframe;
  100271. _best_bits = _candidate_bits;
  100272. }
  100273. }
  100274. }
  100275. }
  100276. }
  100277. }
  100278. }
  100279. }
  100280. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100281. }
  100282. }
  100283. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  100284. if(_best_bits == UINT_MAX) {
  100285. FLAC__ASSERT(_best_subframe == 0);
  100286. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100287. }
  100288. *best_subframe = _best_subframe;
  100289. *best_bits = _best_bits;
  100290. return true;
  100291. }
  100292. FLAC__bool add_subframe_(
  100293. FLAC__StreamEncoder *encoder,
  100294. unsigned blocksize,
  100295. unsigned subframe_bps,
  100296. const FLAC__Subframe *subframe,
  100297. FLAC__BitWriter *frame
  100298. )
  100299. {
  100300. switch(subframe->type) {
  100301. case FLAC__SUBFRAME_TYPE_CONSTANT:
  100302. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  100303. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100304. return false;
  100305. }
  100306. break;
  100307. case FLAC__SUBFRAME_TYPE_FIXED:
  100308. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  100309. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100310. return false;
  100311. }
  100312. break;
  100313. case FLAC__SUBFRAME_TYPE_LPC:
  100314. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  100315. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100316. return false;
  100317. }
  100318. break;
  100319. case FLAC__SUBFRAME_TYPE_VERBATIM:
  100320. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  100321. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100322. return false;
  100323. }
  100324. break;
  100325. default:
  100326. FLAC__ASSERT(0);
  100327. }
  100328. return true;
  100329. }
  100330. #define SPOTCHECK_ESTIMATE 0
  100331. #if SPOTCHECK_ESTIMATE
  100332. static void spotcheck_subframe_estimate_(
  100333. FLAC__StreamEncoder *encoder,
  100334. unsigned blocksize,
  100335. unsigned subframe_bps,
  100336. const FLAC__Subframe *subframe,
  100337. unsigned estimate
  100338. )
  100339. {
  100340. FLAC__bool ret;
  100341. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  100342. if(frame == 0) {
  100343. fprintf(stderr, "EST: can't allocate frame\n");
  100344. return;
  100345. }
  100346. if(!FLAC__bitwriter_init(frame)) {
  100347. fprintf(stderr, "EST: can't init frame\n");
  100348. return;
  100349. }
  100350. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  100351. FLAC__ASSERT(ret);
  100352. {
  100353. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  100354. if(estimate != actual)
  100355. 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);
  100356. }
  100357. FLAC__bitwriter_delete(frame);
  100358. }
  100359. #endif
  100360. unsigned evaluate_constant_subframe_(
  100361. FLAC__StreamEncoder *encoder,
  100362. const FLAC__int32 signal,
  100363. unsigned blocksize,
  100364. unsigned subframe_bps,
  100365. FLAC__Subframe *subframe
  100366. )
  100367. {
  100368. unsigned estimate;
  100369. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100370. subframe->data.constant.value = signal;
  100371. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  100372. #if SPOTCHECK_ESTIMATE
  100373. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100374. #else
  100375. (void)encoder, (void)blocksize;
  100376. #endif
  100377. return estimate;
  100378. }
  100379. unsigned evaluate_fixed_subframe_(
  100380. FLAC__StreamEncoder *encoder,
  100381. const FLAC__int32 signal[],
  100382. FLAC__int32 residual[],
  100383. FLAC__uint64 abs_residual_partition_sums[],
  100384. unsigned raw_bits_per_partition[],
  100385. unsigned blocksize,
  100386. unsigned subframe_bps,
  100387. unsigned order,
  100388. unsigned rice_parameter,
  100389. unsigned rice_parameter_limit,
  100390. unsigned min_partition_order,
  100391. unsigned max_partition_order,
  100392. FLAC__bool do_escape_coding,
  100393. unsigned rice_parameter_search_dist,
  100394. FLAC__Subframe *subframe,
  100395. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  100396. )
  100397. {
  100398. unsigned i, residual_bits, estimate;
  100399. const unsigned residual_samples = blocksize - order;
  100400. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  100401. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  100402. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  100403. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  100404. subframe->data.fixed.residual = residual;
  100405. residual_bits =
  100406. find_best_partition_order_(
  100407. encoder->private_,
  100408. residual,
  100409. abs_residual_partition_sums,
  100410. raw_bits_per_partition,
  100411. residual_samples,
  100412. order,
  100413. rice_parameter,
  100414. rice_parameter_limit,
  100415. min_partition_order,
  100416. max_partition_order,
  100417. subframe_bps,
  100418. do_escape_coding,
  100419. rice_parameter_search_dist,
  100420. &subframe->data.fixed.entropy_coding_method
  100421. );
  100422. subframe->data.fixed.order = order;
  100423. for(i = 0; i < order; i++)
  100424. subframe->data.fixed.warmup[i] = signal[i];
  100425. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  100426. #if SPOTCHECK_ESTIMATE
  100427. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100428. #endif
  100429. return estimate;
  100430. }
  100431. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100432. unsigned evaluate_lpc_subframe_(
  100433. FLAC__StreamEncoder *encoder,
  100434. const FLAC__int32 signal[],
  100435. FLAC__int32 residual[],
  100436. FLAC__uint64 abs_residual_partition_sums[],
  100437. unsigned raw_bits_per_partition[],
  100438. const FLAC__real lp_coeff[],
  100439. unsigned blocksize,
  100440. unsigned subframe_bps,
  100441. unsigned order,
  100442. unsigned qlp_coeff_precision,
  100443. unsigned rice_parameter,
  100444. unsigned rice_parameter_limit,
  100445. unsigned min_partition_order,
  100446. unsigned max_partition_order,
  100447. FLAC__bool do_escape_coding,
  100448. unsigned rice_parameter_search_dist,
  100449. FLAC__Subframe *subframe,
  100450. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  100451. )
  100452. {
  100453. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  100454. unsigned i, residual_bits, estimate;
  100455. int quantization, ret;
  100456. const unsigned residual_samples = blocksize - order;
  100457. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  100458. if(subframe_bps <= 16) {
  100459. FLAC__ASSERT(order > 0);
  100460. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  100461. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  100462. }
  100463. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  100464. if(ret != 0)
  100465. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  100466. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100467. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  100468. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100469. else
  100470. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100471. else
  100472. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100473. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  100474. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  100475. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  100476. subframe->data.lpc.residual = residual;
  100477. residual_bits =
  100478. find_best_partition_order_(
  100479. encoder->private_,
  100480. residual,
  100481. abs_residual_partition_sums,
  100482. raw_bits_per_partition,
  100483. residual_samples,
  100484. order,
  100485. rice_parameter,
  100486. rice_parameter_limit,
  100487. min_partition_order,
  100488. max_partition_order,
  100489. subframe_bps,
  100490. do_escape_coding,
  100491. rice_parameter_search_dist,
  100492. &subframe->data.lpc.entropy_coding_method
  100493. );
  100494. subframe->data.lpc.order = order;
  100495. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  100496. subframe->data.lpc.quantization_level = quantization;
  100497. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  100498. for(i = 0; i < order; i++)
  100499. subframe->data.lpc.warmup[i] = signal[i];
  100500. 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;
  100501. #if SPOTCHECK_ESTIMATE
  100502. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100503. #endif
  100504. return estimate;
  100505. }
  100506. #endif
  100507. unsigned evaluate_verbatim_subframe_(
  100508. FLAC__StreamEncoder *encoder,
  100509. const FLAC__int32 signal[],
  100510. unsigned blocksize,
  100511. unsigned subframe_bps,
  100512. FLAC__Subframe *subframe
  100513. )
  100514. {
  100515. unsigned estimate;
  100516. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100517. subframe->data.verbatim.data = signal;
  100518. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  100519. #if SPOTCHECK_ESTIMATE
  100520. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100521. #else
  100522. (void)encoder;
  100523. #endif
  100524. return estimate;
  100525. }
  100526. unsigned find_best_partition_order_(
  100527. FLAC__StreamEncoderPrivate *private_,
  100528. const FLAC__int32 residual[],
  100529. FLAC__uint64 abs_residual_partition_sums[],
  100530. unsigned raw_bits_per_partition[],
  100531. unsigned residual_samples,
  100532. unsigned predictor_order,
  100533. unsigned rice_parameter,
  100534. unsigned rice_parameter_limit,
  100535. unsigned min_partition_order,
  100536. unsigned max_partition_order,
  100537. unsigned bps,
  100538. FLAC__bool do_escape_coding,
  100539. unsigned rice_parameter_search_dist,
  100540. FLAC__EntropyCodingMethod *best_ecm
  100541. )
  100542. {
  100543. unsigned residual_bits, best_residual_bits = 0;
  100544. unsigned best_parameters_index = 0;
  100545. unsigned best_partition_order = 0;
  100546. const unsigned blocksize = residual_samples + predictor_order;
  100547. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  100548. min_partition_order = min(min_partition_order, max_partition_order);
  100549. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  100550. if(do_escape_coding)
  100551. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  100552. {
  100553. int partition_order;
  100554. unsigned sum;
  100555. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  100556. if(!
  100557. set_partitioned_rice_(
  100558. #ifdef EXACT_RICE_BITS_CALCULATION
  100559. residual,
  100560. #endif
  100561. abs_residual_partition_sums+sum,
  100562. raw_bits_per_partition+sum,
  100563. residual_samples,
  100564. predictor_order,
  100565. rice_parameter,
  100566. rice_parameter_limit,
  100567. rice_parameter_search_dist,
  100568. (unsigned)partition_order,
  100569. do_escape_coding,
  100570. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  100571. &residual_bits
  100572. )
  100573. )
  100574. {
  100575. FLAC__ASSERT(best_residual_bits != 0);
  100576. break;
  100577. }
  100578. sum += 1u << partition_order;
  100579. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  100580. best_residual_bits = residual_bits;
  100581. best_parameters_index = !best_parameters_index;
  100582. best_partition_order = partition_order;
  100583. }
  100584. }
  100585. }
  100586. best_ecm->data.partitioned_rice.order = best_partition_order;
  100587. {
  100588. /*
  100589. * We are allowed to de-const the pointer based on our special
  100590. * knowledge; it is const to the outside world.
  100591. */
  100592. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  100593. unsigned partition;
  100594. /* save best parameters and raw_bits */
  100595. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  100596. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  100597. if(do_escape_coding)
  100598. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  100599. /*
  100600. * Now need to check if the type should be changed to
  100601. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  100602. * size of the rice parameters.
  100603. */
  100604. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  100605. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  100606. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  100607. break;
  100608. }
  100609. }
  100610. }
  100611. return best_residual_bits;
  100612. }
  100613. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  100614. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  100615. const FLAC__int32 residual[],
  100616. FLAC__uint64 abs_residual_partition_sums[],
  100617. unsigned blocksize,
  100618. unsigned predictor_order,
  100619. unsigned min_partition_order,
  100620. unsigned max_partition_order
  100621. );
  100622. #endif
  100623. void precompute_partition_info_sums_(
  100624. const FLAC__int32 residual[],
  100625. FLAC__uint64 abs_residual_partition_sums[],
  100626. unsigned residual_samples,
  100627. unsigned predictor_order,
  100628. unsigned min_partition_order,
  100629. unsigned max_partition_order,
  100630. unsigned bps
  100631. )
  100632. {
  100633. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  100634. unsigned partitions = 1u << max_partition_order;
  100635. FLAC__ASSERT(default_partition_samples > predictor_order);
  100636. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  100637. /* slightly pessimistic but still catches all common cases */
  100638. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  100639. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  100640. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  100641. return;
  100642. }
  100643. #endif
  100644. /* first do max_partition_order */
  100645. {
  100646. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  100647. /* slightly pessimistic but still catches all common cases */
  100648. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  100649. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  100650. FLAC__uint32 abs_residual_partition_sum;
  100651. for(partition = residual_sample = 0; partition < partitions; partition++) {
  100652. end += default_partition_samples;
  100653. abs_residual_partition_sum = 0;
  100654. for( ; residual_sample < end; residual_sample++)
  100655. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  100656. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  100657. }
  100658. }
  100659. else { /* have to pessimistically use 64 bits for accumulator */
  100660. FLAC__uint64 abs_residual_partition_sum;
  100661. for(partition = residual_sample = 0; partition < partitions; partition++) {
  100662. end += default_partition_samples;
  100663. abs_residual_partition_sum = 0;
  100664. for( ; residual_sample < end; residual_sample++)
  100665. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  100666. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  100667. }
  100668. }
  100669. }
  100670. /* now merge partitions for lower orders */
  100671. {
  100672. unsigned from_partition = 0, to_partition = partitions;
  100673. int partition_order;
  100674. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  100675. unsigned i;
  100676. partitions >>= 1;
  100677. for(i = 0; i < partitions; i++) {
  100678. abs_residual_partition_sums[to_partition++] =
  100679. abs_residual_partition_sums[from_partition ] +
  100680. abs_residual_partition_sums[from_partition+1];
  100681. from_partition += 2;
  100682. }
  100683. }
  100684. }
  100685. }
  100686. void precompute_partition_info_escapes_(
  100687. const FLAC__int32 residual[],
  100688. unsigned raw_bits_per_partition[],
  100689. unsigned residual_samples,
  100690. unsigned predictor_order,
  100691. unsigned min_partition_order,
  100692. unsigned max_partition_order
  100693. )
  100694. {
  100695. int partition_order;
  100696. unsigned from_partition, to_partition = 0;
  100697. const unsigned blocksize = residual_samples + predictor_order;
  100698. /* first do max_partition_order */
  100699. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  100700. FLAC__int32 r;
  100701. FLAC__uint32 rmax;
  100702. unsigned partition, partition_sample, partition_samples, residual_sample;
  100703. const unsigned partitions = 1u << partition_order;
  100704. const unsigned default_partition_samples = blocksize >> partition_order;
  100705. FLAC__ASSERT(default_partition_samples > predictor_order);
  100706. for(partition = residual_sample = 0; partition < partitions; partition++) {
  100707. partition_samples = default_partition_samples;
  100708. if(partition == 0)
  100709. partition_samples -= predictor_order;
  100710. rmax = 0;
  100711. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  100712. r = residual[residual_sample++];
  100713. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  100714. if(r < 0)
  100715. rmax |= ~r;
  100716. else
  100717. rmax |= r;
  100718. }
  100719. /* now we know all residual values are in the range [-rmax-1,rmax] */
  100720. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  100721. }
  100722. to_partition = partitions;
  100723. break; /*@@@ yuck, should remove the 'for' loop instead */
  100724. }
  100725. /* now merge partitions for lower orders */
  100726. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  100727. unsigned m;
  100728. unsigned i;
  100729. const unsigned partitions = 1u << partition_order;
  100730. for(i = 0; i < partitions; i++) {
  100731. m = raw_bits_per_partition[from_partition];
  100732. from_partition++;
  100733. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  100734. from_partition++;
  100735. to_partition++;
  100736. }
  100737. }
  100738. }
  100739. #ifdef EXACT_RICE_BITS_CALCULATION
  100740. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  100741. const unsigned rice_parameter,
  100742. const unsigned partition_samples,
  100743. const FLAC__int32 *residual
  100744. )
  100745. {
  100746. unsigned i, partition_bits =
  100747. 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 */
  100748. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  100749. ;
  100750. for(i = 0; i < partition_samples; i++)
  100751. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  100752. return partition_bits;
  100753. }
  100754. #else
  100755. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  100756. const unsigned rice_parameter,
  100757. const unsigned partition_samples,
  100758. const FLAC__uint64 abs_residual_partition_sum
  100759. )
  100760. {
  100761. return
  100762. 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 */
  100763. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  100764. (
  100765. rice_parameter?
  100766. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  100767. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  100768. )
  100769. - (partition_samples >> 1)
  100770. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  100771. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  100772. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  100773. * So the subtraction term tries to guess how many extra bits were contributed.
  100774. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  100775. */
  100776. ;
  100777. }
  100778. #endif
  100779. FLAC__bool set_partitioned_rice_(
  100780. #ifdef EXACT_RICE_BITS_CALCULATION
  100781. const FLAC__int32 residual[],
  100782. #endif
  100783. const FLAC__uint64 abs_residual_partition_sums[],
  100784. const unsigned raw_bits_per_partition[],
  100785. const unsigned residual_samples,
  100786. const unsigned predictor_order,
  100787. const unsigned suggested_rice_parameter,
  100788. const unsigned rice_parameter_limit,
  100789. const unsigned rice_parameter_search_dist,
  100790. const unsigned partition_order,
  100791. const FLAC__bool search_for_escapes,
  100792. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  100793. unsigned *bits
  100794. )
  100795. {
  100796. unsigned rice_parameter, partition_bits;
  100797. unsigned best_partition_bits, best_rice_parameter = 0;
  100798. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  100799. unsigned *parameters, *raw_bits;
  100800. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100801. unsigned min_rice_parameter, max_rice_parameter;
  100802. #else
  100803. (void)rice_parameter_search_dist;
  100804. #endif
  100805. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  100806. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  100807. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  100808. parameters = partitioned_rice_contents->parameters;
  100809. raw_bits = partitioned_rice_contents->raw_bits;
  100810. if(partition_order == 0) {
  100811. best_partition_bits = (unsigned)(-1);
  100812. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100813. if(rice_parameter_search_dist) {
  100814. if(suggested_rice_parameter < rice_parameter_search_dist)
  100815. min_rice_parameter = 0;
  100816. else
  100817. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  100818. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  100819. if(max_rice_parameter >= rice_parameter_limit) {
  100820. #ifdef DEBUG_VERBOSE
  100821. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  100822. #endif
  100823. max_rice_parameter = rice_parameter_limit - 1;
  100824. }
  100825. }
  100826. else
  100827. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  100828. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  100829. #else
  100830. rice_parameter = suggested_rice_parameter;
  100831. #endif
  100832. #ifdef EXACT_RICE_BITS_CALCULATION
  100833. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  100834. #else
  100835. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  100836. #endif
  100837. if(partition_bits < best_partition_bits) {
  100838. best_rice_parameter = rice_parameter;
  100839. best_partition_bits = partition_bits;
  100840. }
  100841. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100842. }
  100843. #endif
  100844. if(search_for_escapes) {
  100845. 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;
  100846. if(partition_bits <= best_partition_bits) {
  100847. raw_bits[0] = raw_bits_per_partition[0];
  100848. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  100849. best_partition_bits = partition_bits;
  100850. }
  100851. else
  100852. raw_bits[0] = 0;
  100853. }
  100854. parameters[0] = best_rice_parameter;
  100855. bits_ += best_partition_bits;
  100856. }
  100857. else {
  100858. unsigned partition, residual_sample;
  100859. unsigned partition_samples;
  100860. FLAC__uint64 mean, k;
  100861. const unsigned partitions = 1u << partition_order;
  100862. for(partition = residual_sample = 0; partition < partitions; partition++) {
  100863. partition_samples = (residual_samples+predictor_order) >> partition_order;
  100864. if(partition == 0) {
  100865. if(partition_samples <= predictor_order)
  100866. return false;
  100867. else
  100868. partition_samples -= predictor_order;
  100869. }
  100870. mean = abs_residual_partition_sums[partition];
  100871. /* we are basically calculating the size in bits of the
  100872. * average residual magnitude in the partition:
  100873. * rice_parameter = floor(log2(mean/partition_samples))
  100874. * 'mean' is not a good name for the variable, it is
  100875. * actually the sum of magnitudes of all residual values
  100876. * in the partition, so the actual mean is
  100877. * mean/partition_samples
  100878. */
  100879. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  100880. ;
  100881. if(rice_parameter >= rice_parameter_limit) {
  100882. #ifdef DEBUG_VERBOSE
  100883. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  100884. #endif
  100885. rice_parameter = rice_parameter_limit - 1;
  100886. }
  100887. best_partition_bits = (unsigned)(-1);
  100888. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100889. if(rice_parameter_search_dist) {
  100890. if(rice_parameter < rice_parameter_search_dist)
  100891. min_rice_parameter = 0;
  100892. else
  100893. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  100894. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  100895. if(max_rice_parameter >= rice_parameter_limit) {
  100896. #ifdef DEBUG_VERBOSE
  100897. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  100898. #endif
  100899. max_rice_parameter = rice_parameter_limit - 1;
  100900. }
  100901. }
  100902. else
  100903. min_rice_parameter = max_rice_parameter = rice_parameter;
  100904. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  100905. #endif
  100906. #ifdef EXACT_RICE_BITS_CALCULATION
  100907. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  100908. #else
  100909. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  100910. #endif
  100911. if(partition_bits < best_partition_bits) {
  100912. best_rice_parameter = rice_parameter;
  100913. best_partition_bits = partition_bits;
  100914. }
  100915. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100916. }
  100917. #endif
  100918. if(search_for_escapes) {
  100919. 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;
  100920. if(partition_bits <= best_partition_bits) {
  100921. raw_bits[partition] = raw_bits_per_partition[partition];
  100922. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  100923. best_partition_bits = partition_bits;
  100924. }
  100925. else
  100926. raw_bits[partition] = 0;
  100927. }
  100928. parameters[partition] = best_rice_parameter;
  100929. bits_ += best_partition_bits;
  100930. residual_sample += partition_samples;
  100931. }
  100932. }
  100933. *bits = bits_;
  100934. return true;
  100935. }
  100936. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  100937. {
  100938. unsigned i, shift;
  100939. FLAC__int32 x = 0;
  100940. for(i = 0; i < samples && !(x&1); i++)
  100941. x |= signal[i];
  100942. if(x == 0) {
  100943. shift = 0;
  100944. }
  100945. else {
  100946. for(shift = 0; !(x&1); shift++)
  100947. x >>= 1;
  100948. }
  100949. if(shift > 0) {
  100950. for(i = 0; i < samples; i++)
  100951. signal[i] >>= shift;
  100952. }
  100953. return shift;
  100954. }
  100955. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  100956. {
  100957. unsigned channel;
  100958. for(channel = 0; channel < channels; channel++)
  100959. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  100960. fifo->tail += wide_samples;
  100961. FLAC__ASSERT(fifo->tail <= fifo->size);
  100962. }
  100963. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  100964. {
  100965. unsigned channel;
  100966. unsigned sample, wide_sample;
  100967. unsigned tail = fifo->tail;
  100968. sample = input_offset * channels;
  100969. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  100970. for(channel = 0; channel < channels; channel++)
  100971. fifo->data[channel][tail] = input[sample++];
  100972. tail++;
  100973. }
  100974. fifo->tail = tail;
  100975. FLAC__ASSERT(fifo->tail <= fifo->size);
  100976. }
  100977. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100978. {
  100979. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  100980. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  100981. (void)decoder;
  100982. if(encoder->private_->verify.needs_magic_hack) {
  100983. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  100984. *bytes = FLAC__STREAM_SYNC_LENGTH;
  100985. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  100986. encoder->private_->verify.needs_magic_hack = false;
  100987. }
  100988. else {
  100989. if(encoded_bytes == 0) {
  100990. /*
  100991. * If we get here, a FIFO underflow has occurred,
  100992. * which means there is a bug somewhere.
  100993. */
  100994. FLAC__ASSERT(0);
  100995. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100996. }
  100997. else if(encoded_bytes < *bytes)
  100998. *bytes = encoded_bytes;
  100999. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  101000. encoder->private_->verify.output.data += *bytes;
  101001. encoder->private_->verify.output.bytes -= *bytes;
  101002. }
  101003. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101004. }
  101005. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  101006. {
  101007. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  101008. unsigned channel;
  101009. const unsigned channels = frame->header.channels;
  101010. const unsigned blocksize = frame->header.blocksize;
  101011. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  101012. (void)decoder;
  101013. for(channel = 0; channel < channels; channel++) {
  101014. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  101015. unsigned i, sample = 0;
  101016. FLAC__int32 expect = 0, got = 0;
  101017. for(i = 0; i < blocksize; i++) {
  101018. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  101019. sample = i;
  101020. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  101021. got = (FLAC__int32)buffer[channel][i];
  101022. break;
  101023. }
  101024. }
  101025. FLAC__ASSERT(i < blocksize);
  101026. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101027. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  101028. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  101029. encoder->private_->verify.error_stats.channel = channel;
  101030. encoder->private_->verify.error_stats.sample = sample;
  101031. encoder->private_->verify.error_stats.expected = expect;
  101032. encoder->private_->verify.error_stats.got = got;
  101033. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  101034. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101035. }
  101036. }
  101037. /* dequeue the frame from the fifo */
  101038. encoder->private_->verify.input_fifo.tail -= blocksize;
  101039. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  101040. for(channel = 0; channel < channels; channel++)
  101041. 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]));
  101042. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101043. }
  101044. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  101045. {
  101046. (void)decoder, (void)metadata, (void)client_data;
  101047. }
  101048. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  101049. {
  101050. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101051. (void)decoder, (void)status;
  101052. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101053. }
  101054. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101055. {
  101056. (void)client_data;
  101057. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  101058. if (*bytes == 0) {
  101059. if (feof(encoder->private_->file))
  101060. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  101061. else if (ferror(encoder->private_->file))
  101062. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  101063. }
  101064. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  101065. }
  101066. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101067. {
  101068. (void)client_data;
  101069. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101070. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  101071. else
  101072. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  101073. }
  101074. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101075. {
  101076. off_t offset;
  101077. (void)client_data;
  101078. offset = ftello(encoder->private_->file);
  101079. if(offset < 0) {
  101080. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  101081. }
  101082. else {
  101083. *absolute_byte_offset = (FLAC__uint64)offset;
  101084. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  101085. }
  101086. }
  101087. #ifdef FLAC__VALGRIND_TESTING
  101088. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  101089. {
  101090. size_t ret = fwrite(ptr, size, nmemb, stream);
  101091. if(!ferror(stream))
  101092. fflush(stream);
  101093. return ret;
  101094. }
  101095. #else
  101096. #define local__fwrite fwrite
  101097. #endif
  101098. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  101099. {
  101100. (void)client_data, (void)current_frame;
  101101. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  101102. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  101103. #if FLAC__HAS_OGG
  101104. /* We would like to be able to use 'samples > 0' in the
  101105. * clause here but currently because of the nature of our
  101106. * Ogg writing implementation, 'samples' is always 0 (see
  101107. * ogg_encoder_aspect.c). The downside is extra progress
  101108. * callbacks.
  101109. */
  101110. encoder->private_->is_ogg? true :
  101111. #endif
  101112. samples > 0
  101113. );
  101114. if(call_it) {
  101115. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  101116. * because at this point in the callback chain, the stats
  101117. * have not been updated. Only after we return and control
  101118. * gets back to write_frame_() are the stats updated
  101119. */
  101120. 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);
  101121. }
  101122. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  101123. }
  101124. else
  101125. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101126. }
  101127. /*
  101128. * This will forcibly set stdout to binary mode (for OSes that require it)
  101129. */
  101130. FILE *get_binary_stdout_(void)
  101131. {
  101132. /* if something breaks here it is probably due to the presence or
  101133. * absence of an underscore before the identifiers 'setmode',
  101134. * 'fileno', and/or 'O_BINARY'; check your system header files.
  101135. */
  101136. #if defined _MSC_VER || defined __MINGW32__
  101137. _setmode(_fileno(stdout), _O_BINARY);
  101138. #elif defined __CYGWIN__
  101139. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  101140. setmode(_fileno(stdout), _O_BINARY);
  101141. #elif defined __EMX__
  101142. setmode(fileno(stdout), O_BINARY);
  101143. #endif
  101144. return stdout;
  101145. }
  101146. #endif
  101147. /********* End of inlined file: stream_encoder.c *********/
  101148. /********* Start of inlined file: stream_encoder_framing.c *********/
  101149. /********* Start of inlined file: juce_FlacHeader.h *********/
  101150. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101151. // tasks..
  101152. #define VERSION "1.2.1"
  101153. #define FLAC__NO_DLL 1
  101154. #ifdef _MSC_VER
  101155. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101156. #endif
  101157. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  101158. #define FLAC__SYS_DARWIN 1
  101159. #endif
  101160. /********* End of inlined file: juce_FlacHeader.h *********/
  101161. #if JUCE_USE_FLAC
  101162. #if HAVE_CONFIG_H
  101163. # include <config.h>
  101164. #endif
  101165. #include <stdio.h>
  101166. #include <string.h> /* for strlen() */
  101167. #ifdef max
  101168. #undef max
  101169. #endif
  101170. #define max(x,y) ((x)>(y)?(x):(y))
  101171. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  101172. 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);
  101173. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  101174. {
  101175. unsigned i, j;
  101176. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  101177. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  101178. return false;
  101179. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  101180. return false;
  101181. /*
  101182. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  101183. */
  101184. i = metadata->length;
  101185. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101186. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  101187. i -= metadata->data.vorbis_comment.vendor_string.length;
  101188. i += vendor_string_length;
  101189. }
  101190. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  101191. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  101192. return false;
  101193. switch(metadata->type) {
  101194. case FLAC__METADATA_TYPE_STREAMINFO:
  101195. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  101196. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  101197. return false;
  101198. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  101199. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  101200. return false;
  101201. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  101202. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  101203. return false;
  101204. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  101205. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  101206. return false;
  101207. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  101208. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  101209. return false;
  101210. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  101211. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  101212. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  101213. return false;
  101214. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  101215. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101216. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  101217. return false;
  101218. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  101219. return false;
  101220. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  101221. return false;
  101222. break;
  101223. case FLAC__METADATA_TYPE_PADDING:
  101224. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  101225. return false;
  101226. break;
  101227. case FLAC__METADATA_TYPE_APPLICATION:
  101228. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  101229. return false;
  101230. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  101231. return false;
  101232. break;
  101233. case FLAC__METADATA_TYPE_SEEKTABLE:
  101234. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  101235. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  101236. return false;
  101237. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  101238. return false;
  101239. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  101240. return false;
  101241. }
  101242. break;
  101243. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  101244. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  101245. return false;
  101246. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  101247. return false;
  101248. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  101249. return false;
  101250. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  101251. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  101252. return false;
  101253. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  101254. return false;
  101255. }
  101256. break;
  101257. case FLAC__METADATA_TYPE_CUESHEET:
  101258. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  101259. 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))
  101260. return false;
  101261. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  101262. return false;
  101263. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  101264. return false;
  101265. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  101266. return false;
  101267. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  101268. return false;
  101269. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  101270. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  101271. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  101272. return false;
  101273. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  101274. return false;
  101275. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  101276. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  101277. return false;
  101278. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  101279. return false;
  101280. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  101281. return false;
  101282. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  101283. return false;
  101284. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  101285. return false;
  101286. for(j = 0; j < track->num_indices; j++) {
  101287. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  101288. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  101289. return false;
  101290. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  101291. return false;
  101292. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  101293. return false;
  101294. }
  101295. }
  101296. break;
  101297. case FLAC__METADATA_TYPE_PICTURE:
  101298. {
  101299. size_t len;
  101300. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  101301. return false;
  101302. len = strlen(metadata->data.picture.mime_type);
  101303. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  101304. return false;
  101305. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  101306. return false;
  101307. len = strlen((const char *)metadata->data.picture.description);
  101308. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  101309. return false;
  101310. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  101311. return false;
  101312. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  101313. return false;
  101314. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  101315. return false;
  101316. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  101317. return false;
  101318. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  101319. return false;
  101320. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  101321. return false;
  101322. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  101323. return false;
  101324. }
  101325. break;
  101326. default:
  101327. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  101328. return false;
  101329. break;
  101330. }
  101331. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101332. return true;
  101333. }
  101334. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  101335. {
  101336. unsigned u, blocksize_hint, sample_rate_hint;
  101337. FLAC__byte crc;
  101338. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101339. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  101340. return false;
  101341. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  101342. return false;
  101343. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  101344. return false;
  101345. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  101346. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  101347. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  101348. blocksize_hint = 0;
  101349. switch(header->blocksize) {
  101350. case 192: u = 1; break;
  101351. case 576: u = 2; break;
  101352. case 1152: u = 3; break;
  101353. case 2304: u = 4; break;
  101354. case 4608: u = 5; break;
  101355. case 256: u = 8; break;
  101356. case 512: u = 9; break;
  101357. case 1024: u = 10; break;
  101358. case 2048: u = 11; break;
  101359. case 4096: u = 12; break;
  101360. case 8192: u = 13; break;
  101361. case 16384: u = 14; break;
  101362. case 32768: u = 15; break;
  101363. default:
  101364. if(header->blocksize <= 0x100)
  101365. blocksize_hint = u = 6;
  101366. else
  101367. blocksize_hint = u = 7;
  101368. break;
  101369. }
  101370. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  101371. return false;
  101372. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  101373. sample_rate_hint = 0;
  101374. switch(header->sample_rate) {
  101375. case 88200: u = 1; break;
  101376. case 176400: u = 2; break;
  101377. case 192000: u = 3; break;
  101378. case 8000: u = 4; break;
  101379. case 16000: u = 5; break;
  101380. case 22050: u = 6; break;
  101381. case 24000: u = 7; break;
  101382. case 32000: u = 8; break;
  101383. case 44100: u = 9; break;
  101384. case 48000: u = 10; break;
  101385. case 96000: u = 11; break;
  101386. default:
  101387. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  101388. sample_rate_hint = u = 12;
  101389. else if(header->sample_rate % 10 == 0)
  101390. sample_rate_hint = u = 14;
  101391. else if(header->sample_rate <= 0xffff)
  101392. sample_rate_hint = u = 13;
  101393. else
  101394. u = 0;
  101395. break;
  101396. }
  101397. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  101398. return false;
  101399. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  101400. switch(header->channel_assignment) {
  101401. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101402. u = header->channels - 1;
  101403. break;
  101404. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101405. FLAC__ASSERT(header->channels == 2);
  101406. u = 8;
  101407. break;
  101408. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101409. FLAC__ASSERT(header->channels == 2);
  101410. u = 9;
  101411. break;
  101412. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101413. FLAC__ASSERT(header->channels == 2);
  101414. u = 10;
  101415. break;
  101416. default:
  101417. FLAC__ASSERT(0);
  101418. }
  101419. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  101420. return false;
  101421. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101422. switch(header->bits_per_sample) {
  101423. case 8 : u = 1; break;
  101424. case 12: u = 2; break;
  101425. case 16: u = 4; break;
  101426. case 20: u = 5; break;
  101427. case 24: u = 6; break;
  101428. default: u = 0; break;
  101429. }
  101430. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  101431. return false;
  101432. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  101433. return false;
  101434. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101435. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  101436. return false;
  101437. }
  101438. else {
  101439. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  101440. return false;
  101441. }
  101442. if(blocksize_hint)
  101443. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  101444. return false;
  101445. switch(sample_rate_hint) {
  101446. case 12:
  101447. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  101448. return false;
  101449. break;
  101450. case 13:
  101451. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  101452. return false;
  101453. break;
  101454. case 14:
  101455. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  101456. return false;
  101457. break;
  101458. }
  101459. /* write the CRC */
  101460. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  101461. return false;
  101462. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  101463. return false;
  101464. return true;
  101465. }
  101466. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101467. {
  101468. FLAC__bool ok;
  101469. ok =
  101470. 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) &&
  101471. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  101472. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  101473. ;
  101474. return ok;
  101475. }
  101476. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101477. {
  101478. unsigned i;
  101479. 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))
  101480. return false;
  101481. if(wasted_bits)
  101482. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  101483. return false;
  101484. for(i = 0; i < subframe->order; i++)
  101485. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  101486. return false;
  101487. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  101488. return false;
  101489. switch(subframe->entropy_coding_method.type) {
  101490. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101491. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101492. if(!add_residual_partitioned_rice_(
  101493. bw,
  101494. subframe->residual,
  101495. residual_samples,
  101496. subframe->order,
  101497. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  101498. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  101499. subframe->entropy_coding_method.data.partitioned_rice.order,
  101500. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  101501. ))
  101502. return false;
  101503. break;
  101504. default:
  101505. FLAC__ASSERT(0);
  101506. }
  101507. return true;
  101508. }
  101509. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101510. {
  101511. unsigned i;
  101512. 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))
  101513. return false;
  101514. if(wasted_bits)
  101515. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  101516. return false;
  101517. for(i = 0; i < subframe->order; i++)
  101518. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  101519. return false;
  101520. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101521. return false;
  101522. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101523. return false;
  101524. for(i = 0; i < subframe->order; i++)
  101525. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  101526. return false;
  101527. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  101528. return false;
  101529. switch(subframe->entropy_coding_method.type) {
  101530. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101531. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101532. if(!add_residual_partitioned_rice_(
  101533. bw,
  101534. subframe->residual,
  101535. residual_samples,
  101536. subframe->order,
  101537. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  101538. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  101539. subframe->entropy_coding_method.data.partitioned_rice.order,
  101540. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  101541. ))
  101542. return false;
  101543. break;
  101544. default:
  101545. FLAC__ASSERT(0);
  101546. }
  101547. return true;
  101548. }
  101549. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101550. {
  101551. unsigned i;
  101552. const FLAC__int32 *signal = subframe->data;
  101553. 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))
  101554. return false;
  101555. if(wasted_bits)
  101556. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  101557. return false;
  101558. for(i = 0; i < samples; i++)
  101559. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  101560. return false;
  101561. return true;
  101562. }
  101563. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  101564. {
  101565. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101566. return false;
  101567. switch(method->type) {
  101568. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101569. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101570. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101571. return false;
  101572. break;
  101573. default:
  101574. FLAC__ASSERT(0);
  101575. }
  101576. return true;
  101577. }
  101578. 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)
  101579. {
  101580. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101581. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101582. if(partition_order == 0) {
  101583. unsigned i;
  101584. if(raw_bits[0] == 0) {
  101585. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  101586. return false;
  101587. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  101588. return false;
  101589. }
  101590. else {
  101591. FLAC__ASSERT(rice_parameters[0] == 0);
  101592. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  101593. return false;
  101594. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101595. return false;
  101596. for(i = 0; i < residual_samples; i++) {
  101597. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  101598. return false;
  101599. }
  101600. }
  101601. return true;
  101602. }
  101603. else {
  101604. unsigned i, j, k = 0, k_last = 0;
  101605. unsigned partition_samples;
  101606. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  101607. for(i = 0; i < (1u<<partition_order); i++) {
  101608. partition_samples = default_partition_samples;
  101609. if(i == 0)
  101610. partition_samples -= predictor_order;
  101611. k += partition_samples;
  101612. if(raw_bits[i] == 0) {
  101613. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  101614. return false;
  101615. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  101616. return false;
  101617. }
  101618. else {
  101619. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  101620. return false;
  101621. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101622. return false;
  101623. for(j = k_last; j < k; j++) {
  101624. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  101625. return false;
  101626. }
  101627. }
  101628. k_last = k;
  101629. }
  101630. return true;
  101631. }
  101632. }
  101633. #endif
  101634. /********* End of inlined file: stream_encoder_framing.c *********/
  101635. /********* Start of inlined file: window_flac.c *********/
  101636. /********* Start of inlined file: juce_FlacHeader.h *********/
  101637. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101638. // tasks..
  101639. #define VERSION "1.2.1"
  101640. #define FLAC__NO_DLL 1
  101641. #ifdef _MSC_VER
  101642. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101643. #endif
  101644. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  101645. #define FLAC__SYS_DARWIN 1
  101646. #endif
  101647. /********* End of inlined file: juce_FlacHeader.h *********/
  101648. #if JUCE_USE_FLAC
  101649. #if HAVE_CONFIG_H
  101650. # include <config.h>
  101651. #endif
  101652. #include <math.h>
  101653. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101654. #ifndef M_PI
  101655. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  101656. #define M_PI 3.14159265358979323846
  101657. #endif
  101658. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  101659. {
  101660. const FLAC__int32 N = L - 1;
  101661. FLAC__int32 n;
  101662. if (L & 1) {
  101663. for (n = 0; n <= N/2; n++)
  101664. window[n] = 2.0f * n / (float)N;
  101665. for (; n <= N; n++)
  101666. window[n] = 2.0f - 2.0f * n / (float)N;
  101667. }
  101668. else {
  101669. for (n = 0; n <= L/2-1; n++)
  101670. window[n] = 2.0f * n / (float)N;
  101671. for (; n <= N; n++)
  101672. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  101673. }
  101674. }
  101675. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  101676. {
  101677. const FLAC__int32 N = L - 1;
  101678. FLAC__int32 n;
  101679. for (n = 0; n < L; n++)
  101680. 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)));
  101681. }
  101682. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  101683. {
  101684. const FLAC__int32 N = L - 1;
  101685. FLAC__int32 n;
  101686. for (n = 0; n < L; n++)
  101687. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  101688. }
  101689. /* 4-term -92dB side-lobe */
  101690. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  101691. {
  101692. const FLAC__int32 N = L - 1;
  101693. FLAC__int32 n;
  101694. for (n = 0; n <= N; n++)
  101695. 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));
  101696. }
  101697. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  101698. {
  101699. const FLAC__int32 N = L - 1;
  101700. const double N2 = (double)N / 2.;
  101701. FLAC__int32 n;
  101702. for (n = 0; n <= N; n++) {
  101703. double k = ((double)n - N2) / N2;
  101704. k = 1.0f - k * k;
  101705. window[n] = (FLAC__real)(k * k);
  101706. }
  101707. }
  101708. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  101709. {
  101710. const FLAC__int32 N = L - 1;
  101711. FLAC__int32 n;
  101712. for (n = 0; n < L; n++)
  101713. 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));
  101714. }
  101715. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  101716. {
  101717. const FLAC__int32 N = L - 1;
  101718. const double N2 = (double)N / 2.;
  101719. FLAC__int32 n;
  101720. for (n = 0; n <= N; n++) {
  101721. const double k = ((double)n - N2) / (stddev * N2);
  101722. window[n] = (FLAC__real)exp(-0.5f * k * k);
  101723. }
  101724. }
  101725. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  101726. {
  101727. const FLAC__int32 N = L - 1;
  101728. FLAC__int32 n;
  101729. for (n = 0; n < L; n++)
  101730. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  101731. }
  101732. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  101733. {
  101734. const FLAC__int32 N = L - 1;
  101735. FLAC__int32 n;
  101736. for (n = 0; n < L; n++)
  101737. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  101738. }
  101739. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  101740. {
  101741. const FLAC__int32 N = L - 1;
  101742. FLAC__int32 n;
  101743. for (n = 0; n < L; n++)
  101744. 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));
  101745. }
  101746. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  101747. {
  101748. const FLAC__int32 N = L - 1;
  101749. FLAC__int32 n;
  101750. for (n = 0; n < L; n++)
  101751. 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));
  101752. }
  101753. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  101754. {
  101755. FLAC__int32 n;
  101756. for (n = 0; n < L; n++)
  101757. window[n] = 1.0f;
  101758. }
  101759. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  101760. {
  101761. FLAC__int32 n;
  101762. if (L & 1) {
  101763. for (n = 1; n <= L+1/2; n++)
  101764. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  101765. for (; n <= L; n++)
  101766. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  101767. }
  101768. else {
  101769. for (n = 1; n <= L/2; n++)
  101770. window[n-1] = 2.0f * n / (float)L;
  101771. for (; n <= L; n++)
  101772. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  101773. }
  101774. }
  101775. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  101776. {
  101777. if (p <= 0.0)
  101778. FLAC__window_rectangle(window, L);
  101779. else if (p >= 1.0)
  101780. FLAC__window_hann(window, L);
  101781. else {
  101782. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  101783. FLAC__int32 n;
  101784. /* start with rectangle... */
  101785. FLAC__window_rectangle(window, L);
  101786. /* ...replace ends with hann */
  101787. if (Np > 0) {
  101788. for (n = 0; n <= Np; n++) {
  101789. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  101790. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  101791. }
  101792. }
  101793. }
  101794. }
  101795. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  101796. {
  101797. const FLAC__int32 N = L - 1;
  101798. const double N2 = (double)N / 2.;
  101799. FLAC__int32 n;
  101800. for (n = 0; n <= N; n++) {
  101801. const double k = ((double)n - N2) / N2;
  101802. window[n] = (FLAC__real)(1.0f - k * k);
  101803. }
  101804. }
  101805. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101806. #endif
  101807. /********* End of inlined file: window_flac.c *********/
  101808. #else
  101809. #include <FLAC/all.h>
  101810. #endif
  101811. }
  101812. #ifdef _MSC_VER
  101813. #pragma warning (pop)
  101814. #endif
  101815. BEGIN_JUCE_NAMESPACE
  101816. using namespace FlacNamespace;
  101817. #define flacFormatName TRANS("FLAC file")
  101818. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  101819. class FlacReader : public AudioFormatReader
  101820. {
  101821. FLAC__StreamDecoder* decoder;
  101822. AudioSampleBuffer reservoir;
  101823. int reservoirStart, samplesInReservoir;
  101824. bool ok, scanningForLength;
  101825. public:
  101826. FlacReader (InputStream* const in)
  101827. : AudioFormatReader (in, flacFormatName),
  101828. reservoir (2, 0),
  101829. reservoirStart (0),
  101830. samplesInReservoir (0),
  101831. scanningForLength (false)
  101832. {
  101833. using namespace FlacNamespace;
  101834. lengthInSamples = 0;
  101835. decoder = FLAC__stream_decoder_new();
  101836. ok = FLAC__stream_decoder_init_stream (decoder,
  101837. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  101838. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  101839. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  101840. if (ok)
  101841. {
  101842. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  101843. if (lengthInSamples == 0 && sampleRate > 0)
  101844. {
  101845. // the length hasn't been stored in the metadata, so we'll need to
  101846. // work it out the length the hard way, by scanning the whole file..
  101847. scanningForLength = true;
  101848. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  101849. scanningForLength = false;
  101850. const int64 tempLength = lengthInSamples;
  101851. FLAC__stream_decoder_reset (decoder);
  101852. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  101853. lengthInSamples = tempLength;
  101854. }
  101855. }
  101856. }
  101857. ~FlacReader()
  101858. {
  101859. FLAC__stream_decoder_delete (decoder);
  101860. }
  101861. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  101862. {
  101863. sampleRate = info.sample_rate;
  101864. bitsPerSample = info.bits_per_sample;
  101865. lengthInSamples = (unsigned int) info.total_samples;
  101866. numChannels = info.channels;
  101867. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  101868. }
  101869. // returns the number of samples read
  101870. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  101871. int64 startSampleInFile, int numSamples)
  101872. {
  101873. using namespace FlacNamespace;
  101874. if (! ok)
  101875. return false;
  101876. while (numSamples > 0)
  101877. {
  101878. if (startSampleInFile >= reservoirStart
  101879. && startSampleInFile < reservoirStart + samplesInReservoir)
  101880. {
  101881. const int num = (int) jmin ((int64) numSamples,
  101882. reservoirStart + samplesInReservoir - startSampleInFile);
  101883. jassert (num > 0);
  101884. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  101885. if (destSamples[i] != 0)
  101886. memcpy (destSamples[i] + startOffsetInDestBuffer,
  101887. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  101888. sizeof (int) * num);
  101889. startOffsetInDestBuffer += num;
  101890. startSampleInFile += num;
  101891. numSamples -= num;
  101892. }
  101893. else
  101894. {
  101895. if (startSampleInFile < reservoirStart
  101896. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  101897. {
  101898. if (startSampleInFile >= (int) lengthInSamples)
  101899. {
  101900. samplesInReservoir = 0;
  101901. break;
  101902. }
  101903. // had some problems with flac crashing if the read pos is aligned more
  101904. // accurately than this. Probably fixed in newer versions of the library, though.
  101905. reservoirStart = (int) (startSampleInFile & ~511);
  101906. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  101907. }
  101908. else
  101909. {
  101910. reservoirStart += samplesInReservoir;
  101911. }
  101912. samplesInReservoir = 0;
  101913. FLAC__stream_decoder_process_single (decoder);
  101914. if (samplesInReservoir == 0)
  101915. break;
  101916. }
  101917. }
  101918. if (numSamples > 0)
  101919. {
  101920. for (int i = numDestChannels; --i >= 0;)
  101921. if (destSamples[i] != 0)
  101922. zeromem (destSamples[i] + startOffsetInDestBuffer,
  101923. sizeof (int) * numSamples);
  101924. }
  101925. return true;
  101926. }
  101927. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  101928. {
  101929. if (scanningForLength)
  101930. {
  101931. lengthInSamples += numSamples;
  101932. }
  101933. else
  101934. {
  101935. if (numSamples > reservoir.getNumSamples())
  101936. reservoir.setSize (numChannels, numSamples, false, false, true);
  101937. const int bitsToShift = 32 - bitsPerSample;
  101938. for (int i = 0; i < (int) numChannels; ++i)
  101939. {
  101940. const FLAC__int32* src = buffer[i];
  101941. int n = i;
  101942. while (src == 0 && n > 0)
  101943. src = buffer [--n];
  101944. if (src != 0)
  101945. {
  101946. int* dest = (int*) reservoir.getSampleData(i);
  101947. for (int j = 0; j < numSamples; ++j)
  101948. dest[j] = src[j] << bitsToShift;
  101949. }
  101950. }
  101951. samplesInReservoir = numSamples;
  101952. }
  101953. }
  101954. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  101955. {
  101956. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  101957. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101958. }
  101959. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  101960. {
  101961. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  101962. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101963. }
  101964. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  101965. {
  101966. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  101967. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101968. }
  101969. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  101970. {
  101971. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  101972. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101973. }
  101974. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  101975. {
  101976. return ((const FlacReader*) client_data)->input->isExhausted();
  101977. }
  101978. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  101979. const FLAC__Frame* frame,
  101980. const FLAC__int32* const buffer[],
  101981. void* client_data)
  101982. {
  101983. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  101984. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101985. }
  101986. static void metadataCallback_ (const FLAC__StreamDecoder*,
  101987. const FLAC__StreamMetadata* metadata,
  101988. void* client_data)
  101989. {
  101990. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  101991. }
  101992. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  101993. {
  101994. }
  101995. juce_UseDebuggingNewOperator
  101996. };
  101997. class FlacWriter : public AudioFormatWriter
  101998. {
  101999. FLAC__StreamEncoder* encoder;
  102000. MemoryBlock temp;
  102001. public:
  102002. bool ok;
  102003. FlacWriter (OutputStream* const out,
  102004. const double sampleRate,
  102005. const int numChannels,
  102006. const int bitsPerSample_)
  102007. : AudioFormatWriter (out, flacFormatName,
  102008. sampleRate,
  102009. numChannels,
  102010. bitsPerSample_)
  102011. {
  102012. using namespace FlacNamespace;
  102013. encoder = FLAC__stream_encoder_new();
  102014. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  102015. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  102016. FLAC__stream_encoder_set_channels (encoder, numChannels);
  102017. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  102018. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  102019. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  102020. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  102021. ok = FLAC__stream_encoder_init_stream (encoder,
  102022. encodeWriteCallback, encodeSeekCallback,
  102023. encodeTellCallback, encodeMetadataCallback,
  102024. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102025. }
  102026. ~FlacWriter()
  102027. {
  102028. if (ok)
  102029. {
  102030. FLAC__stream_encoder_finish (encoder);
  102031. output->flush();
  102032. }
  102033. else
  102034. {
  102035. output = 0; // to stop the base class deleting this, as it needs to be returned
  102036. // to the caller of createWriter()
  102037. }
  102038. FLAC__stream_encoder_delete (encoder);
  102039. }
  102040. bool write (const int** samplesToWrite, int numSamples)
  102041. {
  102042. if (! ok)
  102043. return false;
  102044. int* buf[3];
  102045. const int bitsToShift = 32 - bitsPerSample;
  102046. if (bitsToShift > 0)
  102047. {
  102048. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  102049. temp.setSize (sizeof (int) * numSamples * numChannels);
  102050. buf[0] = (int*) temp.getData();
  102051. buf[1] = buf[0] + numSamples;
  102052. buf[2] = 0;
  102053. for (int i = numChannels; --i >= 0;)
  102054. {
  102055. if (samplesToWrite[i] != 0)
  102056. {
  102057. for (int j = 0; j < numSamples; ++j)
  102058. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  102059. }
  102060. }
  102061. samplesToWrite = (const int**) buf;
  102062. }
  102063. return FLAC__stream_encoder_process (encoder,
  102064. (const FLAC__int32**) samplesToWrite,
  102065. numSamples) != 0;
  102066. }
  102067. bool writeData (const void* const data, const int size) const
  102068. {
  102069. return output->write (data, size);
  102070. }
  102071. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  102072. {
  102073. b += bytes;
  102074. for (int i = 0; i < bytes; ++i)
  102075. {
  102076. *(--b) = (FLAC__byte) (val & 0xff);
  102077. val >>= 8;
  102078. }
  102079. }
  102080. void writeMetaData (const FLAC__StreamMetadata* metadata)
  102081. {
  102082. using namespace FlacNamespace;
  102083. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  102084. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  102085. const unsigned int channelsMinus1 = info.channels - 1;
  102086. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  102087. packUint32 (info.min_blocksize, buffer, 2);
  102088. packUint32 (info.max_blocksize, buffer + 2, 2);
  102089. packUint32 (info.min_framesize, buffer + 4, 3);
  102090. packUint32 (info.max_framesize, buffer + 7, 3);
  102091. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  102092. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  102093. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  102094. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  102095. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  102096. memcpy (buffer + 18, info.md5sum, 16);
  102097. const bool ok = output->setPosition (4);
  102098. (void) ok;
  102099. // if this fails, you've given it an output stream that can't seek! It needs
  102100. // to be able to seek back to write the header
  102101. jassert (ok);
  102102. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102103. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102104. }
  102105. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  102106. const FLAC__byte buffer[],
  102107. size_t bytes,
  102108. unsigned int /*samples*/,
  102109. unsigned int /*current_frame*/,
  102110. void* client_data)
  102111. {
  102112. using namespace FlacNamespace;
  102113. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  102114. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  102115. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  102116. }
  102117. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  102118. {
  102119. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  102120. }
  102121. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  102122. {
  102123. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  102124. }
  102125. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  102126. const FLAC__StreamMetadata* metadata,
  102127. void* client_data)
  102128. {
  102129. ((FlacWriter*) client_data)->writeMetaData (metadata);
  102130. }
  102131. juce_UseDebuggingNewOperator
  102132. };
  102133. FlacAudioFormat::FlacAudioFormat()
  102134. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  102135. {
  102136. }
  102137. FlacAudioFormat::~FlacAudioFormat()
  102138. {
  102139. }
  102140. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  102141. {
  102142. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  102143. return Array <int> (rates);
  102144. }
  102145. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  102146. {
  102147. const int depths[] = { 16, 24, 0 };
  102148. return Array <int> (depths);
  102149. }
  102150. bool FlacAudioFormat::canDoStereo()
  102151. {
  102152. return true;
  102153. }
  102154. bool FlacAudioFormat::canDoMono()
  102155. {
  102156. return true;
  102157. }
  102158. bool FlacAudioFormat::isCompressed()
  102159. {
  102160. return true;
  102161. }
  102162. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  102163. const bool deleteStreamIfOpeningFails)
  102164. {
  102165. FlacReader* r = new FlacReader (in);
  102166. if (r->sampleRate == 0)
  102167. {
  102168. if (! deleteStreamIfOpeningFails)
  102169. r->input = 0;
  102170. deleteAndZero (r);
  102171. }
  102172. return r;
  102173. }
  102174. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  102175. double sampleRate,
  102176. unsigned int numberOfChannels,
  102177. int bitsPerSample,
  102178. const StringPairArray& /*metadataValues*/,
  102179. int /*qualityOptionIndex*/)
  102180. {
  102181. if (getPossibleBitDepths().contains (bitsPerSample))
  102182. {
  102183. FlacWriter* w = new FlacWriter (out,
  102184. sampleRate,
  102185. numberOfChannels,
  102186. bitsPerSample);
  102187. if (! w->ok)
  102188. deleteAndZero (w);
  102189. return w;
  102190. }
  102191. return 0;
  102192. }
  102193. END_JUCE_NAMESPACE
  102194. #endif
  102195. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  102196. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  102197. #if JUCE_USE_OGGVORBIS
  102198. #if JUCE_MAC
  102199. #define __MACOSX__ 1
  102200. #endif
  102201. namespace OggVorbisNamespace
  102202. {
  102203. #if JUCE_INCLUDE_OGGVORBIS_CODE
  102204. /********* Start of inlined file: vorbisenc.h *********/
  102205. #ifndef _OV_ENC_H_
  102206. #define _OV_ENC_H_
  102207. #ifdef __cplusplus
  102208. extern "C"
  102209. {
  102210. #endif /* __cplusplus */
  102211. /********* Start of inlined file: codec.h *********/
  102212. #ifndef _vorbis_codec_h_
  102213. #define _vorbis_codec_h_
  102214. #ifdef __cplusplus
  102215. extern "C"
  102216. {
  102217. #endif /* __cplusplus */
  102218. /********* Start of inlined file: ogg.h *********/
  102219. #ifndef _OGG_H
  102220. #define _OGG_H
  102221. #ifdef __cplusplus
  102222. extern "C" {
  102223. #endif
  102224. /********* Start of inlined file: os_types.h *********/
  102225. #ifndef _OS_TYPES_H
  102226. #define _OS_TYPES_H
  102227. /* make it easy on the folks that want to compile the libs with a
  102228. different malloc than stdlib */
  102229. #define _ogg_malloc malloc
  102230. #define _ogg_calloc calloc
  102231. #define _ogg_realloc realloc
  102232. #define _ogg_free free
  102233. #if defined(_WIN32)
  102234. # if defined(__CYGWIN__)
  102235. # include <_G_config.h>
  102236. typedef _G_int64_t ogg_int64_t;
  102237. typedef _G_int32_t ogg_int32_t;
  102238. typedef _G_uint32_t ogg_uint32_t;
  102239. typedef _G_int16_t ogg_int16_t;
  102240. typedef _G_uint16_t ogg_uint16_t;
  102241. # elif defined(__MINGW32__)
  102242. typedef short ogg_int16_t;
  102243. typedef unsigned short ogg_uint16_t;
  102244. typedef int ogg_int32_t;
  102245. typedef unsigned int ogg_uint32_t;
  102246. typedef long long ogg_int64_t;
  102247. typedef unsigned long long ogg_uint64_t;
  102248. # elif defined(__MWERKS__)
  102249. typedef long long ogg_int64_t;
  102250. typedef int ogg_int32_t;
  102251. typedef unsigned int ogg_uint32_t;
  102252. typedef short ogg_int16_t;
  102253. typedef unsigned short ogg_uint16_t;
  102254. # else
  102255. /* MSVC/Borland */
  102256. typedef __int64 ogg_int64_t;
  102257. typedef __int32 ogg_int32_t;
  102258. typedef unsigned __int32 ogg_uint32_t;
  102259. typedef __int16 ogg_int16_t;
  102260. typedef unsigned __int16 ogg_uint16_t;
  102261. # endif
  102262. #elif defined(__MACOS__)
  102263. # include <sys/types.h>
  102264. typedef SInt16 ogg_int16_t;
  102265. typedef UInt16 ogg_uint16_t;
  102266. typedef SInt32 ogg_int32_t;
  102267. typedef UInt32 ogg_uint32_t;
  102268. typedef SInt64 ogg_int64_t;
  102269. #elif defined(__MACOSX__) /* MacOS X Framework build */
  102270. # include <sys/types.h>
  102271. typedef int16_t ogg_int16_t;
  102272. typedef u_int16_t ogg_uint16_t;
  102273. typedef int32_t ogg_int32_t;
  102274. typedef u_int32_t ogg_uint32_t;
  102275. typedef int64_t ogg_int64_t;
  102276. #elif defined(__BEOS__)
  102277. /* Be */
  102278. # include <inttypes.h>
  102279. typedef int16_t ogg_int16_t;
  102280. typedef u_int16_t ogg_uint16_t;
  102281. typedef int32_t ogg_int32_t;
  102282. typedef u_int32_t ogg_uint32_t;
  102283. typedef int64_t ogg_int64_t;
  102284. #elif defined (__EMX__)
  102285. /* OS/2 GCC */
  102286. typedef short ogg_int16_t;
  102287. typedef unsigned short ogg_uint16_t;
  102288. typedef int ogg_int32_t;
  102289. typedef unsigned int ogg_uint32_t;
  102290. typedef long long ogg_int64_t;
  102291. #elif defined (DJGPP)
  102292. /* DJGPP */
  102293. typedef short ogg_int16_t;
  102294. typedef int ogg_int32_t;
  102295. typedef unsigned int ogg_uint32_t;
  102296. typedef long long ogg_int64_t;
  102297. #elif defined(R5900)
  102298. /* PS2 EE */
  102299. typedef long ogg_int64_t;
  102300. typedef int ogg_int32_t;
  102301. typedef unsigned ogg_uint32_t;
  102302. typedef short ogg_int16_t;
  102303. #elif defined(__SYMBIAN32__)
  102304. /* Symbian GCC */
  102305. typedef signed short ogg_int16_t;
  102306. typedef unsigned short ogg_uint16_t;
  102307. typedef signed int ogg_int32_t;
  102308. typedef unsigned int ogg_uint32_t;
  102309. typedef long long int ogg_int64_t;
  102310. #else
  102311. # include <sys/types.h>
  102312. /********* Start of inlined file: config_types.h *********/
  102313. #ifndef __CONFIG_TYPES_H__
  102314. #define __CONFIG_TYPES_H__
  102315. typedef int16_t ogg_int16_t;
  102316. typedef unsigned short ogg_uint16_t;
  102317. typedef int32_t ogg_int32_t;
  102318. typedef unsigned int ogg_uint32_t;
  102319. typedef int64_t ogg_int64_t;
  102320. #endif
  102321. /********* End of inlined file: config_types.h *********/
  102322. #endif
  102323. #endif /* _OS_TYPES_H */
  102324. /********* End of inlined file: os_types.h *********/
  102325. typedef struct {
  102326. long endbyte;
  102327. int endbit;
  102328. unsigned char *buffer;
  102329. unsigned char *ptr;
  102330. long storage;
  102331. } oggpack_buffer;
  102332. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  102333. typedef struct {
  102334. unsigned char *header;
  102335. long header_len;
  102336. unsigned char *body;
  102337. long body_len;
  102338. } ogg_page;
  102339. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  102340. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  102341. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  102342. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  102343. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  102344. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  102345. }
  102346. /* ogg_stream_state contains the current encode/decode state of a logical
  102347. Ogg bitstream **********************************************************/
  102348. typedef struct {
  102349. unsigned char *body_data; /* bytes from packet bodies */
  102350. long body_storage; /* storage elements allocated */
  102351. long body_fill; /* elements stored; fill mark */
  102352. long body_returned; /* elements of fill returned */
  102353. int *lacing_vals; /* The values that will go to the segment table */
  102354. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  102355. this way, but it is simple coupled to the
  102356. lacing fifo */
  102357. long lacing_storage;
  102358. long lacing_fill;
  102359. long lacing_packet;
  102360. long lacing_returned;
  102361. unsigned char header[282]; /* working space for header encode */
  102362. int header_fill;
  102363. int e_o_s; /* set when we have buffered the last packet in the
  102364. logical bitstream */
  102365. int b_o_s; /* set after we've written the initial page
  102366. of a logical bitstream */
  102367. long serialno;
  102368. long pageno;
  102369. ogg_int64_t packetno; /* sequence number for decode; the framing
  102370. knows where there's a hole in the data,
  102371. but we need coupling so that the codec
  102372. (which is in a seperate abstraction
  102373. layer) also knows about the gap */
  102374. ogg_int64_t granulepos;
  102375. } ogg_stream_state;
  102376. /* ogg_packet is used to encapsulate the data and metadata belonging
  102377. to a single raw Ogg/Vorbis packet *************************************/
  102378. typedef struct {
  102379. unsigned char *packet;
  102380. long bytes;
  102381. long b_o_s;
  102382. long e_o_s;
  102383. ogg_int64_t granulepos;
  102384. ogg_int64_t packetno; /* sequence number for decode; the framing
  102385. knows where there's a hole in the data,
  102386. but we need coupling so that the codec
  102387. (which is in a seperate abstraction
  102388. layer) also knows about the gap */
  102389. } ogg_packet;
  102390. typedef struct {
  102391. unsigned char *data;
  102392. int storage;
  102393. int fill;
  102394. int returned;
  102395. int unsynced;
  102396. int headerbytes;
  102397. int bodybytes;
  102398. } ogg_sync_state;
  102399. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  102400. extern void oggpack_writeinit(oggpack_buffer *b);
  102401. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  102402. extern void oggpack_writealign(oggpack_buffer *b);
  102403. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  102404. extern void oggpack_reset(oggpack_buffer *b);
  102405. extern void oggpack_writeclear(oggpack_buffer *b);
  102406. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  102407. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  102408. extern long oggpack_look(oggpack_buffer *b,int bits);
  102409. extern long oggpack_look1(oggpack_buffer *b);
  102410. extern void oggpack_adv(oggpack_buffer *b,int bits);
  102411. extern void oggpack_adv1(oggpack_buffer *b);
  102412. extern long oggpack_read(oggpack_buffer *b,int bits);
  102413. extern long oggpack_read1(oggpack_buffer *b);
  102414. extern long oggpack_bytes(oggpack_buffer *b);
  102415. extern long oggpack_bits(oggpack_buffer *b);
  102416. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  102417. extern void oggpackB_writeinit(oggpack_buffer *b);
  102418. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  102419. extern void oggpackB_writealign(oggpack_buffer *b);
  102420. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  102421. extern void oggpackB_reset(oggpack_buffer *b);
  102422. extern void oggpackB_writeclear(oggpack_buffer *b);
  102423. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  102424. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  102425. extern long oggpackB_look(oggpack_buffer *b,int bits);
  102426. extern long oggpackB_look1(oggpack_buffer *b);
  102427. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  102428. extern void oggpackB_adv1(oggpack_buffer *b);
  102429. extern long oggpackB_read(oggpack_buffer *b,int bits);
  102430. extern long oggpackB_read1(oggpack_buffer *b);
  102431. extern long oggpackB_bytes(oggpack_buffer *b);
  102432. extern long oggpackB_bits(oggpack_buffer *b);
  102433. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  102434. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  102435. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  102436. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  102437. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  102438. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  102439. extern int ogg_sync_init(ogg_sync_state *oy);
  102440. extern int ogg_sync_clear(ogg_sync_state *oy);
  102441. extern int ogg_sync_reset(ogg_sync_state *oy);
  102442. extern int ogg_sync_destroy(ogg_sync_state *oy);
  102443. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  102444. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  102445. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  102446. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  102447. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  102448. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  102449. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  102450. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  102451. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  102452. extern int ogg_stream_clear(ogg_stream_state *os);
  102453. extern int ogg_stream_reset(ogg_stream_state *os);
  102454. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  102455. extern int ogg_stream_destroy(ogg_stream_state *os);
  102456. extern int ogg_stream_eos(ogg_stream_state *os);
  102457. extern void ogg_page_checksum_set(ogg_page *og);
  102458. extern int ogg_page_version(ogg_page *og);
  102459. extern int ogg_page_continued(ogg_page *og);
  102460. extern int ogg_page_bos(ogg_page *og);
  102461. extern int ogg_page_eos(ogg_page *og);
  102462. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  102463. extern int ogg_page_serialno(ogg_page *og);
  102464. extern long ogg_page_pageno(ogg_page *og);
  102465. extern int ogg_page_packets(ogg_page *og);
  102466. extern void ogg_packet_clear(ogg_packet *op);
  102467. #ifdef __cplusplus
  102468. }
  102469. #endif
  102470. #endif /* _OGG_H */
  102471. /********* End of inlined file: ogg.h *********/
  102472. typedef struct vorbis_info{
  102473. int version;
  102474. int channels;
  102475. long rate;
  102476. /* The below bitrate declarations are *hints*.
  102477. Combinations of the three values carry the following implications:
  102478. all three set to the same value:
  102479. implies a fixed rate bitstream
  102480. only nominal set:
  102481. implies a VBR stream that averages the nominal bitrate. No hard
  102482. upper/lower limit
  102483. upper and or lower set:
  102484. implies a VBR bitstream that obeys the bitrate limits. nominal
  102485. may also be set to give a nominal rate.
  102486. none set:
  102487. the coder does not care to speculate.
  102488. */
  102489. long bitrate_upper;
  102490. long bitrate_nominal;
  102491. long bitrate_lower;
  102492. long bitrate_window;
  102493. void *codec_setup;
  102494. } vorbis_info;
  102495. /* vorbis_dsp_state buffers the current vorbis audio
  102496. analysis/synthesis state. The DSP state belongs to a specific
  102497. logical bitstream ****************************************************/
  102498. typedef struct vorbis_dsp_state{
  102499. int analysisp;
  102500. vorbis_info *vi;
  102501. float **pcm;
  102502. float **pcmret;
  102503. int pcm_storage;
  102504. int pcm_current;
  102505. int pcm_returned;
  102506. int preextrapolate;
  102507. int eofflag;
  102508. long lW;
  102509. long W;
  102510. long nW;
  102511. long centerW;
  102512. ogg_int64_t granulepos;
  102513. ogg_int64_t sequence;
  102514. ogg_int64_t glue_bits;
  102515. ogg_int64_t time_bits;
  102516. ogg_int64_t floor_bits;
  102517. ogg_int64_t res_bits;
  102518. void *backend_state;
  102519. } vorbis_dsp_state;
  102520. typedef struct vorbis_block{
  102521. /* necessary stream state for linking to the framing abstraction */
  102522. float **pcm; /* this is a pointer into local storage */
  102523. oggpack_buffer opb;
  102524. long lW;
  102525. long W;
  102526. long nW;
  102527. int pcmend;
  102528. int mode;
  102529. int eofflag;
  102530. ogg_int64_t granulepos;
  102531. ogg_int64_t sequence;
  102532. vorbis_dsp_state *vd; /* For read-only access of configuration */
  102533. /* local storage to avoid remallocing; it's up to the mapping to
  102534. structure it */
  102535. void *localstore;
  102536. long localtop;
  102537. long localalloc;
  102538. long totaluse;
  102539. struct alloc_chain *reap;
  102540. /* bitmetrics for the frame */
  102541. long glue_bits;
  102542. long time_bits;
  102543. long floor_bits;
  102544. long res_bits;
  102545. void *internal;
  102546. } vorbis_block;
  102547. /* vorbis_block is a single block of data to be processed as part of
  102548. the analysis/synthesis stream; it belongs to a specific logical
  102549. bitstream, but is independant from other vorbis_blocks belonging to
  102550. that logical bitstream. *************************************************/
  102551. struct alloc_chain{
  102552. void *ptr;
  102553. struct alloc_chain *next;
  102554. };
  102555. /* vorbis_info contains all the setup information specific to the
  102556. specific compression/decompression mode in progress (eg,
  102557. psychoacoustic settings, channel setup, options, codebook
  102558. etc). vorbis_info and substructures are in backends.h.
  102559. *********************************************************************/
  102560. /* the comments are not part of vorbis_info so that vorbis_info can be
  102561. static storage */
  102562. typedef struct vorbis_comment{
  102563. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  102564. whatever vendor is set to in encode */
  102565. char **user_comments;
  102566. int *comment_lengths;
  102567. int comments;
  102568. char *vendor;
  102569. } vorbis_comment;
  102570. /* libvorbis encodes in two abstraction layers; first we perform DSP
  102571. and produce a packet (see docs/analysis.txt). The packet is then
  102572. coded into a framed OggSquish bitstream by the second layer (see
  102573. docs/framing.txt). Decode is the reverse process; we sync/frame
  102574. the bitstream and extract individual packets, then decode the
  102575. packet back into PCM audio.
  102576. The extra framing/packetizing is used in streaming formats, such as
  102577. files. Over the net (such as with UDP), the framing and
  102578. packetization aren't necessary as they're provided by the transport
  102579. and the streaming layer is not used */
  102580. /* Vorbis PRIMITIVES: general ***************************************/
  102581. extern void vorbis_info_init(vorbis_info *vi);
  102582. extern void vorbis_info_clear(vorbis_info *vi);
  102583. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  102584. extern void vorbis_comment_init(vorbis_comment *vc);
  102585. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  102586. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  102587. const char *tag, char *contents);
  102588. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  102589. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  102590. extern void vorbis_comment_clear(vorbis_comment *vc);
  102591. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  102592. extern int vorbis_block_clear(vorbis_block *vb);
  102593. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  102594. extern double vorbis_granule_time(vorbis_dsp_state *v,
  102595. ogg_int64_t granulepos);
  102596. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  102597. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  102598. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  102599. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  102600. vorbis_comment *vc,
  102601. ogg_packet *op,
  102602. ogg_packet *op_comm,
  102603. ogg_packet *op_code);
  102604. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  102605. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  102606. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  102607. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  102608. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  102609. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  102610. ogg_packet *op);
  102611. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  102612. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  102613. ogg_packet *op);
  102614. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  102615. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  102616. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  102617. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  102618. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  102619. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  102620. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  102621. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  102622. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  102623. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  102624. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  102625. /* Vorbis ERRORS and return codes ***********************************/
  102626. #define OV_FALSE -1
  102627. #define OV_EOF -2
  102628. #define OV_HOLE -3
  102629. #define OV_EREAD -128
  102630. #define OV_EFAULT -129
  102631. #define OV_EIMPL -130
  102632. #define OV_EINVAL -131
  102633. #define OV_ENOTVORBIS -132
  102634. #define OV_EBADHEADER -133
  102635. #define OV_EVERSION -134
  102636. #define OV_ENOTAUDIO -135
  102637. #define OV_EBADPACKET -136
  102638. #define OV_EBADLINK -137
  102639. #define OV_ENOSEEK -138
  102640. #ifdef __cplusplus
  102641. }
  102642. #endif /* __cplusplus */
  102643. #endif
  102644. /********* End of inlined file: codec.h *********/
  102645. extern int vorbis_encode_init(vorbis_info *vi,
  102646. long channels,
  102647. long rate,
  102648. long max_bitrate,
  102649. long nominal_bitrate,
  102650. long min_bitrate);
  102651. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  102652. long channels,
  102653. long rate,
  102654. long max_bitrate,
  102655. long nominal_bitrate,
  102656. long min_bitrate);
  102657. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  102658. long channels,
  102659. long rate,
  102660. float quality /* quality level from 0. (lo) to 1. (hi) */
  102661. );
  102662. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  102663. long channels,
  102664. long rate,
  102665. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  102666. );
  102667. extern int vorbis_encode_setup_init(vorbis_info *vi);
  102668. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  102669. /* deprecated rate management supported only for compatability */
  102670. #define OV_ECTL_RATEMANAGE_GET 0x10
  102671. #define OV_ECTL_RATEMANAGE_SET 0x11
  102672. #define OV_ECTL_RATEMANAGE_AVG 0x12
  102673. #define OV_ECTL_RATEMANAGE_HARD 0x13
  102674. struct ovectl_ratemanage_arg {
  102675. int management_active;
  102676. long bitrate_hard_min;
  102677. long bitrate_hard_max;
  102678. double bitrate_hard_window;
  102679. long bitrate_av_lo;
  102680. long bitrate_av_hi;
  102681. double bitrate_av_window;
  102682. double bitrate_av_window_center;
  102683. };
  102684. /* new rate setup */
  102685. #define OV_ECTL_RATEMANAGE2_GET 0x14
  102686. #define OV_ECTL_RATEMANAGE2_SET 0x15
  102687. struct ovectl_ratemanage2_arg {
  102688. int management_active;
  102689. long bitrate_limit_min_kbps;
  102690. long bitrate_limit_max_kbps;
  102691. long bitrate_limit_reservoir_bits;
  102692. double bitrate_limit_reservoir_bias;
  102693. long bitrate_average_kbps;
  102694. double bitrate_average_damping;
  102695. };
  102696. #define OV_ECTL_LOWPASS_GET 0x20
  102697. #define OV_ECTL_LOWPASS_SET 0x21
  102698. #define OV_ECTL_IBLOCK_GET 0x30
  102699. #define OV_ECTL_IBLOCK_SET 0x31
  102700. #ifdef __cplusplus
  102701. }
  102702. #endif /* __cplusplus */
  102703. #endif
  102704. /********* End of inlined file: vorbisenc.h *********/
  102705. /********* Start of inlined file: vorbisfile.h *********/
  102706. #ifndef _OV_FILE_H_
  102707. #define _OV_FILE_H_
  102708. #ifdef __cplusplus
  102709. extern "C"
  102710. {
  102711. #endif /* __cplusplus */
  102712. #include <stdio.h>
  102713. /* The function prototypes for the callbacks are basically the same as for
  102714. * the stdio functions fread, fseek, fclose, ftell.
  102715. * The one difference is that the FILE * arguments have been replaced with
  102716. * a void * - this is to be used as a pointer to whatever internal data these
  102717. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  102718. *
  102719. * If you use other functions, check the docs for these functions and return
  102720. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  102721. * unseekable
  102722. */
  102723. typedef struct {
  102724. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  102725. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  102726. int (*close_func) (void *datasource);
  102727. long (*tell_func) (void *datasource);
  102728. } ov_callbacks;
  102729. #define NOTOPEN 0
  102730. #define PARTOPEN 1
  102731. #define OPENED 2
  102732. #define STREAMSET 3
  102733. #define INITSET 4
  102734. typedef struct OggVorbis_File {
  102735. void *datasource; /* Pointer to a FILE *, etc. */
  102736. int seekable;
  102737. ogg_int64_t offset;
  102738. ogg_int64_t end;
  102739. ogg_sync_state oy;
  102740. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  102741. stream appears */
  102742. int links;
  102743. ogg_int64_t *offsets;
  102744. ogg_int64_t *dataoffsets;
  102745. long *serialnos;
  102746. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  102747. compatability; x2 size, stores both
  102748. beginning and end values */
  102749. vorbis_info *vi;
  102750. vorbis_comment *vc;
  102751. /* Decoding working state local storage */
  102752. ogg_int64_t pcm_offset;
  102753. int ready_state;
  102754. long current_serialno;
  102755. int current_link;
  102756. double bittrack;
  102757. double samptrack;
  102758. ogg_stream_state os; /* take physical pages, weld into a logical
  102759. stream of packets */
  102760. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  102761. vorbis_block vb; /* local working space for packet->PCM decode */
  102762. ov_callbacks callbacks;
  102763. } OggVorbis_File;
  102764. extern int ov_clear(OggVorbis_File *vf);
  102765. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  102766. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  102767. char *initial, long ibytes, ov_callbacks callbacks);
  102768. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  102769. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  102770. char *initial, long ibytes, ov_callbacks callbacks);
  102771. extern int ov_test_open(OggVorbis_File *vf);
  102772. extern long ov_bitrate(OggVorbis_File *vf,int i);
  102773. extern long ov_bitrate_instant(OggVorbis_File *vf);
  102774. extern long ov_streams(OggVorbis_File *vf);
  102775. extern long ov_seekable(OggVorbis_File *vf);
  102776. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  102777. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  102778. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  102779. extern double ov_time_total(OggVorbis_File *vf,int i);
  102780. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  102781. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  102782. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  102783. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  102784. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  102785. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  102786. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  102787. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  102788. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  102789. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  102790. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  102791. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  102792. extern double ov_time_tell(OggVorbis_File *vf);
  102793. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  102794. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  102795. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  102796. int *bitstream);
  102797. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  102798. int bigendianp,int word,int sgned,int *bitstream);
  102799. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  102800. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  102801. extern int ov_halfrate_p(OggVorbis_File *vf);
  102802. #ifdef __cplusplus
  102803. }
  102804. #endif /* __cplusplus */
  102805. #endif
  102806. /********* End of inlined file: vorbisfile.h *********/
  102807. /********* Start of inlined file: bitwise.c *********/
  102808. /* We're 'LSb' endian; if we write a word but read individual bits,
  102809. then we'll read the lsb first */
  102810. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  102811. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  102812. // tasks..
  102813. #ifdef _MSC_VER
  102814. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  102815. #endif
  102816. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  102817. #if JUCE_USE_OGGVORBIS
  102818. #include <string.h>
  102819. #include <stdlib.h>
  102820. #define BUFFER_INCREMENT 256
  102821. static const unsigned long mask[]=
  102822. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  102823. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  102824. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  102825. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  102826. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  102827. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  102828. 0x3fffffff,0x7fffffff,0xffffffff };
  102829. static const unsigned int mask8B[]=
  102830. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  102831. void oggpack_writeinit(oggpack_buffer *b){
  102832. memset(b,0,sizeof(*b));
  102833. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  102834. b->buffer[0]='\0';
  102835. b->storage=BUFFER_INCREMENT;
  102836. }
  102837. void oggpackB_writeinit(oggpack_buffer *b){
  102838. oggpack_writeinit(b);
  102839. }
  102840. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  102841. long bytes=bits>>3;
  102842. bits-=bytes*8;
  102843. b->ptr=b->buffer+bytes;
  102844. b->endbit=bits;
  102845. b->endbyte=bytes;
  102846. *b->ptr&=mask[bits];
  102847. }
  102848. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  102849. long bytes=bits>>3;
  102850. bits-=bytes*8;
  102851. b->ptr=b->buffer+bytes;
  102852. b->endbit=bits;
  102853. b->endbyte=bytes;
  102854. *b->ptr&=mask8B[bits];
  102855. }
  102856. /* Takes only up to 32 bits. */
  102857. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  102858. if(b->endbyte+4>=b->storage){
  102859. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  102860. b->storage+=BUFFER_INCREMENT;
  102861. b->ptr=b->buffer+b->endbyte;
  102862. }
  102863. value&=mask[bits];
  102864. bits+=b->endbit;
  102865. b->ptr[0]|=value<<b->endbit;
  102866. if(bits>=8){
  102867. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  102868. if(bits>=16){
  102869. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  102870. if(bits>=24){
  102871. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  102872. if(bits>=32){
  102873. if(b->endbit)
  102874. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  102875. else
  102876. b->ptr[4]=0;
  102877. }
  102878. }
  102879. }
  102880. }
  102881. b->endbyte+=bits/8;
  102882. b->ptr+=bits/8;
  102883. b->endbit=bits&7;
  102884. }
  102885. /* Takes only up to 32 bits. */
  102886. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  102887. if(b->endbyte+4>=b->storage){
  102888. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  102889. b->storage+=BUFFER_INCREMENT;
  102890. b->ptr=b->buffer+b->endbyte;
  102891. }
  102892. value=(value&mask[bits])<<(32-bits);
  102893. bits+=b->endbit;
  102894. b->ptr[0]|=value>>(24+b->endbit);
  102895. if(bits>=8){
  102896. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  102897. if(bits>=16){
  102898. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  102899. if(bits>=24){
  102900. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  102901. if(bits>=32){
  102902. if(b->endbit)
  102903. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  102904. else
  102905. b->ptr[4]=0;
  102906. }
  102907. }
  102908. }
  102909. }
  102910. b->endbyte+=bits/8;
  102911. b->ptr+=bits/8;
  102912. b->endbit=bits&7;
  102913. }
  102914. void oggpack_writealign(oggpack_buffer *b){
  102915. int bits=8-b->endbit;
  102916. if(bits<8)
  102917. oggpack_write(b,0,bits);
  102918. }
  102919. void oggpackB_writealign(oggpack_buffer *b){
  102920. int bits=8-b->endbit;
  102921. if(bits<8)
  102922. oggpackB_write(b,0,bits);
  102923. }
  102924. static void oggpack_writecopy_helper(oggpack_buffer *b,
  102925. void *source,
  102926. long bits,
  102927. void (*w)(oggpack_buffer *,
  102928. unsigned long,
  102929. int),
  102930. int msb){
  102931. unsigned char *ptr=(unsigned char *)source;
  102932. long bytes=bits/8;
  102933. bits-=bytes*8;
  102934. if(b->endbit){
  102935. int i;
  102936. /* unaligned copy. Do it the hard way. */
  102937. for(i=0;i<bytes;i++)
  102938. w(b,(unsigned long)(ptr[i]),8);
  102939. }else{
  102940. /* aligned block copy */
  102941. if(b->endbyte+bytes+1>=b->storage){
  102942. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  102943. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  102944. b->ptr=b->buffer+b->endbyte;
  102945. }
  102946. memmove(b->ptr,source,bytes);
  102947. b->ptr+=bytes;
  102948. b->endbyte+=bytes;
  102949. *b->ptr=0;
  102950. }
  102951. if(bits){
  102952. if(msb)
  102953. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  102954. else
  102955. w(b,(unsigned long)(ptr[bytes]),bits);
  102956. }
  102957. }
  102958. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  102959. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  102960. }
  102961. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  102962. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  102963. }
  102964. void oggpack_reset(oggpack_buffer *b){
  102965. b->ptr=b->buffer;
  102966. b->buffer[0]=0;
  102967. b->endbit=b->endbyte=0;
  102968. }
  102969. void oggpackB_reset(oggpack_buffer *b){
  102970. oggpack_reset(b);
  102971. }
  102972. void oggpack_writeclear(oggpack_buffer *b){
  102973. _ogg_free(b->buffer);
  102974. memset(b,0,sizeof(*b));
  102975. }
  102976. void oggpackB_writeclear(oggpack_buffer *b){
  102977. oggpack_writeclear(b);
  102978. }
  102979. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  102980. memset(b,0,sizeof(*b));
  102981. b->buffer=b->ptr=buf;
  102982. b->storage=bytes;
  102983. }
  102984. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  102985. oggpack_readinit(b,buf,bytes);
  102986. }
  102987. /* Read in bits without advancing the bitptr; bits <= 32 */
  102988. long oggpack_look(oggpack_buffer *b,int bits){
  102989. unsigned long ret;
  102990. unsigned long m=mask[bits];
  102991. bits+=b->endbit;
  102992. if(b->endbyte+4>=b->storage){
  102993. /* not the main path */
  102994. if(b->endbyte*8+bits>b->storage*8)return(-1);
  102995. }
  102996. ret=b->ptr[0]>>b->endbit;
  102997. if(bits>8){
  102998. ret|=b->ptr[1]<<(8-b->endbit);
  102999. if(bits>16){
  103000. ret|=b->ptr[2]<<(16-b->endbit);
  103001. if(bits>24){
  103002. ret|=b->ptr[3]<<(24-b->endbit);
  103003. if(bits>32 && b->endbit)
  103004. ret|=b->ptr[4]<<(32-b->endbit);
  103005. }
  103006. }
  103007. }
  103008. return(m&ret);
  103009. }
  103010. /* Read in bits without advancing the bitptr; bits <= 32 */
  103011. long oggpackB_look(oggpack_buffer *b,int bits){
  103012. unsigned long ret;
  103013. int m=32-bits;
  103014. bits+=b->endbit;
  103015. if(b->endbyte+4>=b->storage){
  103016. /* not the main path */
  103017. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103018. }
  103019. ret=b->ptr[0]<<(24+b->endbit);
  103020. if(bits>8){
  103021. ret|=b->ptr[1]<<(16+b->endbit);
  103022. if(bits>16){
  103023. ret|=b->ptr[2]<<(8+b->endbit);
  103024. if(bits>24){
  103025. ret|=b->ptr[3]<<(b->endbit);
  103026. if(bits>32 && b->endbit)
  103027. ret|=b->ptr[4]>>(8-b->endbit);
  103028. }
  103029. }
  103030. }
  103031. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  103032. }
  103033. long oggpack_look1(oggpack_buffer *b){
  103034. if(b->endbyte>=b->storage)return(-1);
  103035. return((b->ptr[0]>>b->endbit)&1);
  103036. }
  103037. long oggpackB_look1(oggpack_buffer *b){
  103038. if(b->endbyte>=b->storage)return(-1);
  103039. return((b->ptr[0]>>(7-b->endbit))&1);
  103040. }
  103041. void oggpack_adv(oggpack_buffer *b,int bits){
  103042. bits+=b->endbit;
  103043. b->ptr+=bits/8;
  103044. b->endbyte+=bits/8;
  103045. b->endbit=bits&7;
  103046. }
  103047. void oggpackB_adv(oggpack_buffer *b,int bits){
  103048. oggpack_adv(b,bits);
  103049. }
  103050. void oggpack_adv1(oggpack_buffer *b){
  103051. if(++(b->endbit)>7){
  103052. b->endbit=0;
  103053. b->ptr++;
  103054. b->endbyte++;
  103055. }
  103056. }
  103057. void oggpackB_adv1(oggpack_buffer *b){
  103058. oggpack_adv1(b);
  103059. }
  103060. /* bits <= 32 */
  103061. long oggpack_read(oggpack_buffer *b,int bits){
  103062. long ret;
  103063. unsigned long m=mask[bits];
  103064. bits+=b->endbit;
  103065. if(b->endbyte+4>=b->storage){
  103066. /* not the main path */
  103067. ret=-1L;
  103068. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103069. }
  103070. ret=b->ptr[0]>>b->endbit;
  103071. if(bits>8){
  103072. ret|=b->ptr[1]<<(8-b->endbit);
  103073. if(bits>16){
  103074. ret|=b->ptr[2]<<(16-b->endbit);
  103075. if(bits>24){
  103076. ret|=b->ptr[3]<<(24-b->endbit);
  103077. if(bits>32 && b->endbit){
  103078. ret|=b->ptr[4]<<(32-b->endbit);
  103079. }
  103080. }
  103081. }
  103082. }
  103083. ret&=m;
  103084. overflow:
  103085. b->ptr+=bits/8;
  103086. b->endbyte+=bits/8;
  103087. b->endbit=bits&7;
  103088. return(ret);
  103089. }
  103090. /* bits <= 32 */
  103091. long oggpackB_read(oggpack_buffer *b,int bits){
  103092. long ret;
  103093. long m=32-bits;
  103094. bits+=b->endbit;
  103095. if(b->endbyte+4>=b->storage){
  103096. /* not the main path */
  103097. ret=-1L;
  103098. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103099. }
  103100. ret=b->ptr[0]<<(24+b->endbit);
  103101. if(bits>8){
  103102. ret|=b->ptr[1]<<(16+b->endbit);
  103103. if(bits>16){
  103104. ret|=b->ptr[2]<<(8+b->endbit);
  103105. if(bits>24){
  103106. ret|=b->ptr[3]<<(b->endbit);
  103107. if(bits>32 && b->endbit)
  103108. ret|=b->ptr[4]>>(8-b->endbit);
  103109. }
  103110. }
  103111. }
  103112. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  103113. overflow:
  103114. b->ptr+=bits/8;
  103115. b->endbyte+=bits/8;
  103116. b->endbit=bits&7;
  103117. return(ret);
  103118. }
  103119. long oggpack_read1(oggpack_buffer *b){
  103120. long ret;
  103121. if(b->endbyte>=b->storage){
  103122. /* not the main path */
  103123. ret=-1L;
  103124. goto overflow;
  103125. }
  103126. ret=(b->ptr[0]>>b->endbit)&1;
  103127. overflow:
  103128. b->endbit++;
  103129. if(b->endbit>7){
  103130. b->endbit=0;
  103131. b->ptr++;
  103132. b->endbyte++;
  103133. }
  103134. return(ret);
  103135. }
  103136. long oggpackB_read1(oggpack_buffer *b){
  103137. long ret;
  103138. if(b->endbyte>=b->storage){
  103139. /* not the main path */
  103140. ret=-1L;
  103141. goto overflow;
  103142. }
  103143. ret=(b->ptr[0]>>(7-b->endbit))&1;
  103144. overflow:
  103145. b->endbit++;
  103146. if(b->endbit>7){
  103147. b->endbit=0;
  103148. b->ptr++;
  103149. b->endbyte++;
  103150. }
  103151. return(ret);
  103152. }
  103153. long oggpack_bytes(oggpack_buffer *b){
  103154. return(b->endbyte+(b->endbit+7)/8);
  103155. }
  103156. long oggpack_bits(oggpack_buffer *b){
  103157. return(b->endbyte*8+b->endbit);
  103158. }
  103159. long oggpackB_bytes(oggpack_buffer *b){
  103160. return oggpack_bytes(b);
  103161. }
  103162. long oggpackB_bits(oggpack_buffer *b){
  103163. return oggpack_bits(b);
  103164. }
  103165. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  103166. return(b->buffer);
  103167. }
  103168. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  103169. return oggpack_get_buffer(b);
  103170. }
  103171. /* Self test of the bitwise routines; everything else is based on
  103172. them, so they damned well better be solid. */
  103173. #ifdef _V_SELFTEST
  103174. #include <stdio.h>
  103175. static int ilog(unsigned int v){
  103176. int ret=0;
  103177. while(v){
  103178. ret++;
  103179. v>>=1;
  103180. }
  103181. return(ret);
  103182. }
  103183. oggpack_buffer o;
  103184. oggpack_buffer r;
  103185. void report(char *in){
  103186. fprintf(stderr,"%s",in);
  103187. exit(1);
  103188. }
  103189. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103190. long bytes,i;
  103191. unsigned char *buffer;
  103192. oggpack_reset(&o);
  103193. for(i=0;i<vals;i++)
  103194. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  103195. buffer=oggpack_get_buffer(&o);
  103196. bytes=oggpack_bytes(&o);
  103197. if(bytes!=compsize)report("wrong number of bytes!\n");
  103198. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103199. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103200. report("wrote incorrect value!\n");
  103201. }
  103202. oggpack_readinit(&r,buffer,bytes);
  103203. for(i=0;i<vals;i++){
  103204. int tbit=bits?bits:ilog(b[i]);
  103205. if(oggpack_look(&r,tbit)==-1)
  103206. report("out of data!\n");
  103207. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  103208. report("looked at incorrect value!\n");
  103209. if(tbit==1)
  103210. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  103211. report("looked at single bit incorrect value!\n");
  103212. if(tbit==1){
  103213. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  103214. report("read incorrect single bit value!\n");
  103215. }else{
  103216. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  103217. report("read incorrect value!\n");
  103218. }
  103219. }
  103220. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103221. }
  103222. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103223. long bytes,i;
  103224. unsigned char *buffer;
  103225. oggpackB_reset(&o);
  103226. for(i=0;i<vals;i++)
  103227. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  103228. buffer=oggpackB_get_buffer(&o);
  103229. bytes=oggpackB_bytes(&o);
  103230. if(bytes!=compsize)report("wrong number of bytes!\n");
  103231. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103232. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103233. report("wrote incorrect value!\n");
  103234. }
  103235. oggpackB_readinit(&r,buffer,bytes);
  103236. for(i=0;i<vals;i++){
  103237. int tbit=bits?bits:ilog(b[i]);
  103238. if(oggpackB_look(&r,tbit)==-1)
  103239. report("out of data!\n");
  103240. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  103241. report("looked at incorrect value!\n");
  103242. if(tbit==1)
  103243. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  103244. report("looked at single bit incorrect value!\n");
  103245. if(tbit==1){
  103246. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  103247. report("read incorrect single bit value!\n");
  103248. }else{
  103249. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  103250. report("read incorrect value!\n");
  103251. }
  103252. }
  103253. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103254. }
  103255. int main(void){
  103256. unsigned char *buffer;
  103257. long bytes,i;
  103258. static unsigned long testbuffer1[]=
  103259. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  103260. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  103261. int test1size=43;
  103262. static unsigned long testbuffer2[]=
  103263. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  103264. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  103265. 85525151,0,12321,1,349528352};
  103266. int test2size=21;
  103267. static unsigned long testbuffer3[]=
  103268. {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,
  103269. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  103270. int test3size=56;
  103271. static unsigned long large[]=
  103272. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  103273. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  103274. 85525151,0,12321,1,2146528352};
  103275. int onesize=33;
  103276. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  103277. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  103278. 223,4};
  103279. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  103280. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  103281. 245,251,128};
  103282. int twosize=6;
  103283. static int two[6]={61,255,255,251,231,29};
  103284. static int twoB[6]={247,63,255,253,249,120};
  103285. int threesize=54;
  103286. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  103287. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  103288. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  103289. 100,52,4,14,18,86,77,1};
  103290. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  103291. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  103292. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  103293. 200,20,254,4,58,106,176,144,0};
  103294. int foursize=38;
  103295. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  103296. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  103297. 28,2,133,0,1};
  103298. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  103299. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  103300. 129,10,4,32};
  103301. int fivesize=45;
  103302. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  103303. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  103304. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  103305. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  103306. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  103307. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  103308. int sixsize=7;
  103309. static int six[7]={17,177,170,242,169,19,148};
  103310. static int sixB[7]={136,141,85,79,149,200,41};
  103311. /* Test read/write together */
  103312. /* Later we test against pregenerated bitstreams */
  103313. oggpack_writeinit(&o);
  103314. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  103315. cliptest(testbuffer1,test1size,0,one,onesize);
  103316. fprintf(stderr,"ok.");
  103317. fprintf(stderr,"\nNull bit call (LSb): ");
  103318. cliptest(testbuffer3,test3size,0,two,twosize);
  103319. fprintf(stderr,"ok.");
  103320. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  103321. cliptest(testbuffer2,test2size,0,three,threesize);
  103322. fprintf(stderr,"ok.");
  103323. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  103324. oggpack_reset(&o);
  103325. for(i=0;i<test2size;i++)
  103326. oggpack_write(&o,large[i],32);
  103327. buffer=oggpack_get_buffer(&o);
  103328. bytes=oggpack_bytes(&o);
  103329. oggpack_readinit(&r,buffer,bytes);
  103330. for(i=0;i<test2size;i++){
  103331. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  103332. if(oggpack_look(&r,32)!=large[i]){
  103333. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  103334. oggpack_look(&r,32),large[i]);
  103335. report("read incorrect value!\n");
  103336. }
  103337. oggpack_adv(&r,32);
  103338. }
  103339. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103340. fprintf(stderr,"ok.");
  103341. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  103342. cliptest(testbuffer1,test1size,7,four,foursize);
  103343. fprintf(stderr,"ok.");
  103344. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  103345. cliptest(testbuffer2,test2size,17,five,fivesize);
  103346. fprintf(stderr,"ok.");
  103347. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  103348. cliptest(testbuffer3,test3size,1,six,sixsize);
  103349. fprintf(stderr,"ok.");
  103350. fprintf(stderr,"\nTesting read past end (LSb): ");
  103351. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103352. for(i=0;i<64;i++){
  103353. if(oggpack_read(&r,1)!=0){
  103354. fprintf(stderr,"failed; got -1 prematurely.\n");
  103355. exit(1);
  103356. }
  103357. }
  103358. if(oggpack_look(&r,1)!=-1 ||
  103359. oggpack_read(&r,1)!=-1){
  103360. fprintf(stderr,"failed; read past end without -1.\n");
  103361. exit(1);
  103362. }
  103363. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103364. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  103365. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  103366. exit(1);
  103367. }
  103368. if(oggpack_look(&r,18)!=0 ||
  103369. oggpack_look(&r,18)!=0){
  103370. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  103371. exit(1);
  103372. }
  103373. if(oggpack_look(&r,19)!=-1 ||
  103374. oggpack_look(&r,19)!=-1){
  103375. fprintf(stderr,"failed; read past end without -1.\n");
  103376. exit(1);
  103377. }
  103378. if(oggpack_look(&r,32)!=-1 ||
  103379. oggpack_look(&r,32)!=-1){
  103380. fprintf(stderr,"failed; read past end without -1.\n");
  103381. exit(1);
  103382. }
  103383. oggpack_writeclear(&o);
  103384. fprintf(stderr,"ok.\n");
  103385. /********** lazy, cut-n-paste retest with MSb packing ***********/
  103386. /* Test read/write together */
  103387. /* Later we test against pregenerated bitstreams */
  103388. oggpackB_writeinit(&o);
  103389. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  103390. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  103391. fprintf(stderr,"ok.");
  103392. fprintf(stderr,"\nNull bit call (MSb): ");
  103393. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  103394. fprintf(stderr,"ok.");
  103395. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  103396. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  103397. fprintf(stderr,"ok.");
  103398. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  103399. oggpackB_reset(&o);
  103400. for(i=0;i<test2size;i++)
  103401. oggpackB_write(&o,large[i],32);
  103402. buffer=oggpackB_get_buffer(&o);
  103403. bytes=oggpackB_bytes(&o);
  103404. oggpackB_readinit(&r,buffer,bytes);
  103405. for(i=0;i<test2size;i++){
  103406. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  103407. if(oggpackB_look(&r,32)!=large[i]){
  103408. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  103409. oggpackB_look(&r,32),large[i]);
  103410. report("read incorrect value!\n");
  103411. }
  103412. oggpackB_adv(&r,32);
  103413. }
  103414. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103415. fprintf(stderr,"ok.");
  103416. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  103417. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  103418. fprintf(stderr,"ok.");
  103419. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  103420. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  103421. fprintf(stderr,"ok.");
  103422. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  103423. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  103424. fprintf(stderr,"ok.");
  103425. fprintf(stderr,"\nTesting read past end (MSb): ");
  103426. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103427. for(i=0;i<64;i++){
  103428. if(oggpackB_read(&r,1)!=0){
  103429. fprintf(stderr,"failed; got -1 prematurely.\n");
  103430. exit(1);
  103431. }
  103432. }
  103433. if(oggpackB_look(&r,1)!=-1 ||
  103434. oggpackB_read(&r,1)!=-1){
  103435. fprintf(stderr,"failed; read past end without -1.\n");
  103436. exit(1);
  103437. }
  103438. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103439. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  103440. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  103441. exit(1);
  103442. }
  103443. if(oggpackB_look(&r,18)!=0 ||
  103444. oggpackB_look(&r,18)!=0){
  103445. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  103446. exit(1);
  103447. }
  103448. if(oggpackB_look(&r,19)!=-1 ||
  103449. oggpackB_look(&r,19)!=-1){
  103450. fprintf(stderr,"failed; read past end without -1.\n");
  103451. exit(1);
  103452. }
  103453. if(oggpackB_look(&r,32)!=-1 ||
  103454. oggpackB_look(&r,32)!=-1){
  103455. fprintf(stderr,"failed; read past end without -1.\n");
  103456. exit(1);
  103457. }
  103458. oggpackB_writeclear(&o);
  103459. fprintf(stderr,"ok.\n\n");
  103460. return(0);
  103461. }
  103462. #endif /* _V_SELFTEST */
  103463. #undef BUFFER_INCREMENT
  103464. #endif
  103465. /********* End of inlined file: bitwise.c *********/
  103466. /********* Start of inlined file: framing.c *********/
  103467. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103468. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103469. // tasks..
  103470. #ifdef _MSC_VER
  103471. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103472. #endif
  103473. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103474. #if JUCE_USE_OGGVORBIS
  103475. #include <stdlib.h>
  103476. #include <string.h>
  103477. /* A complete description of Ogg framing exists in docs/framing.html */
  103478. int ogg_page_version(ogg_page *og){
  103479. return((int)(og->header[4]));
  103480. }
  103481. int ogg_page_continued(ogg_page *og){
  103482. return((int)(og->header[5]&0x01));
  103483. }
  103484. int ogg_page_bos(ogg_page *og){
  103485. return((int)(og->header[5]&0x02));
  103486. }
  103487. int ogg_page_eos(ogg_page *og){
  103488. return((int)(og->header[5]&0x04));
  103489. }
  103490. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  103491. unsigned char *page=og->header;
  103492. ogg_int64_t granulepos=page[13]&(0xff);
  103493. granulepos= (granulepos<<8)|(page[12]&0xff);
  103494. granulepos= (granulepos<<8)|(page[11]&0xff);
  103495. granulepos= (granulepos<<8)|(page[10]&0xff);
  103496. granulepos= (granulepos<<8)|(page[9]&0xff);
  103497. granulepos= (granulepos<<8)|(page[8]&0xff);
  103498. granulepos= (granulepos<<8)|(page[7]&0xff);
  103499. granulepos= (granulepos<<8)|(page[6]&0xff);
  103500. return(granulepos);
  103501. }
  103502. int ogg_page_serialno(ogg_page *og){
  103503. return(og->header[14] |
  103504. (og->header[15]<<8) |
  103505. (og->header[16]<<16) |
  103506. (og->header[17]<<24));
  103507. }
  103508. long ogg_page_pageno(ogg_page *og){
  103509. return(og->header[18] |
  103510. (og->header[19]<<8) |
  103511. (og->header[20]<<16) |
  103512. (og->header[21]<<24));
  103513. }
  103514. /* returns the number of packets that are completed on this page (if
  103515. the leading packet is begun on a previous page, but ends on this
  103516. page, it's counted */
  103517. /* NOTE:
  103518. If a page consists of a packet begun on a previous page, and a new
  103519. packet begun (but not completed) on this page, the return will be:
  103520. ogg_page_packets(page) ==1,
  103521. ogg_page_continued(page) !=0
  103522. If a page happens to be a single packet that was begun on a
  103523. previous page, and spans to the next page (in the case of a three or
  103524. more page packet), the return will be:
  103525. ogg_page_packets(page) ==0,
  103526. ogg_page_continued(page) !=0
  103527. */
  103528. int ogg_page_packets(ogg_page *og){
  103529. int i,n=og->header[26],count=0;
  103530. for(i=0;i<n;i++)
  103531. if(og->header[27+i]<255)count++;
  103532. return(count);
  103533. }
  103534. #if 0
  103535. /* helper to initialize lookup for direct-table CRC (illustrative; we
  103536. use the static init below) */
  103537. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  103538. int i;
  103539. unsigned long r;
  103540. r = index << 24;
  103541. for (i=0; i<8; i++)
  103542. if (r & 0x80000000UL)
  103543. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  103544. polynomial, although we use an
  103545. unreflected alg and an init/final
  103546. of 0, not 0xffffffff */
  103547. else
  103548. r<<=1;
  103549. return (r & 0xffffffffUL);
  103550. }
  103551. #endif
  103552. static const ogg_uint32_t crc_lookup[256]={
  103553. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  103554. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  103555. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  103556. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  103557. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  103558. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  103559. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  103560. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  103561. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  103562. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  103563. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  103564. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  103565. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  103566. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  103567. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  103568. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  103569. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  103570. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  103571. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  103572. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  103573. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  103574. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  103575. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  103576. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  103577. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  103578. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  103579. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  103580. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  103581. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  103582. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  103583. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  103584. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  103585. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  103586. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  103587. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  103588. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  103589. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  103590. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  103591. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  103592. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  103593. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  103594. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  103595. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  103596. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  103597. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  103598. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  103599. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  103600. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  103601. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  103602. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  103603. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  103604. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  103605. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  103606. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  103607. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  103608. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  103609. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  103610. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  103611. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  103612. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  103613. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  103614. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  103615. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  103616. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  103617. /* init the encode/decode logical stream state */
  103618. int ogg_stream_init(ogg_stream_state *os,int serialno){
  103619. if(os){
  103620. memset(os,0,sizeof(*os));
  103621. os->body_storage=16*1024;
  103622. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  103623. os->lacing_storage=1024;
  103624. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  103625. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  103626. os->serialno=serialno;
  103627. return(0);
  103628. }
  103629. return(-1);
  103630. }
  103631. /* _clear does not free os, only the non-flat storage within */
  103632. int ogg_stream_clear(ogg_stream_state *os){
  103633. if(os){
  103634. if(os->body_data)_ogg_free(os->body_data);
  103635. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  103636. if(os->granule_vals)_ogg_free(os->granule_vals);
  103637. memset(os,0,sizeof(*os));
  103638. }
  103639. return(0);
  103640. }
  103641. int ogg_stream_destroy(ogg_stream_state *os){
  103642. if(os){
  103643. ogg_stream_clear(os);
  103644. _ogg_free(os);
  103645. }
  103646. return(0);
  103647. }
  103648. /* Helpers for ogg_stream_encode; this keeps the structure and
  103649. what's happening fairly clear */
  103650. static void _os_body_expand(ogg_stream_state *os,int needed){
  103651. if(os->body_storage<=os->body_fill+needed){
  103652. os->body_storage+=(needed+1024);
  103653. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  103654. }
  103655. }
  103656. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  103657. if(os->lacing_storage<=os->lacing_fill+needed){
  103658. os->lacing_storage+=(needed+32);
  103659. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  103660. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  103661. }
  103662. }
  103663. /* checksum the page */
  103664. /* Direct table CRC; note that this will be faster in the future if we
  103665. perform the checksum silmultaneously with other copies */
  103666. void ogg_page_checksum_set(ogg_page *og){
  103667. if(og){
  103668. ogg_uint32_t crc_reg=0;
  103669. int i;
  103670. /* safety; needed for API behavior, but not framing code */
  103671. og->header[22]=0;
  103672. og->header[23]=0;
  103673. og->header[24]=0;
  103674. og->header[25]=0;
  103675. for(i=0;i<og->header_len;i++)
  103676. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  103677. for(i=0;i<og->body_len;i++)
  103678. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  103679. og->header[22]=(unsigned char)(crc_reg&0xff);
  103680. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  103681. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  103682. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  103683. }
  103684. }
  103685. /* submit data to the internal buffer of the framing engine */
  103686. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  103687. int lacing_vals=op->bytes/255+1,i;
  103688. if(os->body_returned){
  103689. /* advance packet data according to the body_returned pointer. We
  103690. had to keep it around to return a pointer into the buffer last
  103691. call */
  103692. os->body_fill-=os->body_returned;
  103693. if(os->body_fill)
  103694. memmove(os->body_data,os->body_data+os->body_returned,
  103695. os->body_fill);
  103696. os->body_returned=0;
  103697. }
  103698. /* make sure we have the buffer storage */
  103699. _os_body_expand(os,op->bytes);
  103700. _os_lacing_expand(os,lacing_vals);
  103701. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  103702. the liability of overly clean abstraction for the time being. It
  103703. will actually be fairly easy to eliminate the extra copy in the
  103704. future */
  103705. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  103706. os->body_fill+=op->bytes;
  103707. /* Store lacing vals for this packet */
  103708. for(i=0;i<lacing_vals-1;i++){
  103709. os->lacing_vals[os->lacing_fill+i]=255;
  103710. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  103711. }
  103712. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  103713. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  103714. /* flag the first segment as the beginning of the packet */
  103715. os->lacing_vals[os->lacing_fill]|= 0x100;
  103716. os->lacing_fill+=lacing_vals;
  103717. /* for the sake of completeness */
  103718. os->packetno++;
  103719. if(op->e_o_s)os->e_o_s=1;
  103720. return(0);
  103721. }
  103722. /* This will flush remaining packets into a page (returning nonzero),
  103723. even if there is not enough data to trigger a flush normally
  103724. (undersized page). If there are no packets or partial packets to
  103725. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  103726. try to flush a normal sized page like ogg_stream_pageout; a call to
  103727. ogg_stream_flush does not guarantee that all packets have flushed.
  103728. Only a return value of 0 from ogg_stream_flush indicates all packet
  103729. data is flushed into pages.
  103730. since ogg_stream_flush will flush the last page in a stream even if
  103731. it's undersized, you almost certainly want to use ogg_stream_pageout
  103732. (and *not* ogg_stream_flush) unless you specifically need to flush
  103733. an page regardless of size in the middle of a stream. */
  103734. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  103735. int i;
  103736. int vals=0;
  103737. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  103738. int bytes=0;
  103739. long acc=0;
  103740. ogg_int64_t granule_pos=-1;
  103741. if(maxvals==0)return(0);
  103742. /* construct a page */
  103743. /* decide how many segments to include */
  103744. /* If this is the initial header case, the first page must only include
  103745. the initial header packet */
  103746. if(os->b_o_s==0){ /* 'initial header page' case */
  103747. granule_pos=0;
  103748. for(vals=0;vals<maxvals;vals++){
  103749. if((os->lacing_vals[vals]&0x0ff)<255){
  103750. vals++;
  103751. break;
  103752. }
  103753. }
  103754. }else{
  103755. for(vals=0;vals<maxvals;vals++){
  103756. if(acc>4096)break;
  103757. acc+=os->lacing_vals[vals]&0x0ff;
  103758. if((os->lacing_vals[vals]&0xff)<255)
  103759. granule_pos=os->granule_vals[vals];
  103760. }
  103761. }
  103762. /* construct the header in temp storage */
  103763. memcpy(os->header,"OggS",4);
  103764. /* stream structure version */
  103765. os->header[4]=0x00;
  103766. /* continued packet flag? */
  103767. os->header[5]=0x00;
  103768. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  103769. /* first page flag? */
  103770. if(os->b_o_s==0)os->header[5]|=0x02;
  103771. /* last page flag? */
  103772. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  103773. os->b_o_s=1;
  103774. /* 64 bits of PCM position */
  103775. for(i=6;i<14;i++){
  103776. os->header[i]=(unsigned char)(granule_pos&0xff);
  103777. granule_pos>>=8;
  103778. }
  103779. /* 32 bits of stream serial number */
  103780. {
  103781. long serialno=os->serialno;
  103782. for(i=14;i<18;i++){
  103783. os->header[i]=(unsigned char)(serialno&0xff);
  103784. serialno>>=8;
  103785. }
  103786. }
  103787. /* 32 bits of page counter (we have both counter and page header
  103788. because this val can roll over) */
  103789. if(os->pageno==-1)os->pageno=0; /* because someone called
  103790. stream_reset; this would be a
  103791. strange thing to do in an
  103792. encode stream, but it has
  103793. plausible uses */
  103794. {
  103795. long pageno=os->pageno++;
  103796. for(i=18;i<22;i++){
  103797. os->header[i]=(unsigned char)(pageno&0xff);
  103798. pageno>>=8;
  103799. }
  103800. }
  103801. /* zero for computation; filled in later */
  103802. os->header[22]=0;
  103803. os->header[23]=0;
  103804. os->header[24]=0;
  103805. os->header[25]=0;
  103806. /* segment table */
  103807. os->header[26]=(unsigned char)(vals&0xff);
  103808. for(i=0;i<vals;i++)
  103809. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  103810. /* set pointers in the ogg_page struct */
  103811. og->header=os->header;
  103812. og->header_len=os->header_fill=vals+27;
  103813. og->body=os->body_data+os->body_returned;
  103814. og->body_len=bytes;
  103815. /* advance the lacing data and set the body_returned pointer */
  103816. os->lacing_fill-=vals;
  103817. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  103818. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  103819. os->body_returned+=bytes;
  103820. /* calculate the checksum */
  103821. ogg_page_checksum_set(og);
  103822. /* done */
  103823. return(1);
  103824. }
  103825. /* This constructs pages from buffered packet segments. The pointers
  103826. returned are to static buffers; do not free. The returned buffers are
  103827. good only until the next call (using the same ogg_stream_state) */
  103828. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  103829. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  103830. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  103831. os->lacing_fill>=255 || /* 'segment table full' case */
  103832. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  103833. return(ogg_stream_flush(os,og));
  103834. }
  103835. /* not enough data to construct a page and not end of stream */
  103836. return(0);
  103837. }
  103838. int ogg_stream_eos(ogg_stream_state *os){
  103839. return os->e_o_s;
  103840. }
  103841. /* DECODING PRIMITIVES: packet streaming layer **********************/
  103842. /* This has two layers to place more of the multi-serialno and paging
  103843. control in the application's hands. First, we expose a data buffer
  103844. using ogg_sync_buffer(). The app either copies into the
  103845. buffer, or passes it directly to read(), etc. We then call
  103846. ogg_sync_wrote() to tell how many bytes we just added.
  103847. Pages are returned (pointers into the buffer in ogg_sync_state)
  103848. by ogg_sync_pageout(). The page is then submitted to
  103849. ogg_stream_pagein() along with the appropriate
  103850. ogg_stream_state* (ie, matching serialno). We then get raw
  103851. packets out calling ogg_stream_packetout() with a
  103852. ogg_stream_state. */
  103853. /* initialize the struct to a known state */
  103854. int ogg_sync_init(ogg_sync_state *oy){
  103855. if(oy){
  103856. memset(oy,0,sizeof(*oy));
  103857. }
  103858. return(0);
  103859. }
  103860. /* clear non-flat storage within */
  103861. int ogg_sync_clear(ogg_sync_state *oy){
  103862. if(oy){
  103863. if(oy->data)_ogg_free(oy->data);
  103864. ogg_sync_init(oy);
  103865. }
  103866. return(0);
  103867. }
  103868. int ogg_sync_destroy(ogg_sync_state *oy){
  103869. if(oy){
  103870. ogg_sync_clear(oy);
  103871. _ogg_free(oy);
  103872. }
  103873. return(0);
  103874. }
  103875. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  103876. /* first, clear out any space that has been previously returned */
  103877. if(oy->returned){
  103878. oy->fill-=oy->returned;
  103879. if(oy->fill>0)
  103880. memmove(oy->data,oy->data+oy->returned,oy->fill);
  103881. oy->returned=0;
  103882. }
  103883. if(size>oy->storage-oy->fill){
  103884. /* We need to extend the internal buffer */
  103885. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  103886. if(oy->data)
  103887. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  103888. else
  103889. oy->data=(unsigned char*) _ogg_malloc(newsize);
  103890. oy->storage=newsize;
  103891. }
  103892. /* expose a segment at least as large as requested at the fill mark */
  103893. return((char *)oy->data+oy->fill);
  103894. }
  103895. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  103896. if(oy->fill+bytes>oy->storage)return(-1);
  103897. oy->fill+=bytes;
  103898. return(0);
  103899. }
  103900. /* sync the stream. This is meant to be useful for finding page
  103901. boundaries.
  103902. return values for this:
  103903. -n) skipped n bytes
  103904. 0) page not ready; more data (no bytes skipped)
  103905. n) page synced at current location; page length n bytes
  103906. */
  103907. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  103908. unsigned char *page=oy->data+oy->returned;
  103909. unsigned char *next;
  103910. long bytes=oy->fill-oy->returned;
  103911. if(oy->headerbytes==0){
  103912. int headerbytes,i;
  103913. if(bytes<27)return(0); /* not enough for a header */
  103914. /* verify capture pattern */
  103915. if(memcmp(page,"OggS",4))goto sync_fail;
  103916. headerbytes=page[26]+27;
  103917. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  103918. /* count up body length in the segment table */
  103919. for(i=0;i<page[26];i++)
  103920. oy->bodybytes+=page[27+i];
  103921. oy->headerbytes=headerbytes;
  103922. }
  103923. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  103924. /* The whole test page is buffered. Verify the checksum */
  103925. {
  103926. /* Grab the checksum bytes, set the header field to zero */
  103927. char chksum[4];
  103928. ogg_page log;
  103929. memcpy(chksum,page+22,4);
  103930. memset(page+22,0,4);
  103931. /* set up a temp page struct and recompute the checksum */
  103932. log.header=page;
  103933. log.header_len=oy->headerbytes;
  103934. log.body=page+oy->headerbytes;
  103935. log.body_len=oy->bodybytes;
  103936. ogg_page_checksum_set(&log);
  103937. /* Compare */
  103938. if(memcmp(chksum,page+22,4)){
  103939. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  103940. at all) */
  103941. /* replace the computed checksum with the one actually read in */
  103942. memcpy(page+22,chksum,4);
  103943. /* Bad checksum. Lose sync */
  103944. goto sync_fail;
  103945. }
  103946. }
  103947. /* yes, have a whole page all ready to go */
  103948. {
  103949. unsigned char *page=oy->data+oy->returned;
  103950. long bytes;
  103951. if(og){
  103952. og->header=page;
  103953. og->header_len=oy->headerbytes;
  103954. og->body=page+oy->headerbytes;
  103955. og->body_len=oy->bodybytes;
  103956. }
  103957. oy->unsynced=0;
  103958. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  103959. oy->headerbytes=0;
  103960. oy->bodybytes=0;
  103961. return(bytes);
  103962. }
  103963. sync_fail:
  103964. oy->headerbytes=0;
  103965. oy->bodybytes=0;
  103966. /* search for possible capture */
  103967. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  103968. if(!next)
  103969. next=oy->data+oy->fill;
  103970. oy->returned=next-oy->data;
  103971. return(-(next-page));
  103972. }
  103973. /* sync the stream and get a page. Keep trying until we find a page.
  103974. Supress 'sync errors' after reporting the first.
  103975. return values:
  103976. -1) recapture (hole in data)
  103977. 0) need more data
  103978. 1) page returned
  103979. Returns pointers into buffered data; invalidated by next call to
  103980. _stream, _clear, _init, or _buffer */
  103981. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  103982. /* all we need to do is verify a page at the head of the stream
  103983. buffer. If it doesn't verify, we look for the next potential
  103984. frame */
  103985. for(;;){
  103986. long ret=ogg_sync_pageseek(oy,og);
  103987. if(ret>0){
  103988. /* have a page */
  103989. return(1);
  103990. }
  103991. if(ret==0){
  103992. /* need more data */
  103993. return(0);
  103994. }
  103995. /* head did not start a synced page... skipped some bytes */
  103996. if(!oy->unsynced){
  103997. oy->unsynced=1;
  103998. return(-1);
  103999. }
  104000. /* loop. keep looking */
  104001. }
  104002. }
  104003. /* add the incoming page to the stream state; we decompose the page
  104004. into packet segments here as well. */
  104005. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  104006. unsigned char *header=og->header;
  104007. unsigned char *body=og->body;
  104008. long bodysize=og->body_len;
  104009. int segptr=0;
  104010. int version=ogg_page_version(og);
  104011. int continued=ogg_page_continued(og);
  104012. int bos=ogg_page_bos(og);
  104013. int eos=ogg_page_eos(og);
  104014. ogg_int64_t granulepos=ogg_page_granulepos(og);
  104015. int serialno=ogg_page_serialno(og);
  104016. long pageno=ogg_page_pageno(og);
  104017. int segments=header[26];
  104018. /* clean up 'returned data' */
  104019. {
  104020. long lr=os->lacing_returned;
  104021. long br=os->body_returned;
  104022. /* body data */
  104023. if(br){
  104024. os->body_fill-=br;
  104025. if(os->body_fill)
  104026. memmove(os->body_data,os->body_data+br,os->body_fill);
  104027. os->body_returned=0;
  104028. }
  104029. if(lr){
  104030. /* segment table */
  104031. if(os->lacing_fill-lr){
  104032. memmove(os->lacing_vals,os->lacing_vals+lr,
  104033. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  104034. memmove(os->granule_vals,os->granule_vals+lr,
  104035. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  104036. }
  104037. os->lacing_fill-=lr;
  104038. os->lacing_packet-=lr;
  104039. os->lacing_returned=0;
  104040. }
  104041. }
  104042. /* check the serial number */
  104043. if(serialno!=os->serialno)return(-1);
  104044. if(version>0)return(-1);
  104045. _os_lacing_expand(os,segments+1);
  104046. /* are we in sequence? */
  104047. if(pageno!=os->pageno){
  104048. int i;
  104049. /* unroll previous partial packet (if any) */
  104050. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  104051. os->body_fill-=os->lacing_vals[i]&0xff;
  104052. os->lacing_fill=os->lacing_packet;
  104053. /* make a note of dropped data in segment table */
  104054. if(os->pageno!=-1){
  104055. os->lacing_vals[os->lacing_fill++]=0x400;
  104056. os->lacing_packet++;
  104057. }
  104058. }
  104059. /* are we a 'continued packet' page? If so, we may need to skip
  104060. some segments */
  104061. if(continued){
  104062. if(os->lacing_fill<1 ||
  104063. os->lacing_vals[os->lacing_fill-1]==0x400){
  104064. bos=0;
  104065. for(;segptr<segments;segptr++){
  104066. int val=header[27+segptr];
  104067. body+=val;
  104068. bodysize-=val;
  104069. if(val<255){
  104070. segptr++;
  104071. break;
  104072. }
  104073. }
  104074. }
  104075. }
  104076. if(bodysize){
  104077. _os_body_expand(os,bodysize);
  104078. memcpy(os->body_data+os->body_fill,body,bodysize);
  104079. os->body_fill+=bodysize;
  104080. }
  104081. {
  104082. int saved=-1;
  104083. while(segptr<segments){
  104084. int val=header[27+segptr];
  104085. os->lacing_vals[os->lacing_fill]=val;
  104086. os->granule_vals[os->lacing_fill]=-1;
  104087. if(bos){
  104088. os->lacing_vals[os->lacing_fill]|=0x100;
  104089. bos=0;
  104090. }
  104091. if(val<255)saved=os->lacing_fill;
  104092. os->lacing_fill++;
  104093. segptr++;
  104094. if(val<255)os->lacing_packet=os->lacing_fill;
  104095. }
  104096. /* set the granulepos on the last granuleval of the last full packet */
  104097. if(saved!=-1){
  104098. os->granule_vals[saved]=granulepos;
  104099. }
  104100. }
  104101. if(eos){
  104102. os->e_o_s=1;
  104103. if(os->lacing_fill>0)
  104104. os->lacing_vals[os->lacing_fill-1]|=0x200;
  104105. }
  104106. os->pageno=pageno+1;
  104107. return(0);
  104108. }
  104109. /* clear things to an initial state. Good to call, eg, before seeking */
  104110. int ogg_sync_reset(ogg_sync_state *oy){
  104111. oy->fill=0;
  104112. oy->returned=0;
  104113. oy->unsynced=0;
  104114. oy->headerbytes=0;
  104115. oy->bodybytes=0;
  104116. return(0);
  104117. }
  104118. int ogg_stream_reset(ogg_stream_state *os){
  104119. os->body_fill=0;
  104120. os->body_returned=0;
  104121. os->lacing_fill=0;
  104122. os->lacing_packet=0;
  104123. os->lacing_returned=0;
  104124. os->header_fill=0;
  104125. os->e_o_s=0;
  104126. os->b_o_s=0;
  104127. os->pageno=-1;
  104128. os->packetno=0;
  104129. os->granulepos=0;
  104130. return(0);
  104131. }
  104132. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  104133. ogg_stream_reset(os);
  104134. os->serialno=serialno;
  104135. return(0);
  104136. }
  104137. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  104138. /* The last part of decode. We have the stream broken into packet
  104139. segments. Now we need to group them into packets (or return the
  104140. out of sync markers) */
  104141. int ptr=os->lacing_returned;
  104142. if(os->lacing_packet<=ptr)return(0);
  104143. if(os->lacing_vals[ptr]&0x400){
  104144. /* we need to tell the codec there's a gap; it might need to
  104145. handle previous packet dependencies. */
  104146. os->lacing_returned++;
  104147. os->packetno++;
  104148. return(-1);
  104149. }
  104150. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  104151. to ask if there's a whole packet
  104152. waiting */
  104153. /* Gather the whole packet. We'll have no holes or a partial packet */
  104154. {
  104155. int size=os->lacing_vals[ptr]&0xff;
  104156. int bytes=size;
  104157. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  104158. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  104159. while(size==255){
  104160. int val=os->lacing_vals[++ptr];
  104161. size=val&0xff;
  104162. if(val&0x200)eos=0x200;
  104163. bytes+=size;
  104164. }
  104165. if(op){
  104166. op->e_o_s=eos;
  104167. op->b_o_s=bos;
  104168. op->packet=os->body_data+os->body_returned;
  104169. op->packetno=os->packetno;
  104170. op->granulepos=os->granule_vals[ptr];
  104171. op->bytes=bytes;
  104172. }
  104173. if(adv){
  104174. os->body_returned+=bytes;
  104175. os->lacing_returned=ptr+1;
  104176. os->packetno++;
  104177. }
  104178. }
  104179. return(1);
  104180. }
  104181. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  104182. return _packetout(os,op,1);
  104183. }
  104184. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  104185. return _packetout(os,op,0);
  104186. }
  104187. void ogg_packet_clear(ogg_packet *op) {
  104188. _ogg_free(op->packet);
  104189. memset(op, 0, sizeof(*op));
  104190. }
  104191. #ifdef _V_SELFTEST
  104192. #include <stdio.h>
  104193. ogg_stream_state os_en, os_de;
  104194. ogg_sync_state oy;
  104195. void checkpacket(ogg_packet *op,int len, int no, int pos){
  104196. long j;
  104197. static int sequence=0;
  104198. static int lastno=0;
  104199. if(op->bytes!=len){
  104200. fprintf(stderr,"incorrect packet length!\n");
  104201. exit(1);
  104202. }
  104203. if(op->granulepos!=pos){
  104204. fprintf(stderr,"incorrect packet position!\n");
  104205. exit(1);
  104206. }
  104207. /* packet number just follows sequence/gap; adjust the input number
  104208. for that */
  104209. if(no==0){
  104210. sequence=0;
  104211. }else{
  104212. sequence++;
  104213. if(no>lastno+1)
  104214. sequence++;
  104215. }
  104216. lastno=no;
  104217. if(op->packetno!=sequence){
  104218. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  104219. (long)(op->packetno),sequence);
  104220. exit(1);
  104221. }
  104222. /* Test data */
  104223. for(j=0;j<op->bytes;j++)
  104224. if(op->packet[j]!=((j+no)&0xff)){
  104225. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  104226. j,op->packet[j],(j+no)&0xff);
  104227. exit(1);
  104228. }
  104229. }
  104230. void check_page(unsigned char *data,const int *header,ogg_page *og){
  104231. long j;
  104232. /* Test data */
  104233. for(j=0;j<og->body_len;j++)
  104234. if(og->body[j]!=data[j]){
  104235. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  104236. j,data[j],og->body[j]);
  104237. exit(1);
  104238. }
  104239. /* Test header */
  104240. for(j=0;j<og->header_len;j++){
  104241. if(og->header[j]!=header[j]){
  104242. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  104243. for(j=0;j<header[26]+27;j++)
  104244. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  104245. fprintf(stderr,"\n");
  104246. exit(1);
  104247. }
  104248. }
  104249. if(og->header_len!=header[26]+27){
  104250. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  104251. og->header_len,header[26]+27);
  104252. exit(1);
  104253. }
  104254. }
  104255. void print_header(ogg_page *og){
  104256. int j;
  104257. fprintf(stderr,"\nHEADER:\n");
  104258. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  104259. og->header[0],og->header[1],og->header[2],og->header[3],
  104260. (int)og->header[4],(int)og->header[5]);
  104261. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  104262. (og->header[9]<<24)|(og->header[8]<<16)|
  104263. (og->header[7]<<8)|og->header[6],
  104264. (og->header[17]<<24)|(og->header[16]<<16)|
  104265. (og->header[15]<<8)|og->header[14],
  104266. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  104267. (og->header[19]<<8)|og->header[18]);
  104268. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  104269. (int)og->header[22],(int)og->header[23],
  104270. (int)og->header[24],(int)og->header[25],
  104271. (int)og->header[26]);
  104272. for(j=27;j<og->header_len;j++)
  104273. fprintf(stderr,"%d ",(int)og->header[j]);
  104274. fprintf(stderr,")\n\n");
  104275. }
  104276. void copy_page(ogg_page *og){
  104277. unsigned char *temp=_ogg_malloc(og->header_len);
  104278. memcpy(temp,og->header,og->header_len);
  104279. og->header=temp;
  104280. temp=_ogg_malloc(og->body_len);
  104281. memcpy(temp,og->body,og->body_len);
  104282. og->body=temp;
  104283. }
  104284. void free_page(ogg_page *og){
  104285. _ogg_free (og->header);
  104286. _ogg_free (og->body);
  104287. }
  104288. void error(void){
  104289. fprintf(stderr,"error!\n");
  104290. exit(1);
  104291. }
  104292. /* 17 only */
  104293. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  104294. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104295. 0x01,0x02,0x03,0x04,0,0,0,0,
  104296. 0x15,0xed,0xec,0x91,
  104297. 1,
  104298. 17};
  104299. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  104300. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104301. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104302. 0x01,0x02,0x03,0x04,0,0,0,0,
  104303. 0x59,0x10,0x6c,0x2c,
  104304. 1,
  104305. 17};
  104306. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104307. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  104308. 0x01,0x02,0x03,0x04,1,0,0,0,
  104309. 0x89,0x33,0x85,0xce,
  104310. 13,
  104311. 254,255,0,255,1,255,245,255,255,0,
  104312. 255,255,90};
  104313. /* nil packets; beginning,middle,end */
  104314. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104315. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104316. 0x01,0x02,0x03,0x04,0,0,0,0,
  104317. 0xff,0x7b,0x23,0x17,
  104318. 1,
  104319. 0};
  104320. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104321. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  104322. 0x01,0x02,0x03,0x04,1,0,0,0,
  104323. 0x5c,0x3f,0x66,0xcb,
  104324. 17,
  104325. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  104326. 255,255,90,0};
  104327. /* large initial packet */
  104328. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104329. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104330. 0x01,0x02,0x03,0x04,0,0,0,0,
  104331. 0x01,0x27,0x31,0xaa,
  104332. 18,
  104333. 255,255,255,255,255,255,255,255,
  104334. 255,255,255,255,255,255,255,255,255,10};
  104335. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104336. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104337. 0x01,0x02,0x03,0x04,1,0,0,0,
  104338. 0x7f,0x4e,0x8a,0xd2,
  104339. 4,
  104340. 255,4,255,0};
  104341. /* continuing packet test */
  104342. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104343. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104344. 0x01,0x02,0x03,0x04,0,0,0,0,
  104345. 0xff,0x7b,0x23,0x17,
  104346. 1,
  104347. 0};
  104348. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104349. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  104350. 0x01,0x02,0x03,0x04,1,0,0,0,
  104351. 0x54,0x05,0x51,0xc8,
  104352. 17,
  104353. 255,255,255,255,255,255,255,255,
  104354. 255,255,255,255,255,255,255,255,255};
  104355. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104356. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  104357. 0x01,0x02,0x03,0x04,2,0,0,0,
  104358. 0xc8,0xc3,0xcb,0xed,
  104359. 5,
  104360. 10,255,4,255,0};
  104361. /* page with the 255 segment limit */
  104362. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104363. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104364. 0x01,0x02,0x03,0x04,0,0,0,0,
  104365. 0xff,0x7b,0x23,0x17,
  104366. 1,
  104367. 0};
  104368. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104369. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  104370. 0x01,0x02,0x03,0x04,1,0,0,0,
  104371. 0xed,0x2a,0x2e,0xa7,
  104372. 255,
  104373. 10,10,10,10,10,10,10,10,
  104374. 10,10,10,10,10,10,10,10,
  104375. 10,10,10,10,10,10,10,10,
  104376. 10,10,10,10,10,10,10,10,
  104377. 10,10,10,10,10,10,10,10,
  104378. 10,10,10,10,10,10,10,10,
  104379. 10,10,10,10,10,10,10,10,
  104380. 10,10,10,10,10,10,10,10,
  104381. 10,10,10,10,10,10,10,10,
  104382. 10,10,10,10,10,10,10,10,
  104383. 10,10,10,10,10,10,10,10,
  104384. 10,10,10,10,10,10,10,10,
  104385. 10,10,10,10,10,10,10,10,
  104386. 10,10,10,10,10,10,10,10,
  104387. 10,10,10,10,10,10,10,10,
  104388. 10,10,10,10,10,10,10,10,
  104389. 10,10,10,10,10,10,10,10,
  104390. 10,10,10,10,10,10,10,10,
  104391. 10,10,10,10,10,10,10,10,
  104392. 10,10,10,10,10,10,10,10,
  104393. 10,10,10,10,10,10,10,10,
  104394. 10,10,10,10,10,10,10,10,
  104395. 10,10,10,10,10,10,10,10,
  104396. 10,10,10,10,10,10,10,10,
  104397. 10,10,10,10,10,10,10,10,
  104398. 10,10,10,10,10,10,10,10,
  104399. 10,10,10,10,10,10,10,10,
  104400. 10,10,10,10,10,10,10,10,
  104401. 10,10,10,10,10,10,10,10,
  104402. 10,10,10,10,10,10,10,10,
  104403. 10,10,10,10,10,10,10,10,
  104404. 10,10,10,10,10,10,10};
  104405. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104406. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  104407. 0x01,0x02,0x03,0x04,2,0,0,0,
  104408. 0x6c,0x3b,0x82,0x3d,
  104409. 1,
  104410. 50};
  104411. /* packet that overspans over an entire page */
  104412. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104413. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104414. 0x01,0x02,0x03,0x04,0,0,0,0,
  104415. 0xff,0x7b,0x23,0x17,
  104416. 1,
  104417. 0};
  104418. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104419. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  104420. 0x01,0x02,0x03,0x04,1,0,0,0,
  104421. 0x3c,0xd9,0x4d,0x3f,
  104422. 17,
  104423. 100,255,255,255,255,255,255,255,255,
  104424. 255,255,255,255,255,255,255,255};
  104425. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  104426. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  104427. 0x01,0x02,0x03,0x04,2,0,0,0,
  104428. 0x01,0xd2,0xe5,0xe5,
  104429. 17,
  104430. 255,255,255,255,255,255,255,255,
  104431. 255,255,255,255,255,255,255,255,255};
  104432. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104433. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  104434. 0x01,0x02,0x03,0x04,3,0,0,0,
  104435. 0xef,0xdd,0x88,0xde,
  104436. 7,
  104437. 255,255,75,255,4,255,0};
  104438. /* packet that overspans over an entire page */
  104439. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104440. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104441. 0x01,0x02,0x03,0x04,0,0,0,0,
  104442. 0xff,0x7b,0x23,0x17,
  104443. 1,
  104444. 0};
  104445. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104446. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  104447. 0x01,0x02,0x03,0x04,1,0,0,0,
  104448. 0x3c,0xd9,0x4d,0x3f,
  104449. 17,
  104450. 100,255,255,255,255,255,255,255,255,
  104451. 255,255,255,255,255,255,255,255};
  104452. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104453. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104454. 0x01,0x02,0x03,0x04,2,0,0,0,
  104455. 0xd4,0xe0,0x60,0xe5,
  104456. 1,0};
  104457. void test_pack(const int *pl, const int **headers, int byteskip,
  104458. int pageskip, int packetskip){
  104459. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  104460. long inptr=0;
  104461. long outptr=0;
  104462. long deptr=0;
  104463. long depacket=0;
  104464. long granule_pos=7,pageno=0;
  104465. int i,j,packets,pageout=pageskip;
  104466. int eosflag=0;
  104467. int bosflag=0;
  104468. int byteskipcount=0;
  104469. ogg_stream_reset(&os_en);
  104470. ogg_stream_reset(&os_de);
  104471. ogg_sync_reset(&oy);
  104472. for(packets=0;packets<packetskip;packets++)
  104473. depacket+=pl[packets];
  104474. for(packets=0;;packets++)if(pl[packets]==-1)break;
  104475. for(i=0;i<packets;i++){
  104476. /* construct a test packet */
  104477. ogg_packet op;
  104478. int len=pl[i];
  104479. op.packet=data+inptr;
  104480. op.bytes=len;
  104481. op.e_o_s=(pl[i+1]<0?1:0);
  104482. op.granulepos=granule_pos;
  104483. granule_pos+=1024;
  104484. for(j=0;j<len;j++)data[inptr++]=i+j;
  104485. /* submit the test packet */
  104486. ogg_stream_packetin(&os_en,&op);
  104487. /* retrieve any finished pages */
  104488. {
  104489. ogg_page og;
  104490. while(ogg_stream_pageout(&os_en,&og)){
  104491. /* We have a page. Check it carefully */
  104492. fprintf(stderr,"%ld, ",pageno);
  104493. if(headers[pageno]==NULL){
  104494. fprintf(stderr,"coded too many pages!\n");
  104495. exit(1);
  104496. }
  104497. check_page(data+outptr,headers[pageno],&og);
  104498. outptr+=og.body_len;
  104499. pageno++;
  104500. if(pageskip){
  104501. bosflag=1;
  104502. pageskip--;
  104503. deptr+=og.body_len;
  104504. }
  104505. /* have a complete page; submit it to sync/decode */
  104506. {
  104507. ogg_page og_de;
  104508. ogg_packet op_de,op_de2;
  104509. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  104510. char *next=buf;
  104511. byteskipcount+=og.header_len;
  104512. if(byteskipcount>byteskip){
  104513. memcpy(next,og.header,byteskipcount-byteskip);
  104514. next+=byteskipcount-byteskip;
  104515. byteskipcount=byteskip;
  104516. }
  104517. byteskipcount+=og.body_len;
  104518. if(byteskipcount>byteskip){
  104519. memcpy(next,og.body,byteskipcount-byteskip);
  104520. next+=byteskipcount-byteskip;
  104521. byteskipcount=byteskip;
  104522. }
  104523. ogg_sync_wrote(&oy,next-buf);
  104524. while(1){
  104525. int ret=ogg_sync_pageout(&oy,&og_de);
  104526. if(ret==0)break;
  104527. if(ret<0)continue;
  104528. /* got a page. Happy happy. Verify that it's good. */
  104529. fprintf(stderr,"(%ld), ",pageout);
  104530. check_page(data+deptr,headers[pageout],&og_de);
  104531. deptr+=og_de.body_len;
  104532. pageout++;
  104533. /* submit it to deconstitution */
  104534. ogg_stream_pagein(&os_de,&og_de);
  104535. /* packets out? */
  104536. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  104537. ogg_stream_packetpeek(&os_de,NULL);
  104538. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  104539. /* verify peek and out match */
  104540. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  104541. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  104542. depacket);
  104543. exit(1);
  104544. }
  104545. /* verify the packet! */
  104546. /* check data */
  104547. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  104548. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  104549. depacket);
  104550. exit(1);
  104551. }
  104552. /* check bos flag */
  104553. if(bosflag==0 && op_de.b_o_s==0){
  104554. fprintf(stderr,"b_o_s flag not set on packet!\n");
  104555. exit(1);
  104556. }
  104557. if(bosflag && op_de.b_o_s){
  104558. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  104559. exit(1);
  104560. }
  104561. bosflag=1;
  104562. depacket+=op_de.bytes;
  104563. /* check eos flag */
  104564. if(eosflag){
  104565. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  104566. exit(1);
  104567. }
  104568. if(op_de.e_o_s)eosflag=1;
  104569. /* check granulepos flag */
  104570. if(op_de.granulepos!=-1){
  104571. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  104572. }
  104573. }
  104574. }
  104575. }
  104576. }
  104577. }
  104578. }
  104579. _ogg_free(data);
  104580. if(headers[pageno]!=NULL){
  104581. fprintf(stderr,"did not write last page!\n");
  104582. exit(1);
  104583. }
  104584. if(headers[pageout]!=NULL){
  104585. fprintf(stderr,"did not decode last page!\n");
  104586. exit(1);
  104587. }
  104588. if(inptr!=outptr){
  104589. fprintf(stderr,"encoded page data incomplete!\n");
  104590. exit(1);
  104591. }
  104592. if(inptr!=deptr){
  104593. fprintf(stderr,"decoded page data incomplete!\n");
  104594. exit(1);
  104595. }
  104596. if(inptr!=depacket){
  104597. fprintf(stderr,"decoded packet data incomplete!\n");
  104598. exit(1);
  104599. }
  104600. if(!eosflag){
  104601. fprintf(stderr,"Never got a packet with EOS set!\n");
  104602. exit(1);
  104603. }
  104604. fprintf(stderr,"ok.\n");
  104605. }
  104606. int main(void){
  104607. ogg_stream_init(&os_en,0x04030201);
  104608. ogg_stream_init(&os_de,0x04030201);
  104609. ogg_sync_init(&oy);
  104610. /* Exercise each code path in the framing code. Also verify that
  104611. the checksums are working. */
  104612. {
  104613. /* 17 only */
  104614. const int packets[]={17, -1};
  104615. const int *headret[]={head1_0,NULL};
  104616. fprintf(stderr,"testing single page encoding... ");
  104617. test_pack(packets,headret,0,0,0);
  104618. }
  104619. {
  104620. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  104621. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  104622. const int *headret[]={head1_1,head2_1,NULL};
  104623. fprintf(stderr,"testing basic page encoding... ");
  104624. test_pack(packets,headret,0,0,0);
  104625. }
  104626. {
  104627. /* nil packets; beginning,middle,end */
  104628. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  104629. const int *headret[]={head1_2,head2_2,NULL};
  104630. fprintf(stderr,"testing basic nil packets... ");
  104631. test_pack(packets,headret,0,0,0);
  104632. }
  104633. {
  104634. /* large initial packet */
  104635. const int packets[]={4345,259,255,-1};
  104636. const int *headret[]={head1_3,head2_3,NULL};
  104637. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  104638. test_pack(packets,headret,0,0,0);
  104639. }
  104640. {
  104641. /* continuing packet test */
  104642. const int packets[]={0,4345,259,255,-1};
  104643. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  104644. fprintf(stderr,"testing single packet page span... ");
  104645. test_pack(packets,headret,0,0,0);
  104646. }
  104647. /* page with the 255 segment limit */
  104648. {
  104649. const int packets[]={0,10,10,10,10,10,10,10,10,
  104650. 10,10,10,10,10,10,10,10,
  104651. 10,10,10,10,10,10,10,10,
  104652. 10,10,10,10,10,10,10,10,
  104653. 10,10,10,10,10,10,10,10,
  104654. 10,10,10,10,10,10,10,10,
  104655. 10,10,10,10,10,10,10,10,
  104656. 10,10,10,10,10,10,10,10,
  104657. 10,10,10,10,10,10,10,10,
  104658. 10,10,10,10,10,10,10,10,
  104659. 10,10,10,10,10,10,10,10,
  104660. 10,10,10,10,10,10,10,10,
  104661. 10,10,10,10,10,10,10,10,
  104662. 10,10,10,10,10,10,10,10,
  104663. 10,10,10,10,10,10,10,10,
  104664. 10,10,10,10,10,10,10,10,
  104665. 10,10,10,10,10,10,10,10,
  104666. 10,10,10,10,10,10,10,10,
  104667. 10,10,10,10,10,10,10,10,
  104668. 10,10,10,10,10,10,10,10,
  104669. 10,10,10,10,10,10,10,10,
  104670. 10,10,10,10,10,10,10,10,
  104671. 10,10,10,10,10,10,10,10,
  104672. 10,10,10,10,10,10,10,10,
  104673. 10,10,10,10,10,10,10,10,
  104674. 10,10,10,10,10,10,10,10,
  104675. 10,10,10,10,10,10,10,10,
  104676. 10,10,10,10,10,10,10,10,
  104677. 10,10,10,10,10,10,10,10,
  104678. 10,10,10,10,10,10,10,10,
  104679. 10,10,10,10,10,10,10,10,
  104680. 10,10,10,10,10,10,10,50,-1};
  104681. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  104682. fprintf(stderr,"testing max packet segments... ");
  104683. test_pack(packets,headret,0,0,0);
  104684. }
  104685. {
  104686. /* packet that overspans over an entire page */
  104687. const int packets[]={0,100,9000,259,255,-1};
  104688. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  104689. fprintf(stderr,"testing very large packets... ");
  104690. test_pack(packets,headret,0,0,0);
  104691. }
  104692. {
  104693. /* test for the libogg 1.1.1 resync in large continuation bug
  104694. found by Josh Coalson) */
  104695. const int packets[]={0,100,9000,259,255,-1};
  104696. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  104697. fprintf(stderr,"testing continuation resync in very large packets... ");
  104698. test_pack(packets,headret,100,2,3);
  104699. }
  104700. {
  104701. /* term only page. why not? */
  104702. const int packets[]={0,100,4080,-1};
  104703. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  104704. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  104705. test_pack(packets,headret,0,0,0);
  104706. }
  104707. {
  104708. /* build a bunch of pages for testing */
  104709. unsigned char *data=_ogg_malloc(1024*1024);
  104710. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  104711. int inptr=0,i,j;
  104712. ogg_page og[5];
  104713. ogg_stream_reset(&os_en);
  104714. for(i=0;pl[i]!=-1;i++){
  104715. ogg_packet op;
  104716. int len=pl[i];
  104717. op.packet=data+inptr;
  104718. op.bytes=len;
  104719. op.e_o_s=(pl[i+1]<0?1:0);
  104720. op.granulepos=(i+1)*1000;
  104721. for(j=0;j<len;j++)data[inptr++]=i+j;
  104722. ogg_stream_packetin(&os_en,&op);
  104723. }
  104724. _ogg_free(data);
  104725. /* retrieve finished pages */
  104726. for(i=0;i<5;i++){
  104727. if(ogg_stream_pageout(&os_en,&og[i])==0){
  104728. fprintf(stderr,"Too few pages output building sync tests!\n");
  104729. exit(1);
  104730. }
  104731. copy_page(&og[i]);
  104732. }
  104733. /* Test lost pages on pagein/packetout: no rollback */
  104734. {
  104735. ogg_page temp;
  104736. ogg_packet test;
  104737. fprintf(stderr,"Testing loss of pages... ");
  104738. ogg_sync_reset(&oy);
  104739. ogg_stream_reset(&os_de);
  104740. for(i=0;i<5;i++){
  104741. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  104742. og[i].header_len);
  104743. ogg_sync_wrote(&oy,og[i].header_len);
  104744. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  104745. ogg_sync_wrote(&oy,og[i].body_len);
  104746. }
  104747. ogg_sync_pageout(&oy,&temp);
  104748. ogg_stream_pagein(&os_de,&temp);
  104749. ogg_sync_pageout(&oy,&temp);
  104750. ogg_stream_pagein(&os_de,&temp);
  104751. ogg_sync_pageout(&oy,&temp);
  104752. /* skip */
  104753. ogg_sync_pageout(&oy,&temp);
  104754. ogg_stream_pagein(&os_de,&temp);
  104755. /* do we get the expected results/packets? */
  104756. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104757. checkpacket(&test,0,0,0);
  104758. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104759. checkpacket(&test,100,1,-1);
  104760. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104761. checkpacket(&test,4079,2,3000);
  104762. if(ogg_stream_packetout(&os_de,&test)!=-1){
  104763. fprintf(stderr,"Error: loss of page did not return error\n");
  104764. exit(1);
  104765. }
  104766. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104767. checkpacket(&test,76,5,-1);
  104768. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104769. checkpacket(&test,34,6,-1);
  104770. fprintf(stderr,"ok.\n");
  104771. }
  104772. /* Test lost pages on pagein/packetout: rollback with continuation */
  104773. {
  104774. ogg_page temp;
  104775. ogg_packet test;
  104776. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  104777. ogg_sync_reset(&oy);
  104778. ogg_stream_reset(&os_de);
  104779. for(i=0;i<5;i++){
  104780. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  104781. og[i].header_len);
  104782. ogg_sync_wrote(&oy,og[i].header_len);
  104783. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  104784. ogg_sync_wrote(&oy,og[i].body_len);
  104785. }
  104786. ogg_sync_pageout(&oy,&temp);
  104787. ogg_stream_pagein(&os_de,&temp);
  104788. ogg_sync_pageout(&oy,&temp);
  104789. ogg_stream_pagein(&os_de,&temp);
  104790. ogg_sync_pageout(&oy,&temp);
  104791. ogg_stream_pagein(&os_de,&temp);
  104792. ogg_sync_pageout(&oy,&temp);
  104793. /* skip */
  104794. ogg_sync_pageout(&oy,&temp);
  104795. ogg_stream_pagein(&os_de,&temp);
  104796. /* do we get the expected results/packets? */
  104797. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104798. checkpacket(&test,0,0,0);
  104799. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104800. checkpacket(&test,100,1,-1);
  104801. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104802. checkpacket(&test,4079,2,3000);
  104803. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104804. checkpacket(&test,2956,3,4000);
  104805. if(ogg_stream_packetout(&os_de,&test)!=-1){
  104806. fprintf(stderr,"Error: loss of page did not return error\n");
  104807. exit(1);
  104808. }
  104809. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104810. checkpacket(&test,300,13,14000);
  104811. fprintf(stderr,"ok.\n");
  104812. }
  104813. /* the rest only test sync */
  104814. {
  104815. ogg_page og_de;
  104816. /* Test fractional page inputs: incomplete capture */
  104817. fprintf(stderr,"Testing sync on partial inputs... ");
  104818. ogg_sync_reset(&oy);
  104819. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104820. 3);
  104821. ogg_sync_wrote(&oy,3);
  104822. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104823. /* Test fractional page inputs: incomplete fixed header */
  104824. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  104825. 20);
  104826. ogg_sync_wrote(&oy,20);
  104827. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104828. /* Test fractional page inputs: incomplete header */
  104829. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  104830. 5);
  104831. ogg_sync_wrote(&oy,5);
  104832. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104833. /* Test fractional page inputs: incomplete body */
  104834. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  104835. og[1].header_len-28);
  104836. ogg_sync_wrote(&oy,og[1].header_len-28);
  104837. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104838. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  104839. ogg_sync_wrote(&oy,1000);
  104840. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104841. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  104842. og[1].body_len-1000);
  104843. ogg_sync_wrote(&oy,og[1].body_len-1000);
  104844. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104845. fprintf(stderr,"ok.\n");
  104846. }
  104847. /* Test fractional page inputs: page + incomplete capture */
  104848. {
  104849. ogg_page og_de;
  104850. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  104851. ogg_sync_reset(&oy);
  104852. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104853. og[1].header_len);
  104854. ogg_sync_wrote(&oy,og[1].header_len);
  104855. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104856. og[1].body_len);
  104857. ogg_sync_wrote(&oy,og[1].body_len);
  104858. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104859. 20);
  104860. ogg_sync_wrote(&oy,20);
  104861. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104862. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104863. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  104864. og[1].header_len-20);
  104865. ogg_sync_wrote(&oy,og[1].header_len-20);
  104866. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104867. og[1].body_len);
  104868. ogg_sync_wrote(&oy,og[1].body_len);
  104869. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104870. fprintf(stderr,"ok.\n");
  104871. }
  104872. /* Test recapture: garbage + page */
  104873. {
  104874. ogg_page og_de;
  104875. fprintf(stderr,"Testing search for capture... ");
  104876. ogg_sync_reset(&oy);
  104877. /* 'garbage' */
  104878. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104879. og[1].body_len);
  104880. ogg_sync_wrote(&oy,og[1].body_len);
  104881. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104882. og[1].header_len);
  104883. ogg_sync_wrote(&oy,og[1].header_len);
  104884. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104885. og[1].body_len);
  104886. ogg_sync_wrote(&oy,og[1].body_len);
  104887. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  104888. 20);
  104889. ogg_sync_wrote(&oy,20);
  104890. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104891. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104892. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104893. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  104894. og[2].header_len-20);
  104895. ogg_sync_wrote(&oy,og[2].header_len-20);
  104896. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  104897. og[2].body_len);
  104898. ogg_sync_wrote(&oy,og[2].body_len);
  104899. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104900. fprintf(stderr,"ok.\n");
  104901. }
  104902. /* Test recapture: page + garbage + page */
  104903. {
  104904. ogg_page og_de;
  104905. fprintf(stderr,"Testing recapture... ");
  104906. ogg_sync_reset(&oy);
  104907. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104908. og[1].header_len);
  104909. ogg_sync_wrote(&oy,og[1].header_len);
  104910. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104911. og[1].body_len);
  104912. ogg_sync_wrote(&oy,og[1].body_len);
  104913. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  104914. og[2].header_len);
  104915. ogg_sync_wrote(&oy,og[2].header_len);
  104916. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  104917. og[2].header_len);
  104918. ogg_sync_wrote(&oy,og[2].header_len);
  104919. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104920. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  104921. og[2].body_len-5);
  104922. ogg_sync_wrote(&oy,og[2].body_len-5);
  104923. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  104924. og[3].header_len);
  104925. ogg_sync_wrote(&oy,og[3].header_len);
  104926. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  104927. og[3].body_len);
  104928. ogg_sync_wrote(&oy,og[3].body_len);
  104929. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104930. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104931. fprintf(stderr,"ok.\n");
  104932. }
  104933. /* Free page data that was previously copied */
  104934. {
  104935. for(i=0;i<5;i++){
  104936. free_page(&og[i]);
  104937. }
  104938. }
  104939. }
  104940. return(0);
  104941. }
  104942. #endif
  104943. #endif
  104944. /********* End of inlined file: framing.c *********/
  104945. /********* Start of inlined file: analysis.c *********/
  104946. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104947. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104948. // tasks..
  104949. #ifdef _MSC_VER
  104950. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104951. #endif
  104952. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104953. #if JUCE_USE_OGGVORBIS
  104954. #include <stdio.h>
  104955. #include <string.h>
  104956. #include <math.h>
  104957. /********* Start of inlined file: codec_internal.h *********/
  104958. #ifndef _V_CODECI_H_
  104959. #define _V_CODECI_H_
  104960. /********* Start of inlined file: envelope.h *********/
  104961. #ifndef _V_ENVELOPE_
  104962. #define _V_ENVELOPE_
  104963. /********* Start of inlined file: mdct.h *********/
  104964. #ifndef _OGG_mdct_H_
  104965. #define _OGG_mdct_H_
  104966. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  104967. #ifdef MDCT_INTEGERIZED
  104968. #define DATA_TYPE int
  104969. #define REG_TYPE register int
  104970. #define TRIGBITS 14
  104971. #define cPI3_8 6270
  104972. #define cPI2_8 11585
  104973. #define cPI1_8 15137
  104974. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  104975. #define MULT_NORM(x) ((x)>>TRIGBITS)
  104976. #define HALVE(x) ((x)>>1)
  104977. #else
  104978. #define DATA_TYPE float
  104979. #define REG_TYPE float
  104980. #define cPI3_8 .38268343236508977175F
  104981. #define cPI2_8 .70710678118654752441F
  104982. #define cPI1_8 .92387953251128675613F
  104983. #define FLOAT_CONV(x) (x)
  104984. #define MULT_NORM(x) (x)
  104985. #define HALVE(x) ((x)*.5f)
  104986. #endif
  104987. typedef struct {
  104988. int n;
  104989. int log2n;
  104990. DATA_TYPE *trig;
  104991. int *bitrev;
  104992. DATA_TYPE scale;
  104993. } mdct_lookup;
  104994. extern void mdct_init(mdct_lookup *lookup,int n);
  104995. extern void mdct_clear(mdct_lookup *l);
  104996. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  104997. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  104998. #endif
  104999. /********* End of inlined file: mdct.h *********/
  105000. #define VE_PRE 16
  105001. #define VE_WIN 4
  105002. #define VE_POST 2
  105003. #define VE_AMP (VE_PRE+VE_POST-1)
  105004. #define VE_BANDS 7
  105005. #define VE_NEARDC 15
  105006. #define VE_MINSTRETCH 2 /* a bit less than short block */
  105007. #define VE_MAXSTRETCH 12 /* one-third full block */
  105008. typedef struct {
  105009. float ampbuf[VE_AMP];
  105010. int ampptr;
  105011. float nearDC[VE_NEARDC];
  105012. float nearDC_acc;
  105013. float nearDC_partialacc;
  105014. int nearptr;
  105015. } envelope_filter_state;
  105016. typedef struct {
  105017. int begin;
  105018. int end;
  105019. float *window;
  105020. float total;
  105021. } envelope_band;
  105022. typedef struct {
  105023. int ch;
  105024. int winlength;
  105025. int searchstep;
  105026. float minenergy;
  105027. mdct_lookup mdct;
  105028. float *mdct_win;
  105029. envelope_band band[VE_BANDS];
  105030. envelope_filter_state *filter;
  105031. int stretch;
  105032. int *mark;
  105033. long storage;
  105034. long current;
  105035. long curmark;
  105036. long cursor;
  105037. } envelope_lookup;
  105038. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  105039. extern void _ve_envelope_clear(envelope_lookup *e);
  105040. extern long _ve_envelope_search(vorbis_dsp_state *v);
  105041. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  105042. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  105043. #endif
  105044. /********* End of inlined file: envelope.h *********/
  105045. /********* Start of inlined file: codebook.h *********/
  105046. #ifndef _V_CODEBOOK_H_
  105047. #define _V_CODEBOOK_H_
  105048. /* This structure encapsulates huffman and VQ style encoding books; it
  105049. doesn't do anything specific to either.
  105050. valuelist/quantlist are nonNULL (and q_* significant) only if
  105051. there's entry->value mapping to be done.
  105052. If encode-side mapping must be done (and thus the entry needs to be
  105053. hunted), the auxiliary encode pointer will point to a decision
  105054. tree. This is true of both VQ and huffman, but is mostly useful
  105055. with VQ.
  105056. */
  105057. typedef struct static_codebook{
  105058. long dim; /* codebook dimensions (elements per vector) */
  105059. long entries; /* codebook entries */
  105060. long *lengthlist; /* codeword lengths in bits */
  105061. /* mapping ***************************************************************/
  105062. int maptype; /* 0=none
  105063. 1=implicitly populated values from map column
  105064. 2=listed arbitrary values */
  105065. /* The below does a linear, single monotonic sequence mapping. */
  105066. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  105067. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  105068. int q_quant; /* bits: 0 < quant <= 16 */
  105069. int q_sequencep; /* bitflag */
  105070. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  105071. map == 2: list of dim*entries quantized entry vals
  105072. */
  105073. /* encode helpers ********************************************************/
  105074. struct encode_aux_nearestmatch *nearest_tree;
  105075. struct encode_aux_threshmatch *thresh_tree;
  105076. struct encode_aux_pigeonhole *pigeon_tree;
  105077. int allocedp;
  105078. } static_codebook;
  105079. /* this structures an arbitrary trained book to quickly find the
  105080. nearest cell match */
  105081. typedef struct encode_aux_nearestmatch{
  105082. /* pre-calculated partitioning tree */
  105083. long *ptr0;
  105084. long *ptr1;
  105085. long *p; /* decision points (each is an entry) */
  105086. long *q; /* decision points (each is an entry) */
  105087. long aux; /* number of tree entries */
  105088. long alloc;
  105089. } encode_aux_nearestmatch;
  105090. /* assumes a maptype of 1; encode side only, so that's OK */
  105091. typedef struct encode_aux_threshmatch{
  105092. float *quantthresh;
  105093. long *quantmap;
  105094. int quantvals;
  105095. int threshvals;
  105096. } encode_aux_threshmatch;
  105097. typedef struct encode_aux_pigeonhole{
  105098. float min;
  105099. float del;
  105100. int mapentries;
  105101. int quantvals;
  105102. long *pigeonmap;
  105103. long fittotal;
  105104. long *fitlist;
  105105. long *fitmap;
  105106. long *fitlength;
  105107. } encode_aux_pigeonhole;
  105108. typedef struct codebook{
  105109. long dim; /* codebook dimensions (elements per vector) */
  105110. long entries; /* codebook entries */
  105111. long used_entries; /* populated codebook entries */
  105112. const static_codebook *c;
  105113. /* for encode, the below are entry-ordered, fully populated */
  105114. /* for decode, the below are ordered by bitreversed codeword and only
  105115. used entries are populated */
  105116. float *valuelist; /* list of dim*entries actual entry values */
  105117. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  105118. int *dec_index; /* only used if sparseness collapsed */
  105119. char *dec_codelengths;
  105120. ogg_uint32_t *dec_firsttable;
  105121. int dec_firsttablen;
  105122. int dec_maxlength;
  105123. } codebook;
  105124. extern void vorbis_staticbook_clear(static_codebook *b);
  105125. extern void vorbis_staticbook_destroy(static_codebook *b);
  105126. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  105127. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  105128. extern void vorbis_book_clear(codebook *b);
  105129. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  105130. extern float *_book_logdist(const static_codebook *b,float *vals);
  105131. extern float _float32_unpack(long val);
  105132. extern long _float32_pack(float val);
  105133. extern int _best(codebook *book, float *a, int step);
  105134. extern int _ilog(unsigned int v);
  105135. extern long _book_maptype1_quantvals(const static_codebook *b);
  105136. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  105137. extern long vorbis_book_codeword(codebook *book,int entry);
  105138. extern long vorbis_book_codelen(codebook *book,int entry);
  105139. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  105140. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  105141. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  105142. extern int vorbis_book_errorv(codebook *book, float *a);
  105143. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  105144. oggpack_buffer *b);
  105145. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  105146. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  105147. oggpack_buffer *b,int n);
  105148. extern long vorbis_book_decodev_set(codebook *book, float *a,
  105149. oggpack_buffer *b,int n);
  105150. extern long vorbis_book_decodev_add(codebook *book, float *a,
  105151. oggpack_buffer *b,int n);
  105152. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  105153. long off,int ch,
  105154. oggpack_buffer *b,int n);
  105155. #endif
  105156. /********* End of inlined file: codebook.h *********/
  105157. #define BLOCKTYPE_IMPULSE 0
  105158. #define BLOCKTYPE_PADDING 1
  105159. #define BLOCKTYPE_TRANSITION 0
  105160. #define BLOCKTYPE_LONG 1
  105161. #define PACKETBLOBS 15
  105162. typedef struct vorbis_block_internal{
  105163. float **pcmdelay; /* this is a pointer into local storage */
  105164. float ampmax;
  105165. int blocktype;
  105166. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  105167. blob [PACKETBLOBS/2] points to
  105168. the oggpack_buffer in the
  105169. main vorbis_block */
  105170. } vorbis_block_internal;
  105171. typedef void vorbis_look_floor;
  105172. typedef void vorbis_look_residue;
  105173. typedef void vorbis_look_transform;
  105174. /* mode ************************************************************/
  105175. typedef struct {
  105176. int blockflag;
  105177. int windowtype;
  105178. int transformtype;
  105179. int mapping;
  105180. } vorbis_info_mode;
  105181. typedef void vorbis_info_floor;
  105182. typedef void vorbis_info_residue;
  105183. typedef void vorbis_info_mapping;
  105184. /********* Start of inlined file: psy.h *********/
  105185. #ifndef _V_PSY_H_
  105186. #define _V_PSY_H_
  105187. /********* Start of inlined file: smallft.h *********/
  105188. #ifndef _V_SMFT_H_
  105189. #define _V_SMFT_H_
  105190. typedef struct {
  105191. int n;
  105192. float *trigcache;
  105193. int *splitcache;
  105194. } drft_lookup;
  105195. extern void drft_forward(drft_lookup *l,float *data);
  105196. extern void drft_backward(drft_lookup *l,float *data);
  105197. extern void drft_init(drft_lookup *l,int n);
  105198. extern void drft_clear(drft_lookup *l);
  105199. #endif
  105200. /********* End of inlined file: smallft.h *********/
  105201. /********* Start of inlined file: backends.h *********/
  105202. /* this is exposed up here because we need it for static modes.
  105203. Lookups for each backend aren't exposed because there's no reason
  105204. to do so */
  105205. #ifndef _vorbis_backend_h_
  105206. #define _vorbis_backend_h_
  105207. /* this would all be simpler/shorter with templates, but.... */
  105208. /* Floor backend generic *****************************************/
  105209. typedef struct{
  105210. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  105211. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  105212. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  105213. void (*free_info) (vorbis_info_floor *);
  105214. void (*free_look) (vorbis_look_floor *);
  105215. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  105216. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  105217. void *buffer,float *);
  105218. } vorbis_func_floor;
  105219. typedef struct{
  105220. int order;
  105221. long rate;
  105222. long barkmap;
  105223. int ampbits;
  105224. int ampdB;
  105225. int numbooks; /* <= 16 */
  105226. int books[16];
  105227. float lessthan; /* encode-only config setting hacks for libvorbis */
  105228. float greaterthan; /* encode-only config setting hacks for libvorbis */
  105229. } vorbis_info_floor0;
  105230. #define VIF_POSIT 63
  105231. #define VIF_CLASS 16
  105232. #define VIF_PARTS 31
  105233. typedef struct{
  105234. int partitions; /* 0 to 31 */
  105235. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  105236. int class_dim[VIF_CLASS]; /* 1 to 8 */
  105237. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  105238. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  105239. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  105240. int mult; /* 1 2 3 or 4 */
  105241. int postlist[VIF_POSIT+2]; /* first two implicit */
  105242. /* encode side analysis parameters */
  105243. float maxover;
  105244. float maxunder;
  105245. float maxerr;
  105246. float twofitweight;
  105247. float twofitatten;
  105248. int n;
  105249. } vorbis_info_floor1;
  105250. /* Residue backend generic *****************************************/
  105251. typedef struct{
  105252. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  105253. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  105254. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  105255. vorbis_info_residue *);
  105256. void (*free_info) (vorbis_info_residue *);
  105257. void (*free_look) (vorbis_look_residue *);
  105258. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  105259. float **,int *,int);
  105260. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  105261. vorbis_look_residue *,
  105262. float **,float **,int *,int,long **);
  105263. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  105264. float **,int *,int);
  105265. } vorbis_func_residue;
  105266. typedef struct vorbis_info_residue0{
  105267. /* block-partitioned VQ coded straight residue */
  105268. long begin;
  105269. long end;
  105270. /* first stage (lossless partitioning) */
  105271. int grouping; /* group n vectors per partition */
  105272. int partitions; /* possible codebooks for a partition */
  105273. int groupbook; /* huffbook for partitioning */
  105274. int secondstages[64]; /* expanded out to pointers in lookup */
  105275. int booklist[256]; /* list of second stage books */
  105276. float classmetric1[64];
  105277. float classmetric2[64];
  105278. } vorbis_info_residue0;
  105279. /* Mapping backend generic *****************************************/
  105280. typedef struct{
  105281. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  105282. oggpack_buffer *);
  105283. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  105284. void (*free_info) (vorbis_info_mapping *);
  105285. int (*forward) (struct vorbis_block *vb);
  105286. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  105287. } vorbis_func_mapping;
  105288. typedef struct vorbis_info_mapping0{
  105289. int submaps; /* <= 16 */
  105290. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  105291. int floorsubmap[16]; /* [mux] submap to floors */
  105292. int residuesubmap[16]; /* [mux] submap to residue */
  105293. int coupling_steps;
  105294. int coupling_mag[256];
  105295. int coupling_ang[256];
  105296. } vorbis_info_mapping0;
  105297. #endif
  105298. /********* End of inlined file: backends.h *********/
  105299. #ifndef EHMER_MAX
  105300. #define EHMER_MAX 56
  105301. #endif
  105302. /* psychoacoustic setup ********************************************/
  105303. #define P_BANDS 17 /* 62Hz to 16kHz */
  105304. #define P_LEVELS 8 /* 30dB to 100dB */
  105305. #define P_LEVEL_0 30. /* 30 dB */
  105306. #define P_NOISECURVES 3
  105307. #define NOISE_COMPAND_LEVELS 40
  105308. typedef struct vorbis_info_psy{
  105309. int blockflag;
  105310. float ath_adjatt;
  105311. float ath_maxatt;
  105312. float tone_masteratt[P_NOISECURVES];
  105313. float tone_centerboost;
  105314. float tone_decay;
  105315. float tone_abs_limit;
  105316. float toneatt[P_BANDS];
  105317. int noisemaskp;
  105318. float noisemaxsupp;
  105319. float noisewindowlo;
  105320. float noisewindowhi;
  105321. int noisewindowlomin;
  105322. int noisewindowhimin;
  105323. int noisewindowfixed;
  105324. float noiseoff[P_NOISECURVES][P_BANDS];
  105325. float noisecompand[NOISE_COMPAND_LEVELS];
  105326. float max_curve_dB;
  105327. int normal_channel_p;
  105328. int normal_point_p;
  105329. int normal_start;
  105330. int normal_partition;
  105331. double normal_thresh;
  105332. } vorbis_info_psy;
  105333. typedef struct{
  105334. int eighth_octave_lines;
  105335. /* for block long/short tuning; encode only */
  105336. float preecho_thresh[VE_BANDS];
  105337. float postecho_thresh[VE_BANDS];
  105338. float stretch_penalty;
  105339. float preecho_minenergy;
  105340. float ampmax_att_per_sec;
  105341. /* channel coupling config */
  105342. int coupling_pkHz[PACKETBLOBS];
  105343. int coupling_pointlimit[2][PACKETBLOBS];
  105344. int coupling_prepointamp[PACKETBLOBS];
  105345. int coupling_postpointamp[PACKETBLOBS];
  105346. int sliding_lowpass[2][PACKETBLOBS];
  105347. } vorbis_info_psy_global;
  105348. typedef struct {
  105349. float ampmax;
  105350. int channels;
  105351. vorbis_info_psy_global *gi;
  105352. int coupling_pointlimit[2][P_NOISECURVES];
  105353. } vorbis_look_psy_global;
  105354. typedef struct {
  105355. int n;
  105356. struct vorbis_info_psy *vi;
  105357. float ***tonecurves;
  105358. float **noiseoffset;
  105359. float *ath;
  105360. long *octave; /* in n.ocshift format */
  105361. long *bark;
  105362. long firstoc;
  105363. long shiftoc;
  105364. int eighth_octave_lines; /* power of two, please */
  105365. int total_octave_lines;
  105366. long rate; /* cache it */
  105367. float m_val; /* Masking compensation value */
  105368. } vorbis_look_psy;
  105369. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  105370. vorbis_info_psy_global *gi,int n,long rate);
  105371. extern void _vp_psy_clear(vorbis_look_psy *p);
  105372. extern void *_vi_psy_dup(void *source);
  105373. extern void _vi_psy_free(vorbis_info_psy *i);
  105374. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  105375. extern void _vp_remove_floor(vorbis_look_psy *p,
  105376. float *mdct,
  105377. int *icodedflr,
  105378. float *residue,
  105379. int sliding_lowpass);
  105380. extern void _vp_noisemask(vorbis_look_psy *p,
  105381. float *logmdct,
  105382. float *logmask);
  105383. extern void _vp_tonemask(vorbis_look_psy *p,
  105384. float *logfft,
  105385. float *logmask,
  105386. float global_specmax,
  105387. float local_specmax);
  105388. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  105389. float *noise,
  105390. float *tone,
  105391. int offset_select,
  105392. float *logmask,
  105393. float *mdct,
  105394. float *logmdct);
  105395. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  105396. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  105397. vorbis_info_psy_global *g,
  105398. vorbis_look_psy *p,
  105399. vorbis_info_mapping0 *vi,
  105400. float **mdct);
  105401. extern void _vp_couple(int blobno,
  105402. vorbis_info_psy_global *g,
  105403. vorbis_look_psy *p,
  105404. vorbis_info_mapping0 *vi,
  105405. float **res,
  105406. float **mag_memo,
  105407. int **mag_sort,
  105408. int **ifloor,
  105409. int *nonzero,
  105410. int sliding_lowpass);
  105411. extern void _vp_noise_normalize(vorbis_look_psy *p,
  105412. float *in,float *out,int *sortedindex);
  105413. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  105414. float *magnitudes,int *sortedindex);
  105415. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  105416. vorbis_look_psy *p,
  105417. vorbis_info_mapping0 *vi,
  105418. float **mags);
  105419. extern void hf_reduction(vorbis_info_psy_global *g,
  105420. vorbis_look_psy *p,
  105421. vorbis_info_mapping0 *vi,
  105422. float **mdct);
  105423. #endif
  105424. /********* End of inlined file: psy.h *********/
  105425. /********* Start of inlined file: bitrate.h *********/
  105426. #ifndef _V_BITRATE_H_
  105427. #define _V_BITRATE_H_
  105428. /********* Start of inlined file: os.h *********/
  105429. #ifndef _OS_H
  105430. #define _OS_H
  105431. /********************************************************************
  105432. * *
  105433. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  105434. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  105435. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  105436. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  105437. * *
  105438. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  105439. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  105440. * *
  105441. ********************************************************************
  105442. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  105443. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  105444. ********************************************************************/
  105445. #ifdef HAVE_CONFIG_H
  105446. #include "config.h"
  105447. #endif
  105448. #include <math.h>
  105449. /********* Start of inlined file: misc.h *********/
  105450. #ifndef _V_RANDOM_H_
  105451. #define _V_RANDOM_H_
  105452. extern int analysis_noisy;
  105453. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  105454. extern void _vorbis_block_ripcord(vorbis_block *vb);
  105455. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  105456. ogg_int64_t off);
  105457. #ifdef DEBUG_MALLOC
  105458. #define _VDBG_GRAPHFILE "malloc.m"
  105459. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  105460. extern void _VDBG_free(void *ptr,char *file,long line);
  105461. #ifndef MISC_C
  105462. #undef _ogg_malloc
  105463. #undef _ogg_calloc
  105464. #undef _ogg_realloc
  105465. #undef _ogg_free
  105466. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  105467. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  105468. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  105469. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  105470. #endif
  105471. #endif
  105472. #endif
  105473. /********* End of inlined file: misc.h *********/
  105474. #ifndef _V_IFDEFJAIL_H_
  105475. # define _V_IFDEFJAIL_H_
  105476. # ifdef __GNUC__
  105477. # define STIN static __inline__
  105478. # elif _WIN32
  105479. # define STIN static __inline
  105480. # else
  105481. # define STIN static
  105482. # endif
  105483. #ifdef DJGPP
  105484. # define rint(x) (floor((x)+0.5f))
  105485. #endif
  105486. #ifndef M_PI
  105487. # define M_PI (3.1415926536f)
  105488. #endif
  105489. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  105490. # include <malloc.h>
  105491. # define rint(x) (floor((x)+0.5f))
  105492. # define NO_FLOAT_MATH_LIB
  105493. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  105494. #endif
  105495. #if defined(__SYMBIAN32__) && defined(__WINS__)
  105496. void *_alloca(size_t size);
  105497. # define alloca _alloca
  105498. #endif
  105499. #ifndef FAST_HYPOT
  105500. # define FAST_HYPOT hypot
  105501. #endif
  105502. #endif
  105503. #ifdef HAVE_ALLOCA_H
  105504. # include <alloca.h>
  105505. #endif
  105506. #ifdef USE_MEMORY_H
  105507. # include <memory.h>
  105508. #endif
  105509. #ifndef min
  105510. # define min(x,y) ((x)>(y)?(y):(x))
  105511. #endif
  105512. #ifndef max
  105513. # define max(x,y) ((x)<(y)?(y):(x))
  105514. #endif
  105515. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  105516. # define VORBIS_FPU_CONTROL
  105517. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  105518. Because of encapsulation constraints (GCC can't see inside the asm
  105519. block and so we end up doing stupid things like a store/load that
  105520. is collectively a noop), we do it this way */
  105521. /* we must set up the fpu before this works!! */
  105522. typedef ogg_int16_t vorbis_fpu_control;
  105523. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  105524. ogg_int16_t ret;
  105525. ogg_int16_t temp;
  105526. __asm__ __volatile__("fnstcw %0\n\t"
  105527. "movw %0,%%dx\n\t"
  105528. "orw $62463,%%dx\n\t"
  105529. "movw %%dx,%1\n\t"
  105530. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  105531. *fpu=ret;
  105532. }
  105533. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  105534. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  105535. }
  105536. /* assumes the FPU is in round mode! */
  105537. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  105538. we get extra fst/fld to
  105539. truncate precision */
  105540. int i;
  105541. __asm__("fistl %0": "=m"(i) : "t"(f));
  105542. return(i);
  105543. }
  105544. #endif
  105545. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  105546. # define VORBIS_FPU_CONTROL
  105547. typedef ogg_int16_t vorbis_fpu_control;
  105548. static __inline int vorbis_ftoi(double f){
  105549. int i;
  105550. __asm{
  105551. fld f
  105552. fistp i
  105553. }
  105554. return i;
  105555. }
  105556. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  105557. }
  105558. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  105559. }
  105560. #endif
  105561. #ifndef VORBIS_FPU_CONTROL
  105562. typedef int vorbis_fpu_control;
  105563. static int vorbis_ftoi(double f){
  105564. return (int)(f+.5);
  105565. }
  105566. /* We don't have special code for this compiler/arch, so do it the slow way */
  105567. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  105568. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  105569. #endif
  105570. #endif /* _OS_H */
  105571. /********* End of inlined file: os.h *********/
  105572. /* encode side bitrate tracking */
  105573. typedef struct bitrate_manager_state {
  105574. int managed;
  105575. long avg_reservoir;
  105576. long minmax_reservoir;
  105577. long avg_bitsper;
  105578. long min_bitsper;
  105579. long max_bitsper;
  105580. long short_per_long;
  105581. double avgfloat;
  105582. vorbis_block *vb;
  105583. int choice;
  105584. } bitrate_manager_state;
  105585. typedef struct bitrate_manager_info{
  105586. long avg_rate;
  105587. long min_rate;
  105588. long max_rate;
  105589. long reservoir_bits;
  105590. double reservoir_bias;
  105591. double slew_damp;
  105592. } bitrate_manager_info;
  105593. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  105594. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  105595. extern int vorbis_bitrate_managed(vorbis_block *vb);
  105596. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  105597. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  105598. #endif
  105599. /********* End of inlined file: bitrate.h *********/
  105600. static int ilog(unsigned int v){
  105601. int ret=0;
  105602. while(v){
  105603. ret++;
  105604. v>>=1;
  105605. }
  105606. return(ret);
  105607. }
  105608. static int ilog2(unsigned int v){
  105609. int ret=0;
  105610. if(v)--v;
  105611. while(v){
  105612. ret++;
  105613. v>>=1;
  105614. }
  105615. return(ret);
  105616. }
  105617. typedef struct private_state {
  105618. /* local lookup storage */
  105619. envelope_lookup *ve; /* envelope lookup */
  105620. int window[2];
  105621. vorbis_look_transform **transform[2]; /* block, type */
  105622. drft_lookup fft_look[2];
  105623. int modebits;
  105624. vorbis_look_floor **flr;
  105625. vorbis_look_residue **residue;
  105626. vorbis_look_psy *psy;
  105627. vorbis_look_psy_global *psy_g_look;
  105628. /* local storage, only used on the encoding side. This way the
  105629. application does not need to worry about freeing some packets'
  105630. memory and not others'; packet storage is always tracked.
  105631. Cleared next call to a _dsp_ function */
  105632. unsigned char *header;
  105633. unsigned char *header1;
  105634. unsigned char *header2;
  105635. bitrate_manager_state bms;
  105636. ogg_int64_t sample_count;
  105637. } private_state;
  105638. /* codec_setup_info contains all the setup information specific to the
  105639. specific compression/decompression mode in progress (eg,
  105640. psychoacoustic settings, channel setup, options, codebook
  105641. etc).
  105642. *********************************************************************/
  105643. /********* Start of inlined file: highlevel.h *********/
  105644. typedef struct highlevel_byblocktype {
  105645. double tone_mask_setting;
  105646. double tone_peaklimit_setting;
  105647. double noise_bias_setting;
  105648. double noise_compand_setting;
  105649. } highlevel_byblocktype;
  105650. typedef struct highlevel_encode_setup {
  105651. void *setup;
  105652. int set_in_stone;
  105653. double base_setting;
  105654. double long_setting;
  105655. double short_setting;
  105656. double impulse_noisetune;
  105657. int managed;
  105658. long bitrate_min;
  105659. long bitrate_av;
  105660. double bitrate_av_damp;
  105661. long bitrate_max;
  105662. long bitrate_reservoir;
  105663. double bitrate_reservoir_bias;
  105664. int impulse_block_p;
  105665. int noise_normalize_p;
  105666. double stereo_point_setting;
  105667. double lowpass_kHz;
  105668. double ath_floating_dB;
  105669. double ath_absolute_dB;
  105670. double amplitude_track_dBpersec;
  105671. double trigger_setting;
  105672. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  105673. } highlevel_encode_setup;
  105674. /********* End of inlined file: highlevel.h *********/
  105675. typedef struct codec_setup_info {
  105676. /* Vorbis supports only short and long blocks, but allows the
  105677. encoder to choose the sizes */
  105678. long blocksizes[2];
  105679. /* modes are the primary means of supporting on-the-fly different
  105680. blocksizes, different channel mappings (LR or M/A),
  105681. different residue backends, etc. Each mode consists of a
  105682. blocksize flag and a mapping (along with the mapping setup */
  105683. int modes;
  105684. int maps;
  105685. int floors;
  105686. int residues;
  105687. int books;
  105688. int psys; /* encode only */
  105689. vorbis_info_mode *mode_param[64];
  105690. int map_type[64];
  105691. vorbis_info_mapping *map_param[64];
  105692. int floor_type[64];
  105693. vorbis_info_floor *floor_param[64];
  105694. int residue_type[64];
  105695. vorbis_info_residue *residue_param[64];
  105696. static_codebook *book_param[256];
  105697. codebook *fullbooks;
  105698. vorbis_info_psy *psy_param[4]; /* encode only */
  105699. vorbis_info_psy_global psy_g_param;
  105700. bitrate_manager_info bi;
  105701. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  105702. highly redundant structure, but
  105703. improves clarity of program flow. */
  105704. int halfrate_flag; /* painless downsample for decode */
  105705. } codec_setup_info;
  105706. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  105707. extern void _vp_global_free(vorbis_look_psy_global *look);
  105708. #endif
  105709. /********* End of inlined file: codec_internal.h *********/
  105710. /********* Start of inlined file: registry.h *********/
  105711. #ifndef _V_REG_H_
  105712. #define _V_REG_H_
  105713. #define VI_TRANSFORMB 1
  105714. #define VI_WINDOWB 1
  105715. #define VI_TIMEB 1
  105716. #define VI_FLOORB 2
  105717. #define VI_RESB 3
  105718. #define VI_MAPB 1
  105719. extern vorbis_func_floor *_floor_P[];
  105720. extern vorbis_func_residue *_residue_P[];
  105721. extern vorbis_func_mapping *_mapping_P[];
  105722. #endif
  105723. /********* End of inlined file: registry.h *********/
  105724. /********* Start of inlined file: scales.h *********/
  105725. #ifndef _V_SCALES_H_
  105726. #define _V_SCALES_H_
  105727. #include <math.h>
  105728. /* 20log10(x) */
  105729. #define VORBIS_IEEE_FLOAT32 1
  105730. #ifdef VORBIS_IEEE_FLOAT32
  105731. static float unitnorm(float x){
  105732. union {
  105733. ogg_uint32_t i;
  105734. float f;
  105735. } ix;
  105736. ix.f = x;
  105737. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  105738. return ix.f;
  105739. }
  105740. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  105741. static float todB(const float *x){
  105742. union {
  105743. ogg_uint32_t i;
  105744. float f;
  105745. } ix;
  105746. ix.f = *x;
  105747. ix.i = ix.i&0x7fffffff;
  105748. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  105749. }
  105750. #define todB_nn(x) todB(x)
  105751. #else
  105752. static float unitnorm(float x){
  105753. if(x<0)return(-1.f);
  105754. return(1.f);
  105755. }
  105756. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  105757. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  105758. #endif
  105759. #define fromdB(x) (exp((x)*.11512925f))
  105760. /* The bark scale equations are approximations, since the original
  105761. table was somewhat hand rolled. The below are chosen to have the
  105762. best possible fit to the rolled tables, thus their somewhat odd
  105763. appearance (these are more accurate and over a longer range than
  105764. the oft-quoted bark equations found in the texts I have). The
  105765. approximations are valid from 0 - 30kHz (nyquist) or so.
  105766. all f in Hz, z in Bark */
  105767. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  105768. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  105769. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  105770. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  105771. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  105772. 0.0 */
  105773. #define toOC(n) (log(n)*1.442695f-5.965784f)
  105774. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  105775. #endif
  105776. /********* End of inlined file: scales.h *********/
  105777. int analysis_noisy=1;
  105778. /* decides between modes, dispatches to the appropriate mapping. */
  105779. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  105780. int ret,i;
  105781. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  105782. vb->glue_bits=0;
  105783. vb->time_bits=0;
  105784. vb->floor_bits=0;
  105785. vb->res_bits=0;
  105786. /* first things first. Make sure encode is ready */
  105787. for(i=0;i<PACKETBLOBS;i++)
  105788. oggpack_reset(vbi->packetblob[i]);
  105789. /* we only have one mapping type (0), and we let the mapping code
  105790. itself figure out what soft mode to use. This allows easier
  105791. bitrate management */
  105792. if((ret=_mapping_P[0]->forward(vb)))
  105793. return(ret);
  105794. if(op){
  105795. if(vorbis_bitrate_managed(vb))
  105796. /* The app is using a bitmanaged mode... but not using the
  105797. bitrate management interface. */
  105798. return(OV_EINVAL);
  105799. op->packet=oggpack_get_buffer(&vb->opb);
  105800. op->bytes=oggpack_bytes(&vb->opb);
  105801. op->b_o_s=0;
  105802. op->e_o_s=vb->eofflag;
  105803. op->granulepos=vb->granulepos;
  105804. op->packetno=vb->sequence; /* for sake of completeness */
  105805. }
  105806. return(0);
  105807. }
  105808. /* there was no great place to put this.... */
  105809. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  105810. int j;
  105811. FILE *of;
  105812. char buffer[80];
  105813. /* if(i==5870){*/
  105814. sprintf(buffer,"%s_%d.m",base,i);
  105815. of=fopen(buffer,"w");
  105816. if(!of)perror("failed to open data dump file");
  105817. for(j=0;j<n;j++){
  105818. if(bark){
  105819. float b=toBARK((4000.f*j/n)+.25);
  105820. fprintf(of,"%f ",b);
  105821. }else
  105822. if(off!=0)
  105823. fprintf(of,"%f ",(double)(j+off)/8000.);
  105824. else
  105825. fprintf(of,"%f ",(double)j);
  105826. if(dB){
  105827. float val;
  105828. if(v[j]==0.)
  105829. val=-140.;
  105830. else
  105831. val=todB(v+j);
  105832. fprintf(of,"%f\n",val);
  105833. }else{
  105834. fprintf(of,"%f\n",v[j]);
  105835. }
  105836. }
  105837. fclose(of);
  105838. /* } */
  105839. }
  105840. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  105841. ogg_int64_t off){
  105842. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  105843. }
  105844. #endif
  105845. /********* End of inlined file: analysis.c *********/
  105846. /********* Start of inlined file: bitrate.c *********/
  105847. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105848. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105849. // tasks..
  105850. #ifdef _MSC_VER
  105851. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105852. #endif
  105853. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105854. #if JUCE_USE_OGGVORBIS
  105855. #include <stdlib.h>
  105856. #include <string.h>
  105857. #include <math.h>
  105858. /* compute bitrate tracking setup */
  105859. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  105860. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105861. bitrate_manager_info *bi=&ci->bi;
  105862. memset(bm,0,sizeof(*bm));
  105863. if(bi && (bi->reservoir_bits>0)){
  105864. long ratesamples=vi->rate;
  105865. int halfsamples=ci->blocksizes[0]>>1;
  105866. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  105867. bm->managed=1;
  105868. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  105869. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  105870. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  105871. bm->avgfloat=PACKETBLOBS/2;
  105872. /* not a necessary fix, but one that leads to a more balanced
  105873. typical initialization */
  105874. {
  105875. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  105876. bm->minmax_reservoir=desired_fill;
  105877. bm->avg_reservoir=desired_fill;
  105878. }
  105879. }
  105880. }
  105881. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  105882. memset(bm,0,sizeof(*bm));
  105883. return;
  105884. }
  105885. int vorbis_bitrate_managed(vorbis_block *vb){
  105886. vorbis_dsp_state *vd=vb->vd;
  105887. private_state *b=(private_state*)vd->backend_state;
  105888. bitrate_manager_state *bm=&b->bms;
  105889. if(bm && bm->managed)return(1);
  105890. return(0);
  105891. }
  105892. /* finish taking in the block we just processed */
  105893. int vorbis_bitrate_addblock(vorbis_block *vb){
  105894. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105895. vorbis_dsp_state *vd=vb->vd;
  105896. private_state *b=(private_state*)vd->backend_state;
  105897. bitrate_manager_state *bm=&b->bms;
  105898. vorbis_info *vi=vd->vi;
  105899. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105900. bitrate_manager_info *bi=&ci->bi;
  105901. int choice=rint(bm->avgfloat);
  105902. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105903. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  105904. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  105905. int samples=ci->blocksizes[vb->W]>>1;
  105906. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  105907. if(!bm->managed){
  105908. /* not a bitrate managed stream, but for API simplicity, we'll
  105909. buffer the packet to keep the code path clean */
  105910. if(bm->vb)return(-1); /* one has been submitted without
  105911. being claimed */
  105912. bm->vb=vb;
  105913. return(0);
  105914. }
  105915. bm->vb=vb;
  105916. /* look ahead for avg floater */
  105917. if(bm->avg_bitsper>0){
  105918. double slew=0.;
  105919. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  105920. double slewlimit= 15./bi->slew_damp;
  105921. /* choosing a new floater:
  105922. if we're over target, we slew down
  105923. if we're under target, we slew up
  105924. choose slew as follows: look through packetblobs of this frame
  105925. and set slew as the first in the appropriate direction that
  105926. gives us the slew we want. This may mean no slew if delta is
  105927. already favorable.
  105928. Then limit slew to slew max */
  105929. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  105930. while(choice>0 && this_bits>avg_target_bits &&
  105931. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  105932. choice--;
  105933. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105934. }
  105935. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  105936. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  105937. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  105938. choice++;
  105939. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105940. }
  105941. }
  105942. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  105943. if(slew<-slewlimit)slew=-slewlimit;
  105944. if(slew>slewlimit)slew=slewlimit;
  105945. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  105946. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105947. }
  105948. /* enforce min(if used) on the current floater (if used) */
  105949. if(bm->min_bitsper>0){
  105950. /* do we need to force the bitrate up? */
  105951. if(this_bits<min_target_bits){
  105952. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  105953. choice++;
  105954. if(choice>=PACKETBLOBS)break;
  105955. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105956. }
  105957. }
  105958. }
  105959. /* enforce max (if used) on the current floater (if used) */
  105960. if(bm->max_bitsper>0){
  105961. /* do we need to force the bitrate down? */
  105962. if(this_bits>max_target_bits){
  105963. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  105964. choice--;
  105965. if(choice<0)break;
  105966. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105967. }
  105968. }
  105969. }
  105970. /* Choice of packetblobs now made based on floater, and min/max
  105971. requirements. Now boundary check extreme choices */
  105972. if(choice<0){
  105973. /* choosing a smaller packetblob is insufficient to trim bitrate.
  105974. frame will need to be truncated */
  105975. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  105976. bm->choice=choice=0;
  105977. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  105978. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  105979. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105980. }
  105981. }else{
  105982. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  105983. if(choice>=PACKETBLOBS)
  105984. choice=PACKETBLOBS-1;
  105985. bm->choice=choice;
  105986. /* prop up bitrate according to demand. pad this frame out with zeroes */
  105987. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  105988. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  105989. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105990. }
  105991. /* now we have the final packet and the final packet size. Update statistics */
  105992. /* min and max reservoir */
  105993. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  105994. if(max_target_bits>0 && this_bits>max_target_bits){
  105995. bm->minmax_reservoir+=(this_bits-max_target_bits);
  105996. }else if(min_target_bits>0 && this_bits<min_target_bits){
  105997. bm->minmax_reservoir+=(this_bits-min_target_bits);
  105998. }else{
  105999. /* inbetween; we want to take reservoir toward but not past desired_fill */
  106000. if(bm->minmax_reservoir>desired_fill){
  106001. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  106002. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106003. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  106004. }else{
  106005. bm->minmax_reservoir=desired_fill;
  106006. }
  106007. }else{
  106008. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  106009. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106010. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  106011. }else{
  106012. bm->minmax_reservoir=desired_fill;
  106013. }
  106014. }
  106015. }
  106016. }
  106017. /* avg reservoir */
  106018. if(bm->avg_bitsper>0){
  106019. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106020. bm->avg_reservoir+=this_bits-avg_target_bits;
  106021. }
  106022. return(0);
  106023. }
  106024. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  106025. private_state *b=(private_state*)vd->backend_state;
  106026. bitrate_manager_state *bm=&b->bms;
  106027. vorbis_block *vb=bm->vb;
  106028. int choice=PACKETBLOBS/2;
  106029. if(!vb)return 0;
  106030. if(op){
  106031. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106032. if(vorbis_bitrate_managed(vb))
  106033. choice=bm->choice;
  106034. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  106035. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  106036. op->b_o_s=0;
  106037. op->e_o_s=vb->eofflag;
  106038. op->granulepos=vb->granulepos;
  106039. op->packetno=vb->sequence; /* for sake of completeness */
  106040. }
  106041. bm->vb=0;
  106042. return(1);
  106043. }
  106044. #endif
  106045. /********* End of inlined file: bitrate.c *********/
  106046. /********* Start of inlined file: block.c *********/
  106047. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106048. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106049. // tasks..
  106050. #ifdef _MSC_VER
  106051. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106052. #endif
  106053. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106054. #if JUCE_USE_OGGVORBIS
  106055. #include <stdio.h>
  106056. #include <stdlib.h>
  106057. #include <string.h>
  106058. /********* Start of inlined file: window.h *********/
  106059. #ifndef _V_WINDOW_
  106060. #define _V_WINDOW_
  106061. extern float *_vorbis_window_get(int n);
  106062. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  106063. int lW,int W,int nW);
  106064. #endif
  106065. /********* End of inlined file: window.h *********/
  106066. /********* Start of inlined file: lpc.h *********/
  106067. #ifndef _V_LPC_H_
  106068. #define _V_LPC_H_
  106069. /* simple linear scale LPC code */
  106070. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  106071. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  106072. float *data,long n);
  106073. #endif
  106074. /********* End of inlined file: lpc.h *********/
  106075. /* pcm accumulator examples (not exhaustive):
  106076. <-------------- lW ---------------->
  106077. <--------------- W ---------------->
  106078. : .....|..... _______________ |
  106079. : .''' | '''_--- | |\ |
  106080. :.....''' |_____--- '''......| | \_______|
  106081. :.................|__________________|_______|__|______|
  106082. |<------ Sl ------>| > Sr < |endW
  106083. |beginSl |endSl | |endSr
  106084. |beginW |endlW |beginSr
  106085. |< lW >|
  106086. <--------------- W ---------------->
  106087. | | .. ______________ |
  106088. | | ' `/ | ---_ |
  106089. |___.'___/`. | ---_____|
  106090. |_______|__|_______|_________________|
  106091. | >|Sl|< |<------ Sr ----->|endW
  106092. | | |endSl |beginSr |endSr
  106093. |beginW | |endlW
  106094. mult[0] |beginSl mult[n]
  106095. <-------------- lW ----------------->
  106096. |<--W-->|
  106097. : .............. ___ | |
  106098. : .''' |`/ \ | |
  106099. :.....''' |/`....\|...|
  106100. :.........................|___|___|___|
  106101. |Sl |Sr |endW
  106102. | | |endSr
  106103. | |beginSr
  106104. | |endSl
  106105. |beginSl
  106106. |beginW
  106107. */
  106108. /* block abstraction setup *********************************************/
  106109. #ifndef WORD_ALIGN
  106110. #define WORD_ALIGN 8
  106111. #endif
  106112. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  106113. int i;
  106114. memset(vb,0,sizeof(*vb));
  106115. vb->vd=v;
  106116. vb->localalloc=0;
  106117. vb->localstore=NULL;
  106118. if(v->analysisp){
  106119. vorbis_block_internal *vbi=(vorbis_block_internal*)
  106120. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  106121. vbi->ampmax=-9999;
  106122. for(i=0;i<PACKETBLOBS;i++){
  106123. if(i==PACKETBLOBS/2){
  106124. vbi->packetblob[i]=&vb->opb;
  106125. }else{
  106126. vbi->packetblob[i]=
  106127. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  106128. }
  106129. oggpack_writeinit(vbi->packetblob[i]);
  106130. }
  106131. }
  106132. return(0);
  106133. }
  106134. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  106135. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  106136. if(bytes+vb->localtop>vb->localalloc){
  106137. /* can't just _ogg_realloc... there are outstanding pointers */
  106138. if(vb->localstore){
  106139. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  106140. vb->totaluse+=vb->localtop;
  106141. link->next=vb->reap;
  106142. link->ptr=vb->localstore;
  106143. vb->reap=link;
  106144. }
  106145. /* highly conservative */
  106146. vb->localalloc=bytes;
  106147. vb->localstore=_ogg_malloc(vb->localalloc);
  106148. vb->localtop=0;
  106149. }
  106150. {
  106151. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  106152. vb->localtop+=bytes;
  106153. return ret;
  106154. }
  106155. }
  106156. /* reap the chain, pull the ripcord */
  106157. void _vorbis_block_ripcord(vorbis_block *vb){
  106158. /* reap the chain */
  106159. struct alloc_chain *reap=vb->reap;
  106160. while(reap){
  106161. struct alloc_chain *next=reap->next;
  106162. _ogg_free(reap->ptr);
  106163. memset(reap,0,sizeof(*reap));
  106164. _ogg_free(reap);
  106165. reap=next;
  106166. }
  106167. /* consolidate storage */
  106168. if(vb->totaluse){
  106169. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  106170. vb->localalloc+=vb->totaluse;
  106171. vb->totaluse=0;
  106172. }
  106173. /* pull the ripcord */
  106174. vb->localtop=0;
  106175. vb->reap=NULL;
  106176. }
  106177. int vorbis_block_clear(vorbis_block *vb){
  106178. int i;
  106179. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106180. _vorbis_block_ripcord(vb);
  106181. if(vb->localstore)_ogg_free(vb->localstore);
  106182. if(vbi){
  106183. for(i=0;i<PACKETBLOBS;i++){
  106184. oggpack_writeclear(vbi->packetblob[i]);
  106185. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  106186. }
  106187. _ogg_free(vbi);
  106188. }
  106189. memset(vb,0,sizeof(*vb));
  106190. return(0);
  106191. }
  106192. /* Analysis side code, but directly related to blocking. Thus it's
  106193. here and not in analysis.c (which is for analysis transforms only).
  106194. The init is here because some of it is shared */
  106195. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  106196. int i;
  106197. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106198. private_state *b=NULL;
  106199. int hs;
  106200. if(ci==NULL) return 1;
  106201. hs=ci->halfrate_flag;
  106202. memset(v,0,sizeof(*v));
  106203. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  106204. v->vi=vi;
  106205. b->modebits=ilog2(ci->modes);
  106206. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  106207. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  106208. /* MDCT is tranform 0 */
  106209. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106210. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106211. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  106212. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  106213. /* Vorbis I uses only window type 0 */
  106214. b->window[0]=ilog2(ci->blocksizes[0])-6;
  106215. b->window[1]=ilog2(ci->blocksizes[1])-6;
  106216. if(encp){ /* encode/decode differ here */
  106217. /* analysis always needs an fft */
  106218. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  106219. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  106220. /* finish the codebooks */
  106221. if(!ci->fullbooks){
  106222. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106223. for(i=0;i<ci->books;i++)
  106224. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  106225. }
  106226. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  106227. for(i=0;i<ci->psys;i++){
  106228. _vp_psy_init(b->psy+i,
  106229. ci->psy_param[i],
  106230. &ci->psy_g_param,
  106231. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  106232. vi->rate);
  106233. }
  106234. v->analysisp=1;
  106235. }else{
  106236. /* finish the codebooks */
  106237. if(!ci->fullbooks){
  106238. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106239. for(i=0;i<ci->books;i++){
  106240. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  106241. /* decode codebooks are now standalone after init */
  106242. vorbis_staticbook_destroy(ci->book_param[i]);
  106243. ci->book_param[i]=NULL;
  106244. }
  106245. }
  106246. }
  106247. /* initialize the storage vectors. blocksize[1] is small for encode,
  106248. but the correct size for decode */
  106249. v->pcm_storage=ci->blocksizes[1];
  106250. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  106251. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  106252. {
  106253. int i;
  106254. for(i=0;i<vi->channels;i++)
  106255. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  106256. }
  106257. /* all 1 (large block) or 0 (small block) */
  106258. /* explicitly set for the sake of clarity */
  106259. v->lW=0; /* previous window size */
  106260. v->W=0; /* current window size */
  106261. /* all vector indexes */
  106262. v->centerW=ci->blocksizes[1]/2;
  106263. v->pcm_current=v->centerW;
  106264. /* initialize all the backend lookups */
  106265. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  106266. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  106267. for(i=0;i<ci->floors;i++)
  106268. b->flr[i]=_floor_P[ci->floor_type[i]]->
  106269. look(v,ci->floor_param[i]);
  106270. for(i=0;i<ci->residues;i++)
  106271. b->residue[i]=_residue_P[ci->residue_type[i]]->
  106272. look(v,ci->residue_param[i]);
  106273. return 0;
  106274. }
  106275. /* arbitrary settings and spec-mandated numbers get filled in here */
  106276. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  106277. private_state *b=NULL;
  106278. if(_vds_shared_init(v,vi,1))return 1;
  106279. b=(private_state*)v->backend_state;
  106280. b->psy_g_look=_vp_global_look(vi);
  106281. /* Initialize the envelope state storage */
  106282. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  106283. _ve_envelope_init(b->ve,vi);
  106284. vorbis_bitrate_init(vi,&b->bms);
  106285. /* compressed audio packets start after the headers
  106286. with sequence number 3 */
  106287. v->sequence=3;
  106288. return(0);
  106289. }
  106290. void vorbis_dsp_clear(vorbis_dsp_state *v){
  106291. int i;
  106292. if(v){
  106293. vorbis_info *vi=v->vi;
  106294. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  106295. private_state *b=(private_state*)v->backend_state;
  106296. if(b){
  106297. if(b->ve){
  106298. _ve_envelope_clear(b->ve);
  106299. _ogg_free(b->ve);
  106300. }
  106301. if(b->transform[0]){
  106302. mdct_clear((mdct_lookup*) b->transform[0][0]);
  106303. _ogg_free(b->transform[0][0]);
  106304. _ogg_free(b->transform[0]);
  106305. }
  106306. if(b->transform[1]){
  106307. mdct_clear((mdct_lookup*) b->transform[1][0]);
  106308. _ogg_free(b->transform[1][0]);
  106309. _ogg_free(b->transform[1]);
  106310. }
  106311. if(b->flr){
  106312. for(i=0;i<ci->floors;i++)
  106313. _floor_P[ci->floor_type[i]]->
  106314. free_look(b->flr[i]);
  106315. _ogg_free(b->flr);
  106316. }
  106317. if(b->residue){
  106318. for(i=0;i<ci->residues;i++)
  106319. _residue_P[ci->residue_type[i]]->
  106320. free_look(b->residue[i]);
  106321. _ogg_free(b->residue);
  106322. }
  106323. if(b->psy){
  106324. for(i=0;i<ci->psys;i++)
  106325. _vp_psy_clear(b->psy+i);
  106326. _ogg_free(b->psy);
  106327. }
  106328. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  106329. vorbis_bitrate_clear(&b->bms);
  106330. drft_clear(&b->fft_look[0]);
  106331. drft_clear(&b->fft_look[1]);
  106332. }
  106333. if(v->pcm){
  106334. for(i=0;i<vi->channels;i++)
  106335. if(v->pcm[i])_ogg_free(v->pcm[i]);
  106336. _ogg_free(v->pcm);
  106337. if(v->pcmret)_ogg_free(v->pcmret);
  106338. }
  106339. if(b){
  106340. /* free header, header1, header2 */
  106341. if(b->header)_ogg_free(b->header);
  106342. if(b->header1)_ogg_free(b->header1);
  106343. if(b->header2)_ogg_free(b->header2);
  106344. _ogg_free(b);
  106345. }
  106346. memset(v,0,sizeof(*v));
  106347. }
  106348. }
  106349. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  106350. int i;
  106351. vorbis_info *vi=v->vi;
  106352. private_state *b=(private_state*)v->backend_state;
  106353. /* free header, header1, header2 */
  106354. if(b->header)_ogg_free(b->header);b->header=NULL;
  106355. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  106356. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  106357. /* Do we have enough storage space for the requested buffer? If not,
  106358. expand the PCM (and envelope) storage */
  106359. if(v->pcm_current+vals>=v->pcm_storage){
  106360. v->pcm_storage=v->pcm_current+vals*2;
  106361. for(i=0;i<vi->channels;i++){
  106362. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  106363. }
  106364. }
  106365. for(i=0;i<vi->channels;i++)
  106366. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  106367. return(v->pcmret);
  106368. }
  106369. static void _preextrapolate_helper(vorbis_dsp_state *v){
  106370. int i;
  106371. int order=32;
  106372. float *lpc=(float*)alloca(order*sizeof(*lpc));
  106373. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  106374. long j;
  106375. v->preextrapolate=1;
  106376. if(v->pcm_current-v->centerW>order*2){ /* safety */
  106377. for(i=0;i<v->vi->channels;i++){
  106378. /* need to run the extrapolation in reverse! */
  106379. for(j=0;j<v->pcm_current;j++)
  106380. work[j]=v->pcm[i][v->pcm_current-j-1];
  106381. /* prime as above */
  106382. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  106383. /* run the predictor filter */
  106384. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  106385. order,
  106386. work+v->pcm_current-v->centerW,
  106387. v->centerW);
  106388. for(j=0;j<v->pcm_current;j++)
  106389. v->pcm[i][v->pcm_current-j-1]=work[j];
  106390. }
  106391. }
  106392. }
  106393. /* call with val<=0 to set eof */
  106394. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  106395. vorbis_info *vi=v->vi;
  106396. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106397. if(vals<=0){
  106398. int order=32;
  106399. int i;
  106400. float *lpc=(float*) alloca(order*sizeof(*lpc));
  106401. /* if it wasn't done earlier (very short sample) */
  106402. if(!v->preextrapolate)
  106403. _preextrapolate_helper(v);
  106404. /* We're encoding the end of the stream. Just make sure we have
  106405. [at least] a few full blocks of zeroes at the end. */
  106406. /* actually, we don't want zeroes; that could drop a large
  106407. amplitude off a cliff, creating spread spectrum noise that will
  106408. suck to encode. Extrapolate for the sake of cleanliness. */
  106409. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  106410. v->eofflag=v->pcm_current;
  106411. v->pcm_current+=ci->blocksizes[1]*3;
  106412. for(i=0;i<vi->channels;i++){
  106413. if(v->eofflag>order*2){
  106414. /* extrapolate with LPC to fill in */
  106415. long n;
  106416. /* make a predictor filter */
  106417. n=v->eofflag;
  106418. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  106419. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  106420. /* run the predictor filter */
  106421. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  106422. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  106423. }else{
  106424. /* not enough data to extrapolate (unlikely to happen due to
  106425. guarding the overlap, but bulletproof in case that
  106426. assumtion goes away). zeroes will do. */
  106427. memset(v->pcm[i]+v->eofflag,0,
  106428. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  106429. }
  106430. }
  106431. }else{
  106432. if(v->pcm_current+vals>v->pcm_storage)
  106433. return(OV_EINVAL);
  106434. v->pcm_current+=vals;
  106435. /* we may want to reverse extrapolate the beginning of a stream
  106436. too... in case we're beginning on a cliff! */
  106437. /* clumsy, but simple. It only runs once, so simple is good. */
  106438. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  106439. _preextrapolate_helper(v);
  106440. }
  106441. return(0);
  106442. }
  106443. /* do the deltas, envelope shaping, pre-echo and determine the size of
  106444. the next block on which to continue analysis */
  106445. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  106446. int i;
  106447. vorbis_info *vi=v->vi;
  106448. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106449. private_state *b=(private_state*)v->backend_state;
  106450. vorbis_look_psy_global *g=b->psy_g_look;
  106451. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  106452. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  106453. /* check to see if we're started... */
  106454. if(!v->preextrapolate)return(0);
  106455. /* check to see if we're done... */
  106456. if(v->eofflag==-1)return(0);
  106457. /* By our invariant, we have lW, W and centerW set. Search for
  106458. the next boundary so we can determine nW (the next window size)
  106459. which lets us compute the shape of the current block's window */
  106460. /* we do an envelope search even on a single blocksize; we may still
  106461. be throwing more bits at impulses, and envelope search handles
  106462. marking impulses too. */
  106463. {
  106464. long bp=_ve_envelope_search(v);
  106465. if(bp==-1){
  106466. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  106467. full long block */
  106468. v->nW=0;
  106469. }else{
  106470. if(ci->blocksizes[0]==ci->blocksizes[1])
  106471. v->nW=0;
  106472. else
  106473. v->nW=bp;
  106474. }
  106475. }
  106476. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  106477. {
  106478. /* center of next block + next block maximum right side. */
  106479. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  106480. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  106481. although this check is
  106482. less strict that the
  106483. _ve_envelope_search,
  106484. the search is not run
  106485. if we only use one
  106486. block size */
  106487. }
  106488. /* fill in the block. Note that for a short window, lW and nW are *short*
  106489. regardless of actual settings in the stream */
  106490. _vorbis_block_ripcord(vb);
  106491. vb->lW=v->lW;
  106492. vb->W=v->W;
  106493. vb->nW=v->nW;
  106494. if(v->W){
  106495. if(!v->lW || !v->nW){
  106496. vbi->blocktype=BLOCKTYPE_TRANSITION;
  106497. /*fprintf(stderr,"-");*/
  106498. }else{
  106499. vbi->blocktype=BLOCKTYPE_LONG;
  106500. /*fprintf(stderr,"_");*/
  106501. }
  106502. }else{
  106503. if(_ve_envelope_mark(v)){
  106504. vbi->blocktype=BLOCKTYPE_IMPULSE;
  106505. /*fprintf(stderr,"|");*/
  106506. }else{
  106507. vbi->blocktype=BLOCKTYPE_PADDING;
  106508. /*fprintf(stderr,".");*/
  106509. }
  106510. }
  106511. vb->vd=v;
  106512. vb->sequence=v->sequence++;
  106513. vb->granulepos=v->granulepos;
  106514. vb->pcmend=ci->blocksizes[v->W];
  106515. /* copy the vectors; this uses the local storage in vb */
  106516. /* this tracks 'strongest peak' for later psychoacoustics */
  106517. /* moved to the global psy state; clean this mess up */
  106518. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  106519. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  106520. vbi->ampmax=g->ampmax;
  106521. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  106522. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  106523. for(i=0;i<vi->channels;i++){
  106524. vbi->pcmdelay[i]=
  106525. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  106526. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  106527. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  106528. /* before we added the delay
  106529. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  106530. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  106531. */
  106532. }
  106533. /* handle eof detection: eof==0 means that we've not yet received EOF
  106534. eof>0 marks the last 'real' sample in pcm[]
  106535. eof<0 'no more to do'; doesn't get here */
  106536. if(v->eofflag){
  106537. if(v->centerW>=v->eofflag){
  106538. v->eofflag=-1;
  106539. vb->eofflag=1;
  106540. return(1);
  106541. }
  106542. }
  106543. /* advance storage vectors and clean up */
  106544. {
  106545. int new_centerNext=ci->blocksizes[1]/2;
  106546. int movementW=centerNext-new_centerNext;
  106547. if(movementW>0){
  106548. _ve_envelope_shift(b->ve,movementW);
  106549. v->pcm_current-=movementW;
  106550. for(i=0;i<vi->channels;i++)
  106551. memmove(v->pcm[i],v->pcm[i]+movementW,
  106552. v->pcm_current*sizeof(*v->pcm[i]));
  106553. v->lW=v->W;
  106554. v->W=v->nW;
  106555. v->centerW=new_centerNext;
  106556. if(v->eofflag){
  106557. v->eofflag-=movementW;
  106558. if(v->eofflag<=0)v->eofflag=-1;
  106559. /* do not add padding to end of stream! */
  106560. if(v->centerW>=v->eofflag){
  106561. v->granulepos+=movementW-(v->centerW-v->eofflag);
  106562. }else{
  106563. v->granulepos+=movementW;
  106564. }
  106565. }else{
  106566. v->granulepos+=movementW;
  106567. }
  106568. }
  106569. }
  106570. /* done */
  106571. return(1);
  106572. }
  106573. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  106574. vorbis_info *vi=v->vi;
  106575. codec_setup_info *ci;
  106576. int hs;
  106577. if(!v->backend_state)return -1;
  106578. if(!vi)return -1;
  106579. ci=(codec_setup_info*) vi->codec_setup;
  106580. if(!ci)return -1;
  106581. hs=ci->halfrate_flag;
  106582. v->centerW=ci->blocksizes[1]>>(hs+1);
  106583. v->pcm_current=v->centerW>>hs;
  106584. v->pcm_returned=-1;
  106585. v->granulepos=-1;
  106586. v->sequence=-1;
  106587. v->eofflag=0;
  106588. ((private_state *)(v->backend_state))->sample_count=-1;
  106589. return(0);
  106590. }
  106591. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  106592. if(_vds_shared_init(v,vi,0)) return 1;
  106593. vorbis_synthesis_restart(v);
  106594. return 0;
  106595. }
  106596. /* Unlike in analysis, the window is only partially applied for each
  106597. block. The time domain envelope is not yet handled at the point of
  106598. calling (as it relies on the previous block). */
  106599. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  106600. vorbis_info *vi=v->vi;
  106601. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106602. private_state *b=(private_state*)v->backend_state;
  106603. int hs=ci->halfrate_flag;
  106604. int i,j;
  106605. if(!vb)return(OV_EINVAL);
  106606. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  106607. v->lW=v->W;
  106608. v->W=vb->W;
  106609. v->nW=-1;
  106610. if((v->sequence==-1)||
  106611. (v->sequence+1 != vb->sequence)){
  106612. v->granulepos=-1; /* out of sequence; lose count */
  106613. b->sample_count=-1;
  106614. }
  106615. v->sequence=vb->sequence;
  106616. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  106617. was called on block */
  106618. int n=ci->blocksizes[v->W]>>(hs+1);
  106619. int n0=ci->blocksizes[0]>>(hs+1);
  106620. int n1=ci->blocksizes[1]>>(hs+1);
  106621. int thisCenter;
  106622. int prevCenter;
  106623. v->glue_bits+=vb->glue_bits;
  106624. v->time_bits+=vb->time_bits;
  106625. v->floor_bits+=vb->floor_bits;
  106626. v->res_bits+=vb->res_bits;
  106627. if(v->centerW){
  106628. thisCenter=n1;
  106629. prevCenter=0;
  106630. }else{
  106631. thisCenter=0;
  106632. prevCenter=n1;
  106633. }
  106634. /* v->pcm is now used like a two-stage double buffer. We don't want
  106635. to have to constantly shift *or* adjust memory usage. Don't
  106636. accept a new block until the old is shifted out */
  106637. for(j=0;j<vi->channels;j++){
  106638. /* the overlap/add section */
  106639. if(v->lW){
  106640. if(v->W){
  106641. /* large/large */
  106642. float *w=_vorbis_window_get(b->window[1]-hs);
  106643. float *pcm=v->pcm[j]+prevCenter;
  106644. float *p=vb->pcm[j];
  106645. for(i=0;i<n1;i++)
  106646. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  106647. }else{
  106648. /* large/small */
  106649. float *w=_vorbis_window_get(b->window[0]-hs);
  106650. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  106651. float *p=vb->pcm[j];
  106652. for(i=0;i<n0;i++)
  106653. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  106654. }
  106655. }else{
  106656. if(v->W){
  106657. /* small/large */
  106658. float *w=_vorbis_window_get(b->window[0]-hs);
  106659. float *pcm=v->pcm[j]+prevCenter;
  106660. float *p=vb->pcm[j]+n1/2-n0/2;
  106661. for(i=0;i<n0;i++)
  106662. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  106663. for(;i<n1/2+n0/2;i++)
  106664. pcm[i]=p[i];
  106665. }else{
  106666. /* small/small */
  106667. float *w=_vorbis_window_get(b->window[0]-hs);
  106668. float *pcm=v->pcm[j]+prevCenter;
  106669. float *p=vb->pcm[j];
  106670. for(i=0;i<n0;i++)
  106671. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  106672. }
  106673. }
  106674. /* the copy section */
  106675. {
  106676. float *pcm=v->pcm[j]+thisCenter;
  106677. float *p=vb->pcm[j]+n;
  106678. for(i=0;i<n;i++)
  106679. pcm[i]=p[i];
  106680. }
  106681. }
  106682. if(v->centerW)
  106683. v->centerW=0;
  106684. else
  106685. v->centerW=n1;
  106686. /* deal with initial packet state; we do this using the explicit
  106687. pcm_returned==-1 flag otherwise we're sensitive to first block
  106688. being short or long */
  106689. if(v->pcm_returned==-1){
  106690. v->pcm_returned=thisCenter;
  106691. v->pcm_current=thisCenter;
  106692. }else{
  106693. v->pcm_returned=prevCenter;
  106694. v->pcm_current=prevCenter+
  106695. ((ci->blocksizes[v->lW]/4+
  106696. ci->blocksizes[v->W]/4)>>hs);
  106697. }
  106698. }
  106699. /* track the frame number... This is for convenience, but also
  106700. making sure our last packet doesn't end with added padding. If
  106701. the last packet is partial, the number of samples we'll have to
  106702. return will be past the vb->granulepos.
  106703. This is not foolproof! It will be confused if we begin
  106704. decoding at the last page after a seek or hole. In that case,
  106705. we don't have a starting point to judge where the last frame
  106706. is. For this reason, vorbisfile will always try to make sure
  106707. it reads the last two marked pages in proper sequence */
  106708. if(b->sample_count==-1){
  106709. b->sample_count=0;
  106710. }else{
  106711. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  106712. }
  106713. if(v->granulepos==-1){
  106714. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  106715. v->granulepos=vb->granulepos;
  106716. /* is this a short page? */
  106717. if(b->sample_count>v->granulepos){
  106718. /* corner case; if this is both the first and last audio page,
  106719. then spec says the end is cut, not beginning */
  106720. if(vb->eofflag){
  106721. /* trim the end */
  106722. /* no preceeding granulepos; assume we started at zero (we'd
  106723. have to in a short single-page stream) */
  106724. /* granulepos could be -1 due to a seek, but that would result
  106725. in a long count, not short count */
  106726. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  106727. }else{
  106728. /* trim the beginning */
  106729. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  106730. if(v->pcm_returned>v->pcm_current)
  106731. v->pcm_returned=v->pcm_current;
  106732. }
  106733. }
  106734. }
  106735. }else{
  106736. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  106737. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  106738. if(v->granulepos>vb->granulepos){
  106739. long extra=v->granulepos-vb->granulepos;
  106740. if(extra)
  106741. if(vb->eofflag){
  106742. /* partial last frame. Strip the extra samples off */
  106743. v->pcm_current-=extra>>hs;
  106744. } /* else {Shouldn't happen *unless* the bitstream is out of
  106745. spec. Either way, believe the bitstream } */
  106746. } /* else {Shouldn't happen *unless* the bitstream is out of
  106747. spec. Either way, believe the bitstream } */
  106748. v->granulepos=vb->granulepos;
  106749. }
  106750. }
  106751. /* Update, cleanup */
  106752. if(vb->eofflag)v->eofflag=1;
  106753. return(0);
  106754. }
  106755. /* pcm==NULL indicates we just want the pending samples, no more */
  106756. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  106757. vorbis_info *vi=v->vi;
  106758. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  106759. if(pcm){
  106760. int i;
  106761. for(i=0;i<vi->channels;i++)
  106762. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  106763. *pcm=v->pcmret;
  106764. }
  106765. return(v->pcm_current-v->pcm_returned);
  106766. }
  106767. return(0);
  106768. }
  106769. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  106770. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  106771. v->pcm_returned+=n;
  106772. return(0);
  106773. }
  106774. /* intended for use with a specific vorbisfile feature; we want access
  106775. to the [usually synthetic/postextrapolated] buffer and lapping at
  106776. the end of a decode cycle, specifically, a half-short-block worth.
  106777. This funtion works like pcmout above, except it will also expose
  106778. this implicit buffer data not normally decoded. */
  106779. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  106780. vorbis_info *vi=v->vi;
  106781. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106782. int hs=ci->halfrate_flag;
  106783. int n=ci->blocksizes[v->W]>>(hs+1);
  106784. int n0=ci->blocksizes[0]>>(hs+1);
  106785. int n1=ci->blocksizes[1]>>(hs+1);
  106786. int i,j;
  106787. if(v->pcm_returned<0)return 0;
  106788. /* our returned data ends at pcm_returned; because the synthesis pcm
  106789. buffer is a two-fragment ring, that means our data block may be
  106790. fragmented by buffering, wrapping or a short block not filling
  106791. out a buffer. To simplify things, we unfragment if it's at all
  106792. possibly needed. Otherwise, we'd need to call lapout more than
  106793. once as well as hold additional dsp state. Opt for
  106794. simplicity. */
  106795. /* centerW was advanced by blockin; it would be the center of the
  106796. *next* block */
  106797. if(v->centerW==n1){
  106798. /* the data buffer wraps; swap the halves */
  106799. /* slow, sure, small */
  106800. for(j=0;j<vi->channels;j++){
  106801. float *p=v->pcm[j];
  106802. for(i=0;i<n1;i++){
  106803. float temp=p[i];
  106804. p[i]=p[i+n1];
  106805. p[i+n1]=temp;
  106806. }
  106807. }
  106808. v->pcm_current-=n1;
  106809. v->pcm_returned-=n1;
  106810. v->centerW=0;
  106811. }
  106812. /* solidify buffer into contiguous space */
  106813. if((v->lW^v->W)==1){
  106814. /* long/short or short/long */
  106815. for(j=0;j<vi->channels;j++){
  106816. float *s=v->pcm[j];
  106817. float *d=v->pcm[j]+(n1-n0)/2;
  106818. for(i=(n1+n0)/2-1;i>=0;--i)
  106819. d[i]=s[i];
  106820. }
  106821. v->pcm_returned+=(n1-n0)/2;
  106822. v->pcm_current+=(n1-n0)/2;
  106823. }else{
  106824. if(v->lW==0){
  106825. /* short/short */
  106826. for(j=0;j<vi->channels;j++){
  106827. float *s=v->pcm[j];
  106828. float *d=v->pcm[j]+n1-n0;
  106829. for(i=n0-1;i>=0;--i)
  106830. d[i]=s[i];
  106831. }
  106832. v->pcm_returned+=n1-n0;
  106833. v->pcm_current+=n1-n0;
  106834. }
  106835. }
  106836. if(pcm){
  106837. int i;
  106838. for(i=0;i<vi->channels;i++)
  106839. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  106840. *pcm=v->pcmret;
  106841. }
  106842. return(n1+n-v->pcm_returned);
  106843. }
  106844. float *vorbis_window(vorbis_dsp_state *v,int W){
  106845. vorbis_info *vi=v->vi;
  106846. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  106847. int hs=ci->halfrate_flag;
  106848. private_state *b=(private_state*)v->backend_state;
  106849. if(b->window[W]-1<0)return NULL;
  106850. return _vorbis_window_get(b->window[W]-hs);
  106851. }
  106852. #endif
  106853. /********* End of inlined file: block.c *********/
  106854. /********* Start of inlined file: codebook.c *********/
  106855. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106856. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106857. // tasks..
  106858. #ifdef _MSC_VER
  106859. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106860. #endif
  106861. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106862. #if JUCE_USE_OGGVORBIS
  106863. #include <stdlib.h>
  106864. #include <string.h>
  106865. #include <math.h>
  106866. /* packs the given codebook into the bitstream **************************/
  106867. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  106868. long i,j;
  106869. int ordered=0;
  106870. /* first the basic parameters */
  106871. oggpack_write(opb,0x564342,24);
  106872. oggpack_write(opb,c->dim,16);
  106873. oggpack_write(opb,c->entries,24);
  106874. /* pack the codewords. There are two packings; length ordered and
  106875. length random. Decide between the two now. */
  106876. for(i=1;i<c->entries;i++)
  106877. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  106878. if(i==c->entries)ordered=1;
  106879. if(ordered){
  106880. /* length ordered. We only need to say how many codewords of
  106881. each length. The actual codewords are generated
  106882. deterministically */
  106883. long count=0;
  106884. oggpack_write(opb,1,1); /* ordered */
  106885. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  106886. for(i=1;i<c->entries;i++){
  106887. long thisx=c->lengthlist[i];
  106888. long last=c->lengthlist[i-1];
  106889. if(thisx>last){
  106890. for(j=last;j<thisx;j++){
  106891. oggpack_write(opb,i-count,_ilog(c->entries-count));
  106892. count=i;
  106893. }
  106894. }
  106895. }
  106896. oggpack_write(opb,i-count,_ilog(c->entries-count));
  106897. }else{
  106898. /* length random. Again, we don't code the codeword itself, just
  106899. the length. This time, though, we have to encode each length */
  106900. oggpack_write(opb,0,1); /* unordered */
  106901. /* algortihmic mapping has use for 'unused entries', which we tag
  106902. here. The algorithmic mapping happens as usual, but the unused
  106903. entry has no codeword. */
  106904. for(i=0;i<c->entries;i++)
  106905. if(c->lengthlist[i]==0)break;
  106906. if(i==c->entries){
  106907. oggpack_write(opb,0,1); /* no unused entries */
  106908. for(i=0;i<c->entries;i++)
  106909. oggpack_write(opb,c->lengthlist[i]-1,5);
  106910. }else{
  106911. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  106912. for(i=0;i<c->entries;i++){
  106913. if(c->lengthlist[i]==0){
  106914. oggpack_write(opb,0,1);
  106915. }else{
  106916. oggpack_write(opb,1,1);
  106917. oggpack_write(opb,c->lengthlist[i]-1,5);
  106918. }
  106919. }
  106920. }
  106921. }
  106922. /* is the entry number the desired return value, or do we have a
  106923. mapping? If we have a mapping, what type? */
  106924. oggpack_write(opb,c->maptype,4);
  106925. switch(c->maptype){
  106926. case 0:
  106927. /* no mapping */
  106928. break;
  106929. case 1:case 2:
  106930. /* implicitly populated value mapping */
  106931. /* explicitly populated value mapping */
  106932. if(!c->quantlist){
  106933. /* no quantlist? error */
  106934. return(-1);
  106935. }
  106936. /* values that define the dequantization */
  106937. oggpack_write(opb,c->q_min,32);
  106938. oggpack_write(opb,c->q_delta,32);
  106939. oggpack_write(opb,c->q_quant-1,4);
  106940. oggpack_write(opb,c->q_sequencep,1);
  106941. {
  106942. int quantvals;
  106943. switch(c->maptype){
  106944. case 1:
  106945. /* a single column of (c->entries/c->dim) quantized values for
  106946. building a full value list algorithmically (square lattice) */
  106947. quantvals=_book_maptype1_quantvals(c);
  106948. break;
  106949. case 2:
  106950. /* every value (c->entries*c->dim total) specified explicitly */
  106951. quantvals=c->entries*c->dim;
  106952. break;
  106953. default: /* NOT_REACHABLE */
  106954. quantvals=-1;
  106955. }
  106956. /* quantized values */
  106957. for(i=0;i<quantvals;i++)
  106958. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  106959. }
  106960. break;
  106961. default:
  106962. /* error case; we don't have any other map types now */
  106963. return(-1);
  106964. }
  106965. return(0);
  106966. }
  106967. /* unpacks a codebook from the packet buffer into the codebook struct,
  106968. readies the codebook auxiliary structures for decode *************/
  106969. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  106970. long i,j;
  106971. memset(s,0,sizeof(*s));
  106972. s->allocedp=1;
  106973. /* make sure alignment is correct */
  106974. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  106975. /* first the basic parameters */
  106976. s->dim=oggpack_read(opb,16);
  106977. s->entries=oggpack_read(opb,24);
  106978. if(s->entries==-1)goto _eofout;
  106979. /* codeword ordering.... length ordered or unordered? */
  106980. switch((int)oggpack_read(opb,1)){
  106981. case 0:
  106982. /* unordered */
  106983. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  106984. /* allocated but unused entries? */
  106985. if(oggpack_read(opb,1)){
  106986. /* yes, unused entries */
  106987. for(i=0;i<s->entries;i++){
  106988. if(oggpack_read(opb,1)){
  106989. long num=oggpack_read(opb,5);
  106990. if(num==-1)goto _eofout;
  106991. s->lengthlist[i]=num+1;
  106992. }else
  106993. s->lengthlist[i]=0;
  106994. }
  106995. }else{
  106996. /* all entries used; no tagging */
  106997. for(i=0;i<s->entries;i++){
  106998. long num=oggpack_read(opb,5);
  106999. if(num==-1)goto _eofout;
  107000. s->lengthlist[i]=num+1;
  107001. }
  107002. }
  107003. break;
  107004. case 1:
  107005. /* ordered */
  107006. {
  107007. long length=oggpack_read(opb,5)+1;
  107008. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107009. for(i=0;i<s->entries;){
  107010. long num=oggpack_read(opb,_ilog(s->entries-i));
  107011. if(num==-1)goto _eofout;
  107012. for(j=0;j<num && i<s->entries;j++,i++)
  107013. s->lengthlist[i]=length;
  107014. length++;
  107015. }
  107016. }
  107017. break;
  107018. default:
  107019. /* EOF */
  107020. return(-1);
  107021. }
  107022. /* Do we have a mapping to unpack? */
  107023. switch((s->maptype=oggpack_read(opb,4))){
  107024. case 0:
  107025. /* no mapping */
  107026. break;
  107027. case 1: case 2:
  107028. /* implicitly populated value mapping */
  107029. /* explicitly populated value mapping */
  107030. s->q_min=oggpack_read(opb,32);
  107031. s->q_delta=oggpack_read(opb,32);
  107032. s->q_quant=oggpack_read(opb,4)+1;
  107033. s->q_sequencep=oggpack_read(opb,1);
  107034. {
  107035. int quantvals=0;
  107036. switch(s->maptype){
  107037. case 1:
  107038. quantvals=_book_maptype1_quantvals(s);
  107039. break;
  107040. case 2:
  107041. quantvals=s->entries*s->dim;
  107042. break;
  107043. }
  107044. /* quantized values */
  107045. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  107046. for(i=0;i<quantvals;i++)
  107047. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  107048. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  107049. }
  107050. break;
  107051. default:
  107052. goto _errout;
  107053. }
  107054. /* all set */
  107055. return(0);
  107056. _errout:
  107057. _eofout:
  107058. vorbis_staticbook_clear(s);
  107059. return(-1);
  107060. }
  107061. /* returns the number of bits ************************************************/
  107062. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  107063. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  107064. return(book->c->lengthlist[a]);
  107065. }
  107066. /* One the encode side, our vector writers are each designed for a
  107067. specific purpose, and the encoder is not flexible without modification:
  107068. The LSP vector coder uses a single stage nearest-match with no
  107069. interleave, so no step and no error return. This is specced by floor0
  107070. and doesn't change.
  107071. Residue0 encoding interleaves, uses multiple stages, and each stage
  107072. peels of a specific amount of resolution from a lattice (thus we want
  107073. to match by threshold, not nearest match). Residue doesn't *have* to
  107074. be encoded that way, but to change it, one will need to add more
  107075. infrastructure on the encode side (decode side is specced and simpler) */
  107076. /* floor0 LSP (single stage, non interleaved, nearest match) */
  107077. /* returns entry number and *modifies a* to the quantization value *****/
  107078. int vorbis_book_errorv(codebook *book,float *a){
  107079. int dim=book->dim,k;
  107080. int best=_best(book,a,1);
  107081. for(k=0;k<dim;k++)
  107082. a[k]=(book->valuelist+best*dim)[k];
  107083. return(best);
  107084. }
  107085. /* returns the number of bits and *modifies a* to the quantization value *****/
  107086. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  107087. int k,dim=book->dim;
  107088. for(k=0;k<dim;k++)
  107089. a[k]=(book->valuelist+best*dim)[k];
  107090. return(vorbis_book_encode(book,best,b));
  107091. }
  107092. /* the 'eliminate the decode tree' optimization actually requires the
  107093. codewords to be MSb first, not LSb. This is an annoying inelegancy
  107094. (and one of the first places where carefully thought out design
  107095. turned out to be wrong; Vorbis II and future Ogg codecs should go
  107096. to an MSb bitpacker), but not actually the huge hit it appears to
  107097. be. The first-stage decode table catches most words so that
  107098. bitreverse is not in the main execution path. */
  107099. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  107100. int read=book->dec_maxlength;
  107101. long lo,hi;
  107102. long lok = oggpack_look(b,book->dec_firsttablen);
  107103. if (lok >= 0) {
  107104. long entry = book->dec_firsttable[lok];
  107105. if(entry&0x80000000UL){
  107106. lo=(entry>>15)&0x7fff;
  107107. hi=book->used_entries-(entry&0x7fff);
  107108. }else{
  107109. oggpack_adv(b, book->dec_codelengths[entry-1]);
  107110. return(entry-1);
  107111. }
  107112. }else{
  107113. lo=0;
  107114. hi=book->used_entries;
  107115. }
  107116. lok = oggpack_look(b, read);
  107117. while(lok<0 && read>1)
  107118. lok = oggpack_look(b, --read);
  107119. if(lok<0)return -1;
  107120. /* bisect search for the codeword in the ordered list */
  107121. {
  107122. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  107123. while(hi-lo>1){
  107124. long p=(hi-lo)>>1;
  107125. long test=book->codelist[lo+p]>testword;
  107126. lo+=p&(test-1);
  107127. hi-=p&(-test);
  107128. }
  107129. if(book->dec_codelengths[lo]<=read){
  107130. oggpack_adv(b, book->dec_codelengths[lo]);
  107131. return(lo);
  107132. }
  107133. }
  107134. oggpack_adv(b, read);
  107135. return(-1);
  107136. }
  107137. /* Decode side is specced and easier, because we don't need to find
  107138. matches using different criteria; we simply read and map. There are
  107139. two things we need to do 'depending':
  107140. We may need to support interleave. We don't really, but it's
  107141. convenient to do it here rather than rebuild the vector later.
  107142. Cascades may be additive or multiplicitive; this is not inherent in
  107143. the codebook, but set in the code using the codebook. Like
  107144. interleaving, it's easiest to do it here.
  107145. addmul==0 -> declarative (set the value)
  107146. addmul==1 -> additive
  107147. addmul==2 -> multiplicitive */
  107148. /* returns the [original, not compacted] entry number or -1 on eof *********/
  107149. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  107150. long packed_entry=decode_packed_entry_number(book,b);
  107151. if(packed_entry>=0)
  107152. return(book->dec_index[packed_entry]);
  107153. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  107154. return(packed_entry);
  107155. }
  107156. /* returns 0 on OK or -1 on eof *************************************/
  107157. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107158. int step=n/book->dim;
  107159. long *entry = (long*)alloca(sizeof(*entry)*step);
  107160. float **t = (float**)alloca(sizeof(*t)*step);
  107161. int i,j,o;
  107162. for (i = 0; i < step; i++) {
  107163. entry[i]=decode_packed_entry_number(book,b);
  107164. if(entry[i]==-1)return(-1);
  107165. t[i] = book->valuelist+entry[i]*book->dim;
  107166. }
  107167. for(i=0,o=0;i<book->dim;i++,o+=step)
  107168. for (j=0;j<step;j++)
  107169. a[o+j]+=t[j][i];
  107170. return(0);
  107171. }
  107172. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107173. int i,j,entry;
  107174. float *t;
  107175. if(book->dim>8){
  107176. for(i=0;i<n;){
  107177. entry = decode_packed_entry_number(book,b);
  107178. if(entry==-1)return(-1);
  107179. t = book->valuelist+entry*book->dim;
  107180. for (j=0;j<book->dim;)
  107181. a[i++]+=t[j++];
  107182. }
  107183. }else{
  107184. for(i=0;i<n;){
  107185. entry = decode_packed_entry_number(book,b);
  107186. if(entry==-1)return(-1);
  107187. t = book->valuelist+entry*book->dim;
  107188. j=0;
  107189. switch((int)book->dim){
  107190. case 8:
  107191. a[i++]+=t[j++];
  107192. case 7:
  107193. a[i++]+=t[j++];
  107194. case 6:
  107195. a[i++]+=t[j++];
  107196. case 5:
  107197. a[i++]+=t[j++];
  107198. case 4:
  107199. a[i++]+=t[j++];
  107200. case 3:
  107201. a[i++]+=t[j++];
  107202. case 2:
  107203. a[i++]+=t[j++];
  107204. case 1:
  107205. a[i++]+=t[j++];
  107206. case 0:
  107207. break;
  107208. }
  107209. }
  107210. }
  107211. return(0);
  107212. }
  107213. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  107214. int i,j,entry;
  107215. float *t;
  107216. for(i=0;i<n;){
  107217. entry = decode_packed_entry_number(book,b);
  107218. if(entry==-1)return(-1);
  107219. t = book->valuelist+entry*book->dim;
  107220. for (j=0;j<book->dim;)
  107221. a[i++]=t[j++];
  107222. }
  107223. return(0);
  107224. }
  107225. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  107226. oggpack_buffer *b,int n){
  107227. long i,j,entry;
  107228. int chptr=0;
  107229. for(i=offset/ch;i<(offset+n)/ch;){
  107230. entry = decode_packed_entry_number(book,b);
  107231. if(entry==-1)return(-1);
  107232. {
  107233. const float *t = book->valuelist+entry*book->dim;
  107234. for (j=0;j<book->dim;j++){
  107235. a[chptr++][i]+=t[j];
  107236. if(chptr==ch){
  107237. chptr=0;
  107238. i++;
  107239. }
  107240. }
  107241. }
  107242. }
  107243. return(0);
  107244. }
  107245. #ifdef _V_SELFTEST
  107246. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  107247. number of vectors through (keeping track of the quantized values),
  107248. and decode using the unpacked book. quantized version of in should
  107249. exactly equal out */
  107250. #include <stdio.h>
  107251. #include "vorbis/book/lsp20_0.vqh"
  107252. #include "vorbis/book/res0a_13.vqh"
  107253. #define TESTSIZE 40
  107254. float test1[TESTSIZE]={
  107255. 0.105939f,
  107256. 0.215373f,
  107257. 0.429117f,
  107258. 0.587974f,
  107259. 0.181173f,
  107260. 0.296583f,
  107261. 0.515707f,
  107262. 0.715261f,
  107263. 0.162327f,
  107264. 0.263834f,
  107265. 0.342876f,
  107266. 0.406025f,
  107267. 0.103571f,
  107268. 0.223561f,
  107269. 0.368513f,
  107270. 0.540313f,
  107271. 0.136672f,
  107272. 0.395882f,
  107273. 0.587183f,
  107274. 0.652476f,
  107275. 0.114338f,
  107276. 0.417300f,
  107277. 0.525486f,
  107278. 0.698679f,
  107279. 0.147492f,
  107280. 0.324481f,
  107281. 0.643089f,
  107282. 0.757582f,
  107283. 0.139556f,
  107284. 0.215795f,
  107285. 0.324559f,
  107286. 0.399387f,
  107287. 0.120236f,
  107288. 0.267420f,
  107289. 0.446940f,
  107290. 0.608760f,
  107291. 0.115587f,
  107292. 0.287234f,
  107293. 0.571081f,
  107294. 0.708603f,
  107295. };
  107296. float test3[TESTSIZE]={
  107297. 0,1,-2,3,4,-5,6,7,8,9,
  107298. 8,-2,7,-1,4,6,8,3,1,-9,
  107299. 10,11,12,13,14,15,26,17,18,19,
  107300. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  107301. static_codebook *testlist[]={&_vq_book_lsp20_0,
  107302. &_vq_book_res0a_13,NULL};
  107303. float *testvec[]={test1,test3};
  107304. int main(){
  107305. oggpack_buffer write;
  107306. oggpack_buffer read;
  107307. long ptr=0,i;
  107308. oggpack_writeinit(&write);
  107309. fprintf(stderr,"Testing codebook abstraction...:\n");
  107310. while(testlist[ptr]){
  107311. codebook c;
  107312. static_codebook s;
  107313. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  107314. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  107315. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  107316. memset(iv,0,sizeof(*iv)*TESTSIZE);
  107317. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  107318. /* pack the codebook, write the testvector */
  107319. oggpack_reset(&write);
  107320. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  107321. we can write */
  107322. vorbis_staticbook_pack(testlist[ptr],&write);
  107323. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  107324. for(i=0;i<TESTSIZE;i+=c.dim){
  107325. int best=_best(&c,qv+i,1);
  107326. vorbis_book_encodev(&c,best,qv+i,&write);
  107327. }
  107328. vorbis_book_clear(&c);
  107329. fprintf(stderr,"OK.\n");
  107330. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  107331. /* transfer the write data to a read buffer and unpack/read */
  107332. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  107333. if(vorbis_staticbook_unpack(&read,&s)){
  107334. fprintf(stderr,"Error unpacking codebook.\n");
  107335. exit(1);
  107336. }
  107337. if(vorbis_book_init_decode(&c,&s)){
  107338. fprintf(stderr,"Error initializing codebook.\n");
  107339. exit(1);
  107340. }
  107341. for(i=0;i<TESTSIZE;i+=c.dim)
  107342. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  107343. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  107344. exit(1);
  107345. }
  107346. for(i=0;i<TESTSIZE;i++)
  107347. if(fabs(qv[i]-iv[i])>.000001){
  107348. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  107349. iv[i],qv[i],i);
  107350. exit(1);
  107351. }
  107352. fprintf(stderr,"OK\n");
  107353. ptr++;
  107354. }
  107355. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  107356. exit(0);
  107357. }
  107358. #endif
  107359. #endif
  107360. /********* End of inlined file: codebook.c *********/
  107361. /********* Start of inlined file: envelope.c *********/
  107362. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107363. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107364. // tasks..
  107365. #ifdef _MSC_VER
  107366. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107367. #endif
  107368. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107369. #if JUCE_USE_OGGVORBIS
  107370. #include <stdlib.h>
  107371. #include <string.h>
  107372. #include <stdio.h>
  107373. #include <math.h>
  107374. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  107375. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107376. vorbis_info_psy_global *gi=&ci->psy_g_param;
  107377. int ch=vi->channels;
  107378. int i,j;
  107379. int n=e->winlength=128;
  107380. e->searchstep=64; /* not random */
  107381. e->minenergy=gi->preecho_minenergy;
  107382. e->ch=ch;
  107383. e->storage=128;
  107384. e->cursor=ci->blocksizes[1]/2;
  107385. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  107386. mdct_init(&e->mdct,n);
  107387. for(i=0;i<n;i++){
  107388. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  107389. e->mdct_win[i]*=e->mdct_win[i];
  107390. }
  107391. /* magic follows */
  107392. e->band[0].begin=2; e->band[0].end=4;
  107393. e->band[1].begin=4; e->band[1].end=5;
  107394. e->band[2].begin=6; e->band[2].end=6;
  107395. e->band[3].begin=9; e->band[3].end=8;
  107396. e->band[4].begin=13; e->band[4].end=8;
  107397. e->band[5].begin=17; e->band[5].end=8;
  107398. e->band[6].begin=22; e->band[6].end=8;
  107399. for(j=0;j<VE_BANDS;j++){
  107400. n=e->band[j].end;
  107401. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  107402. for(i=0;i<n;i++){
  107403. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  107404. e->band[j].total+=e->band[j].window[i];
  107405. }
  107406. e->band[j].total=1./e->band[j].total;
  107407. }
  107408. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  107409. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  107410. }
  107411. void _ve_envelope_clear(envelope_lookup *e){
  107412. int i;
  107413. mdct_clear(&e->mdct);
  107414. for(i=0;i<VE_BANDS;i++)
  107415. _ogg_free(e->band[i].window);
  107416. _ogg_free(e->mdct_win);
  107417. _ogg_free(e->filter);
  107418. _ogg_free(e->mark);
  107419. memset(e,0,sizeof(*e));
  107420. }
  107421. /* fairly straight threshhold-by-band based until we find something
  107422. that works better and isn't patented. */
  107423. static int _ve_amp(envelope_lookup *ve,
  107424. vorbis_info_psy_global *gi,
  107425. float *data,
  107426. envelope_band *bands,
  107427. envelope_filter_state *filters,
  107428. long pos){
  107429. long n=ve->winlength;
  107430. int ret=0;
  107431. long i,j;
  107432. float decay;
  107433. /* we want to have a 'minimum bar' for energy, else we're just
  107434. basing blocks on quantization noise that outweighs the signal
  107435. itself (for low power signals) */
  107436. float minV=ve->minenergy;
  107437. float *vec=(float*) alloca(n*sizeof(*vec));
  107438. /* stretch is used to gradually lengthen the number of windows
  107439. considered prevoius-to-potential-trigger */
  107440. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  107441. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  107442. if(penalty<0.f)penalty=0.f;
  107443. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  107444. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  107445. totalshift+pos*ve->searchstep);*/
  107446. /* window and transform */
  107447. for(i=0;i<n;i++)
  107448. vec[i]=data[i]*ve->mdct_win[i];
  107449. mdct_forward(&ve->mdct,vec,vec);
  107450. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  107451. /* near-DC spreading function; this has nothing to do with
  107452. psychoacoustics, just sidelobe leakage and window size */
  107453. {
  107454. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  107455. int ptr=filters->nearptr;
  107456. /* the accumulation is regularly refreshed from scratch to avoid
  107457. floating point creep */
  107458. if(ptr==0){
  107459. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  107460. filters->nearDC_partialacc=temp;
  107461. }else{
  107462. decay=filters->nearDC_acc+=temp;
  107463. filters->nearDC_partialacc+=temp;
  107464. }
  107465. filters->nearDC_acc-=filters->nearDC[ptr];
  107466. filters->nearDC[ptr]=temp;
  107467. decay*=(1./(VE_NEARDC+1));
  107468. filters->nearptr++;
  107469. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  107470. decay=todB(&decay)*.5-15.f;
  107471. }
  107472. /* perform spreading and limiting, also smooth the spectrum. yes,
  107473. the MDCT results in all real coefficients, but it still *behaves*
  107474. like real/imaginary pairs */
  107475. for(i=0;i<n/2;i+=2){
  107476. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  107477. val=todB(&val)*.5f;
  107478. if(val<decay)val=decay;
  107479. if(val<minV)val=minV;
  107480. vec[i>>1]=val;
  107481. decay-=8.;
  107482. }
  107483. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  107484. /* perform preecho/postecho triggering by band */
  107485. for(j=0;j<VE_BANDS;j++){
  107486. float acc=0.;
  107487. float valmax,valmin;
  107488. /* accumulate amplitude */
  107489. for(i=0;i<bands[j].end;i++)
  107490. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  107491. acc*=bands[j].total;
  107492. /* convert amplitude to delta */
  107493. {
  107494. int p,thisx=filters[j].ampptr;
  107495. float postmax,postmin,premax=-99999.f,premin=99999.f;
  107496. p=thisx;
  107497. p--;
  107498. if(p<0)p+=VE_AMP;
  107499. postmax=max(acc,filters[j].ampbuf[p]);
  107500. postmin=min(acc,filters[j].ampbuf[p]);
  107501. for(i=0;i<stretch;i++){
  107502. p--;
  107503. if(p<0)p+=VE_AMP;
  107504. premax=max(premax,filters[j].ampbuf[p]);
  107505. premin=min(premin,filters[j].ampbuf[p]);
  107506. }
  107507. valmin=postmin-premin;
  107508. valmax=postmax-premax;
  107509. /*filters[j].markers[pos]=valmax;*/
  107510. filters[j].ampbuf[thisx]=acc;
  107511. filters[j].ampptr++;
  107512. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  107513. }
  107514. /* look at min/max, decide trigger */
  107515. if(valmax>gi->preecho_thresh[j]+penalty){
  107516. ret|=1;
  107517. ret|=4;
  107518. }
  107519. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  107520. }
  107521. return(ret);
  107522. }
  107523. #if 0
  107524. static int seq=0;
  107525. static ogg_int64_t totalshift=-1024;
  107526. #endif
  107527. long _ve_envelope_search(vorbis_dsp_state *v){
  107528. vorbis_info *vi=v->vi;
  107529. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107530. vorbis_info_psy_global *gi=&ci->psy_g_param;
  107531. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  107532. long i,j;
  107533. int first=ve->current/ve->searchstep;
  107534. int last=v->pcm_current/ve->searchstep-VE_WIN;
  107535. if(first<0)first=0;
  107536. /* make sure we have enough storage to match the PCM */
  107537. if(last+VE_WIN+VE_POST>ve->storage){
  107538. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  107539. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  107540. }
  107541. for(j=first;j<last;j++){
  107542. int ret=0;
  107543. ve->stretch++;
  107544. if(ve->stretch>VE_MAXSTRETCH*2)
  107545. ve->stretch=VE_MAXSTRETCH*2;
  107546. for(i=0;i<ve->ch;i++){
  107547. float *pcm=v->pcm[i]+ve->searchstep*(j);
  107548. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  107549. }
  107550. ve->mark[j+VE_POST]=0;
  107551. if(ret&1){
  107552. ve->mark[j]=1;
  107553. ve->mark[j+1]=1;
  107554. }
  107555. if(ret&2){
  107556. ve->mark[j]=1;
  107557. if(j>0)ve->mark[j-1]=1;
  107558. }
  107559. if(ret&4)ve->stretch=-1;
  107560. }
  107561. ve->current=last*ve->searchstep;
  107562. {
  107563. long centerW=v->centerW;
  107564. long testW=
  107565. centerW+
  107566. ci->blocksizes[v->W]/4+
  107567. ci->blocksizes[1]/2+
  107568. ci->blocksizes[0]/4;
  107569. j=ve->cursor;
  107570. while(j<ve->current-(ve->searchstep)){/* account for postecho
  107571. working back one window */
  107572. if(j>=testW)return(1);
  107573. ve->cursor=j;
  107574. if(ve->mark[j/ve->searchstep]){
  107575. if(j>centerW){
  107576. #if 0
  107577. if(j>ve->curmark){
  107578. float *marker=alloca(v->pcm_current*sizeof(*marker));
  107579. int l,m;
  107580. memset(marker,0,sizeof(*marker)*v->pcm_current);
  107581. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  107582. seq,
  107583. (totalshift+ve->cursor)/44100.,
  107584. (totalshift+j)/44100.);
  107585. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  107586. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  107587. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  107588. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  107589. for(m=0;m<VE_BANDS;m++){
  107590. char buf[80];
  107591. sprintf(buf,"delL%d",m);
  107592. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  107593. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  107594. }
  107595. for(m=0;m<VE_BANDS;m++){
  107596. char buf[80];
  107597. sprintf(buf,"delR%d",m);
  107598. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  107599. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  107600. }
  107601. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  107602. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  107603. seq++;
  107604. }
  107605. #endif
  107606. ve->curmark=j;
  107607. if(j>=testW)return(1);
  107608. return(0);
  107609. }
  107610. }
  107611. j+=ve->searchstep;
  107612. }
  107613. }
  107614. return(-1);
  107615. }
  107616. int _ve_envelope_mark(vorbis_dsp_state *v){
  107617. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  107618. vorbis_info *vi=v->vi;
  107619. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107620. long centerW=v->centerW;
  107621. long beginW=centerW-ci->blocksizes[v->W]/4;
  107622. long endW=centerW+ci->blocksizes[v->W]/4;
  107623. if(v->W){
  107624. beginW-=ci->blocksizes[v->lW]/4;
  107625. endW+=ci->blocksizes[v->nW]/4;
  107626. }else{
  107627. beginW-=ci->blocksizes[0]/4;
  107628. endW+=ci->blocksizes[0]/4;
  107629. }
  107630. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  107631. {
  107632. long first=beginW/ve->searchstep;
  107633. long last=endW/ve->searchstep;
  107634. long i;
  107635. for(i=first;i<last;i++)
  107636. if(ve->mark[i])return(1);
  107637. }
  107638. return(0);
  107639. }
  107640. void _ve_envelope_shift(envelope_lookup *e,long shift){
  107641. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  107642. ahead of ve->current */
  107643. int smallshift=shift/e->searchstep;
  107644. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  107645. #if 0
  107646. for(i=0;i<VE_BANDS*e->ch;i++)
  107647. memmove(e->filter[i].markers,
  107648. e->filter[i].markers+smallshift,
  107649. (1024-smallshift)*sizeof(*(*e->filter).markers));
  107650. totalshift+=shift;
  107651. #endif
  107652. e->current-=shift;
  107653. if(e->curmark>=0)
  107654. e->curmark-=shift;
  107655. e->cursor-=shift;
  107656. }
  107657. #endif
  107658. /********* End of inlined file: envelope.c *********/
  107659. /********* Start of inlined file: floor0.c *********/
  107660. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107661. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107662. // tasks..
  107663. #ifdef _MSC_VER
  107664. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107665. #endif
  107666. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107667. #if JUCE_USE_OGGVORBIS
  107668. #include <stdlib.h>
  107669. #include <string.h>
  107670. #include <math.h>
  107671. /********* Start of inlined file: lsp.h *********/
  107672. #ifndef _V_LSP_H_
  107673. #define _V_LSP_H_
  107674. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  107675. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  107676. float *lsp,int m,
  107677. float amp,float ampoffset);
  107678. #endif
  107679. /********* End of inlined file: lsp.h *********/
  107680. #include <stdio.h>
  107681. typedef struct {
  107682. int ln;
  107683. int m;
  107684. int **linearmap;
  107685. int n[2];
  107686. vorbis_info_floor0 *vi;
  107687. long bits;
  107688. long frames;
  107689. } vorbis_look_floor0;
  107690. /***********************************************/
  107691. static void floor0_free_info(vorbis_info_floor *i){
  107692. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  107693. if(info){
  107694. memset(info,0,sizeof(*info));
  107695. _ogg_free(info);
  107696. }
  107697. }
  107698. static void floor0_free_look(vorbis_look_floor *i){
  107699. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  107700. if(look){
  107701. if(look->linearmap){
  107702. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  107703. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  107704. _ogg_free(look->linearmap);
  107705. }
  107706. memset(look,0,sizeof(*look));
  107707. _ogg_free(look);
  107708. }
  107709. }
  107710. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  107711. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107712. int j;
  107713. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  107714. info->order=oggpack_read(opb,8);
  107715. info->rate=oggpack_read(opb,16);
  107716. info->barkmap=oggpack_read(opb,16);
  107717. info->ampbits=oggpack_read(opb,6);
  107718. info->ampdB=oggpack_read(opb,8);
  107719. info->numbooks=oggpack_read(opb,4)+1;
  107720. if(info->order<1)goto err_out;
  107721. if(info->rate<1)goto err_out;
  107722. if(info->barkmap<1)goto err_out;
  107723. if(info->numbooks<1)goto err_out;
  107724. for(j=0;j<info->numbooks;j++){
  107725. info->books[j]=oggpack_read(opb,8);
  107726. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  107727. }
  107728. return(info);
  107729. err_out:
  107730. floor0_free_info(info);
  107731. return(NULL);
  107732. }
  107733. /* initialize Bark scale and normalization lookups. We could do this
  107734. with static tables, but Vorbis allows a number of possible
  107735. combinations, so it's best to do it computationally.
  107736. The below is authoritative in terms of defining scale mapping.
  107737. Note that the scale depends on the sampling rate as well as the
  107738. linear block and mapping sizes */
  107739. static void floor0_map_lazy_init(vorbis_block *vb,
  107740. vorbis_info_floor *infoX,
  107741. vorbis_look_floor0 *look){
  107742. if(!look->linearmap[vb->W]){
  107743. vorbis_dsp_state *vd=vb->vd;
  107744. vorbis_info *vi=vd->vi;
  107745. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107746. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  107747. int W=vb->W;
  107748. int n=ci->blocksizes[W]/2,j;
  107749. /* we choose a scaling constant so that:
  107750. floor(bark(rate/2-1)*C)=mapped-1
  107751. floor(bark(rate/2)*C)=mapped */
  107752. float scale=look->ln/toBARK(info->rate/2.f);
  107753. /* the mapping from a linear scale to a smaller bark scale is
  107754. straightforward. We do *not* make sure that the linear mapping
  107755. does not skip bark-scale bins; the decoder simply skips them and
  107756. the encoder may do what it wishes in filling them. They're
  107757. necessary in some mapping combinations to keep the scale spacing
  107758. accurate */
  107759. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  107760. for(j=0;j<n;j++){
  107761. int val=floor( toBARK((info->rate/2.f)/n*j)
  107762. *scale); /* bark numbers represent band edges */
  107763. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  107764. look->linearmap[W][j]=val;
  107765. }
  107766. look->linearmap[W][j]=-1;
  107767. look->n[W]=n;
  107768. }
  107769. }
  107770. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  107771. vorbis_info_floor *i){
  107772. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  107773. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  107774. look->m=info->order;
  107775. look->ln=info->barkmap;
  107776. look->vi=info;
  107777. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  107778. return look;
  107779. }
  107780. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  107781. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  107782. vorbis_info_floor0 *info=look->vi;
  107783. int j,k;
  107784. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  107785. if(ampraw>0){ /* also handles the -1 out of data case */
  107786. long maxval=(1<<info->ampbits)-1;
  107787. float amp=(float)ampraw/maxval*info->ampdB;
  107788. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  107789. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  107790. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  107791. codebook *b=ci->fullbooks+info->books[booknum];
  107792. float last=0.f;
  107793. /* the additional b->dim is a guard against any possible stack
  107794. smash; b->dim is provably more than we can overflow the
  107795. vector */
  107796. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  107797. for(j=0;j<look->m;j+=b->dim)
  107798. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  107799. for(j=0;j<look->m;){
  107800. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  107801. last=lsp[j-1];
  107802. }
  107803. lsp[look->m]=amp;
  107804. return(lsp);
  107805. }
  107806. }
  107807. eop:
  107808. return(NULL);
  107809. }
  107810. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  107811. void *memo,float *out){
  107812. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  107813. vorbis_info_floor0 *info=look->vi;
  107814. floor0_map_lazy_init(vb,info,look);
  107815. if(memo){
  107816. float *lsp=(float *)memo;
  107817. float amp=lsp[look->m];
  107818. /* take the coefficients back to a spectral envelope curve */
  107819. vorbis_lsp_to_curve(out,
  107820. look->linearmap[vb->W],
  107821. look->n[vb->W],
  107822. look->ln,
  107823. lsp,look->m,amp,(float)info->ampdB);
  107824. return(1);
  107825. }
  107826. memset(out,0,sizeof(*out)*look->n[vb->W]);
  107827. return(0);
  107828. }
  107829. /* export hooks */
  107830. vorbis_func_floor floor0_exportbundle={
  107831. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  107832. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  107833. };
  107834. #endif
  107835. /********* End of inlined file: floor0.c *********/
  107836. /********* Start of inlined file: floor1.c *********/
  107837. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107838. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107839. // tasks..
  107840. #ifdef _MSC_VER
  107841. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107842. #endif
  107843. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107844. #if JUCE_USE_OGGVORBIS
  107845. #include <stdlib.h>
  107846. #include <string.h>
  107847. #include <math.h>
  107848. #include <stdio.h>
  107849. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  107850. typedef struct {
  107851. int sorted_index[VIF_POSIT+2];
  107852. int forward_index[VIF_POSIT+2];
  107853. int reverse_index[VIF_POSIT+2];
  107854. int hineighbor[VIF_POSIT];
  107855. int loneighbor[VIF_POSIT];
  107856. int posts;
  107857. int n;
  107858. int quant_q;
  107859. vorbis_info_floor1 *vi;
  107860. long phrasebits;
  107861. long postbits;
  107862. long frames;
  107863. } vorbis_look_floor1;
  107864. typedef struct lsfit_acc{
  107865. long x0;
  107866. long x1;
  107867. long xa;
  107868. long ya;
  107869. long x2a;
  107870. long y2a;
  107871. long xya;
  107872. long an;
  107873. } lsfit_acc;
  107874. /***********************************************/
  107875. static void floor1_free_info(vorbis_info_floor *i){
  107876. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  107877. if(info){
  107878. memset(info,0,sizeof(*info));
  107879. _ogg_free(info);
  107880. }
  107881. }
  107882. static void floor1_free_look(vorbis_look_floor *i){
  107883. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  107884. if(look){
  107885. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  107886. (float)look->phrasebits/look->frames,
  107887. (float)look->postbits/look->frames,
  107888. (float)(look->postbits+look->phrasebits)/look->frames);*/
  107889. memset(look,0,sizeof(*look));
  107890. _ogg_free(look);
  107891. }
  107892. }
  107893. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  107894. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  107895. int j,k;
  107896. int count=0;
  107897. int rangebits;
  107898. int maxposit=info->postlist[1];
  107899. int maxclass=-1;
  107900. /* save out partitions */
  107901. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  107902. for(j=0;j<info->partitions;j++){
  107903. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  107904. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  107905. }
  107906. /* save out partition classes */
  107907. for(j=0;j<maxclass+1;j++){
  107908. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  107909. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  107910. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  107911. for(k=0;k<(1<<info->class_subs[j]);k++)
  107912. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  107913. }
  107914. /* save out the post list */
  107915. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  107916. oggpack_write(opb,ilog2(maxposit),4);
  107917. rangebits=ilog2(maxposit);
  107918. for(j=0,k=0;j<info->partitions;j++){
  107919. count+=info->class_dim[info->partitionclass[j]];
  107920. for(;k<count;k++)
  107921. oggpack_write(opb,info->postlist[k+2],rangebits);
  107922. }
  107923. }
  107924. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  107925. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107926. int j,k,count=0,maxclass=-1,rangebits;
  107927. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  107928. /* read partitions */
  107929. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  107930. for(j=0;j<info->partitions;j++){
  107931. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  107932. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  107933. }
  107934. /* read partition classes */
  107935. for(j=0;j<maxclass+1;j++){
  107936. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  107937. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  107938. if(info->class_subs[j]<0)
  107939. goto err_out;
  107940. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  107941. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  107942. goto err_out;
  107943. for(k=0;k<(1<<info->class_subs[j]);k++){
  107944. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  107945. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  107946. goto err_out;
  107947. }
  107948. }
  107949. /* read the post list */
  107950. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  107951. rangebits=oggpack_read(opb,4);
  107952. for(j=0,k=0;j<info->partitions;j++){
  107953. count+=info->class_dim[info->partitionclass[j]];
  107954. for(;k<count;k++){
  107955. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  107956. if(t<0 || t>=(1<<rangebits))
  107957. goto err_out;
  107958. }
  107959. }
  107960. info->postlist[0]=0;
  107961. info->postlist[1]=1<<rangebits;
  107962. return(info);
  107963. err_out:
  107964. floor1_free_info(info);
  107965. return(NULL);
  107966. }
  107967. static int icomp(const void *a,const void *b){
  107968. return(**(int **)a-**(int **)b);
  107969. }
  107970. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  107971. vorbis_info_floor *in){
  107972. int *sortpointer[VIF_POSIT+2];
  107973. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  107974. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  107975. int i,j,n=0;
  107976. look->vi=info;
  107977. look->n=info->postlist[1];
  107978. /* we drop each position value in-between already decoded values,
  107979. and use linear interpolation to predict each new value past the
  107980. edges. The positions are read in the order of the position
  107981. list... we precompute the bounding positions in the lookup. Of
  107982. course, the neighbors can change (if a position is declined), but
  107983. this is an initial mapping */
  107984. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  107985. n+=2;
  107986. look->posts=n;
  107987. /* also store a sorted position index */
  107988. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  107989. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  107990. /* points from sort order back to range number */
  107991. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  107992. /* points from range order to sorted position */
  107993. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  107994. /* we actually need the post values too */
  107995. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  107996. /* quantize values to multiplier spec */
  107997. switch(info->mult){
  107998. case 1: /* 1024 -> 256 */
  107999. look->quant_q=256;
  108000. break;
  108001. case 2: /* 1024 -> 128 */
  108002. look->quant_q=128;
  108003. break;
  108004. case 3: /* 1024 -> 86 */
  108005. look->quant_q=86;
  108006. break;
  108007. case 4: /* 1024 -> 64 */
  108008. look->quant_q=64;
  108009. break;
  108010. }
  108011. /* discover our neighbors for decode where we don't use fit flags
  108012. (that would push the neighbors outward) */
  108013. for(i=0;i<n-2;i++){
  108014. int lo=0;
  108015. int hi=1;
  108016. int lx=0;
  108017. int hx=look->n;
  108018. int currentx=info->postlist[i+2];
  108019. for(j=0;j<i+2;j++){
  108020. int x=info->postlist[j];
  108021. if(x>lx && x<currentx){
  108022. lo=j;
  108023. lx=x;
  108024. }
  108025. if(x<hx && x>currentx){
  108026. hi=j;
  108027. hx=x;
  108028. }
  108029. }
  108030. look->loneighbor[i]=lo;
  108031. look->hineighbor[i]=hi;
  108032. }
  108033. return(look);
  108034. }
  108035. static int render_point(int x0,int x1,int y0,int y1,int x){
  108036. y0&=0x7fff; /* mask off flag */
  108037. y1&=0x7fff;
  108038. {
  108039. int dy=y1-y0;
  108040. int adx=x1-x0;
  108041. int ady=abs(dy);
  108042. int err=ady*(x-x0);
  108043. int off=err/adx;
  108044. if(dy<0)return(y0-off);
  108045. return(y0+off);
  108046. }
  108047. }
  108048. static int vorbis_dBquant(const float *x){
  108049. int i= *x*7.3142857f+1023.5f;
  108050. if(i>1023)return(1023);
  108051. if(i<0)return(0);
  108052. return i;
  108053. }
  108054. static float FLOOR1_fromdB_LOOKUP[256]={
  108055. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  108056. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  108057. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  108058. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  108059. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  108060. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  108061. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  108062. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  108063. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  108064. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  108065. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  108066. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  108067. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  108068. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  108069. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  108070. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  108071. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  108072. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  108073. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  108074. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  108075. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  108076. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  108077. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  108078. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  108079. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  108080. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  108081. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  108082. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  108083. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  108084. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  108085. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  108086. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  108087. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  108088. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  108089. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  108090. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  108091. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  108092. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  108093. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  108094. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  108095. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  108096. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  108097. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  108098. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  108099. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  108100. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  108101. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  108102. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  108103. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  108104. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  108105. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  108106. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  108107. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  108108. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  108109. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  108110. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  108111. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  108112. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  108113. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  108114. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  108115. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  108116. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  108117. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  108118. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  108119. };
  108120. static void render_line(int x0,int x1,int y0,int y1,float *d){
  108121. int dy=y1-y0;
  108122. int adx=x1-x0;
  108123. int ady=abs(dy);
  108124. int base=dy/adx;
  108125. int sy=(dy<0?base-1:base+1);
  108126. int x=x0;
  108127. int y=y0;
  108128. int err=0;
  108129. ady-=abs(base*adx);
  108130. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108131. while(++x<x1){
  108132. err=err+ady;
  108133. if(err>=adx){
  108134. err-=adx;
  108135. y+=sy;
  108136. }else{
  108137. y+=base;
  108138. }
  108139. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108140. }
  108141. }
  108142. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  108143. int dy=y1-y0;
  108144. int adx=x1-x0;
  108145. int ady=abs(dy);
  108146. int base=dy/adx;
  108147. int sy=(dy<0?base-1:base+1);
  108148. int x=x0;
  108149. int y=y0;
  108150. int err=0;
  108151. ady-=abs(base*adx);
  108152. d[x]=y;
  108153. while(++x<x1){
  108154. err=err+ady;
  108155. if(err>=adx){
  108156. err-=adx;
  108157. y+=sy;
  108158. }else{
  108159. y+=base;
  108160. }
  108161. d[x]=y;
  108162. }
  108163. }
  108164. /* the floor has already been filtered to only include relevant sections */
  108165. static int accumulate_fit(const float *flr,const float *mdct,
  108166. int x0, int x1,lsfit_acc *a,
  108167. int n,vorbis_info_floor1 *info){
  108168. long i;
  108169. 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;
  108170. memset(a,0,sizeof(*a));
  108171. a->x0=x0;
  108172. a->x1=x1;
  108173. if(x1>=n)x1=n-1;
  108174. for(i=x0;i<=x1;i++){
  108175. int quantized=vorbis_dBquant(flr+i);
  108176. if(quantized){
  108177. if(mdct[i]+info->twofitatten>=flr[i]){
  108178. xa += i;
  108179. ya += quantized;
  108180. x2a += i*i;
  108181. y2a += quantized*quantized;
  108182. xya += i*quantized;
  108183. na++;
  108184. }else{
  108185. xb += i;
  108186. yb += quantized;
  108187. x2b += i*i;
  108188. y2b += quantized*quantized;
  108189. xyb += i*quantized;
  108190. nb++;
  108191. }
  108192. }
  108193. }
  108194. xb+=xa;
  108195. yb+=ya;
  108196. x2b+=x2a;
  108197. y2b+=y2a;
  108198. xyb+=xya;
  108199. nb+=na;
  108200. /* weight toward the actually used frequencies if we meet the threshhold */
  108201. {
  108202. int weight=nb*info->twofitweight/(na+1);
  108203. a->xa=xa*weight+xb;
  108204. a->ya=ya*weight+yb;
  108205. a->x2a=x2a*weight+x2b;
  108206. a->y2a=y2a*weight+y2b;
  108207. a->xya=xya*weight+xyb;
  108208. a->an=na*weight+nb;
  108209. }
  108210. return(na);
  108211. }
  108212. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  108213. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  108214. long x0=a[0].x0;
  108215. long x1=a[fits-1].x1;
  108216. for(i=0;i<fits;i++){
  108217. x+=a[i].xa;
  108218. y+=a[i].ya;
  108219. x2+=a[i].x2a;
  108220. y2+=a[i].y2a;
  108221. xy+=a[i].xya;
  108222. an+=a[i].an;
  108223. }
  108224. if(*y0>=0){
  108225. x+= x0;
  108226. y+= *y0;
  108227. x2+= x0 * x0;
  108228. y2+= *y0 * *y0;
  108229. xy+= *y0 * x0;
  108230. an++;
  108231. }
  108232. if(*y1>=0){
  108233. x+= x1;
  108234. y+= *y1;
  108235. x2+= x1 * x1;
  108236. y2+= *y1 * *y1;
  108237. xy+= *y1 * x1;
  108238. an++;
  108239. }
  108240. if(an){
  108241. /* need 64 bit multiplies, which C doesn't give portably as int */
  108242. double fx=x;
  108243. double fy=y;
  108244. double fx2=x2;
  108245. double fxy=xy;
  108246. double denom=1./(an*fx2-fx*fx);
  108247. double a=(fy*fx2-fxy*fx)*denom;
  108248. double b=(an*fxy-fx*fy)*denom;
  108249. *y0=rint(a+b*x0);
  108250. *y1=rint(a+b*x1);
  108251. /* limit to our range! */
  108252. if(*y0>1023)*y0=1023;
  108253. if(*y1>1023)*y1=1023;
  108254. if(*y0<0)*y0=0;
  108255. if(*y1<0)*y1=0;
  108256. }else{
  108257. *y0=0;
  108258. *y1=0;
  108259. }
  108260. }
  108261. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  108262. long y=0;
  108263. int i;
  108264. for(i=0;i<fits && y==0;i++)
  108265. y+=a[i].ya;
  108266. *y0=*y1=y;
  108267. }*/
  108268. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  108269. const float *mdct,
  108270. vorbis_info_floor1 *info){
  108271. int dy=y1-y0;
  108272. int adx=x1-x0;
  108273. int ady=abs(dy);
  108274. int base=dy/adx;
  108275. int sy=(dy<0?base-1:base+1);
  108276. int x=x0;
  108277. int y=y0;
  108278. int err=0;
  108279. int val=vorbis_dBquant(mask+x);
  108280. int mse=0;
  108281. int n=0;
  108282. ady-=abs(base*adx);
  108283. mse=(y-val);
  108284. mse*=mse;
  108285. n++;
  108286. if(mdct[x]+info->twofitatten>=mask[x]){
  108287. if(y+info->maxover<val)return(1);
  108288. if(y-info->maxunder>val)return(1);
  108289. }
  108290. while(++x<x1){
  108291. err=err+ady;
  108292. if(err>=adx){
  108293. err-=adx;
  108294. y+=sy;
  108295. }else{
  108296. y+=base;
  108297. }
  108298. val=vorbis_dBquant(mask+x);
  108299. mse+=((y-val)*(y-val));
  108300. n++;
  108301. if(mdct[x]+info->twofitatten>=mask[x]){
  108302. if(val){
  108303. if(y+info->maxover<val)return(1);
  108304. if(y-info->maxunder>val)return(1);
  108305. }
  108306. }
  108307. }
  108308. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  108309. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  108310. if(mse/n>info->maxerr)return(1);
  108311. return(0);
  108312. }
  108313. static int post_Y(int *A,int *B,int pos){
  108314. if(A[pos]<0)
  108315. return B[pos];
  108316. if(B[pos]<0)
  108317. return A[pos];
  108318. return (A[pos]+B[pos])>>1;
  108319. }
  108320. int *floor1_fit(vorbis_block *vb,void *look_,
  108321. const float *logmdct, /* in */
  108322. const float *logmask){
  108323. long i,j;
  108324. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  108325. vorbis_info_floor1 *info=look->vi;
  108326. long n=look->n;
  108327. long posts=look->posts;
  108328. long nonzero=0;
  108329. lsfit_acc fits[VIF_POSIT+1];
  108330. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  108331. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  108332. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  108333. int hineighbor[VIF_POSIT+2];
  108334. int *output=NULL;
  108335. int memo[VIF_POSIT+2];
  108336. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  108337. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  108338. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  108339. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  108340. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  108341. /* quantize the relevant floor points and collect them into line fit
  108342. structures (one per minimal division) at the same time */
  108343. if(posts==0){
  108344. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  108345. }else{
  108346. for(i=0;i<posts-1;i++)
  108347. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  108348. look->sorted_index[i+1],fits+i,
  108349. n,info);
  108350. }
  108351. if(nonzero){
  108352. /* start by fitting the implicit base case.... */
  108353. int y0=-200;
  108354. int y1=-200;
  108355. fit_line(fits,posts-1,&y0,&y1);
  108356. fit_valueA[0]=y0;
  108357. fit_valueB[0]=y0;
  108358. fit_valueB[1]=y1;
  108359. fit_valueA[1]=y1;
  108360. /* Non degenerate case */
  108361. /* start progressive splitting. This is a greedy, non-optimal
  108362. algorithm, but simple and close enough to the best
  108363. answer. */
  108364. for(i=2;i<posts;i++){
  108365. int sortpos=look->reverse_index[i];
  108366. int ln=loneighbor[sortpos];
  108367. int hn=hineighbor[sortpos];
  108368. /* eliminate repeat searches of a particular range with a memo */
  108369. if(memo[ln]!=hn){
  108370. /* haven't performed this error search yet */
  108371. int lsortpos=look->reverse_index[ln];
  108372. int hsortpos=look->reverse_index[hn];
  108373. memo[ln]=hn;
  108374. {
  108375. /* A note: we want to bound/minimize *local*, not global, error */
  108376. int lx=info->postlist[ln];
  108377. int hx=info->postlist[hn];
  108378. int ly=post_Y(fit_valueA,fit_valueB,ln);
  108379. int hy=post_Y(fit_valueA,fit_valueB,hn);
  108380. if(ly==-1 || hy==-1){
  108381. exit(1);
  108382. }
  108383. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  108384. /* outside error bounds/begin search area. Split it. */
  108385. int ly0=-200;
  108386. int ly1=-200;
  108387. int hy0=-200;
  108388. int hy1=-200;
  108389. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  108390. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  108391. /* store new edge values */
  108392. fit_valueB[ln]=ly0;
  108393. if(ln==0)fit_valueA[ln]=ly0;
  108394. fit_valueA[i]=ly1;
  108395. fit_valueB[i]=hy0;
  108396. fit_valueA[hn]=hy1;
  108397. if(hn==1)fit_valueB[hn]=hy1;
  108398. if(ly1>=0 || hy0>=0){
  108399. /* store new neighbor values */
  108400. for(j=sortpos-1;j>=0;j--)
  108401. if(hineighbor[j]==hn)
  108402. hineighbor[j]=i;
  108403. else
  108404. break;
  108405. for(j=sortpos+1;j<posts;j++)
  108406. if(loneighbor[j]==ln)
  108407. loneighbor[j]=i;
  108408. else
  108409. break;
  108410. }
  108411. }else{
  108412. fit_valueA[i]=-200;
  108413. fit_valueB[i]=-200;
  108414. }
  108415. }
  108416. }
  108417. }
  108418. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  108419. output[0]=post_Y(fit_valueA,fit_valueB,0);
  108420. output[1]=post_Y(fit_valueA,fit_valueB,1);
  108421. /* fill in posts marked as not using a fit; we will zero
  108422. back out to 'unused' when encoding them so long as curve
  108423. interpolation doesn't force them into use */
  108424. for(i=2;i<posts;i++){
  108425. int ln=look->loneighbor[i-2];
  108426. int hn=look->hineighbor[i-2];
  108427. int x0=info->postlist[ln];
  108428. int x1=info->postlist[hn];
  108429. int y0=output[ln];
  108430. int y1=output[hn];
  108431. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  108432. int vx=post_Y(fit_valueA,fit_valueB,i);
  108433. if(vx>=0 && predicted!=vx){
  108434. output[i]=vx;
  108435. }else{
  108436. output[i]= predicted|0x8000;
  108437. }
  108438. }
  108439. }
  108440. return(output);
  108441. }
  108442. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  108443. int *A,int *B,
  108444. int del){
  108445. long i;
  108446. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  108447. long posts=look->posts;
  108448. int *output=NULL;
  108449. if(A && B){
  108450. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  108451. for(i=0;i<posts;i++){
  108452. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  108453. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  108454. }
  108455. }
  108456. return(output);
  108457. }
  108458. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  108459. void*look_,
  108460. int *post,int *ilogmask){
  108461. long i,j;
  108462. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  108463. vorbis_info_floor1 *info=look->vi;
  108464. long posts=look->posts;
  108465. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  108466. int out[VIF_POSIT+2];
  108467. static_codebook **sbooks=ci->book_param;
  108468. codebook *books=ci->fullbooks;
  108469. static long seq=0;
  108470. /* quantize values to multiplier spec */
  108471. if(post){
  108472. for(i=0;i<posts;i++){
  108473. int val=post[i]&0x7fff;
  108474. switch(info->mult){
  108475. case 1: /* 1024 -> 256 */
  108476. val>>=2;
  108477. break;
  108478. case 2: /* 1024 -> 128 */
  108479. val>>=3;
  108480. break;
  108481. case 3: /* 1024 -> 86 */
  108482. val/=12;
  108483. break;
  108484. case 4: /* 1024 -> 64 */
  108485. val>>=4;
  108486. break;
  108487. }
  108488. post[i]=val | (post[i]&0x8000);
  108489. }
  108490. out[0]=post[0];
  108491. out[1]=post[1];
  108492. /* find prediction values for each post and subtract them */
  108493. for(i=2;i<posts;i++){
  108494. int ln=look->loneighbor[i-2];
  108495. int hn=look->hineighbor[i-2];
  108496. int x0=info->postlist[ln];
  108497. int x1=info->postlist[hn];
  108498. int y0=post[ln];
  108499. int y1=post[hn];
  108500. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  108501. if((post[i]&0x8000) || (predicted==post[i])){
  108502. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  108503. in interpolation */
  108504. out[i]=0;
  108505. }else{
  108506. int headroom=(look->quant_q-predicted<predicted?
  108507. look->quant_q-predicted:predicted);
  108508. int val=post[i]-predicted;
  108509. /* at this point the 'deviation' value is in the range +/- max
  108510. range, but the real, unique range can always be mapped to
  108511. only [0-maxrange). So we want to wrap the deviation into
  108512. this limited range, but do it in the way that least screws
  108513. an essentially gaussian probability distribution. */
  108514. if(val<0)
  108515. if(val<-headroom)
  108516. val=headroom-val-1;
  108517. else
  108518. val=-1-(val<<1);
  108519. else
  108520. if(val>=headroom)
  108521. val= val+headroom;
  108522. else
  108523. val<<=1;
  108524. out[i]=val;
  108525. post[ln]&=0x7fff;
  108526. post[hn]&=0x7fff;
  108527. }
  108528. }
  108529. /* we have everything we need. pack it out */
  108530. /* mark nontrivial floor */
  108531. oggpack_write(opb,1,1);
  108532. /* beginning/end post */
  108533. look->frames++;
  108534. look->postbits+=ilog(look->quant_q-1)*2;
  108535. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  108536. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  108537. /* partition by partition */
  108538. for(i=0,j=2;i<info->partitions;i++){
  108539. int classx=info->partitionclass[i];
  108540. int cdim=info->class_dim[classx];
  108541. int csubbits=info->class_subs[classx];
  108542. int csub=1<<csubbits;
  108543. int bookas[8]={0,0,0,0,0,0,0,0};
  108544. int cval=0;
  108545. int cshift=0;
  108546. int k,l;
  108547. /* generate the partition's first stage cascade value */
  108548. if(csubbits){
  108549. int maxval[8];
  108550. for(k=0;k<csub;k++){
  108551. int booknum=info->class_subbook[classx][k];
  108552. if(booknum<0){
  108553. maxval[k]=1;
  108554. }else{
  108555. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  108556. }
  108557. }
  108558. for(k=0;k<cdim;k++){
  108559. for(l=0;l<csub;l++){
  108560. int val=out[j+k];
  108561. if(val<maxval[l]){
  108562. bookas[k]=l;
  108563. break;
  108564. }
  108565. }
  108566. cval|= bookas[k]<<cshift;
  108567. cshift+=csubbits;
  108568. }
  108569. /* write it */
  108570. look->phrasebits+=
  108571. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  108572. #ifdef TRAIN_FLOOR1
  108573. {
  108574. FILE *of;
  108575. char buffer[80];
  108576. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  108577. vb->pcmend/2,posts-2,class);
  108578. of=fopen(buffer,"a");
  108579. fprintf(of,"%d\n",cval);
  108580. fclose(of);
  108581. }
  108582. #endif
  108583. }
  108584. /* write post values */
  108585. for(k=0;k<cdim;k++){
  108586. int book=info->class_subbook[classx][bookas[k]];
  108587. if(book>=0){
  108588. /* hack to allow training with 'bad' books */
  108589. if(out[j+k]<(books+book)->entries)
  108590. look->postbits+=vorbis_book_encode(books+book,
  108591. out[j+k],opb);
  108592. /*else
  108593. fprintf(stderr,"+!");*/
  108594. #ifdef TRAIN_FLOOR1
  108595. {
  108596. FILE *of;
  108597. char buffer[80];
  108598. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  108599. vb->pcmend/2,posts-2,class,bookas[k]);
  108600. of=fopen(buffer,"a");
  108601. fprintf(of,"%d\n",out[j+k]);
  108602. fclose(of);
  108603. }
  108604. #endif
  108605. }
  108606. }
  108607. j+=cdim;
  108608. }
  108609. {
  108610. /* generate quantized floor equivalent to what we'd unpack in decode */
  108611. /* render the lines */
  108612. int hx=0;
  108613. int lx=0;
  108614. int ly=post[0]*info->mult;
  108615. for(j=1;j<look->posts;j++){
  108616. int current=look->forward_index[j];
  108617. int hy=post[current]&0x7fff;
  108618. if(hy==post[current]){
  108619. hy*=info->mult;
  108620. hx=info->postlist[current];
  108621. render_line0(lx,hx,ly,hy,ilogmask);
  108622. lx=hx;
  108623. ly=hy;
  108624. }
  108625. }
  108626. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  108627. seq++;
  108628. return(1);
  108629. }
  108630. }else{
  108631. oggpack_write(opb,0,1);
  108632. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  108633. seq++;
  108634. return(0);
  108635. }
  108636. }
  108637. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  108638. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  108639. vorbis_info_floor1 *info=look->vi;
  108640. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  108641. int i,j,k;
  108642. codebook *books=ci->fullbooks;
  108643. /* unpack wrapped/predicted values from stream */
  108644. if(oggpack_read(&vb->opb,1)==1){
  108645. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  108646. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  108647. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  108648. /* partition by partition */
  108649. for(i=0,j=2;i<info->partitions;i++){
  108650. int classx=info->partitionclass[i];
  108651. int cdim=info->class_dim[classx];
  108652. int csubbits=info->class_subs[classx];
  108653. int csub=1<<csubbits;
  108654. int cval=0;
  108655. /* decode the partition's first stage cascade value */
  108656. if(csubbits){
  108657. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  108658. if(cval==-1)goto eop;
  108659. }
  108660. for(k=0;k<cdim;k++){
  108661. int book=info->class_subbook[classx][cval&(csub-1)];
  108662. cval>>=csubbits;
  108663. if(book>=0){
  108664. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  108665. goto eop;
  108666. }else{
  108667. fit_value[j+k]=0;
  108668. }
  108669. }
  108670. j+=cdim;
  108671. }
  108672. /* unwrap positive values and reconsitute via linear interpolation */
  108673. for(i=2;i<look->posts;i++){
  108674. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  108675. info->postlist[look->hineighbor[i-2]],
  108676. fit_value[look->loneighbor[i-2]],
  108677. fit_value[look->hineighbor[i-2]],
  108678. info->postlist[i]);
  108679. int hiroom=look->quant_q-predicted;
  108680. int loroom=predicted;
  108681. int room=(hiroom<loroom?hiroom:loroom)<<1;
  108682. int val=fit_value[i];
  108683. if(val){
  108684. if(val>=room){
  108685. if(hiroom>loroom){
  108686. val = val-loroom;
  108687. }else{
  108688. val = -1-(val-hiroom);
  108689. }
  108690. }else{
  108691. if(val&1){
  108692. val= -((val+1)>>1);
  108693. }else{
  108694. val>>=1;
  108695. }
  108696. }
  108697. fit_value[i]=val+predicted;
  108698. fit_value[look->loneighbor[i-2]]&=0x7fff;
  108699. fit_value[look->hineighbor[i-2]]&=0x7fff;
  108700. }else{
  108701. fit_value[i]=predicted|0x8000;
  108702. }
  108703. }
  108704. return(fit_value);
  108705. }
  108706. eop:
  108707. return(NULL);
  108708. }
  108709. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  108710. float *out){
  108711. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  108712. vorbis_info_floor1 *info=look->vi;
  108713. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  108714. int n=ci->blocksizes[vb->W]/2;
  108715. int j;
  108716. if(memo){
  108717. /* render the lines */
  108718. int *fit_value=(int *)memo;
  108719. int hx=0;
  108720. int lx=0;
  108721. int ly=fit_value[0]*info->mult;
  108722. for(j=1;j<look->posts;j++){
  108723. int current=look->forward_index[j];
  108724. int hy=fit_value[current]&0x7fff;
  108725. if(hy==fit_value[current]){
  108726. hy*=info->mult;
  108727. hx=info->postlist[current];
  108728. render_line(lx,hx,ly,hy,out);
  108729. lx=hx;
  108730. ly=hy;
  108731. }
  108732. }
  108733. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  108734. return(1);
  108735. }
  108736. memset(out,0,sizeof(*out)*n);
  108737. return(0);
  108738. }
  108739. /* export hooks */
  108740. vorbis_func_floor floor1_exportbundle={
  108741. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  108742. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  108743. };
  108744. #endif
  108745. /********* End of inlined file: floor1.c *********/
  108746. /********* Start of inlined file: info.c *********/
  108747. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108748. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108749. // tasks..
  108750. #ifdef _MSC_VER
  108751. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108752. #endif
  108753. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108754. #if JUCE_USE_OGGVORBIS
  108755. /* general handling of the header and the vorbis_info structure (and
  108756. substructures) */
  108757. #include <stdlib.h>
  108758. #include <string.h>
  108759. #include <ctype.h>
  108760. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  108761. while(bytes--){
  108762. oggpack_write(o,*s++,8);
  108763. }
  108764. }
  108765. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  108766. while(bytes--){
  108767. *buf++=oggpack_read(o,8);
  108768. }
  108769. }
  108770. void vorbis_comment_init(vorbis_comment *vc){
  108771. memset(vc,0,sizeof(*vc));
  108772. }
  108773. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  108774. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  108775. (vc->comments+2)*sizeof(*vc->user_comments));
  108776. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  108777. (vc->comments+2)*sizeof(*vc->comment_lengths));
  108778. vc->comment_lengths[vc->comments]=strlen(comment);
  108779. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  108780. strcpy(vc->user_comments[vc->comments], comment);
  108781. vc->comments++;
  108782. vc->user_comments[vc->comments]=NULL;
  108783. }
  108784. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  108785. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  108786. strcpy(comment, tag);
  108787. strcat(comment, "=");
  108788. strcat(comment, contents);
  108789. vorbis_comment_add(vc, comment);
  108790. }
  108791. /* This is more or less the same as strncasecmp - but that doesn't exist
  108792. * everywhere, and this is a fairly trivial function, so we include it */
  108793. static int tagcompare(const char *s1, const char *s2, int n){
  108794. int c=0;
  108795. while(c < n){
  108796. if(toupper(s1[c]) != toupper(s2[c]))
  108797. return !0;
  108798. c++;
  108799. }
  108800. return 0;
  108801. }
  108802. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  108803. long i;
  108804. int found = 0;
  108805. int taglen = strlen(tag)+1; /* +1 for the = we append */
  108806. char *fulltag = (char*)alloca(taglen+ 1);
  108807. strcpy(fulltag, tag);
  108808. strcat(fulltag, "=");
  108809. for(i=0;i<vc->comments;i++){
  108810. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  108811. if(count == found)
  108812. /* We return a pointer to the data, not a copy */
  108813. return vc->user_comments[i] + taglen;
  108814. else
  108815. found++;
  108816. }
  108817. }
  108818. return NULL; /* didn't find anything */
  108819. }
  108820. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  108821. int i,count=0;
  108822. int taglen = strlen(tag)+1; /* +1 for the = we append */
  108823. char *fulltag = (char*)alloca(taglen+1);
  108824. strcpy(fulltag,tag);
  108825. strcat(fulltag, "=");
  108826. for(i=0;i<vc->comments;i++){
  108827. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  108828. count++;
  108829. }
  108830. return count;
  108831. }
  108832. void vorbis_comment_clear(vorbis_comment *vc){
  108833. if(vc){
  108834. long i;
  108835. for(i=0;i<vc->comments;i++)
  108836. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  108837. if(vc->user_comments)_ogg_free(vc->user_comments);
  108838. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  108839. if(vc->vendor)_ogg_free(vc->vendor);
  108840. }
  108841. memset(vc,0,sizeof(*vc));
  108842. }
  108843. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  108844. They may be equal, but short will never ge greater than long */
  108845. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  108846. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  108847. return ci ? ci->blocksizes[zo] : -1;
  108848. }
  108849. /* used by synthesis, which has a full, alloced vi */
  108850. void vorbis_info_init(vorbis_info *vi){
  108851. memset(vi,0,sizeof(*vi));
  108852. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  108853. }
  108854. void vorbis_info_clear(vorbis_info *vi){
  108855. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108856. int i;
  108857. if(ci){
  108858. for(i=0;i<ci->modes;i++)
  108859. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  108860. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  108861. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  108862. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  108863. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  108864. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  108865. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  108866. for(i=0;i<ci->books;i++){
  108867. if(ci->book_param[i]){
  108868. /* knows if the book was not alloced */
  108869. vorbis_staticbook_destroy(ci->book_param[i]);
  108870. }
  108871. if(ci->fullbooks)
  108872. vorbis_book_clear(ci->fullbooks+i);
  108873. }
  108874. if(ci->fullbooks)
  108875. _ogg_free(ci->fullbooks);
  108876. for(i=0;i<ci->psys;i++)
  108877. _vi_psy_free(ci->psy_param[i]);
  108878. _ogg_free(ci);
  108879. }
  108880. memset(vi,0,sizeof(*vi));
  108881. }
  108882. /* Header packing/unpacking ********************************************/
  108883. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  108884. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108885. if(!ci)return(OV_EFAULT);
  108886. vi->version=oggpack_read(opb,32);
  108887. if(vi->version!=0)return(OV_EVERSION);
  108888. vi->channels=oggpack_read(opb,8);
  108889. vi->rate=oggpack_read(opb,32);
  108890. vi->bitrate_upper=oggpack_read(opb,32);
  108891. vi->bitrate_nominal=oggpack_read(opb,32);
  108892. vi->bitrate_lower=oggpack_read(opb,32);
  108893. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  108894. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  108895. if(vi->rate<1)goto err_out;
  108896. if(vi->channels<1)goto err_out;
  108897. if(ci->blocksizes[0]<8)goto err_out;
  108898. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  108899. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  108900. return(0);
  108901. err_out:
  108902. vorbis_info_clear(vi);
  108903. return(OV_EBADHEADER);
  108904. }
  108905. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  108906. int i;
  108907. int vendorlen=oggpack_read(opb,32);
  108908. if(vendorlen<0)goto err_out;
  108909. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  108910. _v_readstring(opb,vc->vendor,vendorlen);
  108911. vc->comments=oggpack_read(opb,32);
  108912. if(vc->comments<0)goto err_out;
  108913. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  108914. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  108915. for(i=0;i<vc->comments;i++){
  108916. int len=oggpack_read(opb,32);
  108917. if(len<0)goto err_out;
  108918. vc->comment_lengths[i]=len;
  108919. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  108920. _v_readstring(opb,vc->user_comments[i],len);
  108921. }
  108922. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  108923. return(0);
  108924. err_out:
  108925. vorbis_comment_clear(vc);
  108926. return(OV_EBADHEADER);
  108927. }
  108928. /* all of the real encoding details are here. The modes, books,
  108929. everything */
  108930. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  108931. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108932. int i;
  108933. if(!ci)return(OV_EFAULT);
  108934. /* codebooks */
  108935. ci->books=oggpack_read(opb,8)+1;
  108936. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  108937. for(i=0;i<ci->books;i++){
  108938. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  108939. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  108940. }
  108941. /* time backend settings; hooks are unused */
  108942. {
  108943. int times=oggpack_read(opb,6)+1;
  108944. for(i=0;i<times;i++){
  108945. int test=oggpack_read(opb,16);
  108946. if(test<0 || test>=VI_TIMEB)goto err_out;
  108947. }
  108948. }
  108949. /* floor backend settings */
  108950. ci->floors=oggpack_read(opb,6)+1;
  108951. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  108952. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  108953. for(i=0;i<ci->floors;i++){
  108954. ci->floor_type[i]=oggpack_read(opb,16);
  108955. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  108956. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  108957. if(!ci->floor_param[i])goto err_out;
  108958. }
  108959. /* residue backend settings */
  108960. ci->residues=oggpack_read(opb,6)+1;
  108961. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  108962. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  108963. for(i=0;i<ci->residues;i++){
  108964. ci->residue_type[i]=oggpack_read(opb,16);
  108965. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  108966. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  108967. if(!ci->residue_param[i])goto err_out;
  108968. }
  108969. /* map backend settings */
  108970. ci->maps=oggpack_read(opb,6)+1;
  108971. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  108972. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  108973. for(i=0;i<ci->maps;i++){
  108974. ci->map_type[i]=oggpack_read(opb,16);
  108975. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  108976. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  108977. if(!ci->map_param[i])goto err_out;
  108978. }
  108979. /* mode settings */
  108980. ci->modes=oggpack_read(opb,6)+1;
  108981. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  108982. for(i=0;i<ci->modes;i++){
  108983. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  108984. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  108985. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  108986. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  108987. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  108988. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  108989. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  108990. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  108991. }
  108992. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  108993. return(0);
  108994. err_out:
  108995. vorbis_info_clear(vi);
  108996. return(OV_EBADHEADER);
  108997. }
  108998. /* The Vorbis header is in three packets; the initial small packet in
  108999. the first page that identifies basic parameters, a second packet
  109000. with bitstream comments and a third packet that holds the
  109001. codebook. */
  109002. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  109003. oggpack_buffer opb;
  109004. if(op){
  109005. oggpack_readinit(&opb,op->packet,op->bytes);
  109006. /* Which of the three types of header is this? */
  109007. /* Also verify header-ness, vorbis */
  109008. {
  109009. char buffer[6];
  109010. int packtype=oggpack_read(&opb,8);
  109011. memset(buffer,0,6);
  109012. _v_readstring(&opb,buffer,6);
  109013. if(memcmp(buffer,"vorbis",6)){
  109014. /* not a vorbis header */
  109015. return(OV_ENOTVORBIS);
  109016. }
  109017. switch(packtype){
  109018. case 0x01: /* least significant *bit* is read first */
  109019. if(!op->b_o_s){
  109020. /* Not the initial packet */
  109021. return(OV_EBADHEADER);
  109022. }
  109023. if(vi->rate!=0){
  109024. /* previously initialized info header */
  109025. return(OV_EBADHEADER);
  109026. }
  109027. return(_vorbis_unpack_info(vi,&opb));
  109028. case 0x03: /* least significant *bit* is read first */
  109029. if(vi->rate==0){
  109030. /* um... we didn't get the initial header */
  109031. return(OV_EBADHEADER);
  109032. }
  109033. return(_vorbis_unpack_comment(vc,&opb));
  109034. case 0x05: /* least significant *bit* is read first */
  109035. if(vi->rate==0 || vc->vendor==NULL){
  109036. /* um... we didn;t get the initial header or comments yet */
  109037. return(OV_EBADHEADER);
  109038. }
  109039. return(_vorbis_unpack_books(vi,&opb));
  109040. default:
  109041. /* Not a valid vorbis header type */
  109042. return(OV_EBADHEADER);
  109043. break;
  109044. }
  109045. }
  109046. }
  109047. return(OV_EBADHEADER);
  109048. }
  109049. /* pack side **********************************************************/
  109050. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  109051. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109052. if(!ci)return(OV_EFAULT);
  109053. /* preamble */
  109054. oggpack_write(opb,0x01,8);
  109055. _v_writestring(opb,"vorbis", 6);
  109056. /* basic information about the stream */
  109057. oggpack_write(opb,0x00,32);
  109058. oggpack_write(opb,vi->channels,8);
  109059. oggpack_write(opb,vi->rate,32);
  109060. oggpack_write(opb,vi->bitrate_upper,32);
  109061. oggpack_write(opb,vi->bitrate_nominal,32);
  109062. oggpack_write(opb,vi->bitrate_lower,32);
  109063. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  109064. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  109065. oggpack_write(opb,1,1);
  109066. return(0);
  109067. }
  109068. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  109069. char temp[]="Xiph.Org libVorbis I 20050304";
  109070. int bytes = strlen(temp);
  109071. /* preamble */
  109072. oggpack_write(opb,0x03,8);
  109073. _v_writestring(opb,"vorbis", 6);
  109074. /* vendor */
  109075. oggpack_write(opb,bytes,32);
  109076. _v_writestring(opb,temp, bytes);
  109077. /* comments */
  109078. oggpack_write(opb,vc->comments,32);
  109079. if(vc->comments){
  109080. int i;
  109081. for(i=0;i<vc->comments;i++){
  109082. if(vc->user_comments[i]){
  109083. oggpack_write(opb,vc->comment_lengths[i],32);
  109084. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  109085. }else{
  109086. oggpack_write(opb,0,32);
  109087. }
  109088. }
  109089. }
  109090. oggpack_write(opb,1,1);
  109091. return(0);
  109092. }
  109093. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  109094. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109095. int i;
  109096. if(!ci)return(OV_EFAULT);
  109097. oggpack_write(opb,0x05,8);
  109098. _v_writestring(opb,"vorbis", 6);
  109099. /* books */
  109100. oggpack_write(opb,ci->books-1,8);
  109101. for(i=0;i<ci->books;i++)
  109102. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  109103. /* times; hook placeholders */
  109104. oggpack_write(opb,0,6);
  109105. oggpack_write(opb,0,16);
  109106. /* floors */
  109107. oggpack_write(opb,ci->floors-1,6);
  109108. for(i=0;i<ci->floors;i++){
  109109. oggpack_write(opb,ci->floor_type[i],16);
  109110. if(_floor_P[ci->floor_type[i]]->pack)
  109111. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  109112. else
  109113. goto err_out;
  109114. }
  109115. /* residues */
  109116. oggpack_write(opb,ci->residues-1,6);
  109117. for(i=0;i<ci->residues;i++){
  109118. oggpack_write(opb,ci->residue_type[i],16);
  109119. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  109120. }
  109121. /* maps */
  109122. oggpack_write(opb,ci->maps-1,6);
  109123. for(i=0;i<ci->maps;i++){
  109124. oggpack_write(opb,ci->map_type[i],16);
  109125. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  109126. }
  109127. /* modes */
  109128. oggpack_write(opb,ci->modes-1,6);
  109129. for(i=0;i<ci->modes;i++){
  109130. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  109131. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  109132. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  109133. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  109134. }
  109135. oggpack_write(opb,1,1);
  109136. return(0);
  109137. err_out:
  109138. return(-1);
  109139. }
  109140. int vorbis_commentheader_out(vorbis_comment *vc,
  109141. ogg_packet *op){
  109142. oggpack_buffer opb;
  109143. oggpack_writeinit(&opb);
  109144. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  109145. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109146. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  109147. op->bytes=oggpack_bytes(&opb);
  109148. op->b_o_s=0;
  109149. op->e_o_s=0;
  109150. op->granulepos=0;
  109151. op->packetno=1;
  109152. return 0;
  109153. }
  109154. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  109155. vorbis_comment *vc,
  109156. ogg_packet *op,
  109157. ogg_packet *op_comm,
  109158. ogg_packet *op_code){
  109159. int ret=OV_EIMPL;
  109160. vorbis_info *vi=v->vi;
  109161. oggpack_buffer opb;
  109162. private_state *b=(private_state*)v->backend_state;
  109163. if(!b){
  109164. ret=OV_EFAULT;
  109165. goto err_out;
  109166. }
  109167. /* first header packet **********************************************/
  109168. oggpack_writeinit(&opb);
  109169. if(_vorbis_pack_info(&opb,vi))goto err_out;
  109170. /* build the packet */
  109171. if(b->header)_ogg_free(b->header);
  109172. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109173. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  109174. op->packet=b->header;
  109175. op->bytes=oggpack_bytes(&opb);
  109176. op->b_o_s=1;
  109177. op->e_o_s=0;
  109178. op->granulepos=0;
  109179. op->packetno=0;
  109180. /* second header packet (comments) **********************************/
  109181. oggpack_reset(&opb);
  109182. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  109183. if(b->header1)_ogg_free(b->header1);
  109184. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109185. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  109186. op_comm->packet=b->header1;
  109187. op_comm->bytes=oggpack_bytes(&opb);
  109188. op_comm->b_o_s=0;
  109189. op_comm->e_o_s=0;
  109190. op_comm->granulepos=0;
  109191. op_comm->packetno=1;
  109192. /* third header packet (modes/codebooks) ****************************/
  109193. oggpack_reset(&opb);
  109194. if(_vorbis_pack_books(&opb,vi))goto err_out;
  109195. if(b->header2)_ogg_free(b->header2);
  109196. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109197. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  109198. op_code->packet=b->header2;
  109199. op_code->bytes=oggpack_bytes(&opb);
  109200. op_code->b_o_s=0;
  109201. op_code->e_o_s=0;
  109202. op_code->granulepos=0;
  109203. op_code->packetno=2;
  109204. oggpack_writeclear(&opb);
  109205. return(0);
  109206. err_out:
  109207. oggpack_writeclear(&opb);
  109208. memset(op,0,sizeof(*op));
  109209. memset(op_comm,0,sizeof(*op_comm));
  109210. memset(op_code,0,sizeof(*op_code));
  109211. if(b->header)_ogg_free(b->header);
  109212. if(b->header1)_ogg_free(b->header1);
  109213. if(b->header2)_ogg_free(b->header2);
  109214. b->header=NULL;
  109215. b->header1=NULL;
  109216. b->header2=NULL;
  109217. return(ret);
  109218. }
  109219. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  109220. if(granulepos>=0)
  109221. return((double)granulepos/v->vi->rate);
  109222. return(-1);
  109223. }
  109224. #endif
  109225. /********* End of inlined file: info.c *********/
  109226. /********* Start of inlined file: lpc.c *********/
  109227. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  109228. are derived from code written by Jutta Degener and Carsten Bormann;
  109229. thus we include their copyright below. The entirety of this file
  109230. is freely redistributable on the condition that both of these
  109231. copyright notices are preserved without modification. */
  109232. /* Preserved Copyright: *********************************************/
  109233. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  109234. Technische Universita"t Berlin
  109235. Any use of this software is permitted provided that this notice is not
  109236. removed and that neither the authors nor the Technische Universita"t
  109237. Berlin are deemed to have made any representations as to the
  109238. suitability of this software for any purpose nor are held responsible
  109239. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  109240. THIS SOFTWARE.
  109241. As a matter of courtesy, the authors request to be informed about uses
  109242. this software has found, about bugs in this software, and about any
  109243. improvements that may be of general interest.
  109244. Berlin, 28.11.1994
  109245. Jutta Degener
  109246. Carsten Bormann
  109247. *********************************************************************/
  109248. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109249. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109250. // tasks..
  109251. #ifdef _MSC_VER
  109252. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109253. #endif
  109254. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109255. #if JUCE_USE_OGGVORBIS
  109256. #include <stdlib.h>
  109257. #include <string.h>
  109258. #include <math.h>
  109259. /* Autocorrelation LPC coeff generation algorithm invented by
  109260. N. Levinson in 1947, modified by J. Durbin in 1959. */
  109261. /* Input : n elements of time doamin data
  109262. Output: m lpc coefficients, excitation energy */
  109263. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  109264. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  109265. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  109266. double error;
  109267. int i,j;
  109268. /* autocorrelation, p+1 lag coefficients */
  109269. j=m+1;
  109270. while(j--){
  109271. double d=0; /* double needed for accumulator depth */
  109272. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  109273. aut[j]=d;
  109274. }
  109275. /* Generate lpc coefficients from autocorr values */
  109276. error=aut[0];
  109277. for(i=0;i<m;i++){
  109278. double r= -aut[i+1];
  109279. if(error==0){
  109280. memset(lpci,0,m*sizeof(*lpci));
  109281. return 0;
  109282. }
  109283. /* Sum up this iteration's reflection coefficient; note that in
  109284. Vorbis we don't save it. If anyone wants to recycle this code
  109285. and needs reflection coefficients, save the results of 'r' from
  109286. each iteration. */
  109287. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  109288. r/=error;
  109289. /* Update LPC coefficients and total error */
  109290. lpc[i]=r;
  109291. for(j=0;j<i/2;j++){
  109292. double tmp=lpc[j];
  109293. lpc[j]+=r*lpc[i-1-j];
  109294. lpc[i-1-j]+=r*tmp;
  109295. }
  109296. if(i%2)lpc[j]+=lpc[j]*r;
  109297. error*=1.f-r*r;
  109298. }
  109299. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  109300. /* we need the error value to know how big an impulse to hit the
  109301. filter with later */
  109302. return error;
  109303. }
  109304. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  109305. float *data,long n){
  109306. /* in: coeff[0...m-1] LPC coefficients
  109307. prime[0...m-1] initial values (allocated size of n+m-1)
  109308. out: data[0...n-1] data samples */
  109309. long i,j,o,p;
  109310. float y;
  109311. float *work=(float*)alloca(sizeof(*work)*(m+n));
  109312. if(!prime)
  109313. for(i=0;i<m;i++)
  109314. work[i]=0.f;
  109315. else
  109316. for(i=0;i<m;i++)
  109317. work[i]=prime[i];
  109318. for(i=0;i<n;i++){
  109319. y=0;
  109320. o=i;
  109321. p=m;
  109322. for(j=0;j<m;j++)
  109323. y-=work[o++]*coeff[--p];
  109324. data[i]=work[o]=y;
  109325. }
  109326. }
  109327. #endif
  109328. /********* End of inlined file: lpc.c *********/
  109329. /********* Start of inlined file: lsp.c *********/
  109330. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  109331. an iterative root polisher (CACM algorithm 283). It *is* possible
  109332. to confuse this algorithm into not converging; that should only
  109333. happen with absurdly closely spaced roots (very sharp peaks in the
  109334. LPC f response) which in turn should be impossible in our use of
  109335. the code. If this *does* happen anyway, it's a bug in the floor
  109336. finder; find the cause of the confusion (probably a single bin
  109337. spike or accidental near-float-limit resolution problems) and
  109338. correct it. */
  109339. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109340. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109341. // tasks..
  109342. #ifdef _MSC_VER
  109343. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109344. #endif
  109345. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109346. #if JUCE_USE_OGGVORBIS
  109347. #include <math.h>
  109348. #include <string.h>
  109349. #include <stdlib.h>
  109350. /********* Start of inlined file: lookup.h *********/
  109351. #ifndef _V_LOOKUP_H_
  109352. #ifdef FLOAT_LOOKUP
  109353. extern float vorbis_coslook(float a);
  109354. extern float vorbis_invsqlook(float a);
  109355. extern float vorbis_invsq2explook(int a);
  109356. extern float vorbis_fromdBlook(float a);
  109357. #endif
  109358. #ifdef INT_LOOKUP
  109359. extern long vorbis_invsqlook_i(long a,long e);
  109360. extern long vorbis_coslook_i(long a);
  109361. extern float vorbis_fromdBlook_i(long a);
  109362. #endif
  109363. #endif
  109364. /********* End of inlined file: lookup.h *********/
  109365. /* three possible LSP to f curve functions; the exact computation
  109366. (float), a lookup based float implementation, and an integer
  109367. implementation. The float lookup is likely the optimal choice on
  109368. any machine with an FPU. The integer implementation is *not* fixed
  109369. point (due to the need for a large dynamic range and thus a
  109370. seperately tracked exponent) and thus much more complex than the
  109371. relatively simple float implementations. It's mostly for future
  109372. work on a fully fixed point implementation for processors like the
  109373. ARM family. */
  109374. /* undefine both for the 'old' but more precise implementation */
  109375. #define FLOAT_LOOKUP
  109376. #undef INT_LOOKUP
  109377. #ifdef FLOAT_LOOKUP
  109378. /********* Start of inlined file: lookup.c *********/
  109379. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109380. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109381. // tasks..
  109382. #ifdef _MSC_VER
  109383. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109384. #endif
  109385. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109386. #if JUCE_USE_OGGVORBIS
  109387. #include <math.h>
  109388. /********* Start of inlined file: lookup.h *********/
  109389. #ifndef _V_LOOKUP_H_
  109390. #ifdef FLOAT_LOOKUP
  109391. extern float vorbis_coslook(float a);
  109392. extern float vorbis_invsqlook(float a);
  109393. extern float vorbis_invsq2explook(int a);
  109394. extern float vorbis_fromdBlook(float a);
  109395. #endif
  109396. #ifdef INT_LOOKUP
  109397. extern long vorbis_invsqlook_i(long a,long e);
  109398. extern long vorbis_coslook_i(long a);
  109399. extern float vorbis_fromdBlook_i(long a);
  109400. #endif
  109401. #endif
  109402. /********* End of inlined file: lookup.h *********/
  109403. /********* Start of inlined file: lookup_data.h *********/
  109404. #ifndef _V_LOOKUP_DATA_H_
  109405. #ifdef FLOAT_LOOKUP
  109406. #define COS_LOOKUP_SZ 128
  109407. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  109408. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  109409. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  109410. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  109411. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  109412. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  109413. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  109414. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  109415. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  109416. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  109417. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  109418. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  109419. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  109420. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  109421. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  109422. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  109423. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  109424. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  109425. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  109426. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  109427. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  109428. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  109429. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  109430. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  109431. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  109432. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  109433. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  109434. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  109435. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  109436. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  109437. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  109438. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  109439. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  109440. -1.0000000000000f,
  109441. };
  109442. #define INVSQ_LOOKUP_SZ 32
  109443. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  109444. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  109445. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  109446. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  109447. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  109448. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  109449. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  109450. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  109451. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  109452. 1.000000000000f,
  109453. };
  109454. #define INVSQ2EXP_LOOKUP_MIN (-32)
  109455. #define INVSQ2EXP_LOOKUP_MAX 32
  109456. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  109457. INVSQ2EXP_LOOKUP_MIN+1]={
  109458. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  109459. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  109460. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  109461. 1024.f, 724.0773439f, 512.f, 362.038672f,
  109462. 256.f, 181.019336f, 128.f, 90.50966799f,
  109463. 64.f, 45.254834f, 32.f, 22.627417f,
  109464. 16.f, 11.3137085f, 8.f, 5.656854249f,
  109465. 4.f, 2.828427125f, 2.f, 1.414213562f,
  109466. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  109467. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  109468. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  109469. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  109470. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  109471. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  109472. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  109473. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  109474. 1.525878906e-05f,
  109475. };
  109476. #endif
  109477. #define FROMdB_LOOKUP_SZ 35
  109478. #define FROMdB2_LOOKUP_SZ 32
  109479. #define FROMdB_SHIFT 5
  109480. #define FROMdB2_SHIFT 3
  109481. #define FROMdB2_MASK 31
  109482. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  109483. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  109484. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  109485. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  109486. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  109487. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  109488. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  109489. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  109490. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  109491. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  109492. };
  109493. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  109494. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  109495. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  109496. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  109497. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  109498. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  109499. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  109500. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  109501. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  109502. };
  109503. #ifdef INT_LOOKUP
  109504. #define INVSQ_LOOKUP_I_SHIFT 10
  109505. #define INVSQ_LOOKUP_I_MASK 1023
  109506. static long INVSQ_LOOKUP_I[64+1]={
  109507. 92682l, 91966l, 91267l, 90583l,
  109508. 89915l, 89261l, 88621l, 87995l,
  109509. 87381l, 86781l, 86192l, 85616l,
  109510. 85051l, 84497l, 83953l, 83420l,
  109511. 82897l, 82384l, 81880l, 81385l,
  109512. 80899l, 80422l, 79953l, 79492l,
  109513. 79039l, 78594l, 78156l, 77726l,
  109514. 77302l, 76885l, 76475l, 76072l,
  109515. 75674l, 75283l, 74898l, 74519l,
  109516. 74146l, 73778l, 73415l, 73058l,
  109517. 72706l, 72359l, 72016l, 71679l,
  109518. 71347l, 71019l, 70695l, 70376l,
  109519. 70061l, 69750l, 69444l, 69141l,
  109520. 68842l, 68548l, 68256l, 67969l,
  109521. 67685l, 67405l, 67128l, 66855l,
  109522. 66585l, 66318l, 66054l, 65794l,
  109523. 65536l,
  109524. };
  109525. #define COS_LOOKUP_I_SHIFT 9
  109526. #define COS_LOOKUP_I_MASK 511
  109527. #define COS_LOOKUP_I_SZ 128
  109528. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  109529. 16384l, 16379l, 16364l, 16340l,
  109530. 16305l, 16261l, 16207l, 16143l,
  109531. 16069l, 15986l, 15893l, 15791l,
  109532. 15679l, 15557l, 15426l, 15286l,
  109533. 15137l, 14978l, 14811l, 14635l,
  109534. 14449l, 14256l, 14053l, 13842l,
  109535. 13623l, 13395l, 13160l, 12916l,
  109536. 12665l, 12406l, 12140l, 11866l,
  109537. 11585l, 11297l, 11003l, 10702l,
  109538. 10394l, 10080l, 9760l, 9434l,
  109539. 9102l, 8765l, 8423l, 8076l,
  109540. 7723l, 7366l, 7005l, 6639l,
  109541. 6270l, 5897l, 5520l, 5139l,
  109542. 4756l, 4370l, 3981l, 3590l,
  109543. 3196l, 2801l, 2404l, 2006l,
  109544. 1606l, 1205l, 804l, 402l,
  109545. 0l, -401l, -803l, -1204l,
  109546. -1605l, -2005l, -2403l, -2800l,
  109547. -3195l, -3589l, -3980l, -4369l,
  109548. -4755l, -5138l, -5519l, -5896l,
  109549. -6269l, -6638l, -7004l, -7365l,
  109550. -7722l, -8075l, -8422l, -8764l,
  109551. -9101l, -9433l, -9759l, -10079l,
  109552. -10393l, -10701l, -11002l, -11296l,
  109553. -11584l, -11865l, -12139l, -12405l,
  109554. -12664l, -12915l, -13159l, -13394l,
  109555. -13622l, -13841l, -14052l, -14255l,
  109556. -14448l, -14634l, -14810l, -14977l,
  109557. -15136l, -15285l, -15425l, -15556l,
  109558. -15678l, -15790l, -15892l, -15985l,
  109559. -16068l, -16142l, -16206l, -16260l,
  109560. -16304l, -16339l, -16363l, -16378l,
  109561. -16383l,
  109562. };
  109563. #endif
  109564. #endif
  109565. /********* End of inlined file: lookup_data.h *********/
  109566. #ifdef FLOAT_LOOKUP
  109567. /* interpolated lookup based cos function, domain 0 to PI only */
  109568. float vorbis_coslook(float a){
  109569. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  109570. int i=vorbis_ftoi(d-.5);
  109571. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  109572. }
  109573. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  109574. float vorbis_invsqlook(float a){
  109575. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  109576. int i=vorbis_ftoi(d-.5f);
  109577. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  109578. }
  109579. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  109580. float vorbis_invsq2explook(int a){
  109581. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  109582. }
  109583. #include <stdio.h>
  109584. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  109585. float vorbis_fromdBlook(float a){
  109586. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  109587. return (i<0)?1.f:
  109588. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  109589. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  109590. }
  109591. #endif
  109592. #ifdef INT_LOOKUP
  109593. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  109594. 16.16 format
  109595. returns in m.8 format */
  109596. long vorbis_invsqlook_i(long a,long e){
  109597. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  109598. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  109599. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  109600. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  109601. d)>>16); /* result 1.16 */
  109602. e+=32;
  109603. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  109604. e=(e>>1)-8;
  109605. return(val>>e);
  109606. }
  109607. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  109608. /* a is in n.12 format */
  109609. float vorbis_fromdBlook_i(long a){
  109610. int i=(-a)>>(12-FROMdB2_SHIFT);
  109611. return (i<0)?1.f:
  109612. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  109613. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  109614. }
  109615. /* interpolated lookup based cos function, domain 0 to PI only */
  109616. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  109617. long vorbis_coslook_i(long a){
  109618. int i=a>>COS_LOOKUP_I_SHIFT;
  109619. int d=a&COS_LOOKUP_I_MASK;
  109620. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  109621. COS_LOOKUP_I_SHIFT);
  109622. }
  109623. #endif
  109624. #endif
  109625. /********* End of inlined file: lookup.c *********/
  109626. /* catch this in the build system; we #include for
  109627. compilers (like gcc) that can't inline across
  109628. modules */
  109629. /* side effect: changes *lsp to cosines of lsp */
  109630. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109631. float amp,float ampoffset){
  109632. int i;
  109633. float wdel=M_PI/ln;
  109634. vorbis_fpu_control fpu;
  109635. (void) fpu; // to avoid an unused variable warning
  109636. vorbis_fpu_setround(&fpu);
  109637. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  109638. i=0;
  109639. while(i<n){
  109640. int k=map[i];
  109641. int qexp;
  109642. float p=.7071067812f;
  109643. float q=.7071067812f;
  109644. float w=vorbis_coslook(wdel*k);
  109645. float *ftmp=lsp;
  109646. int c=m>>1;
  109647. do{
  109648. q*=ftmp[0]-w;
  109649. p*=ftmp[1]-w;
  109650. ftmp+=2;
  109651. }while(--c);
  109652. if(m&1){
  109653. /* odd order filter; slightly assymetric */
  109654. /* the last coefficient */
  109655. q*=ftmp[0]-w;
  109656. q*=q;
  109657. p*=p*(1.f-w*w);
  109658. }else{
  109659. /* even order filter; still symmetric */
  109660. q*=q*(1.f+w);
  109661. p*=p*(1.f-w);
  109662. }
  109663. q=frexp(p+q,&qexp);
  109664. q=vorbis_fromdBlook(amp*
  109665. vorbis_invsqlook(q)*
  109666. vorbis_invsq2explook(qexp+m)-
  109667. ampoffset);
  109668. do{
  109669. curve[i++]*=q;
  109670. }while(map[i]==k);
  109671. }
  109672. vorbis_fpu_restore(fpu);
  109673. }
  109674. #else
  109675. #ifdef INT_LOOKUP
  109676. /********* Start of inlined file: lookup.c *********/
  109677. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109678. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109679. // tasks..
  109680. #ifdef _MSC_VER
  109681. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109682. #endif
  109683. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109684. #if JUCE_USE_OGGVORBIS
  109685. #include <math.h>
  109686. /********* Start of inlined file: lookup.h *********/
  109687. #ifndef _V_LOOKUP_H_
  109688. #ifdef FLOAT_LOOKUP
  109689. extern float vorbis_coslook(float a);
  109690. extern float vorbis_invsqlook(float a);
  109691. extern float vorbis_invsq2explook(int a);
  109692. extern float vorbis_fromdBlook(float a);
  109693. #endif
  109694. #ifdef INT_LOOKUP
  109695. extern long vorbis_invsqlook_i(long a,long e);
  109696. extern long vorbis_coslook_i(long a);
  109697. extern float vorbis_fromdBlook_i(long a);
  109698. #endif
  109699. #endif
  109700. /********* End of inlined file: lookup.h *********/
  109701. /********* Start of inlined file: lookup_data.h *********/
  109702. #ifndef _V_LOOKUP_DATA_H_
  109703. #ifdef FLOAT_LOOKUP
  109704. #define COS_LOOKUP_SZ 128
  109705. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  109706. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  109707. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  109708. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  109709. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  109710. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  109711. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  109712. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  109713. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  109714. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  109715. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  109716. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  109717. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  109718. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  109719. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  109720. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  109721. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  109722. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  109723. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  109724. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  109725. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  109726. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  109727. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  109728. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  109729. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  109730. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  109731. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  109732. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  109733. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  109734. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  109735. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  109736. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  109737. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  109738. -1.0000000000000f,
  109739. };
  109740. #define INVSQ_LOOKUP_SZ 32
  109741. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  109742. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  109743. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  109744. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  109745. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  109746. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  109747. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  109748. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  109749. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  109750. 1.000000000000f,
  109751. };
  109752. #define INVSQ2EXP_LOOKUP_MIN (-32)
  109753. #define INVSQ2EXP_LOOKUP_MAX 32
  109754. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  109755. INVSQ2EXP_LOOKUP_MIN+1]={
  109756. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  109757. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  109758. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  109759. 1024.f, 724.0773439f, 512.f, 362.038672f,
  109760. 256.f, 181.019336f, 128.f, 90.50966799f,
  109761. 64.f, 45.254834f, 32.f, 22.627417f,
  109762. 16.f, 11.3137085f, 8.f, 5.656854249f,
  109763. 4.f, 2.828427125f, 2.f, 1.414213562f,
  109764. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  109765. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  109766. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  109767. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  109768. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  109769. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  109770. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  109771. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  109772. 1.525878906e-05f,
  109773. };
  109774. #endif
  109775. #define FROMdB_LOOKUP_SZ 35
  109776. #define FROMdB2_LOOKUP_SZ 32
  109777. #define FROMdB_SHIFT 5
  109778. #define FROMdB2_SHIFT 3
  109779. #define FROMdB2_MASK 31
  109780. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  109781. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  109782. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  109783. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  109784. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  109785. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  109786. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  109787. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  109788. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  109789. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  109790. };
  109791. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  109792. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  109793. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  109794. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  109795. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  109796. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  109797. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  109798. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  109799. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  109800. };
  109801. #ifdef INT_LOOKUP
  109802. #define INVSQ_LOOKUP_I_SHIFT 10
  109803. #define INVSQ_LOOKUP_I_MASK 1023
  109804. static long INVSQ_LOOKUP_I[64+1]={
  109805. 92682l, 91966l, 91267l, 90583l,
  109806. 89915l, 89261l, 88621l, 87995l,
  109807. 87381l, 86781l, 86192l, 85616l,
  109808. 85051l, 84497l, 83953l, 83420l,
  109809. 82897l, 82384l, 81880l, 81385l,
  109810. 80899l, 80422l, 79953l, 79492l,
  109811. 79039l, 78594l, 78156l, 77726l,
  109812. 77302l, 76885l, 76475l, 76072l,
  109813. 75674l, 75283l, 74898l, 74519l,
  109814. 74146l, 73778l, 73415l, 73058l,
  109815. 72706l, 72359l, 72016l, 71679l,
  109816. 71347l, 71019l, 70695l, 70376l,
  109817. 70061l, 69750l, 69444l, 69141l,
  109818. 68842l, 68548l, 68256l, 67969l,
  109819. 67685l, 67405l, 67128l, 66855l,
  109820. 66585l, 66318l, 66054l, 65794l,
  109821. 65536l,
  109822. };
  109823. #define COS_LOOKUP_I_SHIFT 9
  109824. #define COS_LOOKUP_I_MASK 511
  109825. #define COS_LOOKUP_I_SZ 128
  109826. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  109827. 16384l, 16379l, 16364l, 16340l,
  109828. 16305l, 16261l, 16207l, 16143l,
  109829. 16069l, 15986l, 15893l, 15791l,
  109830. 15679l, 15557l, 15426l, 15286l,
  109831. 15137l, 14978l, 14811l, 14635l,
  109832. 14449l, 14256l, 14053l, 13842l,
  109833. 13623l, 13395l, 13160l, 12916l,
  109834. 12665l, 12406l, 12140l, 11866l,
  109835. 11585l, 11297l, 11003l, 10702l,
  109836. 10394l, 10080l, 9760l, 9434l,
  109837. 9102l, 8765l, 8423l, 8076l,
  109838. 7723l, 7366l, 7005l, 6639l,
  109839. 6270l, 5897l, 5520l, 5139l,
  109840. 4756l, 4370l, 3981l, 3590l,
  109841. 3196l, 2801l, 2404l, 2006l,
  109842. 1606l, 1205l, 804l, 402l,
  109843. 0l, -401l, -803l, -1204l,
  109844. -1605l, -2005l, -2403l, -2800l,
  109845. -3195l, -3589l, -3980l, -4369l,
  109846. -4755l, -5138l, -5519l, -5896l,
  109847. -6269l, -6638l, -7004l, -7365l,
  109848. -7722l, -8075l, -8422l, -8764l,
  109849. -9101l, -9433l, -9759l, -10079l,
  109850. -10393l, -10701l, -11002l, -11296l,
  109851. -11584l, -11865l, -12139l, -12405l,
  109852. -12664l, -12915l, -13159l, -13394l,
  109853. -13622l, -13841l, -14052l, -14255l,
  109854. -14448l, -14634l, -14810l, -14977l,
  109855. -15136l, -15285l, -15425l, -15556l,
  109856. -15678l, -15790l, -15892l, -15985l,
  109857. -16068l, -16142l, -16206l, -16260l,
  109858. -16304l, -16339l, -16363l, -16378l,
  109859. -16383l,
  109860. };
  109861. #endif
  109862. #endif
  109863. /********* End of inlined file: lookup_data.h *********/
  109864. #ifdef FLOAT_LOOKUP
  109865. /* interpolated lookup based cos function, domain 0 to PI only */
  109866. float vorbis_coslook(float a){
  109867. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  109868. int i=vorbis_ftoi(d-.5);
  109869. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  109870. }
  109871. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  109872. float vorbis_invsqlook(float a){
  109873. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  109874. int i=vorbis_ftoi(d-.5f);
  109875. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  109876. }
  109877. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  109878. float vorbis_invsq2explook(int a){
  109879. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  109880. }
  109881. #include <stdio.h>
  109882. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  109883. float vorbis_fromdBlook(float a){
  109884. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  109885. return (i<0)?1.f:
  109886. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  109887. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  109888. }
  109889. #endif
  109890. #ifdef INT_LOOKUP
  109891. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  109892. 16.16 format
  109893. returns in m.8 format */
  109894. long vorbis_invsqlook_i(long a,long e){
  109895. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  109896. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  109897. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  109898. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  109899. d)>>16); /* result 1.16 */
  109900. e+=32;
  109901. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  109902. e=(e>>1)-8;
  109903. return(val>>e);
  109904. }
  109905. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  109906. /* a is in n.12 format */
  109907. float vorbis_fromdBlook_i(long a){
  109908. int i=(-a)>>(12-FROMdB2_SHIFT);
  109909. return (i<0)?1.f:
  109910. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  109911. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  109912. }
  109913. /* interpolated lookup based cos function, domain 0 to PI only */
  109914. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  109915. long vorbis_coslook_i(long a){
  109916. int i=a>>COS_LOOKUP_I_SHIFT;
  109917. int d=a&COS_LOOKUP_I_MASK;
  109918. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  109919. COS_LOOKUP_I_SHIFT);
  109920. }
  109921. #endif
  109922. #endif
  109923. /********* End of inlined file: lookup.c *********/
  109924. /* catch this in the build system; we #include for
  109925. compilers (like gcc) that can't inline across
  109926. modules */
  109927. static int MLOOP_1[64]={
  109928. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  109929. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  109930. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  109931. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  109932. };
  109933. static int MLOOP_2[64]={
  109934. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  109935. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  109936. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  109937. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  109938. };
  109939. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  109940. /* side effect: changes *lsp to cosines of lsp */
  109941. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109942. float amp,float ampoffset){
  109943. /* 0 <= m < 256 */
  109944. /* set up for using all int later */
  109945. int i;
  109946. int ampoffseti=rint(ampoffset*4096.f);
  109947. int ampi=rint(amp*16.f);
  109948. long *ilsp=alloca(m*sizeof(*ilsp));
  109949. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  109950. i=0;
  109951. while(i<n){
  109952. int j,k=map[i];
  109953. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  109954. unsigned long qi=46341;
  109955. int qexp=0,shift;
  109956. long wi=vorbis_coslook_i(k*65536/ln);
  109957. qi*=labs(ilsp[0]-wi);
  109958. pi*=labs(ilsp[1]-wi);
  109959. for(j=3;j<m;j+=2){
  109960. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109961. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109962. shift=MLOOP_3[(pi|qi)>>16];
  109963. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  109964. pi=(pi>>shift)*labs(ilsp[j]-wi);
  109965. qexp+=shift;
  109966. }
  109967. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109968. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109969. shift=MLOOP_3[(pi|qi)>>16];
  109970. /* pi,qi normalized collectively, both tracked using qexp */
  109971. if(m&1){
  109972. /* odd order filter; slightly assymetric */
  109973. /* the last coefficient */
  109974. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  109975. pi=(pi>>shift)<<14;
  109976. qexp+=shift;
  109977. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109978. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109979. shift=MLOOP_3[(pi|qi)>>16];
  109980. pi>>=shift;
  109981. qi>>=shift;
  109982. qexp+=shift-14*((m+1)>>1);
  109983. pi=((pi*pi)>>16);
  109984. qi=((qi*qi)>>16);
  109985. qexp=qexp*2+m;
  109986. pi*=(1<<14)-((wi*wi)>>14);
  109987. qi+=pi>>14;
  109988. }else{
  109989. /* even order filter; still symmetric */
  109990. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  109991. worth tracking step by step */
  109992. pi>>=shift;
  109993. qi>>=shift;
  109994. qexp+=shift-7*m;
  109995. pi=((pi*pi)>>16);
  109996. qi=((qi*qi)>>16);
  109997. qexp=qexp*2+m;
  109998. pi*=(1<<14)-wi;
  109999. qi*=(1<<14)+wi;
  110000. qi=(qi+pi)>>14;
  110001. }
  110002. /* we've let the normalization drift because it wasn't important;
  110003. however, for the lookup, things must be normalized again. We
  110004. need at most one right shift or a number of left shifts */
  110005. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  110006. qi>>=1; qexp++;
  110007. }else
  110008. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  110009. qi<<=1; qexp--;
  110010. }
  110011. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  110012. vorbis_invsqlook_i(qi,qexp)-
  110013. /* m.8, m+n<=8 */
  110014. ampoffseti); /* 8.12[0] */
  110015. curve[i]*=amp;
  110016. while(map[++i]==k)curve[i]*=amp;
  110017. }
  110018. }
  110019. #else
  110020. /* old, nonoptimized but simple version for any poor sap who needs to
  110021. figure out what the hell this code does, or wants the other
  110022. fraction of a dB precision */
  110023. /* side effect: changes *lsp to cosines of lsp */
  110024. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110025. float amp,float ampoffset){
  110026. int i;
  110027. float wdel=M_PI/ln;
  110028. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  110029. i=0;
  110030. while(i<n){
  110031. int j,k=map[i];
  110032. float p=.5f;
  110033. float q=.5f;
  110034. float w=2.f*cos(wdel*k);
  110035. for(j=1;j<m;j+=2){
  110036. q *= w-lsp[j-1];
  110037. p *= w-lsp[j];
  110038. }
  110039. if(j==m){
  110040. /* odd order filter; slightly assymetric */
  110041. /* the last coefficient */
  110042. q*=w-lsp[j-1];
  110043. p*=p*(4.f-w*w);
  110044. q*=q;
  110045. }else{
  110046. /* even order filter; still symmetric */
  110047. p*=p*(2.f-w);
  110048. q*=q*(2.f+w);
  110049. }
  110050. q=fromdB(amp/sqrt(p+q)-ampoffset);
  110051. curve[i]*=q;
  110052. while(map[++i]==k)curve[i]*=q;
  110053. }
  110054. }
  110055. #endif
  110056. #endif
  110057. static void cheby(float *g, int ord) {
  110058. int i, j;
  110059. g[0] *= .5f;
  110060. for(i=2; i<= ord; i++) {
  110061. for(j=ord; j >= i; j--) {
  110062. g[j-2] -= g[j];
  110063. g[j] += g[j];
  110064. }
  110065. }
  110066. }
  110067. static int comp(const void *a,const void *b){
  110068. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  110069. }
  110070. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  110071. but there are root sets for which it gets into limit cycles
  110072. (exacerbated by zero suppression) and fails. We can't afford to
  110073. fail, even if the failure is 1 in 100,000,000, so we now use
  110074. Laguerre and later polish with Newton-Raphson (which can then
  110075. afford to fail) */
  110076. #define EPSILON 10e-7
  110077. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  110078. int i,m;
  110079. double lastdelta=0.f;
  110080. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  110081. for(i=0;i<=ord;i++)defl[i]=a[i];
  110082. for(m=ord;m>0;m--){
  110083. double newx=0.f,delta;
  110084. /* iterate a root */
  110085. while(1){
  110086. double p=defl[m],pp=0.f,ppp=0.f,denom;
  110087. /* eval the polynomial and its first two derivatives */
  110088. for(i=m;i>0;i--){
  110089. ppp = newx*ppp + pp;
  110090. pp = newx*pp + p;
  110091. p = newx*p + defl[i-1];
  110092. }
  110093. /* Laguerre's method */
  110094. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  110095. if(denom<0)
  110096. return(-1); /* complex root! The LPC generator handed us a bad filter */
  110097. if(pp>0){
  110098. denom = pp + sqrt(denom);
  110099. if(denom<EPSILON)denom=EPSILON;
  110100. }else{
  110101. denom = pp - sqrt(denom);
  110102. if(denom>-(EPSILON))denom=-(EPSILON);
  110103. }
  110104. delta = m*p/denom;
  110105. newx -= delta;
  110106. if(delta<0.f)delta*=-1;
  110107. if(fabs(delta/newx)<10e-12)break;
  110108. lastdelta=delta;
  110109. }
  110110. r[m-1]=newx;
  110111. /* forward deflation */
  110112. for(i=m;i>0;i--)
  110113. defl[i-1]+=newx*defl[i];
  110114. defl++;
  110115. }
  110116. return(0);
  110117. }
  110118. /* for spit-and-polish only */
  110119. static int Newton_Raphson(float *a,int ord,float *r){
  110120. int i, k, count=0;
  110121. double error=1.f;
  110122. double *root=(double*)alloca(ord*sizeof(*root));
  110123. for(i=0; i<ord;i++) root[i] = r[i];
  110124. while(error>1e-20){
  110125. error=0;
  110126. for(i=0; i<ord; i++) { /* Update each point. */
  110127. double pp=0.,delta;
  110128. double rooti=root[i];
  110129. double p=a[ord];
  110130. for(k=ord-1; k>= 0; k--) {
  110131. pp= pp* rooti + p;
  110132. p = p * rooti + a[k];
  110133. }
  110134. delta = p/pp;
  110135. root[i] -= delta;
  110136. error+= delta*delta;
  110137. }
  110138. if(count>40)return(-1);
  110139. count++;
  110140. }
  110141. /* Replaced the original bubble sort with a real sort. With your
  110142. help, we can eliminate the bubble sort in our lifetime. --Monty */
  110143. for(i=0; i<ord;i++) r[i] = root[i];
  110144. return(0);
  110145. }
  110146. /* Convert lpc coefficients to lsp coefficients */
  110147. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  110148. int order2=(m+1)>>1;
  110149. int g1_order,g2_order;
  110150. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  110151. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  110152. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  110153. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  110154. int i;
  110155. /* even and odd are slightly different base cases */
  110156. g1_order=(m+1)>>1;
  110157. g2_order=(m) >>1;
  110158. /* Compute the lengths of the x polynomials. */
  110159. /* Compute the first half of K & R F1 & F2 polynomials. */
  110160. /* Compute half of the symmetric and antisymmetric polynomials. */
  110161. /* Remove the roots at +1 and -1. */
  110162. g1[g1_order] = 1.f;
  110163. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  110164. g2[g2_order] = 1.f;
  110165. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  110166. if(g1_order>g2_order){
  110167. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  110168. }else{
  110169. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  110170. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  110171. }
  110172. /* Convert into polynomials in cos(alpha) */
  110173. cheby(g1,g1_order);
  110174. cheby(g2,g2_order);
  110175. /* Find the roots of the 2 even polynomials.*/
  110176. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  110177. Laguerre_With_Deflation(g2,g2_order,g2r))
  110178. return(-1);
  110179. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  110180. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  110181. qsort(g1r,g1_order,sizeof(*g1r),comp);
  110182. qsort(g2r,g2_order,sizeof(*g2r),comp);
  110183. for(i=0;i<g1_order;i++)
  110184. lsp[i*2] = acos(g1r[i]);
  110185. for(i=0;i<g2_order;i++)
  110186. lsp[i*2+1] = acos(g2r[i]);
  110187. return(0);
  110188. }
  110189. #endif
  110190. /********* End of inlined file: lsp.c *********/
  110191. /********* Start of inlined file: mapping0.c *********/
  110192. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110193. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110194. // tasks..
  110195. #ifdef _MSC_VER
  110196. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110197. #endif
  110198. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110199. #if JUCE_USE_OGGVORBIS
  110200. #include <stdlib.h>
  110201. #include <stdio.h>
  110202. #include <string.h>
  110203. #include <math.h>
  110204. /* simplistic, wasteful way of doing this (unique lookup for each
  110205. mode/submapping); there should be a central repository for
  110206. identical lookups. That will require minor work, so I'm putting it
  110207. off as low priority.
  110208. Why a lookup for each backend in a given mode? Because the
  110209. blocksize is set by the mode, and low backend lookups may require
  110210. parameters from other areas of the mode/mapping */
  110211. static void mapping0_free_info(vorbis_info_mapping *i){
  110212. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  110213. if(info){
  110214. memset(info,0,sizeof(*info));
  110215. _ogg_free(info);
  110216. }
  110217. }
  110218. static int ilog3(unsigned int v){
  110219. int ret=0;
  110220. if(v)--v;
  110221. while(v){
  110222. ret++;
  110223. v>>=1;
  110224. }
  110225. return(ret);
  110226. }
  110227. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  110228. oggpack_buffer *opb){
  110229. int i;
  110230. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  110231. /* another 'we meant to do it this way' hack... up to beta 4, we
  110232. packed 4 binary zeros here to signify one submapping in use. We
  110233. now redefine that to mean four bitflags that indicate use of
  110234. deeper features; bit0:submappings, bit1:coupling,
  110235. bit2,3:reserved. This is backward compatable with all actual uses
  110236. of the beta code. */
  110237. if(info->submaps>1){
  110238. oggpack_write(opb,1,1);
  110239. oggpack_write(opb,info->submaps-1,4);
  110240. }else
  110241. oggpack_write(opb,0,1);
  110242. if(info->coupling_steps>0){
  110243. oggpack_write(opb,1,1);
  110244. oggpack_write(opb,info->coupling_steps-1,8);
  110245. for(i=0;i<info->coupling_steps;i++){
  110246. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  110247. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  110248. }
  110249. }else
  110250. oggpack_write(opb,0,1);
  110251. oggpack_write(opb,0,2); /* 2,3:reserved */
  110252. /* we don't write the channel submappings if we only have one... */
  110253. if(info->submaps>1){
  110254. for(i=0;i<vi->channels;i++)
  110255. oggpack_write(opb,info->chmuxlist[i],4);
  110256. }
  110257. for(i=0;i<info->submaps;i++){
  110258. oggpack_write(opb,0,8); /* time submap unused */
  110259. oggpack_write(opb,info->floorsubmap[i],8);
  110260. oggpack_write(opb,info->residuesubmap[i],8);
  110261. }
  110262. }
  110263. /* also responsible for range checking */
  110264. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  110265. int i;
  110266. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  110267. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110268. memset(info,0,sizeof(*info));
  110269. if(oggpack_read(opb,1))
  110270. info->submaps=oggpack_read(opb,4)+1;
  110271. else
  110272. info->submaps=1;
  110273. if(oggpack_read(opb,1)){
  110274. info->coupling_steps=oggpack_read(opb,8)+1;
  110275. for(i=0;i<info->coupling_steps;i++){
  110276. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  110277. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  110278. if(testM<0 ||
  110279. testA<0 ||
  110280. testM==testA ||
  110281. testM>=vi->channels ||
  110282. testA>=vi->channels) goto err_out;
  110283. }
  110284. }
  110285. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  110286. if(info->submaps>1){
  110287. for(i=0;i<vi->channels;i++){
  110288. info->chmuxlist[i]=oggpack_read(opb,4);
  110289. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  110290. }
  110291. }
  110292. for(i=0;i<info->submaps;i++){
  110293. oggpack_read(opb,8); /* time submap unused */
  110294. info->floorsubmap[i]=oggpack_read(opb,8);
  110295. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  110296. info->residuesubmap[i]=oggpack_read(opb,8);
  110297. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  110298. }
  110299. return info;
  110300. err_out:
  110301. mapping0_free_info(info);
  110302. return(NULL);
  110303. }
  110304. #if 0
  110305. static long seq=0;
  110306. static ogg_int64_t total=0;
  110307. static float FLOOR1_fromdB_LOOKUP[256]={
  110308. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  110309. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  110310. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  110311. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  110312. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  110313. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  110314. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  110315. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  110316. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  110317. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  110318. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  110319. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  110320. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  110321. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  110322. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  110323. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  110324. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  110325. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  110326. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  110327. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  110328. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  110329. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  110330. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  110331. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  110332. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  110333. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  110334. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  110335. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  110336. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  110337. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  110338. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  110339. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  110340. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  110341. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  110342. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  110343. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  110344. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  110345. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  110346. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  110347. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  110348. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  110349. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  110350. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  110351. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  110352. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  110353. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  110354. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  110355. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  110356. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  110357. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  110358. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  110359. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  110360. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  110361. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  110362. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  110363. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  110364. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  110365. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  110366. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  110367. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  110368. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  110369. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  110370. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  110371. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  110372. };
  110373. #endif
  110374. extern int *floor1_fit(vorbis_block *vb,void *look,
  110375. const float *logmdct, /* in */
  110376. const float *logmask);
  110377. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  110378. int *A,int *B,
  110379. int del);
  110380. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  110381. void*look,
  110382. int *post,int *ilogmask);
  110383. static int mapping0_forward(vorbis_block *vb){
  110384. vorbis_dsp_state *vd=vb->vd;
  110385. vorbis_info *vi=vd->vi;
  110386. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110387. private_state *b=(private_state*)vb->vd->backend_state;
  110388. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110389. int n=vb->pcmend;
  110390. int i,j,k;
  110391. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  110392. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  110393. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  110394. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  110395. float global_ampmax=vbi->ampmax;
  110396. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  110397. int blocktype=vbi->blocktype;
  110398. int modenumber=vb->W;
  110399. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  110400. vorbis_look_psy *psy_look=
  110401. b->psy+blocktype+(vb->W?2:0);
  110402. vb->mode=modenumber;
  110403. for(i=0;i<vi->channels;i++){
  110404. float scale=4.f/n;
  110405. float scale_dB;
  110406. float *pcm =vb->pcm[i];
  110407. float *logfft =pcm;
  110408. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  110409. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  110410. todB estimation used on IEEE 754
  110411. compliant machines had a bug that
  110412. returned dB values about a third
  110413. of a decibel too high. The bug
  110414. was harmless because tunings
  110415. implicitly took that into
  110416. account. However, fixing the bug
  110417. in the estimator requires
  110418. changing all the tunings as well.
  110419. For now, it's easier to sync
  110420. things back up here, and
  110421. recalibrate the tunings in the
  110422. next major model upgrade. */
  110423. #if 0
  110424. if(vi->channels==2)
  110425. if(i==0)
  110426. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  110427. else
  110428. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  110429. #endif
  110430. /* window the PCM data */
  110431. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  110432. #if 0
  110433. if(vi->channels==2)
  110434. if(i==0)
  110435. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  110436. else
  110437. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  110438. #endif
  110439. /* transform the PCM data */
  110440. /* only MDCT right now.... */
  110441. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  110442. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  110443. drft_forward(&b->fft_look[vb->W],pcm);
  110444. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  110445. original todB estimation used on
  110446. IEEE 754 compliant machines had a
  110447. bug that returned dB values about
  110448. a third of a decibel too high.
  110449. The bug was harmless because
  110450. tunings implicitly took that into
  110451. account. However, fixing the bug
  110452. in the estimator requires
  110453. changing all the tunings as well.
  110454. For now, it's easier to sync
  110455. things back up here, and
  110456. recalibrate the tunings in the
  110457. next major model upgrade. */
  110458. local_ampmax[i]=logfft[0];
  110459. for(j=1;j<n-1;j+=2){
  110460. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  110461. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  110462. .345 is a hack; the original todB
  110463. estimation used on IEEE 754
  110464. compliant machines had a bug that
  110465. returned dB values about a third
  110466. of a decibel too high. The bug
  110467. was harmless because tunings
  110468. implicitly took that into
  110469. account. However, fixing the bug
  110470. in the estimator requires
  110471. changing all the tunings as well.
  110472. For now, it's easier to sync
  110473. things back up here, and
  110474. recalibrate the tunings in the
  110475. next major model upgrade. */
  110476. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  110477. }
  110478. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  110479. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  110480. #if 0
  110481. if(vi->channels==2){
  110482. if(i==0){
  110483. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  110484. }else{
  110485. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  110486. }
  110487. }
  110488. #endif
  110489. }
  110490. {
  110491. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  110492. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  110493. for(i=0;i<vi->channels;i++){
  110494. /* the encoder setup assumes that all the modes used by any
  110495. specific bitrate tweaking use the same floor */
  110496. int submap=info->chmuxlist[i];
  110497. /* the following makes things clearer to *me* anyway */
  110498. float *mdct =gmdct[i];
  110499. float *logfft =vb->pcm[i];
  110500. float *logmdct =logfft+n/2;
  110501. float *logmask =logfft;
  110502. vb->mode=modenumber;
  110503. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  110504. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  110505. for(j=0;j<n/2;j++)
  110506. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  110507. todB estimation used on IEEE 754
  110508. compliant machines had a bug that
  110509. returned dB values about a third
  110510. of a decibel too high. The bug
  110511. was harmless because tunings
  110512. implicitly took that into
  110513. account. However, fixing the bug
  110514. in the estimator requires
  110515. changing all the tunings as well.
  110516. For now, it's easier to sync
  110517. things back up here, and
  110518. recalibrate the tunings in the
  110519. next major model upgrade. */
  110520. #if 0
  110521. if(vi->channels==2){
  110522. if(i==0)
  110523. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  110524. else
  110525. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  110526. }else{
  110527. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  110528. }
  110529. #endif
  110530. /* first step; noise masking. Not only does 'noise masking'
  110531. give us curves from which we can decide how much resolution
  110532. to give noise parts of the spectrum, it also implicitly hands
  110533. us a tonality estimate (the larger the value in the
  110534. 'noise_depth' vector, the more tonal that area is) */
  110535. _vp_noisemask(psy_look,
  110536. logmdct,
  110537. noise); /* noise does not have by-frequency offset
  110538. bias applied yet */
  110539. #if 0
  110540. if(vi->channels==2){
  110541. if(i==0)
  110542. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  110543. else
  110544. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  110545. }
  110546. #endif
  110547. /* second step: 'all the other crap'; all the stuff that isn't
  110548. computed/fit for bitrate management goes in the second psy
  110549. vector. This includes tone masking, peak limiting and ATH */
  110550. _vp_tonemask(psy_look,
  110551. logfft,
  110552. tone,
  110553. global_ampmax,
  110554. local_ampmax[i]);
  110555. #if 0
  110556. if(vi->channels==2){
  110557. if(i==0)
  110558. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  110559. else
  110560. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  110561. }
  110562. #endif
  110563. /* third step; we offset the noise vectors, overlay tone
  110564. masking. We then do a floor1-specific line fit. If we're
  110565. performing bitrate management, the line fit is performed
  110566. multiple times for up/down tweakage on demand. */
  110567. #if 0
  110568. {
  110569. float aotuv[psy_look->n];
  110570. #endif
  110571. _vp_offset_and_mix(psy_look,
  110572. noise,
  110573. tone,
  110574. 1,
  110575. logmask,
  110576. mdct,
  110577. logmdct);
  110578. #if 0
  110579. if(vi->channels==2){
  110580. if(i==0)
  110581. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  110582. else
  110583. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  110584. }
  110585. }
  110586. #endif
  110587. #if 0
  110588. if(vi->channels==2){
  110589. if(i==0)
  110590. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  110591. else
  110592. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  110593. }
  110594. #endif
  110595. /* this algorithm is hardwired to floor 1 for now; abort out if
  110596. we're *not* floor1. This won't happen unless someone has
  110597. broken the encode setup lib. Guard it anyway. */
  110598. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  110599. floor_posts[i][PACKETBLOBS/2]=
  110600. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  110601. logmdct,
  110602. logmask);
  110603. /* are we managing bitrate? If so, perform two more fits for
  110604. later rate tweaking (fits represent hi/lo) */
  110605. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  110606. /* higher rate by way of lower noise curve */
  110607. _vp_offset_and_mix(psy_look,
  110608. noise,
  110609. tone,
  110610. 2,
  110611. logmask,
  110612. mdct,
  110613. logmdct);
  110614. #if 0
  110615. if(vi->channels==2){
  110616. if(i==0)
  110617. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  110618. else
  110619. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  110620. }
  110621. #endif
  110622. floor_posts[i][PACKETBLOBS-1]=
  110623. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  110624. logmdct,
  110625. logmask);
  110626. /* lower rate by way of higher noise curve */
  110627. _vp_offset_and_mix(psy_look,
  110628. noise,
  110629. tone,
  110630. 0,
  110631. logmask,
  110632. mdct,
  110633. logmdct);
  110634. #if 0
  110635. if(vi->channels==2)
  110636. if(i==0)
  110637. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  110638. else
  110639. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  110640. #endif
  110641. floor_posts[i][0]=
  110642. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  110643. logmdct,
  110644. logmask);
  110645. /* we also interpolate a range of intermediate curves for
  110646. intermediate rates */
  110647. for(k=1;k<PACKETBLOBS/2;k++)
  110648. floor_posts[i][k]=
  110649. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  110650. floor_posts[i][0],
  110651. floor_posts[i][PACKETBLOBS/2],
  110652. k*65536/(PACKETBLOBS/2));
  110653. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  110654. floor_posts[i][k]=
  110655. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  110656. floor_posts[i][PACKETBLOBS/2],
  110657. floor_posts[i][PACKETBLOBS-1],
  110658. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  110659. }
  110660. }
  110661. }
  110662. vbi->ampmax=global_ampmax;
  110663. /*
  110664. the next phases are performed once for vbr-only and PACKETBLOB
  110665. times for bitrate managed modes.
  110666. 1) encode actual mode being used
  110667. 2) encode the floor for each channel, compute coded mask curve/res
  110668. 3) normalize and couple.
  110669. 4) encode residue
  110670. 5) save packet bytes to the packetblob vector
  110671. */
  110672. /* iterate over the many masking curve fits we've created */
  110673. {
  110674. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  110675. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  110676. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  110677. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  110678. float **mag_memo;
  110679. int **mag_sort;
  110680. if(info->coupling_steps){
  110681. mag_memo=_vp_quantize_couple_memo(vb,
  110682. &ci->psy_g_param,
  110683. psy_look,
  110684. info,
  110685. gmdct);
  110686. mag_sort=_vp_quantize_couple_sort(vb,
  110687. psy_look,
  110688. info,
  110689. mag_memo);
  110690. hf_reduction(&ci->psy_g_param,
  110691. psy_look,
  110692. info,
  110693. mag_memo);
  110694. }
  110695. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  110696. if(psy_look->vi->normal_channel_p){
  110697. for(i=0;i<vi->channels;i++){
  110698. float *mdct =gmdct[i];
  110699. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  110700. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  110701. }
  110702. }
  110703. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  110704. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  110705. k++){
  110706. oggpack_buffer *opb=vbi->packetblob[k];
  110707. /* start out our new packet blob with packet type and mode */
  110708. /* Encode the packet type */
  110709. oggpack_write(opb,0,1);
  110710. /* Encode the modenumber */
  110711. /* Encode frame mode, pre,post windowsize, then dispatch */
  110712. oggpack_write(opb,modenumber,b->modebits);
  110713. if(vb->W){
  110714. oggpack_write(opb,vb->lW,1);
  110715. oggpack_write(opb,vb->nW,1);
  110716. }
  110717. /* encode floor, compute masking curve, sep out residue */
  110718. for(i=0;i<vi->channels;i++){
  110719. int submap=info->chmuxlist[i];
  110720. float *mdct =gmdct[i];
  110721. float *res =vb->pcm[i];
  110722. int *ilogmask=ilogmaskch[i]=
  110723. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  110724. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  110725. floor_posts[i][k],
  110726. ilogmask);
  110727. #if 0
  110728. {
  110729. char buf[80];
  110730. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  110731. float work[n/2];
  110732. for(j=0;j<n/2;j++)
  110733. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  110734. _analysis_output(buf,seq,work,n/2,1,1,0);
  110735. }
  110736. #endif
  110737. _vp_remove_floor(psy_look,
  110738. mdct,
  110739. ilogmask,
  110740. res,
  110741. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  110742. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  110743. #if 0
  110744. {
  110745. char buf[80];
  110746. float work[n/2];
  110747. for(j=0;j<n/2;j++)
  110748. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  110749. sprintf(buf,"resI%c%d",i?'R':'L',k);
  110750. _analysis_output(buf,seq,work,n/2,1,1,0);
  110751. }
  110752. #endif
  110753. }
  110754. /* our iteration is now based on masking curve, not prequant and
  110755. coupling. Only one prequant/coupling step */
  110756. /* quantize/couple */
  110757. /* incomplete implementation that assumes the tree is all depth
  110758. one, or no tree at all */
  110759. if(info->coupling_steps){
  110760. _vp_couple(k,
  110761. &ci->psy_g_param,
  110762. psy_look,
  110763. info,
  110764. vb->pcm,
  110765. mag_memo,
  110766. mag_sort,
  110767. ilogmaskch,
  110768. nonzero,
  110769. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  110770. }
  110771. /* classify and encode by submap */
  110772. for(i=0;i<info->submaps;i++){
  110773. int ch_in_bundle=0;
  110774. long **classifications;
  110775. int resnum=info->residuesubmap[i];
  110776. for(j=0;j<vi->channels;j++){
  110777. if(info->chmuxlist[j]==i){
  110778. zerobundle[ch_in_bundle]=0;
  110779. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  110780. res_bundle[ch_in_bundle]=vb->pcm[j];
  110781. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  110782. }
  110783. }
  110784. classifications=_residue_P[ci->residue_type[resnum]]->
  110785. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  110786. _residue_P[ci->residue_type[resnum]]->
  110787. forward(opb,vb,b->residue[resnum],
  110788. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  110789. }
  110790. /* ok, done encoding. Next protopacket. */
  110791. }
  110792. }
  110793. #if 0
  110794. seq++;
  110795. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  110796. #endif
  110797. return(0);
  110798. }
  110799. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  110800. vorbis_dsp_state *vd=vb->vd;
  110801. vorbis_info *vi=vd->vi;
  110802. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  110803. private_state *b=(private_state*)vd->backend_state;
  110804. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  110805. int i,j;
  110806. long n=vb->pcmend=ci->blocksizes[vb->W];
  110807. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  110808. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  110809. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  110810. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  110811. /* recover the spectral envelope; store it in the PCM vector for now */
  110812. for(i=0;i<vi->channels;i++){
  110813. int submap=info->chmuxlist[i];
  110814. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  110815. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  110816. if(floormemo[i])
  110817. nonzero[i]=1;
  110818. else
  110819. nonzero[i]=0;
  110820. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  110821. }
  110822. /* channel coupling can 'dirty' the nonzero listing */
  110823. for(i=0;i<info->coupling_steps;i++){
  110824. if(nonzero[info->coupling_mag[i]] ||
  110825. nonzero[info->coupling_ang[i]]){
  110826. nonzero[info->coupling_mag[i]]=1;
  110827. nonzero[info->coupling_ang[i]]=1;
  110828. }
  110829. }
  110830. /* recover the residue into our working vectors */
  110831. for(i=0;i<info->submaps;i++){
  110832. int ch_in_bundle=0;
  110833. for(j=0;j<vi->channels;j++){
  110834. if(info->chmuxlist[j]==i){
  110835. if(nonzero[j])
  110836. zerobundle[ch_in_bundle]=1;
  110837. else
  110838. zerobundle[ch_in_bundle]=0;
  110839. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  110840. }
  110841. }
  110842. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  110843. inverse(vb,b->residue[info->residuesubmap[i]],
  110844. pcmbundle,zerobundle,ch_in_bundle);
  110845. }
  110846. /* channel coupling */
  110847. for(i=info->coupling_steps-1;i>=0;i--){
  110848. float *pcmM=vb->pcm[info->coupling_mag[i]];
  110849. float *pcmA=vb->pcm[info->coupling_ang[i]];
  110850. for(j=0;j<n/2;j++){
  110851. float mag=pcmM[j];
  110852. float ang=pcmA[j];
  110853. if(mag>0)
  110854. if(ang>0){
  110855. pcmM[j]=mag;
  110856. pcmA[j]=mag-ang;
  110857. }else{
  110858. pcmA[j]=mag;
  110859. pcmM[j]=mag+ang;
  110860. }
  110861. else
  110862. if(ang>0){
  110863. pcmM[j]=mag;
  110864. pcmA[j]=mag+ang;
  110865. }else{
  110866. pcmA[j]=mag;
  110867. pcmM[j]=mag-ang;
  110868. }
  110869. }
  110870. }
  110871. /* compute and apply spectral envelope */
  110872. for(i=0;i<vi->channels;i++){
  110873. float *pcm=vb->pcm[i];
  110874. int submap=info->chmuxlist[i];
  110875. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  110876. inverse2(vb,b->flr[info->floorsubmap[submap]],
  110877. floormemo[i],pcm);
  110878. }
  110879. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  110880. /* only MDCT right now.... */
  110881. for(i=0;i<vi->channels;i++){
  110882. float *pcm=vb->pcm[i];
  110883. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  110884. }
  110885. /* all done! */
  110886. return(0);
  110887. }
  110888. /* export hooks */
  110889. vorbis_func_mapping mapping0_exportbundle={
  110890. &mapping0_pack,
  110891. &mapping0_unpack,
  110892. &mapping0_free_info,
  110893. &mapping0_forward,
  110894. &mapping0_inverse
  110895. };
  110896. #endif
  110897. /********* End of inlined file: mapping0.c *********/
  110898. /********* Start of inlined file: mdct.c *********/
  110899. /* this can also be run as an integer transform by uncommenting a
  110900. define in mdct.h; the integerization is a first pass and although
  110901. it's likely stable for Vorbis, the dynamic range is constrained and
  110902. roundoff isn't done (so it's noisy). Consider it functional, but
  110903. only a starting point. There's no point on a machine with an FPU */
  110904. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110905. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110906. // tasks..
  110907. #ifdef _MSC_VER
  110908. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110909. #endif
  110910. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110911. #if JUCE_USE_OGGVORBIS
  110912. #include <stdio.h>
  110913. #include <stdlib.h>
  110914. #include <string.h>
  110915. #include <math.h>
  110916. /* build lookups for trig functions; also pre-figure scaling and
  110917. some window function algebra. */
  110918. void mdct_init(mdct_lookup *lookup,int n){
  110919. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  110920. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  110921. int i;
  110922. int n2=n>>1;
  110923. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  110924. lookup->n=n;
  110925. lookup->trig=T;
  110926. lookup->bitrev=bitrev;
  110927. /* trig lookups... */
  110928. for(i=0;i<n/4;i++){
  110929. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  110930. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  110931. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  110932. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  110933. }
  110934. for(i=0;i<n/8;i++){
  110935. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  110936. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  110937. }
  110938. /* bitreverse lookup... */
  110939. {
  110940. int mask=(1<<(log2n-1))-1,i,j;
  110941. int msb=1<<(log2n-2);
  110942. for(i=0;i<n/8;i++){
  110943. int acc=0;
  110944. for(j=0;msb>>j;j++)
  110945. if((msb>>j)&i)acc|=1<<j;
  110946. bitrev[i*2]=((~acc)&mask)-1;
  110947. bitrev[i*2+1]=acc;
  110948. }
  110949. }
  110950. lookup->scale=FLOAT_CONV(4.f/n);
  110951. }
  110952. /* 8 point butterfly (in place, 4 register) */
  110953. STIN void mdct_butterfly_8(DATA_TYPE *x){
  110954. REG_TYPE r0 = x[6] + x[2];
  110955. REG_TYPE r1 = x[6] - x[2];
  110956. REG_TYPE r2 = x[4] + x[0];
  110957. REG_TYPE r3 = x[4] - x[0];
  110958. x[6] = r0 + r2;
  110959. x[4] = r0 - r2;
  110960. r0 = x[5] - x[1];
  110961. r2 = x[7] - x[3];
  110962. x[0] = r1 + r0;
  110963. x[2] = r1 - r0;
  110964. r0 = x[5] + x[1];
  110965. r1 = x[7] + x[3];
  110966. x[3] = r2 + r3;
  110967. x[1] = r2 - r3;
  110968. x[7] = r1 + r0;
  110969. x[5] = r1 - r0;
  110970. }
  110971. /* 16 point butterfly (in place, 4 register) */
  110972. STIN void mdct_butterfly_16(DATA_TYPE *x){
  110973. REG_TYPE r0 = x[1] - x[9];
  110974. REG_TYPE r1 = x[0] - x[8];
  110975. x[8] += x[0];
  110976. x[9] += x[1];
  110977. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  110978. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  110979. r0 = x[3] - x[11];
  110980. r1 = x[10] - x[2];
  110981. x[10] += x[2];
  110982. x[11] += x[3];
  110983. x[2] = r0;
  110984. x[3] = r1;
  110985. r0 = x[12] - x[4];
  110986. r1 = x[13] - x[5];
  110987. x[12] += x[4];
  110988. x[13] += x[5];
  110989. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  110990. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  110991. r0 = x[14] - x[6];
  110992. r1 = x[15] - x[7];
  110993. x[14] += x[6];
  110994. x[15] += x[7];
  110995. x[6] = r0;
  110996. x[7] = r1;
  110997. mdct_butterfly_8(x);
  110998. mdct_butterfly_8(x+8);
  110999. }
  111000. /* 32 point butterfly (in place, 4 register) */
  111001. STIN void mdct_butterfly_32(DATA_TYPE *x){
  111002. REG_TYPE r0 = x[30] - x[14];
  111003. REG_TYPE r1 = x[31] - x[15];
  111004. x[30] += x[14];
  111005. x[31] += x[15];
  111006. x[14] = r0;
  111007. x[15] = r1;
  111008. r0 = x[28] - x[12];
  111009. r1 = x[29] - x[13];
  111010. x[28] += x[12];
  111011. x[29] += x[13];
  111012. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  111013. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  111014. r0 = x[26] - x[10];
  111015. r1 = x[27] - x[11];
  111016. x[26] += x[10];
  111017. x[27] += x[11];
  111018. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  111019. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  111020. r0 = x[24] - x[8];
  111021. r1 = x[25] - x[9];
  111022. x[24] += x[8];
  111023. x[25] += x[9];
  111024. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  111025. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111026. r0 = x[22] - x[6];
  111027. r1 = x[7] - x[23];
  111028. x[22] += x[6];
  111029. x[23] += x[7];
  111030. x[6] = r1;
  111031. x[7] = r0;
  111032. r0 = x[4] - x[20];
  111033. r1 = x[5] - x[21];
  111034. x[20] += x[4];
  111035. x[21] += x[5];
  111036. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  111037. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  111038. r0 = x[2] - x[18];
  111039. r1 = x[3] - x[19];
  111040. x[18] += x[2];
  111041. x[19] += x[3];
  111042. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  111043. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  111044. r0 = x[0] - x[16];
  111045. r1 = x[1] - x[17];
  111046. x[16] += x[0];
  111047. x[17] += x[1];
  111048. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111049. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  111050. mdct_butterfly_16(x);
  111051. mdct_butterfly_16(x+16);
  111052. }
  111053. /* N point first stage butterfly (in place, 2 register) */
  111054. STIN void mdct_butterfly_first(DATA_TYPE *T,
  111055. DATA_TYPE *x,
  111056. int points){
  111057. DATA_TYPE *x1 = x + points - 8;
  111058. DATA_TYPE *x2 = x + (points>>1) - 8;
  111059. REG_TYPE r0;
  111060. REG_TYPE r1;
  111061. do{
  111062. r0 = x1[6] - x2[6];
  111063. r1 = x1[7] - x2[7];
  111064. x1[6] += x2[6];
  111065. x1[7] += x2[7];
  111066. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111067. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111068. r0 = x1[4] - x2[4];
  111069. r1 = x1[5] - x2[5];
  111070. x1[4] += x2[4];
  111071. x1[5] += x2[5];
  111072. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  111073. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  111074. r0 = x1[2] - x2[2];
  111075. r1 = x1[3] - x2[3];
  111076. x1[2] += x2[2];
  111077. x1[3] += x2[3];
  111078. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  111079. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  111080. r0 = x1[0] - x2[0];
  111081. r1 = x1[1] - x2[1];
  111082. x1[0] += x2[0];
  111083. x1[1] += x2[1];
  111084. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  111085. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  111086. x1-=8;
  111087. x2-=8;
  111088. T+=16;
  111089. }while(x2>=x);
  111090. }
  111091. /* N/stage point generic N stage butterfly (in place, 2 register) */
  111092. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  111093. DATA_TYPE *x,
  111094. int points,
  111095. int trigint){
  111096. DATA_TYPE *x1 = x + points - 8;
  111097. DATA_TYPE *x2 = x + (points>>1) - 8;
  111098. REG_TYPE r0;
  111099. REG_TYPE r1;
  111100. do{
  111101. r0 = x1[6] - x2[6];
  111102. r1 = x1[7] - x2[7];
  111103. x1[6] += x2[6];
  111104. x1[7] += x2[7];
  111105. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111106. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111107. T+=trigint;
  111108. r0 = x1[4] - x2[4];
  111109. r1 = x1[5] - x2[5];
  111110. x1[4] += x2[4];
  111111. x1[5] += x2[5];
  111112. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111113. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111114. T+=trigint;
  111115. r0 = x1[2] - x2[2];
  111116. r1 = x1[3] - x2[3];
  111117. x1[2] += x2[2];
  111118. x1[3] += x2[3];
  111119. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111120. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111121. T+=trigint;
  111122. r0 = x1[0] - x2[0];
  111123. r1 = x1[1] - x2[1];
  111124. x1[0] += x2[0];
  111125. x1[1] += x2[1];
  111126. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111127. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111128. T+=trigint;
  111129. x1-=8;
  111130. x2-=8;
  111131. }while(x2>=x);
  111132. }
  111133. STIN void mdct_butterflies(mdct_lookup *init,
  111134. DATA_TYPE *x,
  111135. int points){
  111136. DATA_TYPE *T=init->trig;
  111137. int stages=init->log2n-5;
  111138. int i,j;
  111139. if(--stages>0){
  111140. mdct_butterfly_first(T,x,points);
  111141. }
  111142. for(i=1;--stages>0;i++){
  111143. for(j=0;j<(1<<i);j++)
  111144. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  111145. }
  111146. for(j=0;j<points;j+=32)
  111147. mdct_butterfly_32(x+j);
  111148. }
  111149. void mdct_clear(mdct_lookup *l){
  111150. if(l){
  111151. if(l->trig)_ogg_free(l->trig);
  111152. if(l->bitrev)_ogg_free(l->bitrev);
  111153. memset(l,0,sizeof(*l));
  111154. }
  111155. }
  111156. STIN void mdct_bitreverse(mdct_lookup *init,
  111157. DATA_TYPE *x){
  111158. int n = init->n;
  111159. int *bit = init->bitrev;
  111160. DATA_TYPE *w0 = x;
  111161. DATA_TYPE *w1 = x = w0+(n>>1);
  111162. DATA_TYPE *T = init->trig+n;
  111163. do{
  111164. DATA_TYPE *x0 = x+bit[0];
  111165. DATA_TYPE *x1 = x+bit[1];
  111166. REG_TYPE r0 = x0[1] - x1[1];
  111167. REG_TYPE r1 = x0[0] + x1[0];
  111168. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  111169. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  111170. w1 -= 4;
  111171. r0 = HALVE(x0[1] + x1[1]);
  111172. r1 = HALVE(x0[0] - x1[0]);
  111173. w0[0] = r0 + r2;
  111174. w1[2] = r0 - r2;
  111175. w0[1] = r1 + r3;
  111176. w1[3] = r3 - r1;
  111177. x0 = x+bit[2];
  111178. x1 = x+bit[3];
  111179. r0 = x0[1] - x1[1];
  111180. r1 = x0[0] + x1[0];
  111181. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  111182. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  111183. r0 = HALVE(x0[1] + x1[1]);
  111184. r1 = HALVE(x0[0] - x1[0]);
  111185. w0[2] = r0 + r2;
  111186. w1[0] = r0 - r2;
  111187. w0[3] = r1 + r3;
  111188. w1[1] = r3 - r1;
  111189. T += 4;
  111190. bit += 4;
  111191. w0 += 4;
  111192. }while(w0<w1);
  111193. }
  111194. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111195. int n=init->n;
  111196. int n2=n>>1;
  111197. int n4=n>>2;
  111198. /* rotate */
  111199. DATA_TYPE *iX = in+n2-7;
  111200. DATA_TYPE *oX = out+n2+n4;
  111201. DATA_TYPE *T = init->trig+n4;
  111202. do{
  111203. oX -= 4;
  111204. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  111205. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  111206. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  111207. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  111208. iX -= 8;
  111209. T += 4;
  111210. }while(iX>=in);
  111211. iX = in+n2-8;
  111212. oX = out+n2+n4;
  111213. T = init->trig+n4;
  111214. do{
  111215. T -= 4;
  111216. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  111217. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  111218. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  111219. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  111220. iX -= 8;
  111221. oX += 4;
  111222. }while(iX>=in);
  111223. mdct_butterflies(init,out+n2,n2);
  111224. mdct_bitreverse(init,out);
  111225. /* roatate + window */
  111226. {
  111227. DATA_TYPE *oX1=out+n2+n4;
  111228. DATA_TYPE *oX2=out+n2+n4;
  111229. DATA_TYPE *iX =out;
  111230. T =init->trig+n2;
  111231. do{
  111232. oX1-=4;
  111233. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  111234. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  111235. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  111236. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  111237. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  111238. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  111239. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  111240. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  111241. oX2+=4;
  111242. iX += 8;
  111243. T += 8;
  111244. }while(iX<oX1);
  111245. iX=out+n2+n4;
  111246. oX1=out+n4;
  111247. oX2=oX1;
  111248. do{
  111249. oX1-=4;
  111250. iX-=4;
  111251. oX2[0] = -(oX1[3] = iX[3]);
  111252. oX2[1] = -(oX1[2] = iX[2]);
  111253. oX2[2] = -(oX1[1] = iX[1]);
  111254. oX2[3] = -(oX1[0] = iX[0]);
  111255. oX2+=4;
  111256. }while(oX2<iX);
  111257. iX=out+n2+n4;
  111258. oX1=out+n2+n4;
  111259. oX2=out+n2;
  111260. do{
  111261. oX1-=4;
  111262. oX1[0]= iX[3];
  111263. oX1[1]= iX[2];
  111264. oX1[2]= iX[1];
  111265. oX1[3]= iX[0];
  111266. iX+=4;
  111267. }while(oX1>oX2);
  111268. }
  111269. }
  111270. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111271. int n=init->n;
  111272. int n2=n>>1;
  111273. int n4=n>>2;
  111274. int n8=n>>3;
  111275. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  111276. DATA_TYPE *w2=w+n2;
  111277. /* rotate */
  111278. /* window + rotate + step 1 */
  111279. REG_TYPE r0;
  111280. REG_TYPE r1;
  111281. DATA_TYPE *x0=in+n2+n4;
  111282. DATA_TYPE *x1=x0+1;
  111283. DATA_TYPE *T=init->trig+n2;
  111284. int i=0;
  111285. for(i=0;i<n8;i+=2){
  111286. x0 -=4;
  111287. T-=2;
  111288. r0= x0[2] + x1[0];
  111289. r1= x0[0] + x1[2];
  111290. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111291. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111292. x1 +=4;
  111293. }
  111294. x1=in+1;
  111295. for(;i<n2-n8;i+=2){
  111296. T-=2;
  111297. x0 -=4;
  111298. r0= x0[2] - x1[0];
  111299. r1= x0[0] - x1[2];
  111300. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111301. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111302. x1 +=4;
  111303. }
  111304. x0=in+n;
  111305. for(;i<n2;i+=2){
  111306. T-=2;
  111307. x0 -=4;
  111308. r0= -x0[2] - x1[0];
  111309. r1= -x0[0] - x1[2];
  111310. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111311. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111312. x1 +=4;
  111313. }
  111314. mdct_butterflies(init,w+n2,n2);
  111315. mdct_bitreverse(init,w);
  111316. /* roatate + window */
  111317. T=init->trig+n2;
  111318. x0=out+n2;
  111319. for(i=0;i<n4;i++){
  111320. x0--;
  111321. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  111322. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  111323. w+=2;
  111324. T+=2;
  111325. }
  111326. }
  111327. #endif
  111328. /********* End of inlined file: mdct.c *********/
  111329. /********* Start of inlined file: psy.c *********/
  111330. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111331. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111332. // tasks..
  111333. #ifdef _MSC_VER
  111334. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111335. #endif
  111336. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111337. #if JUCE_USE_OGGVORBIS
  111338. #include <stdlib.h>
  111339. #include <math.h>
  111340. #include <string.h>
  111341. /********* Start of inlined file: masking.h *********/
  111342. #ifndef _V_MASKING_H_
  111343. #define _V_MASKING_H_
  111344. /* more detailed ATH; the bass if flat to save stressing the floor
  111345. overly for only a bin or two of savings. */
  111346. #define MAX_ATH 88
  111347. static float ATH[]={
  111348. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  111349. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  111350. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  111351. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  111352. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  111353. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  111354. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  111355. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  111356. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  111357. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  111358. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  111359. };
  111360. /* The tone masking curves from Ehmer's and Fielder's papers have been
  111361. replaced by an empirically collected data set. The previously
  111362. published values were, far too often, simply on crack. */
  111363. #define EHMER_OFFSET 16
  111364. #define EHMER_MAX 56
  111365. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  111366. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  111367. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  111368. for collection of these curves) */
  111369. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  111370. /* 62.5 Hz */
  111371. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  111372. -60, -60, -60, -60, -62, -62, -65, -73,
  111373. -69, -68, -68, -67, -70, -70, -72, -74,
  111374. -75, -79, -79, -80, -83, -88, -93, -100,
  111375. -110, -999, -999, -999, -999, -999, -999, -999,
  111376. -999, -999, -999, -999, -999, -999, -999, -999,
  111377. -999, -999, -999, -999, -999, -999, -999, -999},
  111378. { -48, -48, -48, -48, -48, -48, -48, -48,
  111379. -48, -48, -48, -48, -48, -53, -61, -66,
  111380. -66, -68, -67, -70, -76, -76, -72, -73,
  111381. -75, -76, -78, -79, -83, -88, -93, -100,
  111382. -110, -999, -999, -999, -999, -999, -999, -999,
  111383. -999, -999, -999, -999, -999, -999, -999, -999,
  111384. -999, -999, -999, -999, -999, -999, -999, -999},
  111385. { -37, -37, -37, -37, -37, -37, -37, -37,
  111386. -38, -40, -42, -46, -48, -53, -55, -62,
  111387. -65, -58, -56, -56, -61, -60, -65, -67,
  111388. -69, -71, -77, -77, -78, -80, -82, -84,
  111389. -88, -93, -98, -106, -112, -999, -999, -999,
  111390. -999, -999, -999, -999, -999, -999, -999, -999,
  111391. -999, -999, -999, -999, -999, -999, -999, -999},
  111392. { -25, -25, -25, -25, -25, -25, -25, -25,
  111393. -25, -26, -27, -29, -32, -38, -48, -52,
  111394. -52, -50, -48, -48, -51, -52, -54, -60,
  111395. -67, -67, -66, -68, -69, -73, -73, -76,
  111396. -80, -81, -81, -85, -85, -86, -88, -93,
  111397. -100, -110, -999, -999, -999, -999, -999, -999,
  111398. -999, -999, -999, -999, -999, -999, -999, -999},
  111399. { -16, -16, -16, -16, -16, -16, -16, -16,
  111400. -17, -19, -20, -22, -26, -28, -31, -40,
  111401. -47, -39, -39, -40, -42, -43, -47, -51,
  111402. -57, -52, -55, -55, -60, -58, -62, -63,
  111403. -70, -67, -69, -72, -73, -77, -80, -82,
  111404. -83, -87, -90, -94, -98, -104, -115, -999,
  111405. -999, -999, -999, -999, -999, -999, -999, -999},
  111406. { -8, -8, -8, -8, -8, -8, -8, -8,
  111407. -8, -8, -10, -11, -15, -19, -25, -30,
  111408. -34, -31, -30, -31, -29, -32, -35, -42,
  111409. -48, -42, -44, -46, -50, -50, -51, -52,
  111410. -59, -54, -55, -55, -58, -62, -63, -66,
  111411. -72, -73, -76, -75, -78, -80, -80, -81,
  111412. -84, -88, -90, -94, -98, -101, -106, -110}},
  111413. /* 88Hz */
  111414. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  111415. -66, -66, -66, -66, -66, -67, -67, -67,
  111416. -76, -72, -71, -74, -76, -76, -75, -78,
  111417. -79, -79, -81, -83, -86, -89, -93, -97,
  111418. -100, -105, -110, -999, -999, -999, -999, -999,
  111419. -999, -999, -999, -999, -999, -999, -999, -999,
  111420. -999, -999, -999, -999, -999, -999, -999, -999},
  111421. { -47, -47, -47, -47, -47, -47, -47, -47,
  111422. -47, -47, -47, -48, -51, -55, -59, -66,
  111423. -66, -66, -67, -66, -68, -69, -70, -74,
  111424. -79, -77, -77, -78, -80, -81, -82, -84,
  111425. -86, -88, -91, -95, -100, -108, -116, -999,
  111426. -999, -999, -999, -999, -999, -999, -999, -999,
  111427. -999, -999, -999, -999, -999, -999, -999, -999},
  111428. { -36, -36, -36, -36, -36, -36, -36, -36,
  111429. -36, -37, -37, -41, -44, -48, -51, -58,
  111430. -62, -60, -57, -59, -59, -60, -63, -65,
  111431. -72, -71, -70, -72, -74, -77, -76, -78,
  111432. -81, -81, -80, -83, -86, -91, -96, -100,
  111433. -105, -110, -999, -999, -999, -999, -999, -999,
  111434. -999, -999, -999, -999, -999, -999, -999, -999},
  111435. { -28, -28, -28, -28, -28, -28, -28, -28,
  111436. -28, -30, -32, -32, -33, -35, -41, -49,
  111437. -50, -49, -47, -48, -48, -52, -51, -57,
  111438. -65, -61, -59, -61, -64, -69, -70, -74,
  111439. -77, -77, -78, -81, -84, -85, -87, -90,
  111440. -92, -96, -100, -107, -112, -999, -999, -999,
  111441. -999, -999, -999, -999, -999, -999, -999, -999},
  111442. { -19, -19, -19, -19, -19, -19, -19, -19,
  111443. -20, -21, -23, -27, -30, -35, -36, -41,
  111444. -46, -44, -42, -40, -41, -41, -43, -48,
  111445. -55, -53, -52, -53, -56, -59, -58, -60,
  111446. -67, -66, -69, -71, -72, -75, -79, -81,
  111447. -84, -87, -90, -93, -97, -101, -107, -114,
  111448. -999, -999, -999, -999, -999, -999, -999, -999},
  111449. { -9, -9, -9, -9, -9, -9, -9, -9,
  111450. -11, -12, -12, -15, -16, -20, -23, -30,
  111451. -37, -34, -33, -34, -31, -32, -32, -38,
  111452. -47, -44, -41, -40, -47, -49, -46, -46,
  111453. -58, -50, -50, -54, -58, -62, -64, -67,
  111454. -67, -70, -72, -76, -79, -83, -87, -91,
  111455. -96, -100, -104, -110, -999, -999, -999, -999}},
  111456. /* 125 Hz */
  111457. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  111458. -62, -62, -63, -64, -66, -67, -66, -68,
  111459. -75, -72, -76, -75, -76, -78, -79, -82,
  111460. -84, -85, -90, -94, -101, -110, -999, -999,
  111461. -999, -999, -999, -999, -999, -999, -999, -999,
  111462. -999, -999, -999, -999, -999, -999, -999, -999,
  111463. -999, -999, -999, -999, -999, -999, -999, -999},
  111464. { -59, -59, -59, -59, -59, -59, -59, -59,
  111465. -59, -59, -59, -60, -60, -61, -63, -66,
  111466. -71, -68, -70, -70, -71, -72, -72, -75,
  111467. -81, -78, -79, -82, -83, -86, -90, -97,
  111468. -103, -113, -999, -999, -999, -999, -999, -999,
  111469. -999, -999, -999, -999, -999, -999, -999, -999,
  111470. -999, -999, -999, -999, -999, -999, -999, -999},
  111471. { -53, -53, -53, -53, -53, -53, -53, -53,
  111472. -53, -54, -55, -57, -56, -57, -55, -61,
  111473. -65, -60, -60, -62, -63, -63, -66, -68,
  111474. -74, -73, -75, -75, -78, -80, -80, -82,
  111475. -85, -90, -96, -101, -108, -999, -999, -999,
  111476. -999, -999, -999, -999, -999, -999, -999, -999,
  111477. -999, -999, -999, -999, -999, -999, -999, -999},
  111478. { -46, -46, -46, -46, -46, -46, -46, -46,
  111479. -46, -46, -47, -47, -47, -47, -48, -51,
  111480. -57, -51, -49, -50, -51, -53, -54, -59,
  111481. -66, -60, -62, -67, -67, -70, -72, -75,
  111482. -76, -78, -81, -85, -88, -94, -97, -104,
  111483. -112, -999, -999, -999, -999, -999, -999, -999,
  111484. -999, -999, -999, -999, -999, -999, -999, -999},
  111485. { -36, -36, -36, -36, -36, -36, -36, -36,
  111486. -39, -41, -42, -42, -39, -38, -41, -43,
  111487. -52, -44, -40, -39, -37, -37, -40, -47,
  111488. -54, -50, -48, -50, -55, -61, -59, -62,
  111489. -66, -66, -66, -69, -69, -73, -74, -74,
  111490. -75, -77, -79, -82, -87, -91, -95, -100,
  111491. -108, -115, -999, -999, -999, -999, -999, -999},
  111492. { -28, -26, -24, -22, -20, -20, -23, -29,
  111493. -30, -31, -28, -27, -28, -28, -28, -35,
  111494. -40, -33, -32, -29, -30, -30, -30, -37,
  111495. -45, -41, -37, -38, -45, -47, -47, -48,
  111496. -53, -49, -48, -50, -49, -49, -51, -52,
  111497. -58, -56, -57, -56, -60, -61, -62, -70,
  111498. -72, -74, -78, -83, -88, -93, -100, -106}},
  111499. /* 177 Hz */
  111500. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111501. -999, -110, -105, -100, -95, -91, -87, -83,
  111502. -80, -78, -76, -78, -78, -81, -83, -85,
  111503. -86, -85, -86, -87, -90, -97, -107, -999,
  111504. -999, -999, -999, -999, -999, -999, -999, -999,
  111505. -999, -999, -999, -999, -999, -999, -999, -999,
  111506. -999, -999, -999, -999, -999, -999, -999, -999},
  111507. {-999, -999, -999, -110, -105, -100, -95, -90,
  111508. -85, -81, -77, -73, -70, -67, -67, -68,
  111509. -75, -73, -70, -69, -70, -72, -75, -79,
  111510. -84, -83, -84, -86, -88, -89, -89, -93,
  111511. -98, -105, -112, -999, -999, -999, -999, -999,
  111512. -999, -999, -999, -999, -999, -999, -999, -999,
  111513. -999, -999, -999, -999, -999, -999, -999, -999},
  111514. {-105, -100, -95, -90, -85, -80, -76, -71,
  111515. -68, -68, -65, -63, -63, -62, -62, -64,
  111516. -65, -64, -61, -62, -63, -64, -66, -68,
  111517. -73, -73, -74, -75, -76, -81, -83, -85,
  111518. -88, -89, -92, -95, -100, -108, -999, -999,
  111519. -999, -999, -999, -999, -999, -999, -999, -999,
  111520. -999, -999, -999, -999, -999, -999, -999, -999},
  111521. { -80, -75, -71, -68, -65, -63, -62, -61,
  111522. -61, -61, -61, -59, -56, -57, -53, -50,
  111523. -58, -52, -50, -50, -52, -53, -54, -58,
  111524. -67, -63, -67, -68, -72, -75, -78, -80,
  111525. -81, -81, -82, -85, -89, -90, -93, -97,
  111526. -101, -107, -114, -999, -999, -999, -999, -999,
  111527. -999, -999, -999, -999, -999, -999, -999, -999},
  111528. { -65, -61, -59, -57, -56, -55, -55, -56,
  111529. -56, -57, -55, -53, -52, -47, -44, -44,
  111530. -50, -44, -41, -39, -39, -42, -40, -46,
  111531. -51, -49, -50, -53, -54, -63, -60, -61,
  111532. -62, -66, -66, -66, -70, -73, -74, -75,
  111533. -76, -75, -79, -85, -89, -91, -96, -102,
  111534. -110, -999, -999, -999, -999, -999, -999, -999},
  111535. { -52, -50, -49, -49, -48, -48, -48, -49,
  111536. -50, -50, -49, -46, -43, -39, -35, -33,
  111537. -38, -36, -32, -29, -32, -32, -32, -35,
  111538. -44, -39, -38, -38, -46, -50, -45, -46,
  111539. -53, -50, -50, -50, -54, -54, -53, -53,
  111540. -56, -57, -59, -66, -70, -72, -74, -79,
  111541. -83, -85, -90, -97, -114, -999, -999, -999}},
  111542. /* 250 Hz */
  111543. {{-999, -999, -999, -999, -999, -999, -110, -105,
  111544. -100, -95, -90, -86, -80, -75, -75, -79,
  111545. -80, -79, -80, -81, -82, -88, -95, -103,
  111546. -110, -999, -999, -999, -999, -999, -999, -999,
  111547. -999, -999, -999, -999, -999, -999, -999, -999,
  111548. -999, -999, -999, -999, -999, -999, -999, -999,
  111549. -999, -999, -999, -999, -999, -999, -999, -999},
  111550. {-999, -999, -999, -999, -108, -103, -98, -93,
  111551. -88, -83, -79, -78, -75, -71, -67, -68,
  111552. -73, -73, -72, -73, -75, -77, -80, -82,
  111553. -88, -93, -100, -107, -114, -999, -999, -999,
  111554. -999, -999, -999, -999, -999, -999, -999, -999,
  111555. -999, -999, -999, -999, -999, -999, -999, -999,
  111556. -999, -999, -999, -999, -999, -999, -999, -999},
  111557. {-999, -999, -999, -110, -105, -101, -96, -90,
  111558. -86, -81, -77, -73, -69, -66, -61, -62,
  111559. -66, -64, -62, -65, -66, -70, -72, -76,
  111560. -81, -80, -84, -90, -95, -102, -110, -999,
  111561. -999, -999, -999, -999, -999, -999, -999, -999,
  111562. -999, -999, -999, -999, -999, -999, -999, -999,
  111563. -999, -999, -999, -999, -999, -999, -999, -999},
  111564. {-999, -999, -999, -107, -103, -97, -92, -88,
  111565. -83, -79, -74, -70, -66, -59, -53, -58,
  111566. -62, -55, -54, -54, -54, -58, -61, -62,
  111567. -72, -70, -72, -75, -78, -80, -81, -80,
  111568. -83, -83, -88, -93, -100, -107, -115, -999,
  111569. -999, -999, -999, -999, -999, -999, -999, -999,
  111570. -999, -999, -999, -999, -999, -999, -999, -999},
  111571. {-999, -999, -999, -105, -100, -95, -90, -85,
  111572. -80, -75, -70, -66, -62, -56, -48, -44,
  111573. -48, -46, -46, -43, -46, -48, -48, -51,
  111574. -58, -58, -59, -60, -62, -62, -61, -61,
  111575. -65, -64, -65, -68, -70, -74, -75, -78,
  111576. -81, -86, -95, -110, -999, -999, -999, -999,
  111577. -999, -999, -999, -999, -999, -999, -999, -999},
  111578. {-999, -999, -105, -100, -95, -90, -85, -80,
  111579. -75, -70, -65, -61, -55, -49, -39, -33,
  111580. -40, -35, -32, -38, -40, -33, -35, -37,
  111581. -46, -41, -45, -44, -46, -42, -45, -46,
  111582. -52, -50, -50, -50, -54, -54, -55, -57,
  111583. -62, -64, -66, -68, -70, -76, -81, -90,
  111584. -100, -110, -999, -999, -999, -999, -999, -999}},
  111585. /* 354 hz */
  111586. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111587. -105, -98, -90, -85, -82, -83, -80, -78,
  111588. -84, -79, -80, -83, -87, -89, -91, -93,
  111589. -99, -106, -117, -999, -999, -999, -999, -999,
  111590. -999, -999, -999, -999, -999, -999, -999, -999,
  111591. -999, -999, -999, -999, -999, -999, -999, -999,
  111592. -999, -999, -999, -999, -999, -999, -999, -999},
  111593. {-999, -999, -999, -999, -999, -999, -999, -999,
  111594. -105, -98, -90, -85, -80, -75, -70, -68,
  111595. -74, -72, -74, -77, -80, -82, -85, -87,
  111596. -92, -89, -91, -95, -100, -106, -112, -999,
  111597. -999, -999, -999, -999, -999, -999, -999, -999,
  111598. -999, -999, -999, -999, -999, -999, -999, -999,
  111599. -999, -999, -999, -999, -999, -999, -999, -999},
  111600. {-999, -999, -999, -999, -999, -999, -999, -999,
  111601. -105, -98, -90, -83, -75, -71, -63, -64,
  111602. -67, -62, -64, -67, -70, -73, -77, -81,
  111603. -84, -83, -85, -89, -90, -93, -98, -104,
  111604. -109, -114, -999, -999, -999, -999, -999, -999,
  111605. -999, -999, -999, -999, -999, -999, -999, -999,
  111606. -999, -999, -999, -999, -999, -999, -999, -999},
  111607. {-999, -999, -999, -999, -999, -999, -999, -999,
  111608. -103, -96, -88, -81, -75, -68, -58, -54,
  111609. -56, -54, -56, -56, -58, -60, -63, -66,
  111610. -74, -69, -72, -72, -75, -74, -77, -81,
  111611. -81, -82, -84, -87, -93, -96, -99, -104,
  111612. -110, -999, -999, -999, -999, -999, -999, -999,
  111613. -999, -999, -999, -999, -999, -999, -999, -999},
  111614. {-999, -999, -999, -999, -999, -108, -102, -96,
  111615. -91, -85, -80, -74, -68, -60, -51, -46,
  111616. -48, -46, -43, -45, -47, -47, -49, -48,
  111617. -56, -53, -55, -58, -57, -63, -58, -60,
  111618. -66, -64, -67, -70, -70, -74, -77, -84,
  111619. -86, -89, -91, -93, -94, -101, -109, -118,
  111620. -999, -999, -999, -999, -999, -999, -999, -999},
  111621. {-999, -999, -999, -108, -103, -98, -93, -88,
  111622. -83, -78, -73, -68, -60, -53, -44, -35,
  111623. -38, -38, -34, -34, -36, -40, -41, -44,
  111624. -51, -45, -46, -47, -46, -54, -50, -49,
  111625. -50, -50, -50, -51, -54, -57, -58, -60,
  111626. -66, -66, -66, -64, -65, -68, -77, -82,
  111627. -87, -95, -110, -999, -999, -999, -999, -999}},
  111628. /* 500 Hz */
  111629. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111630. -107, -102, -97, -92, -87, -83, -78, -75,
  111631. -82, -79, -83, -85, -89, -92, -95, -98,
  111632. -101, -105, -109, -113, -999, -999, -999, -999,
  111633. -999, -999, -999, -999, -999, -999, -999, -999,
  111634. -999, -999, -999, -999, -999, -999, -999, -999,
  111635. -999, -999, -999, -999, -999, -999, -999, -999},
  111636. {-999, -999, -999, -999, -999, -999, -999, -106,
  111637. -100, -95, -90, -86, -81, -78, -74, -69,
  111638. -74, -74, -76, -79, -83, -84, -86, -89,
  111639. -92, -97, -93, -100, -103, -107, -110, -999,
  111640. -999, -999, -999, -999, -999, -999, -999, -999,
  111641. -999, -999, -999, -999, -999, -999, -999, -999,
  111642. -999, -999, -999, -999, -999, -999, -999, -999},
  111643. {-999, -999, -999, -999, -999, -999, -106, -100,
  111644. -95, -90, -87, -83, -80, -75, -69, -60,
  111645. -66, -66, -68, -70, -74, -78, -79, -81,
  111646. -81, -83, -84, -87, -93, -96, -99, -103,
  111647. -107, -110, -999, -999, -999, -999, -999, -999,
  111648. -999, -999, -999, -999, -999, -999, -999, -999,
  111649. -999, -999, -999, -999, -999, -999, -999, -999},
  111650. {-999, -999, -999, -999, -999, -108, -103, -98,
  111651. -93, -89, -85, -82, -78, -71, -62, -55,
  111652. -58, -58, -54, -54, -55, -59, -61, -62,
  111653. -70, -66, -66, -67, -70, -72, -75, -78,
  111654. -84, -84, -84, -88, -91, -90, -95, -98,
  111655. -102, -103, -106, -110, -999, -999, -999, -999,
  111656. -999, -999, -999, -999, -999, -999, -999, -999},
  111657. {-999, -999, -999, -999, -108, -103, -98, -94,
  111658. -90, -87, -82, -79, -73, -67, -58, -47,
  111659. -50, -45, -41, -45, -48, -44, -44, -49,
  111660. -54, -51, -48, -47, -49, -50, -51, -57,
  111661. -58, -60, -63, -69, -70, -69, -71, -74,
  111662. -78, -82, -90, -95, -101, -105, -110, -999,
  111663. -999, -999, -999, -999, -999, -999, -999, -999},
  111664. {-999, -999, -999, -105, -101, -97, -93, -90,
  111665. -85, -80, -77, -72, -65, -56, -48, -37,
  111666. -40, -36, -34, -40, -50, -47, -38, -41,
  111667. -47, -38, -35, -39, -38, -43, -40, -45,
  111668. -50, -45, -44, -47, -50, -55, -48, -48,
  111669. -52, -66, -70, -76, -82, -90, -97, -105,
  111670. -110, -999, -999, -999, -999, -999, -999, -999}},
  111671. /* 707 Hz */
  111672. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111673. -999, -108, -103, -98, -93, -86, -79, -76,
  111674. -83, -81, -85, -87, -89, -93, -98, -102,
  111675. -107, -112, -999, -999, -999, -999, -999, -999,
  111676. -999, -999, -999, -999, -999, -999, -999, -999,
  111677. -999, -999, -999, -999, -999, -999, -999, -999,
  111678. -999, -999, -999, -999, -999, -999, -999, -999},
  111679. {-999, -999, -999, -999, -999, -999, -999, -999,
  111680. -999, -108, -103, -98, -93, -86, -79, -71,
  111681. -77, -74, -77, -79, -81, -84, -85, -90,
  111682. -92, -93, -92, -98, -101, -108, -112, -999,
  111683. -999, -999, -999, -999, -999, -999, -999, -999,
  111684. -999, -999, -999, -999, -999, -999, -999, -999,
  111685. -999, -999, -999, -999, -999, -999, -999, -999},
  111686. {-999, -999, -999, -999, -999, -999, -999, -999,
  111687. -108, -103, -98, -93, -87, -78, -68, -65,
  111688. -66, -62, -65, -67, -70, -73, -75, -78,
  111689. -82, -82, -83, -84, -91, -93, -98, -102,
  111690. -106, -110, -999, -999, -999, -999, -999, -999,
  111691. -999, -999, -999, -999, -999, -999, -999, -999,
  111692. -999, -999, -999, -999, -999, -999, -999, -999},
  111693. {-999, -999, -999, -999, -999, -999, -999, -999,
  111694. -105, -100, -95, -90, -82, -74, -62, -57,
  111695. -58, -56, -51, -52, -52, -54, -54, -58,
  111696. -66, -59, -60, -63, -66, -69, -73, -79,
  111697. -83, -84, -80, -81, -81, -82, -88, -92,
  111698. -98, -105, -113, -999, -999, -999, -999, -999,
  111699. -999, -999, -999, -999, -999, -999, -999, -999},
  111700. {-999, -999, -999, -999, -999, -999, -999, -107,
  111701. -102, -97, -92, -84, -79, -69, -57, -47,
  111702. -52, -47, -44, -45, -50, -52, -42, -42,
  111703. -53, -43, -43, -48, -51, -56, -55, -52,
  111704. -57, -59, -61, -62, -67, -71, -78, -83,
  111705. -86, -94, -98, -103, -110, -999, -999, -999,
  111706. -999, -999, -999, -999, -999, -999, -999, -999},
  111707. {-999, -999, -999, -999, -999, -999, -105, -100,
  111708. -95, -90, -84, -78, -70, -61, -51, -41,
  111709. -40, -38, -40, -46, -52, -51, -41, -40,
  111710. -46, -40, -38, -38, -41, -46, -41, -46,
  111711. -47, -43, -43, -45, -41, -45, -56, -67,
  111712. -68, -83, -87, -90, -95, -102, -107, -113,
  111713. -999, -999, -999, -999, -999, -999, -999, -999}},
  111714. /* 1000 Hz */
  111715. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111716. -999, -109, -105, -101, -96, -91, -84, -77,
  111717. -82, -82, -85, -89, -94, -100, -106, -110,
  111718. -999, -999, -999, -999, -999, -999, -999, -999,
  111719. -999, -999, -999, -999, -999, -999, -999, -999,
  111720. -999, -999, -999, -999, -999, -999, -999, -999,
  111721. -999, -999, -999, -999, -999, -999, -999, -999},
  111722. {-999, -999, -999, -999, -999, -999, -999, -999,
  111723. -999, -106, -103, -98, -92, -85, -80, -71,
  111724. -75, -72, -76, -80, -84, -86, -89, -93,
  111725. -100, -107, -113, -999, -999, -999, -999, -999,
  111726. -999, -999, -999, -999, -999, -999, -999, -999,
  111727. -999, -999, -999, -999, -999, -999, -999, -999,
  111728. -999, -999, -999, -999, -999, -999, -999, -999},
  111729. {-999, -999, -999, -999, -999, -999, -999, -107,
  111730. -104, -101, -97, -92, -88, -84, -80, -64,
  111731. -66, -63, -64, -66, -69, -73, -77, -83,
  111732. -83, -86, -91, -98, -104, -111, -999, -999,
  111733. -999, -999, -999, -999, -999, -999, -999, -999,
  111734. -999, -999, -999, -999, -999, -999, -999, -999,
  111735. -999, -999, -999, -999, -999, -999, -999, -999},
  111736. {-999, -999, -999, -999, -999, -999, -999, -107,
  111737. -104, -101, -97, -92, -90, -84, -74, -57,
  111738. -58, -52, -55, -54, -50, -52, -50, -52,
  111739. -63, -62, -69, -76, -77, -78, -78, -79,
  111740. -82, -88, -94, -100, -106, -111, -999, -999,
  111741. -999, -999, -999, -999, -999, -999, -999, -999,
  111742. -999, -999, -999, -999, -999, -999, -999, -999},
  111743. {-999, -999, -999, -999, -999, -999, -106, -102,
  111744. -98, -95, -90, -85, -83, -78, -70, -50,
  111745. -50, -41, -44, -49, -47, -50, -50, -44,
  111746. -55, -46, -47, -48, -48, -54, -49, -49,
  111747. -58, -62, -71, -81, -87, -92, -97, -102,
  111748. -108, -114, -999, -999, -999, -999, -999, -999,
  111749. -999, -999, -999, -999, -999, -999, -999, -999},
  111750. {-999, -999, -999, -999, -999, -999, -106, -102,
  111751. -98, -95, -90, -85, -83, -78, -70, -45,
  111752. -43, -41, -47, -50, -51, -50, -49, -45,
  111753. -47, -41, -44, -41, -39, -43, -38, -37,
  111754. -40, -41, -44, -50, -58, -65, -73, -79,
  111755. -85, -92, -97, -101, -105, -109, -113, -999,
  111756. -999, -999, -999, -999, -999, -999, -999, -999}},
  111757. /* 1414 Hz */
  111758. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111759. -999, -999, -999, -107, -100, -95, -87, -81,
  111760. -85, -83, -88, -93, -100, -107, -114, -999,
  111761. -999, -999, -999, -999, -999, -999, -999, -999,
  111762. -999, -999, -999, -999, -999, -999, -999, -999,
  111763. -999, -999, -999, -999, -999, -999, -999, -999,
  111764. -999, -999, -999, -999, -999, -999, -999, -999},
  111765. {-999, -999, -999, -999, -999, -999, -999, -999,
  111766. -999, -999, -107, -101, -95, -88, -83, -76,
  111767. -73, -72, -79, -84, -90, -95, -100, -105,
  111768. -110, -115, -999, -999, -999, -999, -999, -999,
  111769. -999, -999, -999, -999, -999, -999, -999, -999,
  111770. -999, -999, -999, -999, -999, -999, -999, -999,
  111771. -999, -999, -999, -999, -999, -999, -999, -999},
  111772. {-999, -999, -999, -999, -999, -999, -999, -999,
  111773. -999, -999, -104, -98, -92, -87, -81, -70,
  111774. -65, -62, -67, -71, -74, -80, -85, -91,
  111775. -95, -99, -103, -108, -111, -114, -999, -999,
  111776. -999, -999, -999, -999, -999, -999, -999, -999,
  111777. -999, -999, -999, -999, -999, -999, -999, -999,
  111778. -999, -999, -999, -999, -999, -999, -999, -999},
  111779. {-999, -999, -999, -999, -999, -999, -999, -999,
  111780. -999, -999, -103, -97, -90, -85, -76, -60,
  111781. -56, -54, -60, -62, -61, -56, -63, -65,
  111782. -73, -74, -77, -75, -78, -81, -86, -87,
  111783. -88, -91, -94, -98, -103, -110, -999, -999,
  111784. -999, -999, -999, -999, -999, -999, -999, -999,
  111785. -999, -999, -999, -999, -999, -999, -999, -999},
  111786. {-999, -999, -999, -999, -999, -999, -999, -105,
  111787. -100, -97, -92, -86, -81, -79, -70, -57,
  111788. -51, -47, -51, -58, -60, -56, -53, -50,
  111789. -58, -52, -50, -50, -53, -55, -64, -69,
  111790. -71, -85, -82, -78, -81, -85, -95, -102,
  111791. -112, -999, -999, -999, -999, -999, -999, -999,
  111792. -999, -999, -999, -999, -999, -999, -999, -999},
  111793. {-999, -999, -999, -999, -999, -999, -999, -105,
  111794. -100, -97, -92, -85, -83, -79, -72, -49,
  111795. -40, -43, -43, -54, -56, -51, -50, -40,
  111796. -43, -38, -36, -35, -37, -38, -37, -44,
  111797. -54, -60, -57, -60, -70, -75, -84, -92,
  111798. -103, -112, -999, -999, -999, -999, -999, -999,
  111799. -999, -999, -999, -999, -999, -999, -999, -999}},
  111800. /* 2000 Hz */
  111801. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111802. -999, -999, -999, -110, -102, -95, -89, -82,
  111803. -83, -84, -90, -92, -99, -107, -113, -999,
  111804. -999, -999, -999, -999, -999, -999, -999, -999,
  111805. -999, -999, -999, -999, -999, -999, -999, -999,
  111806. -999, -999, -999, -999, -999, -999, -999, -999,
  111807. -999, -999, -999, -999, -999, -999, -999, -999},
  111808. {-999, -999, -999, -999, -999, -999, -999, -999,
  111809. -999, -999, -107, -101, -95, -89, -83, -72,
  111810. -74, -78, -85, -88, -88, -90, -92, -98,
  111811. -105, -111, -999, -999, -999, -999, -999, -999,
  111812. -999, -999, -999, -999, -999, -999, -999, -999,
  111813. -999, -999, -999, -999, -999, -999, -999, -999,
  111814. -999, -999, -999, -999, -999, -999, -999, -999},
  111815. {-999, -999, -999, -999, -999, -999, -999, -999,
  111816. -999, -109, -103, -97, -93, -87, -81, -70,
  111817. -70, -67, -75, -73, -76, -79, -81, -83,
  111818. -88, -89, -97, -103, -110, -999, -999, -999,
  111819. -999, -999, -999, -999, -999, -999, -999, -999,
  111820. -999, -999, -999, -999, -999, -999, -999, -999,
  111821. -999, -999, -999, -999, -999, -999, -999, -999},
  111822. {-999, -999, -999, -999, -999, -999, -999, -999,
  111823. -999, -107, -100, -94, -88, -83, -75, -63,
  111824. -59, -59, -63, -66, -60, -62, -67, -67,
  111825. -77, -76, -81, -88, -86, -92, -96, -102,
  111826. -109, -116, -999, -999, -999, -999, -999, -999,
  111827. -999, -999, -999, -999, -999, -999, -999, -999,
  111828. -999, -999, -999, -999, -999, -999, -999, -999},
  111829. {-999, -999, -999, -999, -999, -999, -999, -999,
  111830. -999, -105, -98, -92, -86, -81, -73, -56,
  111831. -52, -47, -55, -60, -58, -52, -51, -45,
  111832. -49, -50, -53, -54, -61, -71, -70, -69,
  111833. -78, -79, -87, -90, -96, -104, -112, -999,
  111834. -999, -999, -999, -999, -999, -999, -999, -999,
  111835. -999, -999, -999, -999, -999, -999, -999, -999},
  111836. {-999, -999, -999, -999, -999, -999, -999, -999,
  111837. -999, -103, -96, -90, -86, -78, -70, -51,
  111838. -42, -47, -48, -55, -54, -54, -53, -42,
  111839. -35, -28, -33, -38, -37, -44, -47, -49,
  111840. -54, -63, -68, -78, -82, -89, -94, -99,
  111841. -104, -109, -114, -999, -999, -999, -999, -999,
  111842. -999, -999, -999, -999, -999, -999, -999, -999}},
  111843. /* 2828 Hz */
  111844. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111845. -999, -999, -999, -999, -110, -100, -90, -79,
  111846. -85, -81, -82, -82, -89, -94, -99, -103,
  111847. -109, -115, -999, -999, -999, -999, -999, -999,
  111848. -999, -999, -999, -999, -999, -999, -999, -999,
  111849. -999, -999, -999, -999, -999, -999, -999, -999,
  111850. -999, -999, -999, -999, -999, -999, -999, -999},
  111851. {-999, -999, -999, -999, -999, -999, -999, -999,
  111852. -999, -999, -999, -999, -105, -97, -85, -72,
  111853. -74, -70, -70, -70, -76, -85, -91, -93,
  111854. -97, -103, -109, -115, -999, -999, -999, -999,
  111855. -999, -999, -999, -999, -999, -999, -999, -999,
  111856. -999, -999, -999, -999, -999, -999, -999, -999,
  111857. -999, -999, -999, -999, -999, -999, -999, -999},
  111858. {-999, -999, -999, -999, -999, -999, -999, -999,
  111859. -999, -999, -999, -999, -112, -93, -81, -68,
  111860. -62, -60, -60, -57, -63, -70, -77, -82,
  111861. -90, -93, -98, -104, -109, -113, -999, -999,
  111862. -999, -999, -999, -999, -999, -999, -999, -999,
  111863. -999, -999, -999, -999, -999, -999, -999, -999,
  111864. -999, -999, -999, -999, -999, -999, -999, -999},
  111865. {-999, -999, -999, -999, -999, -999, -999, -999,
  111866. -999, -999, -999, -113, -100, -93, -84, -63,
  111867. -58, -48, -53, -54, -52, -52, -57, -64,
  111868. -66, -76, -83, -81, -85, -85, -90, -95,
  111869. -98, -101, -103, -106, -108, -111, -999, -999,
  111870. -999, -999, -999, -999, -999, -999, -999, -999,
  111871. -999, -999, -999, -999, -999, -999, -999, -999},
  111872. {-999, -999, -999, -999, -999, -999, -999, -999,
  111873. -999, -999, -999, -105, -95, -86, -74, -53,
  111874. -50, -38, -43, -49, -43, -42, -39, -39,
  111875. -46, -52, -57, -56, -72, -69, -74, -81,
  111876. -87, -92, -94, -97, -99, -102, -105, -108,
  111877. -999, -999, -999, -999, -999, -999, -999, -999,
  111878. -999, -999, -999, -999, -999, -999, -999, -999},
  111879. {-999, -999, -999, -999, -999, -999, -999, -999,
  111880. -999, -999, -108, -99, -90, -76, -66, -45,
  111881. -43, -41, -44, -47, -43, -47, -40, -30,
  111882. -31, -31, -39, -33, -40, -41, -43, -53,
  111883. -59, -70, -73, -77, -79, -82, -84, -87,
  111884. -999, -999, -999, -999, -999, -999, -999, -999,
  111885. -999, -999, -999, -999, -999, -999, -999, -999}},
  111886. /* 4000 Hz */
  111887. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111888. -999, -999, -999, -999, -999, -110, -91, -76,
  111889. -75, -85, -93, -98, -104, -110, -999, -999,
  111890. -999, -999, -999, -999, -999, -999, -999, -999,
  111891. -999, -999, -999, -999, -999, -999, -999, -999,
  111892. -999, -999, -999, -999, -999, -999, -999, -999,
  111893. -999, -999, -999, -999, -999, -999, -999, -999},
  111894. {-999, -999, -999, -999, -999, -999, -999, -999,
  111895. -999, -999, -999, -999, -999, -110, -91, -70,
  111896. -70, -75, -86, -89, -94, -98, -101, -106,
  111897. -110, -999, -999, -999, -999, -999, -999, -999,
  111898. -999, -999, -999, -999, -999, -999, -999, -999,
  111899. -999, -999, -999, -999, -999, -999, -999, -999,
  111900. -999, -999, -999, -999, -999, -999, -999, -999},
  111901. {-999, -999, -999, -999, -999, -999, -999, -999,
  111902. -999, -999, -999, -999, -110, -95, -80, -60,
  111903. -65, -64, -74, -83, -88, -91, -95, -99,
  111904. -103, -107, -110, -999, -999, -999, -999, -999,
  111905. -999, -999, -999, -999, -999, -999, -999, -999,
  111906. -999, -999, -999, -999, -999, -999, -999, -999,
  111907. -999, -999, -999, -999, -999, -999, -999, -999},
  111908. {-999, -999, -999, -999, -999, -999, -999, -999,
  111909. -999, -999, -999, -999, -110, -95, -80, -58,
  111910. -55, -49, -66, -68, -71, -78, -78, -80,
  111911. -88, -85, -89, -97, -100, -105, -110, -999,
  111912. -999, -999, -999, -999, -999, -999, -999, -999,
  111913. -999, -999, -999, -999, -999, -999, -999, -999,
  111914. -999, -999, -999, -999, -999, -999, -999, -999},
  111915. {-999, -999, -999, -999, -999, -999, -999, -999,
  111916. -999, -999, -999, -999, -110, -95, -80, -53,
  111917. -52, -41, -59, -59, -49, -58, -56, -63,
  111918. -86, -79, -90, -93, -98, -103, -107, -112,
  111919. -999, -999, -999, -999, -999, -999, -999, -999,
  111920. -999, -999, -999, -999, -999, -999, -999, -999,
  111921. -999, -999, -999, -999, -999, -999, -999, -999},
  111922. {-999, -999, -999, -999, -999, -999, -999, -999,
  111923. -999, -999, -999, -110, -97, -91, -73, -45,
  111924. -40, -33, -53, -61, -49, -54, -50, -50,
  111925. -60, -52, -67, -74, -81, -92, -96, -100,
  111926. -105, -110, -999, -999, -999, -999, -999, -999,
  111927. -999, -999, -999, -999, -999, -999, -999, -999,
  111928. -999, -999, -999, -999, -999, -999, -999, -999}},
  111929. /* 5657 Hz */
  111930. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111931. -999, -999, -999, -113, -106, -99, -92, -77,
  111932. -80, -88, -97, -106, -115, -999, -999, -999,
  111933. -999, -999, -999, -999, -999, -999, -999, -999,
  111934. -999, -999, -999, -999, -999, -999, -999, -999,
  111935. -999, -999, -999, -999, -999, -999, -999, -999,
  111936. -999, -999, -999, -999, -999, -999, -999, -999},
  111937. {-999, -999, -999, -999, -999, -999, -999, -999,
  111938. -999, -999, -116, -109, -102, -95, -89, -74,
  111939. -72, -88, -87, -95, -102, -109, -116, -999,
  111940. -999, -999, -999, -999, -999, -999, -999, -999,
  111941. -999, -999, -999, -999, -999, -999, -999, -999,
  111942. -999, -999, -999, -999, -999, -999, -999, -999,
  111943. -999, -999, -999, -999, -999, -999, -999, -999},
  111944. {-999, -999, -999, -999, -999, -999, -999, -999,
  111945. -999, -999, -116, -109, -102, -95, -89, -75,
  111946. -66, -74, -77, -78, -86, -87, -90, -96,
  111947. -105, -115, -999, -999, -999, -999, -999, -999,
  111948. -999, -999, -999, -999, -999, -999, -999, -999,
  111949. -999, -999, -999, -999, -999, -999, -999, -999,
  111950. -999, -999, -999, -999, -999, -999, -999, -999},
  111951. {-999, -999, -999, -999, -999, -999, -999, -999,
  111952. -999, -999, -115, -108, -101, -94, -88, -66,
  111953. -56, -61, -70, -65, -78, -72, -83, -84,
  111954. -93, -98, -105, -110, -999, -999, -999, -999,
  111955. -999, -999, -999, -999, -999, -999, -999, -999,
  111956. -999, -999, -999, -999, -999, -999, -999, -999,
  111957. -999, -999, -999, -999, -999, -999, -999, -999},
  111958. {-999, -999, -999, -999, -999, -999, -999, -999,
  111959. -999, -999, -110, -105, -95, -89, -82, -57,
  111960. -52, -52, -59, -56, -59, -58, -69, -67,
  111961. -88, -82, -82, -89, -94, -100, -108, -999,
  111962. -999, -999, -999, -999, -999, -999, -999, -999,
  111963. -999, -999, -999, -999, -999, -999, -999, -999,
  111964. -999, -999, -999, -999, -999, -999, -999, -999},
  111965. {-999, -999, -999, -999, -999, -999, -999, -999,
  111966. -999, -110, -101, -96, -90, -83, -77, -54,
  111967. -43, -38, -50, -48, -52, -48, -42, -42,
  111968. -51, -52, -53, -59, -65, -71, -78, -85,
  111969. -95, -999, -999, -999, -999, -999, -999, -999,
  111970. -999, -999, -999, -999, -999, -999, -999, -999,
  111971. -999, -999, -999, -999, -999, -999, -999, -999}},
  111972. /* 8000 Hz */
  111973. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111974. -999, -999, -999, -999, -120, -105, -86, -68,
  111975. -78, -79, -90, -100, -110, -999, -999, -999,
  111976. -999, -999, -999, -999, -999, -999, -999, -999,
  111977. -999, -999, -999, -999, -999, -999, -999, -999,
  111978. -999, -999, -999, -999, -999, -999, -999, -999,
  111979. -999, -999, -999, -999, -999, -999, -999, -999},
  111980. {-999, -999, -999, -999, -999, -999, -999, -999,
  111981. -999, -999, -999, -999, -120, -105, -86, -66,
  111982. -73, -77, -88, -96, -105, -115, -999, -999,
  111983. -999, -999, -999, -999, -999, -999, -999, -999,
  111984. -999, -999, -999, -999, -999, -999, -999, -999,
  111985. -999, -999, -999, -999, -999, -999, -999, -999,
  111986. -999, -999, -999, -999, -999, -999, -999, -999},
  111987. {-999, -999, -999, -999, -999, -999, -999, -999,
  111988. -999, -999, -999, -120, -105, -92, -80, -61,
  111989. -64, -68, -80, -87, -92, -100, -110, -999,
  111990. -999, -999, -999, -999, -999, -999, -999, -999,
  111991. -999, -999, -999, -999, -999, -999, -999, -999,
  111992. -999, -999, -999, -999, -999, -999, -999, -999,
  111993. -999, -999, -999, -999, -999, -999, -999, -999},
  111994. {-999, -999, -999, -999, -999, -999, -999, -999,
  111995. -999, -999, -999, -120, -104, -91, -79, -52,
  111996. -60, -54, -64, -69, -77, -80, -82, -84,
  111997. -85, -87, -88, -90, -999, -999, -999, -999,
  111998. -999, -999, -999, -999, -999, -999, -999, -999,
  111999. -999, -999, -999, -999, -999, -999, -999, -999,
  112000. -999, -999, -999, -999, -999, -999, -999, -999},
  112001. {-999, -999, -999, -999, -999, -999, -999, -999,
  112002. -999, -999, -999, -118, -100, -87, -77, -49,
  112003. -50, -44, -58, -61, -61, -67, -65, -62,
  112004. -62, -62, -65, -68, -999, -999, -999, -999,
  112005. -999, -999, -999, -999, -999, -999, -999, -999,
  112006. -999, -999, -999, -999, -999, -999, -999, -999,
  112007. -999, -999, -999, -999, -999, -999, -999, -999},
  112008. {-999, -999, -999, -999, -999, -999, -999, -999,
  112009. -999, -999, -999, -115, -98, -84, -62, -49,
  112010. -44, -38, -46, -49, -49, -46, -39, -37,
  112011. -39, -40, -42, -43, -999, -999, -999, -999,
  112012. -999, -999, -999, -999, -999, -999, -999, -999,
  112013. -999, -999, -999, -999, -999, -999, -999, -999,
  112014. -999, -999, -999, -999, -999, -999, -999, -999}},
  112015. /* 11314 Hz */
  112016. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112017. -999, -999, -999, -999, -999, -110, -88, -74,
  112018. -77, -82, -82, -85, -90, -94, -99, -104,
  112019. -999, -999, -999, -999, -999, -999, -999, -999,
  112020. -999, -999, -999, -999, -999, -999, -999, -999,
  112021. -999, -999, -999, -999, -999, -999, -999, -999,
  112022. -999, -999, -999, -999, -999, -999, -999, -999},
  112023. {-999, -999, -999, -999, -999, -999, -999, -999,
  112024. -999, -999, -999, -999, -999, -110, -88, -66,
  112025. -70, -81, -80, -81, -84, -88, -91, -93,
  112026. -999, -999, -999, -999, -999, -999, -999, -999,
  112027. -999, -999, -999, -999, -999, -999, -999, -999,
  112028. -999, -999, -999, -999, -999, -999, -999, -999,
  112029. -999, -999, -999, -999, -999, -999, -999, -999},
  112030. {-999, -999, -999, -999, -999, -999, -999, -999,
  112031. -999, -999, -999, -999, -999, -110, -88, -61,
  112032. -63, -70, -71, -74, -77, -80, -83, -85,
  112033. -999, -999, -999, -999, -999, -999, -999, -999,
  112034. -999, -999, -999, -999, -999, -999, -999, -999,
  112035. -999, -999, -999, -999, -999, -999, -999, -999,
  112036. -999, -999, -999, -999, -999, -999, -999, -999},
  112037. {-999, -999, -999, -999, -999, -999, -999, -999,
  112038. -999, -999, -999, -999, -999, -110, -86, -62,
  112039. -63, -62, -62, -58, -52, -50, -50, -52,
  112040. -54, -999, -999, -999, -999, -999, -999, -999,
  112041. -999, -999, -999, -999, -999, -999, -999, -999,
  112042. -999, -999, -999, -999, -999, -999, -999, -999,
  112043. -999, -999, -999, -999, -999, -999, -999, -999},
  112044. {-999, -999, -999, -999, -999, -999, -999, -999,
  112045. -999, -999, -999, -999, -118, -108, -84, -53,
  112046. -50, -50, -50, -55, -47, -45, -40, -40,
  112047. -40, -999, -999, -999, -999, -999, -999, -999,
  112048. -999, -999, -999, -999, -999, -999, -999, -999,
  112049. -999, -999, -999, -999, -999, -999, -999, -999,
  112050. -999, -999, -999, -999, -999, -999, -999, -999},
  112051. {-999, -999, -999, -999, -999, -999, -999, -999,
  112052. -999, -999, -999, -999, -118, -100, -73, -43,
  112053. -37, -42, -43, -53, -38, -37, -35, -35,
  112054. -38, -999, -999, -999, -999, -999, -999, -999,
  112055. -999, -999, -999, -999, -999, -999, -999, -999,
  112056. -999, -999, -999, -999, -999, -999, -999, -999,
  112057. -999, -999, -999, -999, -999, -999, -999, -999}},
  112058. /* 16000 Hz */
  112059. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112060. -999, -999, -999, -110, -100, -91, -84, -74,
  112061. -80, -80, -80, -80, -80, -999, -999, -999,
  112062. -999, -999, -999, -999, -999, -999, -999, -999,
  112063. -999, -999, -999, -999, -999, -999, -999, -999,
  112064. -999, -999, -999, -999, -999, -999, -999, -999,
  112065. -999, -999, -999, -999, -999, -999, -999, -999},
  112066. {-999, -999, -999, -999, -999, -999, -999, -999,
  112067. -999, -999, -999, -110, -100, -91, -84, -74,
  112068. -68, -68, -68, -68, -68, -999, -999, -999,
  112069. -999, -999, -999, -999, -999, -999, -999, -999,
  112070. -999, -999, -999, -999, -999, -999, -999, -999,
  112071. -999, -999, -999, -999, -999, -999, -999, -999,
  112072. -999, -999, -999, -999, -999, -999, -999, -999},
  112073. {-999, -999, -999, -999, -999, -999, -999, -999,
  112074. -999, -999, -999, -110, -100, -86, -78, -70,
  112075. -60, -45, -30, -21, -999, -999, -999, -999,
  112076. -999, -999, -999, -999, -999, -999, -999, -999,
  112077. -999, -999, -999, -999, -999, -999, -999, -999,
  112078. -999, -999, -999, -999, -999, -999, -999, -999,
  112079. -999, -999, -999, -999, -999, -999, -999, -999},
  112080. {-999, -999, -999, -999, -999, -999, -999, -999,
  112081. -999, -999, -999, -110, -100, -87, -78, -67,
  112082. -48, -38, -29, -21, -999, -999, -999, -999,
  112083. -999, -999, -999, -999, -999, -999, -999, -999,
  112084. -999, -999, -999, -999, -999, -999, -999, -999,
  112085. -999, -999, -999, -999, -999, -999, -999, -999,
  112086. -999, -999, -999, -999, -999, -999, -999, -999},
  112087. {-999, -999, -999, -999, -999, -999, -999, -999,
  112088. -999, -999, -999, -110, -100, -86, -69, -56,
  112089. -45, -35, -33, -29, -999, -999, -999, -999,
  112090. -999, -999, -999, -999, -999, -999, -999, -999,
  112091. -999, -999, -999, -999, -999, -999, -999, -999,
  112092. -999, -999, -999, -999, -999, -999, -999, -999,
  112093. -999, -999, -999, -999, -999, -999, -999, -999},
  112094. {-999, -999, -999, -999, -999, -999, -999, -999,
  112095. -999, -999, -999, -110, -100, -83, -71, -48,
  112096. -27, -38, -37, -34, -999, -999, -999, -999,
  112097. -999, -999, -999, -999, -999, -999, -999, -999,
  112098. -999, -999, -999, -999, -999, -999, -999, -999,
  112099. -999, -999, -999, -999, -999, -999, -999, -999,
  112100. -999, -999, -999, -999, -999, -999, -999, -999}}
  112101. };
  112102. #endif
  112103. /********* End of inlined file: masking.h *********/
  112104. #define NEGINF -9999.f
  112105. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  112106. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  112107. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  112108. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112109. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112110. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  112111. look->channels=vi->channels;
  112112. look->ampmax=-9999.;
  112113. look->gi=gi;
  112114. return(look);
  112115. }
  112116. void _vp_global_free(vorbis_look_psy_global *look){
  112117. if(look){
  112118. memset(look,0,sizeof(*look));
  112119. _ogg_free(look);
  112120. }
  112121. }
  112122. void _vi_gpsy_free(vorbis_info_psy_global *i){
  112123. if(i){
  112124. memset(i,0,sizeof(*i));
  112125. _ogg_free(i);
  112126. }
  112127. }
  112128. void _vi_psy_free(vorbis_info_psy *i){
  112129. if(i){
  112130. memset(i,0,sizeof(*i));
  112131. _ogg_free(i);
  112132. }
  112133. }
  112134. static void min_curve(float *c,
  112135. float *c2){
  112136. int i;
  112137. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  112138. }
  112139. static void max_curve(float *c,
  112140. float *c2){
  112141. int i;
  112142. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  112143. }
  112144. static void attenuate_curve(float *c,float att){
  112145. int i;
  112146. for(i=0;i<EHMER_MAX;i++)
  112147. c[i]+=att;
  112148. }
  112149. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  112150. float center_boost, float center_decay_rate){
  112151. int i,j,k,m;
  112152. float ath[EHMER_MAX];
  112153. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  112154. float athc[P_LEVELS][EHMER_MAX];
  112155. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  112156. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  112157. memset(workc,0,sizeof(workc));
  112158. for(i=0;i<P_BANDS;i++){
  112159. /* we add back in the ATH to avoid low level curves falling off to
  112160. -infinity and unnecessarily cutting off high level curves in the
  112161. curve limiting (last step). */
  112162. /* A half-band's settings must be valid over the whole band, and
  112163. it's better to mask too little than too much */
  112164. int ath_offset=i*4;
  112165. for(j=0;j<EHMER_MAX;j++){
  112166. float min=999.;
  112167. for(k=0;k<4;k++)
  112168. if(j+k+ath_offset<MAX_ATH){
  112169. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  112170. }else{
  112171. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  112172. }
  112173. ath[j]=min;
  112174. }
  112175. /* copy curves into working space, replicate the 50dB curve to 30
  112176. and 40, replicate the 100dB curve to 110 */
  112177. for(j=0;j<6;j++)
  112178. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  112179. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112180. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112181. /* apply centered curve boost/decay */
  112182. for(j=0;j<P_LEVELS;j++){
  112183. for(k=0;k<EHMER_MAX;k++){
  112184. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  112185. if(adj<0. && center_boost>0)adj=0.;
  112186. if(adj>0. && center_boost<0)adj=0.;
  112187. workc[i][j][k]+=adj;
  112188. }
  112189. }
  112190. /* normalize curves so the driving amplitude is 0dB */
  112191. /* make temp curves with the ATH overlayed */
  112192. for(j=0;j<P_LEVELS;j++){
  112193. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  112194. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  112195. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  112196. max_curve(athc[j],workc[i][j]);
  112197. }
  112198. /* Now limit the louder curves.
  112199. the idea is this: We don't know what the playback attenuation
  112200. will be; 0dB SL moves every time the user twiddles the volume
  112201. knob. So that means we have to use a single 'most pessimal' curve
  112202. for all masking amplitudes, right? Wrong. The *loudest* sound
  112203. can be in (we assume) a range of ...+100dB] SL. However, sounds
  112204. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  112205. etc... */
  112206. for(j=1;j<P_LEVELS;j++){
  112207. min_curve(athc[j],athc[j-1]);
  112208. min_curve(workc[i][j],athc[j]);
  112209. }
  112210. }
  112211. for(i=0;i<P_BANDS;i++){
  112212. int hi_curve,lo_curve,bin;
  112213. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  112214. /* low frequency curves are measured with greater resolution than
  112215. the MDCT/FFT will actually give us; we want the curve applied
  112216. to the tone data to be pessimistic and thus apply the minimum
  112217. masking possible for a given bin. That means that a single bin
  112218. could span more than one octave and that the curve will be a
  112219. composite of multiple octaves. It also may mean that a single
  112220. bin may span > an eighth of an octave and that the eighth
  112221. octave values may also be composited. */
  112222. /* which octave curves will we be compositing? */
  112223. bin=floor(fromOC(i*.5)/binHz);
  112224. lo_curve= ceil(toOC(bin*binHz+1)*2);
  112225. hi_curve= floor(toOC((bin+1)*binHz)*2);
  112226. if(lo_curve>i)lo_curve=i;
  112227. if(lo_curve<0)lo_curve=0;
  112228. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  112229. for(m=0;m<P_LEVELS;m++){
  112230. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  112231. for(j=0;j<n;j++)brute_buffer[j]=999.;
  112232. /* render the curve into bins, then pull values back into curve.
  112233. The point is that any inherent subsampling aliasing results in
  112234. a safe minimum */
  112235. for(k=lo_curve;k<=hi_curve;k++){
  112236. int l=0;
  112237. for(j=0;j<EHMER_MAX;j++){
  112238. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  112239. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  112240. if(lo_bin<0)lo_bin=0;
  112241. if(lo_bin>n)lo_bin=n;
  112242. if(lo_bin<l)l=lo_bin;
  112243. if(hi_bin<0)hi_bin=0;
  112244. if(hi_bin>n)hi_bin=n;
  112245. for(;l<hi_bin && l<n;l++)
  112246. if(brute_buffer[l]>workc[k][m][j])
  112247. brute_buffer[l]=workc[k][m][j];
  112248. }
  112249. for(;l<n;l++)
  112250. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112251. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112252. }
  112253. /* be equally paranoid about being valid up to next half ocatve */
  112254. if(i+1<P_BANDS){
  112255. int l=0;
  112256. k=i+1;
  112257. for(j=0;j<EHMER_MAX;j++){
  112258. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  112259. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  112260. if(lo_bin<0)lo_bin=0;
  112261. if(lo_bin>n)lo_bin=n;
  112262. if(lo_bin<l)l=lo_bin;
  112263. if(hi_bin<0)hi_bin=0;
  112264. if(hi_bin>n)hi_bin=n;
  112265. for(;l<hi_bin && l<n;l++)
  112266. if(brute_buffer[l]>workc[k][m][j])
  112267. brute_buffer[l]=workc[k][m][j];
  112268. }
  112269. for(;l<n;l++)
  112270. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112271. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112272. }
  112273. for(j=0;j<EHMER_MAX;j++){
  112274. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  112275. if(bin<0){
  112276. ret[i][m][j+2]=-999.;
  112277. }else{
  112278. if(bin>=n){
  112279. ret[i][m][j+2]=-999.;
  112280. }else{
  112281. ret[i][m][j+2]=brute_buffer[bin];
  112282. }
  112283. }
  112284. }
  112285. /* add fenceposts */
  112286. for(j=0;j<EHMER_OFFSET;j++)
  112287. if(ret[i][m][j+2]>-200.f)break;
  112288. ret[i][m][0]=j;
  112289. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  112290. if(ret[i][m][j+2]>-200.f)
  112291. break;
  112292. ret[i][m][1]=j;
  112293. }
  112294. }
  112295. return(ret);
  112296. }
  112297. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  112298. vorbis_info_psy_global *gi,int n,long rate){
  112299. long i,j,lo=-99,hi=1;
  112300. long maxoc;
  112301. memset(p,0,sizeof(*p));
  112302. p->eighth_octave_lines=gi->eighth_octave_lines;
  112303. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  112304. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  112305. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  112306. p->total_octave_lines=maxoc-p->firstoc+1;
  112307. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  112308. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  112309. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  112310. p->vi=vi;
  112311. p->n=n;
  112312. p->rate=rate;
  112313. /* AoTuV HF weighting */
  112314. p->m_val = 1.;
  112315. if(rate < 26000) p->m_val = 0;
  112316. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  112317. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  112318. /* set up the lookups for a given blocksize and sample rate */
  112319. for(i=0,j=0;i<MAX_ATH-1;i++){
  112320. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  112321. float base=ATH[i];
  112322. if(j<endpos){
  112323. float delta=(ATH[i+1]-base)/(endpos-j);
  112324. for(;j<endpos && j<n;j++){
  112325. p->ath[j]=base+100.;
  112326. base+=delta;
  112327. }
  112328. }
  112329. }
  112330. for(i=0;i<n;i++){
  112331. float bark=toBARK(rate/(2*n)*i);
  112332. for(;lo+vi->noisewindowlomin<i &&
  112333. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  112334. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  112335. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  112336. p->bark[i]=((lo-1)<<16)+(hi-1);
  112337. }
  112338. for(i=0;i<n;i++)
  112339. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  112340. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  112341. vi->tone_centerboost,vi->tone_decay);
  112342. /* set up rolling noise median */
  112343. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  112344. for(i=0;i<P_NOISECURVES;i++)
  112345. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  112346. for(i=0;i<n;i++){
  112347. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  112348. int inthalfoc;
  112349. float del;
  112350. if(halfoc<0)halfoc=0;
  112351. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  112352. inthalfoc=(int)halfoc;
  112353. del=halfoc-inthalfoc;
  112354. for(j=0;j<P_NOISECURVES;j++)
  112355. p->noiseoffset[j][i]=
  112356. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  112357. p->vi->noiseoff[j][inthalfoc+1]*del;
  112358. }
  112359. #if 0
  112360. {
  112361. static int ls=0;
  112362. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  112363. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  112364. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  112365. }
  112366. #endif
  112367. }
  112368. void _vp_psy_clear(vorbis_look_psy *p){
  112369. int i,j;
  112370. if(p){
  112371. if(p->ath)_ogg_free(p->ath);
  112372. if(p->octave)_ogg_free(p->octave);
  112373. if(p->bark)_ogg_free(p->bark);
  112374. if(p->tonecurves){
  112375. for(i=0;i<P_BANDS;i++){
  112376. for(j=0;j<P_LEVELS;j++){
  112377. _ogg_free(p->tonecurves[i][j]);
  112378. }
  112379. _ogg_free(p->tonecurves[i]);
  112380. }
  112381. _ogg_free(p->tonecurves);
  112382. }
  112383. if(p->noiseoffset){
  112384. for(i=0;i<P_NOISECURVES;i++){
  112385. _ogg_free(p->noiseoffset[i]);
  112386. }
  112387. _ogg_free(p->noiseoffset);
  112388. }
  112389. memset(p,0,sizeof(*p));
  112390. }
  112391. }
  112392. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  112393. static void seed_curve(float *seed,
  112394. const float **curves,
  112395. float amp,
  112396. int oc, int n,
  112397. int linesper,float dBoffset){
  112398. int i,post1;
  112399. int seedptr;
  112400. const float *posts,*curve;
  112401. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  112402. choice=max(choice,0);
  112403. choice=min(choice,P_LEVELS-1);
  112404. posts=curves[choice];
  112405. curve=posts+2;
  112406. post1=(int)posts[1];
  112407. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  112408. for(i=posts[0];i<post1;i++){
  112409. if(seedptr>0){
  112410. float lin=amp+curve[i];
  112411. if(seed[seedptr]<lin)seed[seedptr]=lin;
  112412. }
  112413. seedptr+=linesper;
  112414. if(seedptr>=n)break;
  112415. }
  112416. }
  112417. static void seed_loop(vorbis_look_psy *p,
  112418. const float ***curves,
  112419. const float *f,
  112420. const float *flr,
  112421. float *seed,
  112422. float specmax){
  112423. vorbis_info_psy *vi=p->vi;
  112424. long n=p->n,i;
  112425. float dBoffset=vi->max_curve_dB-specmax;
  112426. /* prime the working vector with peak values */
  112427. for(i=0;i<n;i++){
  112428. float max=f[i];
  112429. long oc=p->octave[i];
  112430. while(i+1<n && p->octave[i+1]==oc){
  112431. i++;
  112432. if(f[i]>max)max=f[i];
  112433. }
  112434. if(max+6.f>flr[i]){
  112435. oc=oc>>p->shiftoc;
  112436. if(oc>=P_BANDS)oc=P_BANDS-1;
  112437. if(oc<0)oc=0;
  112438. seed_curve(seed,
  112439. curves[oc],
  112440. max,
  112441. p->octave[i]-p->firstoc,
  112442. p->total_octave_lines,
  112443. p->eighth_octave_lines,
  112444. dBoffset);
  112445. }
  112446. }
  112447. }
  112448. static void seed_chase(float *seeds, int linesper, long n){
  112449. long *posstack=(long*)alloca(n*sizeof(*posstack));
  112450. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  112451. long stack=0;
  112452. long pos=0;
  112453. long i;
  112454. for(i=0;i<n;i++){
  112455. if(stack<2){
  112456. posstack[stack]=i;
  112457. ampstack[stack++]=seeds[i];
  112458. }else{
  112459. while(1){
  112460. if(seeds[i]<ampstack[stack-1]){
  112461. posstack[stack]=i;
  112462. ampstack[stack++]=seeds[i];
  112463. break;
  112464. }else{
  112465. if(i<posstack[stack-1]+linesper){
  112466. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  112467. i<posstack[stack-2]+linesper){
  112468. /* we completely overlap, making stack-1 irrelevant. pop it */
  112469. stack--;
  112470. continue;
  112471. }
  112472. }
  112473. posstack[stack]=i;
  112474. ampstack[stack++]=seeds[i];
  112475. break;
  112476. }
  112477. }
  112478. }
  112479. }
  112480. /* the stack now contains only the positions that are relevant. Scan
  112481. 'em straight through */
  112482. for(i=0;i<stack;i++){
  112483. long endpos;
  112484. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  112485. endpos=posstack[i+1];
  112486. }else{
  112487. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  112488. discarded in short frames */
  112489. }
  112490. if(endpos>n)endpos=n;
  112491. for(;pos<endpos;pos++)
  112492. seeds[pos]=ampstack[i];
  112493. }
  112494. /* there. Linear time. I now remember this was on a problem set I
  112495. had in Grad Skool... I didn't solve it at the time ;-) */
  112496. }
  112497. /* bleaugh, this is more complicated than it needs to be */
  112498. #include<stdio.h>
  112499. static void max_seeds(vorbis_look_psy *p,
  112500. float *seed,
  112501. float *flr){
  112502. long n=p->total_octave_lines;
  112503. int linesper=p->eighth_octave_lines;
  112504. long linpos=0;
  112505. long pos;
  112506. seed_chase(seed,linesper,n); /* for masking */
  112507. pos=p->octave[0]-p->firstoc-(linesper>>1);
  112508. while(linpos+1<p->n){
  112509. float minV=seed[pos];
  112510. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  112511. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  112512. while(pos+1<=end){
  112513. pos++;
  112514. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  112515. minV=seed[pos];
  112516. }
  112517. end=pos+p->firstoc;
  112518. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  112519. if(flr[linpos]<minV)flr[linpos]=minV;
  112520. }
  112521. {
  112522. float minV=seed[p->total_octave_lines-1];
  112523. for(;linpos<p->n;linpos++)
  112524. if(flr[linpos]<minV)flr[linpos]=minV;
  112525. }
  112526. }
  112527. static void bark_noise_hybridmp(int n,const long *b,
  112528. const float *f,
  112529. float *noise,
  112530. const float offset,
  112531. const int fixed){
  112532. float *N=(float*) alloca(n*sizeof(*N));
  112533. float *X=(float*) alloca(n*sizeof(*N));
  112534. float *XX=(float*) alloca(n*sizeof(*N));
  112535. float *Y=(float*) alloca(n*sizeof(*N));
  112536. float *XY=(float*) alloca(n*sizeof(*N));
  112537. float tN, tX, tXX, tY, tXY;
  112538. int i;
  112539. int lo, hi;
  112540. float R, A, B, D;
  112541. float w, x, y;
  112542. tN = tX = tXX = tY = tXY = 0.f;
  112543. y = f[0] + offset;
  112544. if (y < 1.f) y = 1.f;
  112545. w = y * y * .5;
  112546. tN += w;
  112547. tX += w;
  112548. tY += w * y;
  112549. N[0] = tN;
  112550. X[0] = tX;
  112551. XX[0] = tXX;
  112552. Y[0] = tY;
  112553. XY[0] = tXY;
  112554. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  112555. y = f[i] + offset;
  112556. if (y < 1.f) y = 1.f;
  112557. w = y * y;
  112558. tN += w;
  112559. tX += w * x;
  112560. tXX += w * x * x;
  112561. tY += w * y;
  112562. tXY += w * x * y;
  112563. N[i] = tN;
  112564. X[i] = tX;
  112565. XX[i] = tXX;
  112566. Y[i] = tY;
  112567. XY[i] = tXY;
  112568. }
  112569. for (i = 0, x = 0.f;; i++, x += 1.f) {
  112570. lo = b[i] >> 16;
  112571. if( lo>=0 ) break;
  112572. hi = b[i] & 0xffff;
  112573. tN = N[hi] + N[-lo];
  112574. tX = X[hi] - X[-lo];
  112575. tXX = XX[hi] + XX[-lo];
  112576. tY = Y[hi] + Y[-lo];
  112577. tXY = XY[hi] - XY[-lo];
  112578. A = tY * tXX - tX * tXY;
  112579. B = tN * tXY - tX * tY;
  112580. D = tN * tXX - tX * tX;
  112581. R = (A + x * B) / D;
  112582. if (R < 0.f)
  112583. R = 0.f;
  112584. noise[i] = R - offset;
  112585. }
  112586. for ( ;; i++, x += 1.f) {
  112587. lo = b[i] >> 16;
  112588. hi = b[i] & 0xffff;
  112589. if(hi>=n)break;
  112590. tN = N[hi] - N[lo];
  112591. tX = X[hi] - X[lo];
  112592. tXX = XX[hi] - XX[lo];
  112593. tY = Y[hi] - Y[lo];
  112594. tXY = XY[hi] - XY[lo];
  112595. A = tY * tXX - tX * tXY;
  112596. B = tN * tXY - tX * tY;
  112597. D = tN * tXX - tX * tX;
  112598. R = (A + x * B) / D;
  112599. if (R < 0.f) R = 0.f;
  112600. noise[i] = R - offset;
  112601. }
  112602. for ( ; i < n; i++, x += 1.f) {
  112603. R = (A + x * B) / D;
  112604. if (R < 0.f) R = 0.f;
  112605. noise[i] = R - offset;
  112606. }
  112607. if (fixed <= 0) return;
  112608. for (i = 0, x = 0.f;; i++, x += 1.f) {
  112609. hi = i + fixed / 2;
  112610. lo = hi - fixed;
  112611. if(lo>=0)break;
  112612. tN = N[hi] + N[-lo];
  112613. tX = X[hi] - X[-lo];
  112614. tXX = XX[hi] + XX[-lo];
  112615. tY = Y[hi] + Y[-lo];
  112616. tXY = XY[hi] - XY[-lo];
  112617. A = tY * tXX - tX * tXY;
  112618. B = tN * tXY - tX * tY;
  112619. D = tN * tXX - tX * tX;
  112620. R = (A + x * B) / D;
  112621. if (R - offset < noise[i]) noise[i] = R - offset;
  112622. }
  112623. for ( ;; i++, x += 1.f) {
  112624. hi = i + fixed / 2;
  112625. lo = hi - fixed;
  112626. if(hi>=n)break;
  112627. tN = N[hi] - N[lo];
  112628. tX = X[hi] - X[lo];
  112629. tXX = XX[hi] - XX[lo];
  112630. tY = Y[hi] - Y[lo];
  112631. tXY = XY[hi] - XY[lo];
  112632. A = tY * tXX - tX * tXY;
  112633. B = tN * tXY - tX * tY;
  112634. D = tN * tXX - tX * tX;
  112635. R = (A + x * B) / D;
  112636. if (R - offset < noise[i]) noise[i] = R - offset;
  112637. }
  112638. for ( ; i < n; i++, x += 1.f) {
  112639. R = (A + x * B) / D;
  112640. if (R - offset < noise[i]) noise[i] = R - offset;
  112641. }
  112642. }
  112643. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  112644. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  112645. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  112646. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  112647. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  112648. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  112649. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  112650. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  112651. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  112652. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  112653. 973377.F, 913981.F, 858210.F, 805842.F,
  112654. 756669.F, 710497.F, 667142.F, 626433.F,
  112655. 588208.F, 552316.F, 518613.F, 486967.F,
  112656. 457252.F, 429351.F, 403152.F, 378551.F,
  112657. 355452.F, 333762.F, 313396.F, 294273.F,
  112658. 276316.F, 259455.F, 243623.F, 228757.F,
  112659. 214798.F, 201691.F, 189384.F, 177828.F,
  112660. 166977.F, 156788.F, 147221.F, 138237.F,
  112661. 129802.F, 121881.F, 114444.F, 107461.F,
  112662. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  112663. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  112664. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  112665. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  112666. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  112667. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  112668. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  112669. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  112670. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  112671. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  112672. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  112673. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  112674. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  112675. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  112676. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  112677. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  112678. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  112679. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  112680. 1084.32F, 1018.15F, 956.024F, 897.687F,
  112681. 842.910F, 791.475F, 743.179F, 697.830F,
  112682. 655.249F, 615.265F, 577.722F, 542.469F,
  112683. 509.367F, 478.286F, 449.101F, 421.696F,
  112684. 395.964F, 371.803F, 349.115F, 327.812F,
  112685. 307.809F, 289.026F, 271.390F, 254.830F,
  112686. 239.280F, 224.679F, 210.969F, 198.096F,
  112687. 186.008F, 174.658F, 164.000F, 153.993F,
  112688. 144.596F, 135.773F, 127.488F, 119.708F,
  112689. 112.404F, 105.545F, 99.1046F, 93.0572F,
  112690. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  112691. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  112692. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  112693. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  112694. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  112695. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  112696. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  112697. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  112698. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  112699. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  112700. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  112701. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  112702. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  112703. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  112704. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  112705. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  112706. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  112707. 1.20790F, 1.13419F, 1.06499F, 1.F
  112708. };
  112709. void _vp_remove_floor(vorbis_look_psy *p,
  112710. float *mdct,
  112711. int *codedflr,
  112712. float *residue,
  112713. int sliding_lowpass){
  112714. int i,n=p->n;
  112715. if(sliding_lowpass>n)sliding_lowpass=n;
  112716. for(i=0;i<sliding_lowpass;i++){
  112717. residue[i]=
  112718. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  112719. }
  112720. for(;i<n;i++)
  112721. residue[i]=0.;
  112722. }
  112723. void _vp_noisemask(vorbis_look_psy *p,
  112724. float *logmdct,
  112725. float *logmask){
  112726. int i,n=p->n;
  112727. float *work=(float*) alloca(n*sizeof(*work));
  112728. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  112729. 140.,-1);
  112730. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  112731. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  112732. p->vi->noisewindowfixed);
  112733. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  112734. #if 0
  112735. {
  112736. static int seq=0;
  112737. float work2[n];
  112738. for(i=0;i<n;i++){
  112739. work2[i]=logmask[i]+work[i];
  112740. }
  112741. if(seq&1)
  112742. _analysis_output("median2R",seq/2,work,n,1,0,0);
  112743. else
  112744. _analysis_output("median2L",seq/2,work,n,1,0,0);
  112745. if(seq&1)
  112746. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  112747. else
  112748. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  112749. seq++;
  112750. }
  112751. #endif
  112752. for(i=0;i<n;i++){
  112753. int dB=logmask[i]+.5;
  112754. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  112755. if(dB<0)dB=0;
  112756. logmask[i]= work[i]+p->vi->noisecompand[dB];
  112757. }
  112758. }
  112759. void _vp_tonemask(vorbis_look_psy *p,
  112760. float *logfft,
  112761. float *logmask,
  112762. float global_specmax,
  112763. float local_specmax){
  112764. int i,n=p->n;
  112765. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  112766. float att=local_specmax+p->vi->ath_adjatt;
  112767. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  112768. /* set the ATH (floating below localmax, not global max by a
  112769. specified att) */
  112770. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  112771. for(i=0;i<n;i++)
  112772. logmask[i]=p->ath[i]+att;
  112773. /* tone masking */
  112774. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  112775. max_seeds(p,seed,logmask);
  112776. }
  112777. void _vp_offset_and_mix(vorbis_look_psy *p,
  112778. float *noise,
  112779. float *tone,
  112780. int offset_select,
  112781. float *logmask,
  112782. float *mdct,
  112783. float *logmdct){
  112784. int i,n=p->n;
  112785. float de, coeffi, cx;/* AoTuV */
  112786. float toneatt=p->vi->tone_masteratt[offset_select];
  112787. cx = p->m_val;
  112788. for(i=0;i<n;i++){
  112789. float val= noise[i]+p->noiseoffset[offset_select][i];
  112790. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  112791. logmask[i]=max(val,tone[i]+toneatt);
  112792. /* AoTuV */
  112793. /** @ M1 **
  112794. The following codes improve a noise problem.
  112795. A fundamental idea uses the value of masking and carries out
  112796. the relative compensation of the MDCT.
  112797. However, this code is not perfect and all noise problems cannot be solved.
  112798. by Aoyumi @ 2004/04/18
  112799. */
  112800. if(offset_select == 1) {
  112801. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  112802. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  112803. if(val > coeffi){
  112804. /* mdct value is > -17.2 dB below floor */
  112805. de = 1.0-((val-coeffi)*0.005*cx);
  112806. /* pro-rated attenuation:
  112807. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  112808. -0.77 dB boost if mdct value is 0dB (relative to floor)
  112809. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  112810. etc... */
  112811. if(de < 0) de = 0.0001;
  112812. }else
  112813. /* mdct value is <= -17.2 dB below floor */
  112814. de = 1.0-((val-coeffi)*0.0003*cx);
  112815. /* pro-rated attenuation:
  112816. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  112817. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  112818. etc... */
  112819. mdct[i] *= de;
  112820. }
  112821. }
  112822. }
  112823. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  112824. vorbis_info *vi=vd->vi;
  112825. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112826. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112827. int n=ci->blocksizes[vd->W]/2;
  112828. float secs=(float)n/vi->rate;
  112829. amp+=secs*gi->ampmax_att_per_sec;
  112830. if(amp<-9999)amp=-9999;
  112831. return(amp);
  112832. }
  112833. static void couple_lossless(float A, float B,
  112834. float *qA, float *qB){
  112835. int test1=fabs(*qA)>fabs(*qB);
  112836. test1-= fabs(*qA)<fabs(*qB);
  112837. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  112838. if(test1==1){
  112839. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  112840. }else{
  112841. float temp=*qB;
  112842. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  112843. *qA=temp;
  112844. }
  112845. if(*qB>fabs(*qA)*1.9999f){
  112846. *qB= -fabs(*qA)*2.f;
  112847. *qA= -*qA;
  112848. }
  112849. }
  112850. static float hypot_lookup[32]={
  112851. -0.009935, -0.011245, -0.012726, -0.014397,
  112852. -0.016282, -0.018407, -0.020800, -0.023494,
  112853. -0.026522, -0.029923, -0.033737, -0.038010,
  112854. -0.042787, -0.048121, -0.054064, -0.060671,
  112855. -0.068000, -0.076109, -0.085054, -0.094892,
  112856. -0.105675, -0.117451, -0.130260, -0.144134,
  112857. -0.159093, -0.175146, -0.192286, -0.210490,
  112858. -0.229718, -0.249913, -0.271001, -0.292893};
  112859. static void precomputed_couple_point(float premag,
  112860. int floorA,int floorB,
  112861. float *mag, float *ang){
  112862. int test=(floorA>floorB)-1;
  112863. int offset=31-abs(floorA-floorB);
  112864. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  112865. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  112866. *mag=premag*floormag;
  112867. *ang=0.f;
  112868. }
  112869. /* just like below, this is currently set up to only do
  112870. single-step-depth coupling. Otherwise, we'd have to do more
  112871. copying (which will be inevitable later) */
  112872. /* doing the real circular magnitude calculation is audibly superior
  112873. to (A+B)/sqrt(2) */
  112874. static float dipole_hypot(float a, float b){
  112875. if(a>0.){
  112876. if(b>0.)return sqrt(a*a+b*b);
  112877. if(a>-b)return sqrt(a*a-b*b);
  112878. return -sqrt(b*b-a*a);
  112879. }
  112880. if(b<0.)return -sqrt(a*a+b*b);
  112881. if(-a>b)return -sqrt(a*a-b*b);
  112882. return sqrt(b*b-a*a);
  112883. }
  112884. static float round_hypot(float a, float b){
  112885. if(a>0.){
  112886. if(b>0.)return sqrt(a*a+b*b);
  112887. if(a>-b)return sqrt(a*a+b*b);
  112888. return -sqrt(b*b+a*a);
  112889. }
  112890. if(b<0.)return -sqrt(a*a+b*b);
  112891. if(-a>b)return -sqrt(a*a+b*b);
  112892. return sqrt(b*b+a*a);
  112893. }
  112894. /* revert to round hypot for now */
  112895. float **_vp_quantize_couple_memo(vorbis_block *vb,
  112896. vorbis_info_psy_global *g,
  112897. vorbis_look_psy *p,
  112898. vorbis_info_mapping0 *vi,
  112899. float **mdct){
  112900. int i,j,n=p->n;
  112901. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  112902. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  112903. for(i=0;i<vi->coupling_steps;i++){
  112904. float *mdctM=mdct[vi->coupling_mag[i]];
  112905. float *mdctA=mdct[vi->coupling_ang[i]];
  112906. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  112907. for(j=0;j<limit;j++)
  112908. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  112909. for(;j<n;j++)
  112910. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  112911. }
  112912. return(ret);
  112913. }
  112914. /* this is for per-channel noise normalization */
  112915. static int apsort(const void *a, const void *b){
  112916. float f1=fabs(**(float**)a);
  112917. float f2=fabs(**(float**)b);
  112918. return (f1<f2)-(f1>f2);
  112919. }
  112920. int **_vp_quantize_couple_sort(vorbis_block *vb,
  112921. vorbis_look_psy *p,
  112922. vorbis_info_mapping0 *vi,
  112923. float **mags){
  112924. if(p->vi->normal_point_p){
  112925. int i,j,k,n=p->n;
  112926. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  112927. int partition=p->vi->normal_partition;
  112928. float **work=(float**) alloca(sizeof(*work)*partition);
  112929. for(i=0;i<vi->coupling_steps;i++){
  112930. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  112931. for(j=0;j<n;j+=partition){
  112932. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  112933. qsort(work,partition,sizeof(*work),apsort);
  112934. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  112935. }
  112936. }
  112937. return(ret);
  112938. }
  112939. return(NULL);
  112940. }
  112941. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  112942. float *magnitudes,int *sortedindex){
  112943. int i,j,n=p->n;
  112944. vorbis_info_psy *vi=p->vi;
  112945. int partition=vi->normal_partition;
  112946. float **work=(float**) alloca(sizeof(*work)*partition);
  112947. int start=vi->normal_start;
  112948. for(j=start;j<n;j+=partition){
  112949. if(j+partition>n)partition=n-j;
  112950. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  112951. qsort(work,partition,sizeof(*work),apsort);
  112952. for(i=0;i<partition;i++){
  112953. sortedindex[i+j-start]=work[i]-magnitudes;
  112954. }
  112955. }
  112956. }
  112957. void _vp_noise_normalize(vorbis_look_psy *p,
  112958. float *in,float *out,int *sortedindex){
  112959. int flag=0,i,j=0,n=p->n;
  112960. vorbis_info_psy *vi=p->vi;
  112961. int partition=vi->normal_partition;
  112962. int start=vi->normal_start;
  112963. if(start>n)start=n;
  112964. if(vi->normal_channel_p){
  112965. for(;j<start;j++)
  112966. out[j]=rint(in[j]);
  112967. for(;j+partition<=n;j+=partition){
  112968. float acc=0.;
  112969. int k;
  112970. for(i=j;i<j+partition;i++)
  112971. acc+=in[i]*in[i];
  112972. for(i=0;i<partition;i++){
  112973. k=sortedindex[i+j-start];
  112974. if(in[k]*in[k]>=.25f){
  112975. out[k]=rint(in[k]);
  112976. acc-=in[k]*in[k];
  112977. flag=1;
  112978. }else{
  112979. if(acc<vi->normal_thresh)break;
  112980. out[k]=unitnorm(in[k]);
  112981. acc-=1.;
  112982. }
  112983. }
  112984. for(;i<partition;i++){
  112985. k=sortedindex[i+j-start];
  112986. out[k]=0.;
  112987. }
  112988. }
  112989. }
  112990. for(;j<n;j++)
  112991. out[j]=rint(in[j]);
  112992. }
  112993. void _vp_couple(int blobno,
  112994. vorbis_info_psy_global *g,
  112995. vorbis_look_psy *p,
  112996. vorbis_info_mapping0 *vi,
  112997. float **res,
  112998. float **mag_memo,
  112999. int **mag_sort,
  113000. int **ifloor,
  113001. int *nonzero,
  113002. int sliding_lowpass){
  113003. int i,j,k,n=p->n;
  113004. /* perform any requested channel coupling */
  113005. /* point stereo can only be used in a first stage (in this encoder)
  113006. because of the dependency on floor lookups */
  113007. for(i=0;i<vi->coupling_steps;i++){
  113008. /* once we're doing multistage coupling in which a channel goes
  113009. through more than one coupling step, the floor vector
  113010. magnitudes will also have to be recalculated an propogated
  113011. along with PCM. Right now, we're not (that will wait until 5.1
  113012. most likely), so the code isn't here yet. The memory management
  113013. here is all assuming single depth couplings anyway. */
  113014. /* make sure coupling a zero and a nonzero channel results in two
  113015. nonzero channels. */
  113016. if(nonzero[vi->coupling_mag[i]] ||
  113017. nonzero[vi->coupling_ang[i]]){
  113018. float *rM=res[vi->coupling_mag[i]];
  113019. float *rA=res[vi->coupling_ang[i]];
  113020. float *qM=rM+n;
  113021. float *qA=rA+n;
  113022. int *floorM=ifloor[vi->coupling_mag[i]];
  113023. int *floorA=ifloor[vi->coupling_ang[i]];
  113024. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  113025. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  113026. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  113027. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  113028. int pointlimit=limit;
  113029. nonzero[vi->coupling_mag[i]]=1;
  113030. nonzero[vi->coupling_ang[i]]=1;
  113031. /* The threshold of a stereo is changed with the size of n */
  113032. if(n > 1000)
  113033. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  113034. for(j=0;j<p->n;j+=partition){
  113035. float acc=0.f;
  113036. for(k=0;k<partition;k++){
  113037. int l=k+j;
  113038. if(l<sliding_lowpass){
  113039. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  113040. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  113041. precomputed_couple_point(mag_memo[i][l],
  113042. floorM[l],floorA[l],
  113043. qM+l,qA+l);
  113044. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  113045. }else{
  113046. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  113047. }
  113048. }else{
  113049. qM[l]=0.;
  113050. qA[l]=0.;
  113051. }
  113052. }
  113053. if(p->vi->normal_point_p){
  113054. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  113055. int l=mag_sort[i][j+k];
  113056. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  113057. qM[l]=unitnorm(qM[l]);
  113058. acc-=1.f;
  113059. }
  113060. }
  113061. }
  113062. }
  113063. }
  113064. }
  113065. }
  113066. /* AoTuV */
  113067. /** @ M2 **
  113068. The boost problem by the combination of noise normalization and point stereo is eased.
  113069. However, this is a temporary patch.
  113070. by Aoyumi @ 2004/04/18
  113071. */
  113072. void hf_reduction(vorbis_info_psy_global *g,
  113073. vorbis_look_psy *p,
  113074. vorbis_info_mapping0 *vi,
  113075. float **mdct){
  113076. int i,j,n=p->n, de=0.3*p->m_val;
  113077. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113078. for(i=0; i<vi->coupling_steps; i++){
  113079. /* for(j=start; j<limit; j++){} // ???*/
  113080. for(j=limit; j<n; j++)
  113081. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  113082. }
  113083. }
  113084. #endif
  113085. /********* End of inlined file: psy.c *********/
  113086. /********* Start of inlined file: registry.c *********/
  113087. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113088. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113089. // tasks..
  113090. #ifdef _MSC_VER
  113091. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113092. #endif
  113093. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113094. #if JUCE_USE_OGGVORBIS
  113095. /* seems like major overkill now; the backend numbers will grow into
  113096. the infrastructure soon enough */
  113097. extern vorbis_func_floor floor0_exportbundle;
  113098. extern vorbis_func_floor floor1_exportbundle;
  113099. extern vorbis_func_residue residue0_exportbundle;
  113100. extern vorbis_func_residue residue1_exportbundle;
  113101. extern vorbis_func_residue residue2_exportbundle;
  113102. extern vorbis_func_mapping mapping0_exportbundle;
  113103. vorbis_func_floor *_floor_P[]={
  113104. &floor0_exportbundle,
  113105. &floor1_exportbundle,
  113106. };
  113107. vorbis_func_residue *_residue_P[]={
  113108. &residue0_exportbundle,
  113109. &residue1_exportbundle,
  113110. &residue2_exportbundle,
  113111. };
  113112. vorbis_func_mapping *_mapping_P[]={
  113113. &mapping0_exportbundle,
  113114. };
  113115. #endif
  113116. /********* End of inlined file: registry.c *********/
  113117. /********* Start of inlined file: res0.c *********/
  113118. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  113119. encode/decode loops are coded for clarity and performance is not
  113120. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  113121. it's slow. */
  113122. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113123. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113124. // tasks..
  113125. #ifdef _MSC_VER
  113126. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113127. #endif
  113128. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113129. #if JUCE_USE_OGGVORBIS
  113130. #include <stdlib.h>
  113131. #include <string.h>
  113132. #include <math.h>
  113133. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113134. #include <stdio.h>
  113135. #endif
  113136. typedef struct {
  113137. vorbis_info_residue0 *info;
  113138. int parts;
  113139. int stages;
  113140. codebook *fullbooks;
  113141. codebook *phrasebook;
  113142. codebook ***partbooks;
  113143. int partvals;
  113144. int **decodemap;
  113145. long postbits;
  113146. long phrasebits;
  113147. long frames;
  113148. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  113149. int train_seq;
  113150. long *training_data[8][64];
  113151. float training_max[8][64];
  113152. float training_min[8][64];
  113153. float tmin;
  113154. float tmax;
  113155. #endif
  113156. } vorbis_look_residue0;
  113157. void res0_free_info(vorbis_info_residue *i){
  113158. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  113159. if(info){
  113160. memset(info,0,sizeof(*info));
  113161. _ogg_free(info);
  113162. }
  113163. }
  113164. void res0_free_look(vorbis_look_residue *i){
  113165. int j;
  113166. if(i){
  113167. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  113168. #ifdef TRAIN_RES
  113169. {
  113170. int j,k,l;
  113171. for(j=0;j<look->parts;j++){
  113172. /*fprintf(stderr,"partition %d: ",j);*/
  113173. for(k=0;k<8;k++)
  113174. if(look->training_data[k][j]){
  113175. char buffer[80];
  113176. FILE *of;
  113177. codebook *statebook=look->partbooks[j][k];
  113178. /* long and short into the same bucket by current convention */
  113179. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  113180. of=fopen(buffer,"a");
  113181. for(l=0;l<statebook->entries;l++)
  113182. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  113183. fclose(of);
  113184. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  113185. look->training_min[k][j],look->training_max[k][j]);*/
  113186. _ogg_free(look->training_data[k][j]);
  113187. look->training_data[k][j]=NULL;
  113188. }
  113189. /*fprintf(stderr,"\n");*/
  113190. }
  113191. }
  113192. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  113193. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  113194. (float)look->phrasebits/look->frames,
  113195. (float)look->postbits/look->frames,
  113196. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113197. #endif
  113198. /*vorbis_info_residue0 *info=look->info;
  113199. fprintf(stderr,
  113200. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  113201. "(%g/frame) \n",look->frames,look->phrasebits,
  113202. look->resbitsflat,
  113203. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  113204. for(j=0;j<look->parts;j++){
  113205. long acc=0;
  113206. fprintf(stderr,"\t[%d] == ",j);
  113207. for(k=0;k<look->stages;k++)
  113208. if((info->secondstages[j]>>k)&1){
  113209. fprintf(stderr,"%ld,",look->resbits[j][k]);
  113210. acc+=look->resbits[j][k];
  113211. }
  113212. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  113213. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  113214. }
  113215. fprintf(stderr,"\n");*/
  113216. for(j=0;j<look->parts;j++)
  113217. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  113218. _ogg_free(look->partbooks);
  113219. for(j=0;j<look->partvals;j++)
  113220. _ogg_free(look->decodemap[j]);
  113221. _ogg_free(look->decodemap);
  113222. memset(look,0,sizeof(*look));
  113223. _ogg_free(look);
  113224. }
  113225. }
  113226. static int icount(unsigned int v){
  113227. int ret=0;
  113228. while(v){
  113229. ret+=v&1;
  113230. v>>=1;
  113231. }
  113232. return(ret);
  113233. }
  113234. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  113235. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113236. int j,acc=0;
  113237. oggpack_write(opb,info->begin,24);
  113238. oggpack_write(opb,info->end,24);
  113239. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  113240. code with a partitioned book */
  113241. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  113242. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  113243. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  113244. bitmask of one indicates this partition class has bits to write
  113245. this pass */
  113246. for(j=0;j<info->partitions;j++){
  113247. if(ilog(info->secondstages[j])>3){
  113248. /* yes, this is a minor hack due to not thinking ahead */
  113249. oggpack_write(opb,info->secondstages[j],3);
  113250. oggpack_write(opb,1,1);
  113251. oggpack_write(opb,info->secondstages[j]>>3,5);
  113252. }else
  113253. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  113254. acc+=icount(info->secondstages[j]);
  113255. }
  113256. for(j=0;j<acc;j++)
  113257. oggpack_write(opb,info->booklist[j],8);
  113258. }
  113259. /* vorbis_info is for range checking */
  113260. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  113261. int j,acc=0;
  113262. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  113263. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  113264. info->begin=oggpack_read(opb,24);
  113265. info->end=oggpack_read(opb,24);
  113266. info->grouping=oggpack_read(opb,24)+1;
  113267. info->partitions=oggpack_read(opb,6)+1;
  113268. info->groupbook=oggpack_read(opb,8);
  113269. for(j=0;j<info->partitions;j++){
  113270. int cascade=oggpack_read(opb,3);
  113271. if(oggpack_read(opb,1))
  113272. cascade|=(oggpack_read(opb,5)<<3);
  113273. info->secondstages[j]=cascade;
  113274. acc+=icount(cascade);
  113275. }
  113276. for(j=0;j<acc;j++)
  113277. info->booklist[j]=oggpack_read(opb,8);
  113278. if(info->groupbook>=ci->books)goto errout;
  113279. for(j=0;j<acc;j++)
  113280. if(info->booklist[j]>=ci->books)goto errout;
  113281. return(info);
  113282. errout:
  113283. res0_free_info(info);
  113284. return(NULL);
  113285. }
  113286. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  113287. vorbis_info_residue *vr){
  113288. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113289. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  113290. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  113291. int j,k,acc=0;
  113292. int dim;
  113293. int maxstage=0;
  113294. look->info=info;
  113295. look->parts=info->partitions;
  113296. look->fullbooks=ci->fullbooks;
  113297. look->phrasebook=ci->fullbooks+info->groupbook;
  113298. dim=look->phrasebook->dim;
  113299. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  113300. for(j=0;j<look->parts;j++){
  113301. int stages=ilog(info->secondstages[j]);
  113302. if(stages){
  113303. if(stages>maxstage)maxstage=stages;
  113304. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  113305. for(k=0;k<stages;k++)
  113306. if(info->secondstages[j]&(1<<k)){
  113307. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  113308. #ifdef TRAIN_RES
  113309. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  113310. sizeof(***look->training_data));
  113311. #endif
  113312. }
  113313. }
  113314. }
  113315. look->partvals=rint(pow((float)look->parts,(float)dim));
  113316. look->stages=maxstage;
  113317. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  113318. for(j=0;j<look->partvals;j++){
  113319. long val=j;
  113320. long mult=look->partvals/look->parts;
  113321. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  113322. for(k=0;k<dim;k++){
  113323. long deco=val/mult;
  113324. val-=deco*mult;
  113325. mult/=look->parts;
  113326. look->decodemap[j][k]=deco;
  113327. }
  113328. }
  113329. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113330. {
  113331. static int train_seq=0;
  113332. look->train_seq=train_seq++;
  113333. }
  113334. #endif
  113335. return(look);
  113336. }
  113337. /* break an abstraction and copy some code for performance purposes */
  113338. static int local_book_besterror(codebook *book,float *a){
  113339. int dim=book->dim,i,k,o;
  113340. int best=0;
  113341. encode_aux_threshmatch *tt=book->c->thresh_tree;
  113342. /* find the quant val of each scalar */
  113343. for(k=0,o=dim;k<dim;++k){
  113344. float val=a[--o];
  113345. i=tt->threshvals>>1;
  113346. if(val<tt->quantthresh[i]){
  113347. if(val<tt->quantthresh[i-1]){
  113348. for(--i;i>0;--i)
  113349. if(val>=tt->quantthresh[i-1])
  113350. break;
  113351. }
  113352. }else{
  113353. for(++i;i<tt->threshvals-1;++i)
  113354. if(val<tt->quantthresh[i])break;
  113355. }
  113356. best=(best*tt->quantvals)+tt->quantmap[i];
  113357. }
  113358. /* regular lattices are easy :-) */
  113359. if(book->c->lengthlist[best]<=0){
  113360. const static_codebook *c=book->c;
  113361. int i,j;
  113362. float bestf=0.f;
  113363. float *e=book->valuelist;
  113364. best=-1;
  113365. for(i=0;i<book->entries;i++){
  113366. if(c->lengthlist[i]>0){
  113367. float thisx=0.f;
  113368. for(j=0;j<dim;j++){
  113369. float val=(e[j]-a[j]);
  113370. thisx+=val*val;
  113371. }
  113372. if(best==-1 || thisx<bestf){
  113373. bestf=thisx;
  113374. best=i;
  113375. }
  113376. }
  113377. e+=dim;
  113378. }
  113379. }
  113380. {
  113381. float *ptr=book->valuelist+best*dim;
  113382. for(i=0;i<dim;i++)
  113383. *a++ -= *ptr++;
  113384. }
  113385. return(best);
  113386. }
  113387. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  113388. codebook *book,long *acc){
  113389. int i,bits=0;
  113390. int dim=book->dim;
  113391. int step=n/dim;
  113392. for(i=0;i<step;i++){
  113393. int entry=local_book_besterror(book,vec+i*dim);
  113394. #ifdef TRAIN_RES
  113395. acc[entry]++;
  113396. #endif
  113397. bits+=vorbis_book_encode(book,entry,opb);
  113398. }
  113399. return(bits);
  113400. }
  113401. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  113402. float **in,int ch){
  113403. long i,j,k;
  113404. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113405. vorbis_info_residue0 *info=look->info;
  113406. /* move all this setup out later */
  113407. int samples_per_partition=info->grouping;
  113408. int possible_partitions=info->partitions;
  113409. int n=info->end-info->begin;
  113410. int partvals=n/samples_per_partition;
  113411. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  113412. float scale=100./samples_per_partition;
  113413. /* we find the partition type for each partition of each
  113414. channel. We'll go back and do the interleaved encoding in a
  113415. bit. For now, clarity */
  113416. for(i=0;i<ch;i++){
  113417. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  113418. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  113419. }
  113420. for(i=0;i<partvals;i++){
  113421. int offset=i*samples_per_partition+info->begin;
  113422. for(j=0;j<ch;j++){
  113423. float max=0.;
  113424. float ent=0.;
  113425. for(k=0;k<samples_per_partition;k++){
  113426. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  113427. ent+=fabs(rint(in[j][offset+k]));
  113428. }
  113429. ent*=scale;
  113430. for(k=0;k<possible_partitions-1;k++)
  113431. if(max<=info->classmetric1[k] &&
  113432. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  113433. break;
  113434. partword[j][i]=k;
  113435. }
  113436. }
  113437. #ifdef TRAIN_RESAUX
  113438. {
  113439. FILE *of;
  113440. char buffer[80];
  113441. for(i=0;i<ch;i++){
  113442. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  113443. of=fopen(buffer,"a");
  113444. for(j=0;j<partvals;j++)
  113445. fprintf(of,"%ld, ",partword[i][j]);
  113446. fprintf(of,"\n");
  113447. fclose(of);
  113448. }
  113449. }
  113450. #endif
  113451. look->frames++;
  113452. return(partword);
  113453. }
  113454. /* designed for stereo or other modes where the partition size is an
  113455. integer multiple of the number of channels encoded in the current
  113456. submap */
  113457. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  113458. int ch){
  113459. long i,j,k,l;
  113460. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113461. vorbis_info_residue0 *info=look->info;
  113462. /* move all this setup out later */
  113463. int samples_per_partition=info->grouping;
  113464. int possible_partitions=info->partitions;
  113465. int n=info->end-info->begin;
  113466. int partvals=n/samples_per_partition;
  113467. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  113468. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113469. FILE *of;
  113470. char buffer[80];
  113471. #endif
  113472. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  113473. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  113474. for(i=0,l=info->begin/ch;i<partvals;i++){
  113475. float magmax=0.f;
  113476. float angmax=0.f;
  113477. for(j=0;j<samples_per_partition;j+=ch){
  113478. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  113479. for(k=1;k<ch;k++)
  113480. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  113481. l++;
  113482. }
  113483. for(j=0;j<possible_partitions-1;j++)
  113484. if(magmax<=info->classmetric1[j] &&
  113485. angmax<=info->classmetric2[j])
  113486. break;
  113487. partword[0][i]=j;
  113488. }
  113489. #ifdef TRAIN_RESAUX
  113490. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  113491. of=fopen(buffer,"a");
  113492. for(i=0;i<partvals;i++)
  113493. fprintf(of,"%ld, ",partword[0][i]);
  113494. fprintf(of,"\n");
  113495. fclose(of);
  113496. #endif
  113497. look->frames++;
  113498. return(partword);
  113499. }
  113500. static int _01forward(oggpack_buffer *opb,
  113501. vorbis_block *vb,vorbis_look_residue *vl,
  113502. float **in,int ch,
  113503. long **partword,
  113504. int (*encode)(oggpack_buffer *,float *,int,
  113505. codebook *,long *)){
  113506. long i,j,k,s;
  113507. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113508. vorbis_info_residue0 *info=look->info;
  113509. /* move all this setup out later */
  113510. int samples_per_partition=info->grouping;
  113511. int possible_partitions=info->partitions;
  113512. int partitions_per_word=look->phrasebook->dim;
  113513. int n=info->end-info->begin;
  113514. int partvals=n/samples_per_partition;
  113515. long resbits[128];
  113516. long resvals[128];
  113517. #ifdef TRAIN_RES
  113518. for(i=0;i<ch;i++)
  113519. for(j=info->begin;j<info->end;j++){
  113520. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  113521. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  113522. }
  113523. #endif
  113524. memset(resbits,0,sizeof(resbits));
  113525. memset(resvals,0,sizeof(resvals));
  113526. /* we code the partition words for each channel, then the residual
  113527. words for a partition per channel until we've written all the
  113528. residual words for that partition word. Then write the next
  113529. partition channel words... */
  113530. for(s=0;s<look->stages;s++){
  113531. for(i=0;i<partvals;){
  113532. /* first we encode a partition codeword for each channel */
  113533. if(s==0){
  113534. for(j=0;j<ch;j++){
  113535. long val=partword[j][i];
  113536. for(k=1;k<partitions_per_word;k++){
  113537. val*=possible_partitions;
  113538. if(i+k<partvals)
  113539. val+=partword[j][i+k];
  113540. }
  113541. /* training hack */
  113542. if(val<look->phrasebook->entries)
  113543. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  113544. #if 0 /*def TRAIN_RES*/
  113545. else
  113546. fprintf(stderr,"!");
  113547. #endif
  113548. }
  113549. }
  113550. /* now we encode interleaved residual values for the partitions */
  113551. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  113552. long offset=i*samples_per_partition+info->begin;
  113553. for(j=0;j<ch;j++){
  113554. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  113555. if(info->secondstages[partword[j][i]]&(1<<s)){
  113556. codebook *statebook=look->partbooks[partword[j][i]][s];
  113557. if(statebook){
  113558. int ret;
  113559. long *accumulator=NULL;
  113560. #ifdef TRAIN_RES
  113561. accumulator=look->training_data[s][partword[j][i]];
  113562. {
  113563. int l;
  113564. float *samples=in[j]+offset;
  113565. for(l=0;l<samples_per_partition;l++){
  113566. if(samples[l]<look->training_min[s][partword[j][i]])
  113567. look->training_min[s][partword[j][i]]=samples[l];
  113568. if(samples[l]>look->training_max[s][partword[j][i]])
  113569. look->training_max[s][partword[j][i]]=samples[l];
  113570. }
  113571. }
  113572. #endif
  113573. ret=encode(opb,in[j]+offset,samples_per_partition,
  113574. statebook,accumulator);
  113575. look->postbits+=ret;
  113576. resbits[partword[j][i]]+=ret;
  113577. }
  113578. }
  113579. }
  113580. }
  113581. }
  113582. }
  113583. /*{
  113584. long total=0;
  113585. long totalbits=0;
  113586. fprintf(stderr,"%d :: ",vb->mode);
  113587. for(k=0;k<possible_partitions;k++){
  113588. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  113589. total+=resvals[k];
  113590. totalbits+=resbits[k];
  113591. }
  113592. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  113593. }*/
  113594. return(0);
  113595. }
  113596. /* a truncated packet here just means 'stop working'; it's not an error */
  113597. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  113598. float **in,int ch,
  113599. long (*decodepart)(codebook *, float *,
  113600. oggpack_buffer *,int)){
  113601. long i,j,k,l,s;
  113602. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113603. vorbis_info_residue0 *info=look->info;
  113604. /* move all this setup out later */
  113605. int samples_per_partition=info->grouping;
  113606. int partitions_per_word=look->phrasebook->dim;
  113607. int n=info->end-info->begin;
  113608. int partvals=n/samples_per_partition;
  113609. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  113610. int ***partword=(int***)alloca(ch*sizeof(*partword));
  113611. for(j=0;j<ch;j++)
  113612. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  113613. for(s=0;s<look->stages;s++){
  113614. /* each loop decodes on partition codeword containing
  113615. partitions_pre_word partitions */
  113616. for(i=0,l=0;i<partvals;l++){
  113617. if(s==0){
  113618. /* fetch the partition word for each channel */
  113619. for(j=0;j<ch;j++){
  113620. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  113621. if(temp==-1)goto eopbreak;
  113622. partword[j][l]=look->decodemap[temp];
  113623. if(partword[j][l]==NULL)goto errout;
  113624. }
  113625. }
  113626. /* now we decode residual values for the partitions */
  113627. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  113628. for(j=0;j<ch;j++){
  113629. long offset=info->begin+i*samples_per_partition;
  113630. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  113631. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  113632. if(stagebook){
  113633. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  113634. samples_per_partition)==-1)goto eopbreak;
  113635. }
  113636. }
  113637. }
  113638. }
  113639. }
  113640. errout:
  113641. eopbreak:
  113642. return(0);
  113643. }
  113644. #if 0
  113645. /* residue 0 and 1 are just slight variants of one another. 0 is
  113646. interleaved, 1 is not */
  113647. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  113648. float **in,int *nonzero,int ch){
  113649. /* we encode only the nonzero parts of a bundle */
  113650. int i,used=0;
  113651. for(i=0;i<ch;i++)
  113652. if(nonzero[i])
  113653. in[used++]=in[i];
  113654. if(used)
  113655. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  113656. return(_01class(vb,vl,in,used));
  113657. else
  113658. return(0);
  113659. }
  113660. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  113661. float **in,float **out,int *nonzero,int ch,
  113662. long **partword){
  113663. /* we encode only the nonzero parts of a bundle */
  113664. int i,j,used=0,n=vb->pcmend/2;
  113665. for(i=0;i<ch;i++)
  113666. if(nonzero[i]){
  113667. if(out)
  113668. for(j=0;j<n;j++)
  113669. out[i][j]+=in[i][j];
  113670. in[used++]=in[i];
  113671. }
  113672. if(used){
  113673. int ret=_01forward(vb,vl,in,used,partword,
  113674. _interleaved_encodepart);
  113675. if(out){
  113676. used=0;
  113677. for(i=0;i<ch;i++)
  113678. if(nonzero[i]){
  113679. for(j=0;j<n;j++)
  113680. out[i][j]-=in[used][j];
  113681. used++;
  113682. }
  113683. }
  113684. return(ret);
  113685. }else{
  113686. return(0);
  113687. }
  113688. }
  113689. #endif
  113690. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  113691. float **in,int *nonzero,int ch){
  113692. int i,used=0;
  113693. for(i=0;i<ch;i++)
  113694. if(nonzero[i])
  113695. in[used++]=in[i];
  113696. if(used)
  113697. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  113698. else
  113699. return(0);
  113700. }
  113701. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  113702. float **in,float **out,int *nonzero,int ch,
  113703. long **partword){
  113704. int i,j,used=0,n=vb->pcmend/2;
  113705. for(i=0;i<ch;i++)
  113706. if(nonzero[i]){
  113707. if(out)
  113708. for(j=0;j<n;j++)
  113709. out[i][j]+=in[i][j];
  113710. in[used++]=in[i];
  113711. }
  113712. if(used){
  113713. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  113714. if(out){
  113715. used=0;
  113716. for(i=0;i<ch;i++)
  113717. if(nonzero[i]){
  113718. for(j=0;j<n;j++)
  113719. out[i][j]-=in[used][j];
  113720. used++;
  113721. }
  113722. }
  113723. return(ret);
  113724. }else{
  113725. return(0);
  113726. }
  113727. }
  113728. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  113729. float **in,int *nonzero,int ch){
  113730. int i,used=0;
  113731. for(i=0;i<ch;i++)
  113732. if(nonzero[i])
  113733. in[used++]=in[i];
  113734. if(used)
  113735. return(_01class(vb,vl,in,used));
  113736. else
  113737. return(0);
  113738. }
  113739. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  113740. float **in,int *nonzero,int ch){
  113741. int i,used=0;
  113742. for(i=0;i<ch;i++)
  113743. if(nonzero[i])
  113744. in[used++]=in[i];
  113745. if(used)
  113746. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  113747. else
  113748. return(0);
  113749. }
  113750. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  113751. float **in,int *nonzero,int ch){
  113752. int i,used=0;
  113753. for(i=0;i<ch;i++)
  113754. if(nonzero[i])used++;
  113755. if(used)
  113756. return(_2class(vb,vl,in,ch));
  113757. else
  113758. return(0);
  113759. }
  113760. /* res2 is slightly more different; all the channels are interleaved
  113761. into a single vector and encoded. */
  113762. int res2_forward(oggpack_buffer *opb,
  113763. vorbis_block *vb,vorbis_look_residue *vl,
  113764. float **in,float **out,int *nonzero,int ch,
  113765. long **partword){
  113766. long i,j,k,n=vb->pcmend/2,used=0;
  113767. /* don't duplicate the code; use a working vector hack for now and
  113768. reshape ourselves into a single channel res1 */
  113769. /* ugly; reallocs for each coupling pass :-( */
  113770. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  113771. for(i=0;i<ch;i++){
  113772. float *pcm=in[i];
  113773. if(nonzero[i])used++;
  113774. for(j=0,k=i;j<n;j++,k+=ch)
  113775. work[k]=pcm[j];
  113776. }
  113777. if(used){
  113778. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  113779. /* update the sofar vector */
  113780. if(out){
  113781. for(i=0;i<ch;i++){
  113782. float *pcm=in[i];
  113783. float *sofar=out[i];
  113784. for(j=0,k=i;j<n;j++,k+=ch)
  113785. sofar[j]+=pcm[j]-work[k];
  113786. }
  113787. }
  113788. return(ret);
  113789. }else{
  113790. return(0);
  113791. }
  113792. }
  113793. /* duplicate code here as speed is somewhat more important */
  113794. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  113795. float **in,int *nonzero,int ch){
  113796. long i,k,l,s;
  113797. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113798. vorbis_info_residue0 *info=look->info;
  113799. /* move all this setup out later */
  113800. int samples_per_partition=info->grouping;
  113801. int partitions_per_word=look->phrasebook->dim;
  113802. int n=info->end-info->begin;
  113803. int partvals=n/samples_per_partition;
  113804. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  113805. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  113806. for(i=0;i<ch;i++)if(nonzero[i])break;
  113807. if(i==ch)return(0); /* no nonzero vectors */
  113808. for(s=0;s<look->stages;s++){
  113809. for(i=0,l=0;i<partvals;l++){
  113810. if(s==0){
  113811. /* fetch the partition word */
  113812. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  113813. if(temp==-1)goto eopbreak;
  113814. partword[l]=look->decodemap[temp];
  113815. if(partword[l]==NULL)goto errout;
  113816. }
  113817. /* now we decode residual values for the partitions */
  113818. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  113819. if(info->secondstages[partword[l][k]]&(1<<s)){
  113820. codebook *stagebook=look->partbooks[partword[l][k]][s];
  113821. if(stagebook){
  113822. if(vorbis_book_decodevv_add(stagebook,in,
  113823. i*samples_per_partition+info->begin,ch,
  113824. &vb->opb,samples_per_partition)==-1)
  113825. goto eopbreak;
  113826. }
  113827. }
  113828. }
  113829. }
  113830. errout:
  113831. eopbreak:
  113832. return(0);
  113833. }
  113834. vorbis_func_residue residue0_exportbundle={
  113835. NULL,
  113836. &res0_unpack,
  113837. &res0_look,
  113838. &res0_free_info,
  113839. &res0_free_look,
  113840. NULL,
  113841. NULL,
  113842. &res0_inverse
  113843. };
  113844. vorbis_func_residue residue1_exportbundle={
  113845. &res0_pack,
  113846. &res0_unpack,
  113847. &res0_look,
  113848. &res0_free_info,
  113849. &res0_free_look,
  113850. &res1_class,
  113851. &res1_forward,
  113852. &res1_inverse
  113853. };
  113854. vorbis_func_residue residue2_exportbundle={
  113855. &res0_pack,
  113856. &res0_unpack,
  113857. &res0_look,
  113858. &res0_free_info,
  113859. &res0_free_look,
  113860. &res2_class,
  113861. &res2_forward,
  113862. &res2_inverse
  113863. };
  113864. #endif
  113865. /********* End of inlined file: res0.c *********/
  113866. /********* Start of inlined file: sharedbook.c *********/
  113867. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113868. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113869. // tasks..
  113870. #ifdef _MSC_VER
  113871. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113872. #endif
  113873. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113874. #if JUCE_USE_OGGVORBIS
  113875. #include <stdlib.h>
  113876. #include <math.h>
  113877. #include <string.h>
  113878. /**** pack/unpack helpers ******************************************/
  113879. int _ilog(unsigned int v){
  113880. int ret=0;
  113881. while(v){
  113882. ret++;
  113883. v>>=1;
  113884. }
  113885. return(ret);
  113886. }
  113887. /* 32 bit float (not IEEE; nonnormalized mantissa +
  113888. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  113889. Why not IEEE? It's just not that important here. */
  113890. #define VQ_FEXP 10
  113891. #define VQ_FMAN 21
  113892. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  113893. /* doesn't currently guard under/overflow */
  113894. long _float32_pack(float val){
  113895. int sign=0;
  113896. long exp;
  113897. long mant;
  113898. if(val<0){
  113899. sign=0x80000000;
  113900. val= -val;
  113901. }
  113902. exp= floor(log(val)/log(2.f));
  113903. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  113904. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  113905. return(sign|exp|mant);
  113906. }
  113907. float _float32_unpack(long val){
  113908. double mant=val&0x1fffff;
  113909. int sign=val&0x80000000;
  113910. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  113911. if(sign)mant= -mant;
  113912. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  113913. }
  113914. /* given a list of word lengths, generate a list of codewords. Works
  113915. for length ordered or unordered, always assigns the lowest valued
  113916. codewords first. Extended to handle unused entries (length 0) */
  113917. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  113918. long i,j,count=0;
  113919. ogg_uint32_t marker[33];
  113920. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  113921. memset(marker,0,sizeof(marker));
  113922. for(i=0;i<n;i++){
  113923. long length=l[i];
  113924. if(length>0){
  113925. ogg_uint32_t entry=marker[length];
  113926. /* when we claim a node for an entry, we also claim the nodes
  113927. below it (pruning off the imagined tree that may have dangled
  113928. from it) as well as blocking the use of any nodes directly
  113929. above for leaves */
  113930. /* update ourself */
  113931. if(length<32 && (entry>>length)){
  113932. /* error condition; the lengths must specify an overpopulated tree */
  113933. _ogg_free(r);
  113934. return(NULL);
  113935. }
  113936. r[count++]=entry;
  113937. /* Look to see if the next shorter marker points to the node
  113938. above. if so, update it and repeat. */
  113939. {
  113940. for(j=length;j>0;j--){
  113941. if(marker[j]&1){
  113942. /* have to jump branches */
  113943. if(j==1)
  113944. marker[1]++;
  113945. else
  113946. marker[j]=marker[j-1]<<1;
  113947. break; /* invariant says next upper marker would already
  113948. have been moved if it was on the same path */
  113949. }
  113950. marker[j]++;
  113951. }
  113952. }
  113953. /* prune the tree; the implicit invariant says all the longer
  113954. markers were dangling from our just-taken node. Dangle them
  113955. from our *new* node. */
  113956. for(j=length+1;j<33;j++)
  113957. if((marker[j]>>1) == entry){
  113958. entry=marker[j];
  113959. marker[j]=marker[j-1]<<1;
  113960. }else
  113961. break;
  113962. }else
  113963. if(sparsecount==0)count++;
  113964. }
  113965. /* bitreverse the words because our bitwise packer/unpacker is LSb
  113966. endian */
  113967. for(i=0,count=0;i<n;i++){
  113968. ogg_uint32_t temp=0;
  113969. for(j=0;j<l[i];j++){
  113970. temp<<=1;
  113971. temp|=(r[count]>>j)&1;
  113972. }
  113973. if(sparsecount){
  113974. if(l[i])
  113975. r[count++]=temp;
  113976. }else
  113977. r[count++]=temp;
  113978. }
  113979. return(r);
  113980. }
  113981. /* there might be a straightforward one-line way to do the below
  113982. that's portable and totally safe against roundoff, but I haven't
  113983. thought of it. Therefore, we opt on the side of caution */
  113984. long _book_maptype1_quantvals(const static_codebook *b){
  113985. long vals=floor(pow((float)b->entries,1.f/b->dim));
  113986. /* the above *should* be reliable, but we'll not assume that FP is
  113987. ever reliable when bitstream sync is at stake; verify via integer
  113988. means that vals really is the greatest value of dim for which
  113989. vals^b->bim <= b->entries */
  113990. /* treat the above as an initial guess */
  113991. while(1){
  113992. long acc=1;
  113993. long acc1=1;
  113994. int i;
  113995. for(i=0;i<b->dim;i++){
  113996. acc*=vals;
  113997. acc1*=vals+1;
  113998. }
  113999. if(acc<=b->entries && acc1>b->entries){
  114000. return(vals);
  114001. }else{
  114002. if(acc>b->entries){
  114003. vals--;
  114004. }else{
  114005. vals++;
  114006. }
  114007. }
  114008. }
  114009. }
  114010. /* unpack the quantized list of values for encode/decode ***********/
  114011. /* we need to deal with two map types: in map type 1, the values are
  114012. generated algorithmically (each column of the vector counts through
  114013. the values in the quant vector). in map type 2, all the values came
  114014. in in an explicit list. Both value lists must be unpacked */
  114015. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  114016. long j,k,count=0;
  114017. if(b->maptype==1 || b->maptype==2){
  114018. int quantvals;
  114019. float mindel=_float32_unpack(b->q_min);
  114020. float delta=_float32_unpack(b->q_delta);
  114021. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  114022. /* maptype 1 and 2 both use a quantized value vector, but
  114023. different sizes */
  114024. switch(b->maptype){
  114025. case 1:
  114026. /* most of the time, entries%dimensions == 0, but we need to be
  114027. well defined. We define that the possible vales at each
  114028. scalar is values == entries/dim. If entries%dim != 0, we'll
  114029. have 'too few' values (values*dim<entries), which means that
  114030. we'll have 'left over' entries; left over entries use zeroed
  114031. values (and are wasted). So don't generate codebooks like
  114032. that */
  114033. quantvals=_book_maptype1_quantvals(b);
  114034. for(j=0;j<b->entries;j++){
  114035. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114036. float last=0.f;
  114037. int indexdiv=1;
  114038. for(k=0;k<b->dim;k++){
  114039. int index= (j/indexdiv)%quantvals;
  114040. float val=b->quantlist[index];
  114041. val=fabs(val)*delta+mindel+last;
  114042. if(b->q_sequencep)last=val;
  114043. if(sparsemap)
  114044. r[sparsemap[count]*b->dim+k]=val;
  114045. else
  114046. r[count*b->dim+k]=val;
  114047. indexdiv*=quantvals;
  114048. }
  114049. count++;
  114050. }
  114051. }
  114052. break;
  114053. case 2:
  114054. for(j=0;j<b->entries;j++){
  114055. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114056. float last=0.f;
  114057. for(k=0;k<b->dim;k++){
  114058. float val=b->quantlist[j*b->dim+k];
  114059. val=fabs(val)*delta+mindel+last;
  114060. if(b->q_sequencep)last=val;
  114061. if(sparsemap)
  114062. r[sparsemap[count]*b->dim+k]=val;
  114063. else
  114064. r[count*b->dim+k]=val;
  114065. }
  114066. count++;
  114067. }
  114068. }
  114069. break;
  114070. }
  114071. return(r);
  114072. }
  114073. return(NULL);
  114074. }
  114075. void vorbis_staticbook_clear(static_codebook *b){
  114076. if(b->allocedp){
  114077. if(b->quantlist)_ogg_free(b->quantlist);
  114078. if(b->lengthlist)_ogg_free(b->lengthlist);
  114079. if(b->nearest_tree){
  114080. _ogg_free(b->nearest_tree->ptr0);
  114081. _ogg_free(b->nearest_tree->ptr1);
  114082. _ogg_free(b->nearest_tree->p);
  114083. _ogg_free(b->nearest_tree->q);
  114084. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  114085. _ogg_free(b->nearest_tree);
  114086. }
  114087. if(b->thresh_tree){
  114088. _ogg_free(b->thresh_tree->quantthresh);
  114089. _ogg_free(b->thresh_tree->quantmap);
  114090. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  114091. _ogg_free(b->thresh_tree);
  114092. }
  114093. memset(b,0,sizeof(*b));
  114094. }
  114095. }
  114096. void vorbis_staticbook_destroy(static_codebook *b){
  114097. if(b->allocedp){
  114098. vorbis_staticbook_clear(b);
  114099. _ogg_free(b);
  114100. }
  114101. }
  114102. void vorbis_book_clear(codebook *b){
  114103. /* static book is not cleared; we're likely called on the lookup and
  114104. the static codebook belongs to the info struct */
  114105. if(b->valuelist)_ogg_free(b->valuelist);
  114106. if(b->codelist)_ogg_free(b->codelist);
  114107. if(b->dec_index)_ogg_free(b->dec_index);
  114108. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  114109. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  114110. memset(b,0,sizeof(*b));
  114111. }
  114112. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  114113. memset(c,0,sizeof(*c));
  114114. c->c=s;
  114115. c->entries=s->entries;
  114116. c->used_entries=s->entries;
  114117. c->dim=s->dim;
  114118. c->codelist=_make_words(s->lengthlist,s->entries,0);
  114119. c->valuelist=_book_unquantize(s,s->entries,NULL);
  114120. return(0);
  114121. }
  114122. static int sort32a(const void *a,const void *b){
  114123. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  114124. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  114125. }
  114126. /* decode codebook arrangement is more heavily optimized than encode */
  114127. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  114128. int i,j,n=0,tabn;
  114129. int *sortindex;
  114130. memset(c,0,sizeof(*c));
  114131. /* count actually used entries */
  114132. for(i=0;i<s->entries;i++)
  114133. if(s->lengthlist[i]>0)
  114134. n++;
  114135. c->entries=s->entries;
  114136. c->used_entries=n;
  114137. c->dim=s->dim;
  114138. /* two different remappings go on here.
  114139. First, we collapse the likely sparse codebook down only to
  114140. actually represented values/words. This collapsing needs to be
  114141. indexed as map-valueless books are used to encode original entry
  114142. positions as integers.
  114143. Second, we reorder all vectors, including the entry index above,
  114144. by sorted bitreversed codeword to allow treeless decode. */
  114145. {
  114146. /* perform sort */
  114147. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  114148. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  114149. if(codes==NULL)goto err_out;
  114150. for(i=0;i<n;i++){
  114151. codes[i]=ogg_bitreverse(codes[i]);
  114152. codep[i]=codes+i;
  114153. }
  114154. qsort(codep,n,sizeof(*codep),sort32a);
  114155. sortindex=(int*)alloca(n*sizeof(*sortindex));
  114156. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  114157. /* the index is a reverse index */
  114158. for(i=0;i<n;i++){
  114159. int position=codep[i]-codes;
  114160. sortindex[position]=i;
  114161. }
  114162. for(i=0;i<n;i++)
  114163. c->codelist[sortindex[i]]=codes[i];
  114164. _ogg_free(codes);
  114165. }
  114166. c->valuelist=_book_unquantize(s,n,sortindex);
  114167. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  114168. for(n=0,i=0;i<s->entries;i++)
  114169. if(s->lengthlist[i]>0)
  114170. c->dec_index[sortindex[n++]]=i;
  114171. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  114172. for(n=0,i=0;i<s->entries;i++)
  114173. if(s->lengthlist[i]>0)
  114174. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  114175. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  114176. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  114177. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  114178. tabn=1<<c->dec_firsttablen;
  114179. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  114180. c->dec_maxlength=0;
  114181. for(i=0;i<n;i++){
  114182. if(c->dec_maxlength<c->dec_codelengths[i])
  114183. c->dec_maxlength=c->dec_codelengths[i];
  114184. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  114185. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  114186. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  114187. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  114188. }
  114189. }
  114190. /* now fill in 'unused' entries in the firsttable with hi/lo search
  114191. hints for the non-direct-hits */
  114192. {
  114193. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  114194. long lo=0,hi=0;
  114195. for(i=0;i<tabn;i++){
  114196. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  114197. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  114198. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  114199. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  114200. /* we only actually have 15 bits per hint to play with here.
  114201. In order to overflow gracefully (nothing breaks, efficiency
  114202. just drops), encode as the difference from the extremes. */
  114203. {
  114204. unsigned long loval=lo;
  114205. unsigned long hival=n-hi;
  114206. if(loval>0x7fff)loval=0x7fff;
  114207. if(hival>0x7fff)hival=0x7fff;
  114208. c->dec_firsttable[ogg_bitreverse(word)]=
  114209. 0x80000000UL | (loval<<15) | hival;
  114210. }
  114211. }
  114212. }
  114213. }
  114214. return(0);
  114215. err_out:
  114216. vorbis_book_clear(c);
  114217. return(-1);
  114218. }
  114219. static float _dist(int el,float *ref, float *b,int step){
  114220. int i;
  114221. float acc=0.f;
  114222. for(i=0;i<el;i++){
  114223. float val=(ref[i]-b[i*step]);
  114224. acc+=val*val;
  114225. }
  114226. return(acc);
  114227. }
  114228. int _best(codebook *book, float *a, int step){
  114229. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114230. #if 0
  114231. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  114232. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  114233. #endif
  114234. int dim=book->dim;
  114235. int k,o;
  114236. /*int savebest=-1;
  114237. float saverr;*/
  114238. /* do we have a threshhold encode hint? */
  114239. if(tt){
  114240. int index=0,i;
  114241. /* find the quant val of each scalar */
  114242. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114243. i=tt->threshvals>>1;
  114244. if(a[o]<tt->quantthresh[i]){
  114245. for(;i>0;i--)
  114246. if(a[o]>=tt->quantthresh[i-1])
  114247. break;
  114248. }else{
  114249. for(i++;i<tt->threshvals-1;i++)
  114250. if(a[o]<tt->quantthresh[i])break;
  114251. }
  114252. index=(index*tt->quantvals)+tt->quantmap[i];
  114253. }
  114254. /* regular lattices are easy :-) */
  114255. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  114256. use a decision tree after all
  114257. and fall through*/
  114258. return(index);
  114259. }
  114260. #if 0
  114261. /* do we have a pigeonhole encode hint? */
  114262. if(pt){
  114263. const static_codebook *c=book->c;
  114264. int i,besti=-1;
  114265. float best=0.f;
  114266. int entry=0;
  114267. /* dealing with sequentialness is a pain in the ass */
  114268. if(c->q_sequencep){
  114269. int pv;
  114270. long mul=1;
  114271. float qlast=0;
  114272. for(k=0,o=0;k<dim;k++,o+=step){
  114273. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  114274. if(pv<0 || pv>=pt->mapentries)break;
  114275. entry+=pt->pigeonmap[pv]*mul;
  114276. mul*=pt->quantvals;
  114277. qlast+=pv*pt->del+pt->min;
  114278. }
  114279. }else{
  114280. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114281. int pv=(int)((a[o]-pt->min)/pt->del);
  114282. if(pv<0 || pv>=pt->mapentries)break;
  114283. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  114284. }
  114285. }
  114286. /* must be within the pigeonholable range; if we quant outside (or
  114287. in an entry that we define no list for), brute force it */
  114288. if(k==dim && pt->fitlength[entry]){
  114289. /* search the abbreviated list */
  114290. long *list=pt->fitlist+pt->fitmap[entry];
  114291. for(i=0;i<pt->fitlength[entry];i++){
  114292. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  114293. if(besti==-1 || this<best){
  114294. best=this;
  114295. besti=list[i];
  114296. }
  114297. }
  114298. return(besti);
  114299. }
  114300. }
  114301. if(nt){
  114302. /* optimized using the decision tree */
  114303. while(1){
  114304. float c=0.f;
  114305. float *p=book->valuelist+nt->p[ptr];
  114306. float *q=book->valuelist+nt->q[ptr];
  114307. for(k=0,o=0;k<dim;k++,o+=step)
  114308. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  114309. if(c>0.f) /* in A */
  114310. ptr= -nt->ptr0[ptr];
  114311. else /* in B */
  114312. ptr= -nt->ptr1[ptr];
  114313. if(ptr<=0)break;
  114314. }
  114315. return(-ptr);
  114316. }
  114317. #endif
  114318. /* brute force it! */
  114319. {
  114320. const static_codebook *c=book->c;
  114321. int i,besti=-1;
  114322. float best=0.f;
  114323. float *e=book->valuelist;
  114324. for(i=0;i<book->entries;i++){
  114325. if(c->lengthlist[i]>0){
  114326. float thisx=_dist(dim,e,a,step);
  114327. if(besti==-1 || thisx<best){
  114328. best=thisx;
  114329. besti=i;
  114330. }
  114331. }
  114332. e+=dim;
  114333. }
  114334. /*if(savebest!=-1 && savebest!=besti){
  114335. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  114336. "original:");
  114337. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  114338. fprintf(stderr,"\n"
  114339. "pigeonhole (entry %d, err %g):",savebest,saverr);
  114340. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114341. (book->valuelist+savebest*dim)[i]);
  114342. fprintf(stderr,"\n"
  114343. "bruteforce (entry %d, err %g):",besti,best);
  114344. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114345. (book->valuelist+besti*dim)[i]);
  114346. fprintf(stderr,"\n");
  114347. }*/
  114348. return(besti);
  114349. }
  114350. }
  114351. long vorbis_book_codeword(codebook *book,int entry){
  114352. if(book->c) /* only use with encode; decode optimizations are
  114353. allowed to break this */
  114354. return book->codelist[entry];
  114355. return -1;
  114356. }
  114357. long vorbis_book_codelen(codebook *book,int entry){
  114358. if(book->c) /* only use with encode; decode optimizations are
  114359. allowed to break this */
  114360. return book->c->lengthlist[entry];
  114361. return -1;
  114362. }
  114363. #ifdef _V_SELFTEST
  114364. /* Unit tests of the dequantizer; this stuff will be OK
  114365. cross-platform, I simply want to be sure that special mapping cases
  114366. actually work properly; a bug could go unnoticed for a while */
  114367. #include <stdio.h>
  114368. /* cases:
  114369. no mapping
  114370. full, explicit mapping
  114371. algorithmic mapping
  114372. nonsequential
  114373. sequential
  114374. */
  114375. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  114376. static long partial_quantlist1[]={0,7,2};
  114377. /* no mapping */
  114378. static_codebook test1={
  114379. 4,16,
  114380. NULL,
  114381. 0,
  114382. 0,0,0,0,
  114383. NULL,
  114384. NULL,NULL
  114385. };
  114386. static float *test1_result=NULL;
  114387. /* linear, full mapping, nonsequential */
  114388. static_codebook test2={
  114389. 4,3,
  114390. NULL,
  114391. 2,
  114392. -533200896,1611661312,4,0,
  114393. full_quantlist1,
  114394. NULL,NULL
  114395. };
  114396. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  114397. /* linear, full mapping, sequential */
  114398. static_codebook test3={
  114399. 4,3,
  114400. NULL,
  114401. 2,
  114402. -533200896,1611661312,4,1,
  114403. full_quantlist1,
  114404. NULL,NULL
  114405. };
  114406. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  114407. /* linear, algorithmic mapping, nonsequential */
  114408. static_codebook test4={
  114409. 3,27,
  114410. NULL,
  114411. 1,
  114412. -533200896,1611661312,4,0,
  114413. partial_quantlist1,
  114414. NULL,NULL
  114415. };
  114416. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  114417. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  114418. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  114419. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  114420. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  114421. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  114422. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  114423. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  114424. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  114425. /* linear, algorithmic mapping, sequential */
  114426. static_codebook test5={
  114427. 3,27,
  114428. NULL,
  114429. 1,
  114430. -533200896,1611661312,4,1,
  114431. partial_quantlist1,
  114432. NULL,NULL
  114433. };
  114434. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  114435. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  114436. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  114437. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  114438. -3, 1, 5, 4, 8,12, -1, 3, 7,
  114439. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  114440. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  114441. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  114442. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  114443. void run_test(static_codebook *b,float *comp){
  114444. float *out=_book_unquantize(b,b->entries,NULL);
  114445. int i;
  114446. if(comp){
  114447. if(!out){
  114448. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  114449. exit(1);
  114450. }
  114451. for(i=0;i<b->entries*b->dim;i++)
  114452. if(fabs(out[i]-comp[i])>.0001){
  114453. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  114454. "position %d, %g != %g\n",i,out[i],comp[i]);
  114455. exit(1);
  114456. }
  114457. }else{
  114458. if(out){
  114459. fprintf(stderr,"_book_unquantize returned a value array: \n"
  114460. " correct result should have been NULL\n");
  114461. exit(1);
  114462. }
  114463. }
  114464. }
  114465. int main(){
  114466. /* run the nine dequant tests, and compare to the hand-rolled results */
  114467. fprintf(stderr,"Dequant test 1... ");
  114468. run_test(&test1,test1_result);
  114469. fprintf(stderr,"OK\nDequant test 2... ");
  114470. run_test(&test2,test2_result);
  114471. fprintf(stderr,"OK\nDequant test 3... ");
  114472. run_test(&test3,test3_result);
  114473. fprintf(stderr,"OK\nDequant test 4... ");
  114474. run_test(&test4,test4_result);
  114475. fprintf(stderr,"OK\nDequant test 5... ");
  114476. run_test(&test5,test5_result);
  114477. fprintf(stderr,"OK\n\n");
  114478. return(0);
  114479. }
  114480. #endif
  114481. #endif
  114482. /********* End of inlined file: sharedbook.c *********/
  114483. /********* Start of inlined file: smallft.c *********/
  114484. /* FFT implementation from OggSquish, minus cosine transforms,
  114485. * minus all but radix 2/4 case. In Vorbis we only need this
  114486. * cut-down version.
  114487. *
  114488. * To do more than just power-of-two sized vectors, see the full
  114489. * version I wrote for NetLib.
  114490. *
  114491. * Note that the packing is a little strange; rather than the FFT r/i
  114492. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  114493. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  114494. * FORTRAN version
  114495. */
  114496. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114497. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114498. // tasks..
  114499. #ifdef _MSC_VER
  114500. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114501. #endif
  114502. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114503. #if JUCE_USE_OGGVORBIS
  114504. #include <stdlib.h>
  114505. #include <string.h>
  114506. #include <math.h>
  114507. static void drfti1(int n, float *wa, int *ifac){
  114508. static int ntryh[4] = { 4,2,3,5 };
  114509. static float tpi = 6.28318530717958648f;
  114510. float arg,argh,argld,fi;
  114511. int ntry=0,i,j=-1;
  114512. int k1, l1, l2, ib;
  114513. int ld, ii, ip, is, nq, nr;
  114514. int ido, ipm, nfm1;
  114515. int nl=n;
  114516. int nf=0;
  114517. L101:
  114518. j++;
  114519. if (j < 4)
  114520. ntry=ntryh[j];
  114521. else
  114522. ntry+=2;
  114523. L104:
  114524. nq=nl/ntry;
  114525. nr=nl-ntry*nq;
  114526. if (nr!=0) goto L101;
  114527. nf++;
  114528. ifac[nf+1]=ntry;
  114529. nl=nq;
  114530. if(ntry!=2)goto L107;
  114531. if(nf==1)goto L107;
  114532. for (i=1;i<nf;i++){
  114533. ib=nf-i+1;
  114534. ifac[ib+1]=ifac[ib];
  114535. }
  114536. ifac[2] = 2;
  114537. L107:
  114538. if(nl!=1)goto L104;
  114539. ifac[0]=n;
  114540. ifac[1]=nf;
  114541. argh=tpi/n;
  114542. is=0;
  114543. nfm1=nf-1;
  114544. l1=1;
  114545. if(nfm1==0)return;
  114546. for (k1=0;k1<nfm1;k1++){
  114547. ip=ifac[k1+2];
  114548. ld=0;
  114549. l2=l1*ip;
  114550. ido=n/l2;
  114551. ipm=ip-1;
  114552. for (j=0;j<ipm;j++){
  114553. ld+=l1;
  114554. i=is;
  114555. argld=(float)ld*argh;
  114556. fi=0.f;
  114557. for (ii=2;ii<ido;ii+=2){
  114558. fi+=1.f;
  114559. arg=fi*argld;
  114560. wa[i++]=cos(arg);
  114561. wa[i++]=sin(arg);
  114562. }
  114563. is+=ido;
  114564. }
  114565. l1=l2;
  114566. }
  114567. }
  114568. static void fdrffti(int n, float *wsave, int *ifac){
  114569. if (n == 1) return;
  114570. drfti1(n, wsave+n, ifac);
  114571. }
  114572. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  114573. int i,k;
  114574. float ti2,tr2;
  114575. int t0,t1,t2,t3,t4,t5,t6;
  114576. t1=0;
  114577. t0=(t2=l1*ido);
  114578. t3=ido<<1;
  114579. for(k=0;k<l1;k++){
  114580. ch[t1<<1]=cc[t1]+cc[t2];
  114581. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  114582. t1+=ido;
  114583. t2+=ido;
  114584. }
  114585. if(ido<2)return;
  114586. if(ido==2)goto L105;
  114587. t1=0;
  114588. t2=t0;
  114589. for(k=0;k<l1;k++){
  114590. t3=t2;
  114591. t4=(t1<<1)+(ido<<1);
  114592. t5=t1;
  114593. t6=t1+t1;
  114594. for(i=2;i<ido;i+=2){
  114595. t3+=2;
  114596. t4-=2;
  114597. t5+=2;
  114598. t6+=2;
  114599. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  114600. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  114601. ch[t6]=cc[t5]+ti2;
  114602. ch[t4]=ti2-cc[t5];
  114603. ch[t6-1]=cc[t5-1]+tr2;
  114604. ch[t4-1]=cc[t5-1]-tr2;
  114605. }
  114606. t1+=ido;
  114607. t2+=ido;
  114608. }
  114609. if(ido%2==1)return;
  114610. L105:
  114611. t3=(t2=(t1=ido)-1);
  114612. t2+=t0;
  114613. for(k=0;k<l1;k++){
  114614. ch[t1]=-cc[t2];
  114615. ch[t1-1]=cc[t3];
  114616. t1+=ido<<1;
  114617. t2+=ido;
  114618. t3+=ido;
  114619. }
  114620. }
  114621. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  114622. float *wa2,float *wa3){
  114623. static float hsqt2 = .70710678118654752f;
  114624. int i,k,t0,t1,t2,t3,t4,t5,t6;
  114625. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  114626. t0=l1*ido;
  114627. t1=t0;
  114628. t4=t1<<1;
  114629. t2=t1+(t1<<1);
  114630. t3=0;
  114631. for(k=0;k<l1;k++){
  114632. tr1=cc[t1]+cc[t2];
  114633. tr2=cc[t3]+cc[t4];
  114634. ch[t5=t3<<2]=tr1+tr2;
  114635. ch[(ido<<2)+t5-1]=tr2-tr1;
  114636. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  114637. ch[t5]=cc[t2]-cc[t1];
  114638. t1+=ido;
  114639. t2+=ido;
  114640. t3+=ido;
  114641. t4+=ido;
  114642. }
  114643. if(ido<2)return;
  114644. if(ido==2)goto L105;
  114645. t1=0;
  114646. for(k=0;k<l1;k++){
  114647. t2=t1;
  114648. t4=t1<<2;
  114649. t5=(t6=ido<<1)+t4;
  114650. for(i=2;i<ido;i+=2){
  114651. t3=(t2+=2);
  114652. t4+=2;
  114653. t5-=2;
  114654. t3+=t0;
  114655. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  114656. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  114657. t3+=t0;
  114658. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  114659. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  114660. t3+=t0;
  114661. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  114662. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  114663. tr1=cr2+cr4;
  114664. tr4=cr4-cr2;
  114665. ti1=ci2+ci4;
  114666. ti4=ci2-ci4;
  114667. ti2=cc[t2]+ci3;
  114668. ti3=cc[t2]-ci3;
  114669. tr2=cc[t2-1]+cr3;
  114670. tr3=cc[t2-1]-cr3;
  114671. ch[t4-1]=tr1+tr2;
  114672. ch[t4]=ti1+ti2;
  114673. ch[t5-1]=tr3-ti4;
  114674. ch[t5]=tr4-ti3;
  114675. ch[t4+t6-1]=ti4+tr3;
  114676. ch[t4+t6]=tr4+ti3;
  114677. ch[t5+t6-1]=tr2-tr1;
  114678. ch[t5+t6]=ti1-ti2;
  114679. }
  114680. t1+=ido;
  114681. }
  114682. if(ido&1)return;
  114683. L105:
  114684. t2=(t1=t0+ido-1)+(t0<<1);
  114685. t3=ido<<2;
  114686. t4=ido;
  114687. t5=ido<<1;
  114688. t6=ido;
  114689. for(k=0;k<l1;k++){
  114690. ti1=-hsqt2*(cc[t1]+cc[t2]);
  114691. tr1=hsqt2*(cc[t1]-cc[t2]);
  114692. ch[t4-1]=tr1+cc[t6-1];
  114693. ch[t4+t5-1]=cc[t6-1]-tr1;
  114694. ch[t4]=ti1-cc[t1+t0];
  114695. ch[t4+t5]=ti1+cc[t1+t0];
  114696. t1+=ido;
  114697. t2+=ido;
  114698. t4+=t3;
  114699. t6+=ido;
  114700. }
  114701. }
  114702. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  114703. float *c2,float *ch,float *ch2,float *wa){
  114704. static float tpi=6.283185307179586f;
  114705. int idij,ipph,i,j,k,l,ic,ik,is;
  114706. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  114707. float dc2,ai1,ai2,ar1,ar2,ds2;
  114708. int nbd;
  114709. float dcp,arg,dsp,ar1h,ar2h;
  114710. int idp2,ipp2;
  114711. arg=tpi/(float)ip;
  114712. dcp=cos(arg);
  114713. dsp=sin(arg);
  114714. ipph=(ip+1)>>1;
  114715. ipp2=ip;
  114716. idp2=ido;
  114717. nbd=(ido-1)>>1;
  114718. t0=l1*ido;
  114719. t10=ip*ido;
  114720. if(ido==1)goto L119;
  114721. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  114722. t1=0;
  114723. for(j=1;j<ip;j++){
  114724. t1+=t0;
  114725. t2=t1;
  114726. for(k=0;k<l1;k++){
  114727. ch[t2]=c1[t2];
  114728. t2+=ido;
  114729. }
  114730. }
  114731. is=-ido;
  114732. t1=0;
  114733. if(nbd>l1){
  114734. for(j=1;j<ip;j++){
  114735. t1+=t0;
  114736. is+=ido;
  114737. t2= -ido+t1;
  114738. for(k=0;k<l1;k++){
  114739. idij=is-1;
  114740. t2+=ido;
  114741. t3=t2;
  114742. for(i=2;i<ido;i+=2){
  114743. idij+=2;
  114744. t3+=2;
  114745. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  114746. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  114747. }
  114748. }
  114749. }
  114750. }else{
  114751. for(j=1;j<ip;j++){
  114752. is+=ido;
  114753. idij=is-1;
  114754. t1+=t0;
  114755. t2=t1;
  114756. for(i=2;i<ido;i+=2){
  114757. idij+=2;
  114758. t2+=2;
  114759. t3=t2;
  114760. for(k=0;k<l1;k++){
  114761. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  114762. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  114763. t3+=ido;
  114764. }
  114765. }
  114766. }
  114767. }
  114768. t1=0;
  114769. t2=ipp2*t0;
  114770. if(nbd<l1){
  114771. for(j=1;j<ipph;j++){
  114772. t1+=t0;
  114773. t2-=t0;
  114774. t3=t1;
  114775. t4=t2;
  114776. for(i=2;i<ido;i+=2){
  114777. t3+=2;
  114778. t4+=2;
  114779. t5=t3-ido;
  114780. t6=t4-ido;
  114781. for(k=0;k<l1;k++){
  114782. t5+=ido;
  114783. t6+=ido;
  114784. c1[t5-1]=ch[t5-1]+ch[t6-1];
  114785. c1[t6-1]=ch[t5]-ch[t6];
  114786. c1[t5]=ch[t5]+ch[t6];
  114787. c1[t6]=ch[t6-1]-ch[t5-1];
  114788. }
  114789. }
  114790. }
  114791. }else{
  114792. for(j=1;j<ipph;j++){
  114793. t1+=t0;
  114794. t2-=t0;
  114795. t3=t1;
  114796. t4=t2;
  114797. for(k=0;k<l1;k++){
  114798. t5=t3;
  114799. t6=t4;
  114800. for(i=2;i<ido;i+=2){
  114801. t5+=2;
  114802. t6+=2;
  114803. c1[t5-1]=ch[t5-1]+ch[t6-1];
  114804. c1[t6-1]=ch[t5]-ch[t6];
  114805. c1[t5]=ch[t5]+ch[t6];
  114806. c1[t6]=ch[t6-1]-ch[t5-1];
  114807. }
  114808. t3+=ido;
  114809. t4+=ido;
  114810. }
  114811. }
  114812. }
  114813. L119:
  114814. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  114815. t1=0;
  114816. t2=ipp2*idl1;
  114817. for(j=1;j<ipph;j++){
  114818. t1+=t0;
  114819. t2-=t0;
  114820. t3=t1-ido;
  114821. t4=t2-ido;
  114822. for(k=0;k<l1;k++){
  114823. t3+=ido;
  114824. t4+=ido;
  114825. c1[t3]=ch[t3]+ch[t4];
  114826. c1[t4]=ch[t4]-ch[t3];
  114827. }
  114828. }
  114829. ar1=1.f;
  114830. ai1=0.f;
  114831. t1=0;
  114832. t2=ipp2*idl1;
  114833. t3=(ip-1)*idl1;
  114834. for(l=1;l<ipph;l++){
  114835. t1+=idl1;
  114836. t2-=idl1;
  114837. ar1h=dcp*ar1-dsp*ai1;
  114838. ai1=dcp*ai1+dsp*ar1;
  114839. ar1=ar1h;
  114840. t4=t1;
  114841. t5=t2;
  114842. t6=t3;
  114843. t7=idl1;
  114844. for(ik=0;ik<idl1;ik++){
  114845. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  114846. ch2[t5++]=ai1*c2[t6++];
  114847. }
  114848. dc2=ar1;
  114849. ds2=ai1;
  114850. ar2=ar1;
  114851. ai2=ai1;
  114852. t4=idl1;
  114853. t5=(ipp2-1)*idl1;
  114854. for(j=2;j<ipph;j++){
  114855. t4+=idl1;
  114856. t5-=idl1;
  114857. ar2h=dc2*ar2-ds2*ai2;
  114858. ai2=dc2*ai2+ds2*ar2;
  114859. ar2=ar2h;
  114860. t6=t1;
  114861. t7=t2;
  114862. t8=t4;
  114863. t9=t5;
  114864. for(ik=0;ik<idl1;ik++){
  114865. ch2[t6++]+=ar2*c2[t8++];
  114866. ch2[t7++]+=ai2*c2[t9++];
  114867. }
  114868. }
  114869. }
  114870. t1=0;
  114871. for(j=1;j<ipph;j++){
  114872. t1+=idl1;
  114873. t2=t1;
  114874. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  114875. }
  114876. if(ido<l1)goto L132;
  114877. t1=0;
  114878. t2=0;
  114879. for(k=0;k<l1;k++){
  114880. t3=t1;
  114881. t4=t2;
  114882. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  114883. t1+=ido;
  114884. t2+=t10;
  114885. }
  114886. goto L135;
  114887. L132:
  114888. for(i=0;i<ido;i++){
  114889. t1=i;
  114890. t2=i;
  114891. for(k=0;k<l1;k++){
  114892. cc[t2]=ch[t1];
  114893. t1+=ido;
  114894. t2+=t10;
  114895. }
  114896. }
  114897. L135:
  114898. t1=0;
  114899. t2=ido<<1;
  114900. t3=0;
  114901. t4=ipp2*t0;
  114902. for(j=1;j<ipph;j++){
  114903. t1+=t2;
  114904. t3+=t0;
  114905. t4-=t0;
  114906. t5=t1;
  114907. t6=t3;
  114908. t7=t4;
  114909. for(k=0;k<l1;k++){
  114910. cc[t5-1]=ch[t6];
  114911. cc[t5]=ch[t7];
  114912. t5+=t10;
  114913. t6+=ido;
  114914. t7+=ido;
  114915. }
  114916. }
  114917. if(ido==1)return;
  114918. if(nbd<l1)goto L141;
  114919. t1=-ido;
  114920. t3=0;
  114921. t4=0;
  114922. t5=ipp2*t0;
  114923. for(j=1;j<ipph;j++){
  114924. t1+=t2;
  114925. t3+=t2;
  114926. t4+=t0;
  114927. t5-=t0;
  114928. t6=t1;
  114929. t7=t3;
  114930. t8=t4;
  114931. t9=t5;
  114932. for(k=0;k<l1;k++){
  114933. for(i=2;i<ido;i+=2){
  114934. ic=idp2-i;
  114935. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  114936. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  114937. cc[i+t7]=ch[i+t8]+ch[i+t9];
  114938. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  114939. }
  114940. t6+=t10;
  114941. t7+=t10;
  114942. t8+=ido;
  114943. t9+=ido;
  114944. }
  114945. }
  114946. return;
  114947. L141:
  114948. t1=-ido;
  114949. t3=0;
  114950. t4=0;
  114951. t5=ipp2*t0;
  114952. for(j=1;j<ipph;j++){
  114953. t1+=t2;
  114954. t3+=t2;
  114955. t4+=t0;
  114956. t5-=t0;
  114957. for(i=2;i<ido;i+=2){
  114958. t6=idp2+t1-i;
  114959. t7=i+t3;
  114960. t8=i+t4;
  114961. t9=i+t5;
  114962. for(k=0;k<l1;k++){
  114963. cc[t7-1]=ch[t8-1]+ch[t9-1];
  114964. cc[t6-1]=ch[t8-1]-ch[t9-1];
  114965. cc[t7]=ch[t8]+ch[t9];
  114966. cc[t6]=ch[t9]-ch[t8];
  114967. t6+=t10;
  114968. t7+=t10;
  114969. t8+=ido;
  114970. t9+=ido;
  114971. }
  114972. }
  114973. }
  114974. }
  114975. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  114976. int i,k1,l1,l2;
  114977. int na,kh,nf;
  114978. int ip,iw,ido,idl1,ix2,ix3;
  114979. nf=ifac[1];
  114980. na=1;
  114981. l2=n;
  114982. iw=n;
  114983. for(k1=0;k1<nf;k1++){
  114984. kh=nf-k1;
  114985. ip=ifac[kh+1];
  114986. l1=l2/ip;
  114987. ido=n/l2;
  114988. idl1=ido*l1;
  114989. iw-=(ip-1)*ido;
  114990. na=1-na;
  114991. if(ip!=4)goto L102;
  114992. ix2=iw+ido;
  114993. ix3=ix2+ido;
  114994. if(na!=0)
  114995. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114996. else
  114997. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114998. goto L110;
  114999. L102:
  115000. if(ip!=2)goto L104;
  115001. if(na!=0)goto L103;
  115002. dradf2(ido,l1,c,ch,wa+iw-1);
  115003. goto L110;
  115004. L103:
  115005. dradf2(ido,l1,ch,c,wa+iw-1);
  115006. goto L110;
  115007. L104:
  115008. if(ido==1)na=1-na;
  115009. if(na!=0)goto L109;
  115010. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  115011. na=1;
  115012. goto L110;
  115013. L109:
  115014. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  115015. na=0;
  115016. L110:
  115017. l2=l1;
  115018. }
  115019. if(na==1)return;
  115020. for(i=0;i<n;i++)c[i]=ch[i];
  115021. }
  115022. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  115023. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115024. float ti2,tr2;
  115025. t0=l1*ido;
  115026. t1=0;
  115027. t2=0;
  115028. t3=(ido<<1)-1;
  115029. for(k=0;k<l1;k++){
  115030. ch[t1]=cc[t2]+cc[t3+t2];
  115031. ch[t1+t0]=cc[t2]-cc[t3+t2];
  115032. t2=(t1+=ido)<<1;
  115033. }
  115034. if(ido<2)return;
  115035. if(ido==2)goto L105;
  115036. t1=0;
  115037. t2=0;
  115038. for(k=0;k<l1;k++){
  115039. t3=t1;
  115040. t5=(t4=t2)+(ido<<1);
  115041. t6=t0+t1;
  115042. for(i=2;i<ido;i+=2){
  115043. t3+=2;
  115044. t4+=2;
  115045. t5-=2;
  115046. t6+=2;
  115047. ch[t3-1]=cc[t4-1]+cc[t5-1];
  115048. tr2=cc[t4-1]-cc[t5-1];
  115049. ch[t3]=cc[t4]-cc[t5];
  115050. ti2=cc[t4]+cc[t5];
  115051. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  115052. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  115053. }
  115054. t2=(t1+=ido)<<1;
  115055. }
  115056. if(ido%2==1)return;
  115057. L105:
  115058. t1=ido-1;
  115059. t2=ido-1;
  115060. for(k=0;k<l1;k++){
  115061. ch[t1]=cc[t2]+cc[t2];
  115062. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  115063. t1+=ido;
  115064. t2+=ido<<1;
  115065. }
  115066. }
  115067. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  115068. float *wa2){
  115069. static float taur = -.5f;
  115070. static float taui = .8660254037844386f;
  115071. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115072. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  115073. t0=l1*ido;
  115074. t1=0;
  115075. t2=t0<<1;
  115076. t3=ido<<1;
  115077. t4=ido+(ido<<1);
  115078. t5=0;
  115079. for(k=0;k<l1;k++){
  115080. tr2=cc[t3-1]+cc[t3-1];
  115081. cr2=cc[t5]+(taur*tr2);
  115082. ch[t1]=cc[t5]+tr2;
  115083. ci3=taui*(cc[t3]+cc[t3]);
  115084. ch[t1+t0]=cr2-ci3;
  115085. ch[t1+t2]=cr2+ci3;
  115086. t1+=ido;
  115087. t3+=t4;
  115088. t5+=t4;
  115089. }
  115090. if(ido==1)return;
  115091. t1=0;
  115092. t3=ido<<1;
  115093. for(k=0;k<l1;k++){
  115094. t7=t1+(t1<<1);
  115095. t6=(t5=t7+t3);
  115096. t8=t1;
  115097. t10=(t9=t1+t0)+t0;
  115098. for(i=2;i<ido;i+=2){
  115099. t5+=2;
  115100. t6-=2;
  115101. t7+=2;
  115102. t8+=2;
  115103. t9+=2;
  115104. t10+=2;
  115105. tr2=cc[t5-1]+cc[t6-1];
  115106. cr2=cc[t7-1]+(taur*tr2);
  115107. ch[t8-1]=cc[t7-1]+tr2;
  115108. ti2=cc[t5]-cc[t6];
  115109. ci2=cc[t7]+(taur*ti2);
  115110. ch[t8]=cc[t7]+ti2;
  115111. cr3=taui*(cc[t5-1]-cc[t6-1]);
  115112. ci3=taui*(cc[t5]+cc[t6]);
  115113. dr2=cr2-ci3;
  115114. dr3=cr2+ci3;
  115115. di2=ci2+cr3;
  115116. di3=ci2-cr3;
  115117. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  115118. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  115119. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  115120. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  115121. }
  115122. t1+=ido;
  115123. }
  115124. }
  115125. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  115126. float *wa2,float *wa3){
  115127. static float sqrt2=1.414213562373095f;
  115128. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  115129. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115130. t0=l1*ido;
  115131. t1=0;
  115132. t2=ido<<2;
  115133. t3=0;
  115134. t6=ido<<1;
  115135. for(k=0;k<l1;k++){
  115136. t4=t3+t6;
  115137. t5=t1;
  115138. tr3=cc[t4-1]+cc[t4-1];
  115139. tr4=cc[t4]+cc[t4];
  115140. tr1=cc[t3]-cc[(t4+=t6)-1];
  115141. tr2=cc[t3]+cc[t4-1];
  115142. ch[t5]=tr2+tr3;
  115143. ch[t5+=t0]=tr1-tr4;
  115144. ch[t5+=t0]=tr2-tr3;
  115145. ch[t5+=t0]=tr1+tr4;
  115146. t1+=ido;
  115147. t3+=t2;
  115148. }
  115149. if(ido<2)return;
  115150. if(ido==2)goto L105;
  115151. t1=0;
  115152. for(k=0;k<l1;k++){
  115153. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  115154. t7=t1;
  115155. for(i=2;i<ido;i+=2){
  115156. t2+=2;
  115157. t3+=2;
  115158. t4-=2;
  115159. t5-=2;
  115160. t7+=2;
  115161. ti1=cc[t2]+cc[t5];
  115162. ti2=cc[t2]-cc[t5];
  115163. ti3=cc[t3]-cc[t4];
  115164. tr4=cc[t3]+cc[t4];
  115165. tr1=cc[t2-1]-cc[t5-1];
  115166. tr2=cc[t2-1]+cc[t5-1];
  115167. ti4=cc[t3-1]-cc[t4-1];
  115168. tr3=cc[t3-1]+cc[t4-1];
  115169. ch[t7-1]=tr2+tr3;
  115170. cr3=tr2-tr3;
  115171. ch[t7]=ti2+ti3;
  115172. ci3=ti2-ti3;
  115173. cr2=tr1-tr4;
  115174. cr4=tr1+tr4;
  115175. ci2=ti1+ti4;
  115176. ci4=ti1-ti4;
  115177. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  115178. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  115179. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  115180. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  115181. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  115182. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  115183. }
  115184. t1+=ido;
  115185. }
  115186. if(ido%2 == 1)return;
  115187. L105:
  115188. t1=ido;
  115189. t2=ido<<2;
  115190. t3=ido-1;
  115191. t4=ido+(ido<<1);
  115192. for(k=0;k<l1;k++){
  115193. t5=t3;
  115194. ti1=cc[t1]+cc[t4];
  115195. ti2=cc[t4]-cc[t1];
  115196. tr1=cc[t1-1]-cc[t4-1];
  115197. tr2=cc[t1-1]+cc[t4-1];
  115198. ch[t5]=tr2+tr2;
  115199. ch[t5+=t0]=sqrt2*(tr1-ti1);
  115200. ch[t5+=t0]=ti2+ti2;
  115201. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  115202. t3+=ido;
  115203. t1+=t2;
  115204. t4+=t2;
  115205. }
  115206. }
  115207. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115208. float *c2,float *ch,float *ch2,float *wa){
  115209. static float tpi=6.283185307179586f;
  115210. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  115211. t11,t12;
  115212. float dc2,ai1,ai2,ar1,ar2,ds2;
  115213. int nbd;
  115214. float dcp,arg,dsp,ar1h,ar2h;
  115215. int ipp2;
  115216. t10=ip*ido;
  115217. t0=l1*ido;
  115218. arg=tpi/(float)ip;
  115219. dcp=cos(arg);
  115220. dsp=sin(arg);
  115221. nbd=(ido-1)>>1;
  115222. ipp2=ip;
  115223. ipph=(ip+1)>>1;
  115224. if(ido<l1)goto L103;
  115225. t1=0;
  115226. t2=0;
  115227. for(k=0;k<l1;k++){
  115228. t3=t1;
  115229. t4=t2;
  115230. for(i=0;i<ido;i++){
  115231. ch[t3]=cc[t4];
  115232. t3++;
  115233. t4++;
  115234. }
  115235. t1+=ido;
  115236. t2+=t10;
  115237. }
  115238. goto L106;
  115239. L103:
  115240. t1=0;
  115241. for(i=0;i<ido;i++){
  115242. t2=t1;
  115243. t3=t1;
  115244. for(k=0;k<l1;k++){
  115245. ch[t2]=cc[t3];
  115246. t2+=ido;
  115247. t3+=t10;
  115248. }
  115249. t1++;
  115250. }
  115251. L106:
  115252. t1=0;
  115253. t2=ipp2*t0;
  115254. t7=(t5=ido<<1);
  115255. for(j=1;j<ipph;j++){
  115256. t1+=t0;
  115257. t2-=t0;
  115258. t3=t1;
  115259. t4=t2;
  115260. t6=t5;
  115261. for(k=0;k<l1;k++){
  115262. ch[t3]=cc[t6-1]+cc[t6-1];
  115263. ch[t4]=cc[t6]+cc[t6];
  115264. t3+=ido;
  115265. t4+=ido;
  115266. t6+=t10;
  115267. }
  115268. t5+=t7;
  115269. }
  115270. if (ido == 1)goto L116;
  115271. if(nbd<l1)goto L112;
  115272. t1=0;
  115273. t2=ipp2*t0;
  115274. t7=0;
  115275. for(j=1;j<ipph;j++){
  115276. t1+=t0;
  115277. t2-=t0;
  115278. t3=t1;
  115279. t4=t2;
  115280. t7+=(ido<<1);
  115281. t8=t7;
  115282. for(k=0;k<l1;k++){
  115283. t5=t3;
  115284. t6=t4;
  115285. t9=t8;
  115286. t11=t8;
  115287. for(i=2;i<ido;i+=2){
  115288. t5+=2;
  115289. t6+=2;
  115290. t9+=2;
  115291. t11-=2;
  115292. ch[t5-1]=cc[t9-1]+cc[t11-1];
  115293. ch[t6-1]=cc[t9-1]-cc[t11-1];
  115294. ch[t5]=cc[t9]-cc[t11];
  115295. ch[t6]=cc[t9]+cc[t11];
  115296. }
  115297. t3+=ido;
  115298. t4+=ido;
  115299. t8+=t10;
  115300. }
  115301. }
  115302. goto L116;
  115303. L112:
  115304. t1=0;
  115305. t2=ipp2*t0;
  115306. t7=0;
  115307. for(j=1;j<ipph;j++){
  115308. t1+=t0;
  115309. t2-=t0;
  115310. t3=t1;
  115311. t4=t2;
  115312. t7+=(ido<<1);
  115313. t8=t7;
  115314. t9=t7;
  115315. for(i=2;i<ido;i+=2){
  115316. t3+=2;
  115317. t4+=2;
  115318. t8+=2;
  115319. t9-=2;
  115320. t5=t3;
  115321. t6=t4;
  115322. t11=t8;
  115323. t12=t9;
  115324. for(k=0;k<l1;k++){
  115325. ch[t5-1]=cc[t11-1]+cc[t12-1];
  115326. ch[t6-1]=cc[t11-1]-cc[t12-1];
  115327. ch[t5]=cc[t11]-cc[t12];
  115328. ch[t6]=cc[t11]+cc[t12];
  115329. t5+=ido;
  115330. t6+=ido;
  115331. t11+=t10;
  115332. t12+=t10;
  115333. }
  115334. }
  115335. }
  115336. L116:
  115337. ar1=1.f;
  115338. ai1=0.f;
  115339. t1=0;
  115340. t9=(t2=ipp2*idl1);
  115341. t3=(ip-1)*idl1;
  115342. for(l=1;l<ipph;l++){
  115343. t1+=idl1;
  115344. t2-=idl1;
  115345. ar1h=dcp*ar1-dsp*ai1;
  115346. ai1=dcp*ai1+dsp*ar1;
  115347. ar1=ar1h;
  115348. t4=t1;
  115349. t5=t2;
  115350. t6=0;
  115351. t7=idl1;
  115352. t8=t3;
  115353. for(ik=0;ik<idl1;ik++){
  115354. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  115355. c2[t5++]=ai1*ch2[t8++];
  115356. }
  115357. dc2=ar1;
  115358. ds2=ai1;
  115359. ar2=ar1;
  115360. ai2=ai1;
  115361. t6=idl1;
  115362. t7=t9-idl1;
  115363. for(j=2;j<ipph;j++){
  115364. t6+=idl1;
  115365. t7-=idl1;
  115366. ar2h=dc2*ar2-ds2*ai2;
  115367. ai2=dc2*ai2+ds2*ar2;
  115368. ar2=ar2h;
  115369. t4=t1;
  115370. t5=t2;
  115371. t11=t6;
  115372. t12=t7;
  115373. for(ik=0;ik<idl1;ik++){
  115374. c2[t4++]+=ar2*ch2[t11++];
  115375. c2[t5++]+=ai2*ch2[t12++];
  115376. }
  115377. }
  115378. }
  115379. t1=0;
  115380. for(j=1;j<ipph;j++){
  115381. t1+=idl1;
  115382. t2=t1;
  115383. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  115384. }
  115385. t1=0;
  115386. t2=ipp2*t0;
  115387. for(j=1;j<ipph;j++){
  115388. t1+=t0;
  115389. t2-=t0;
  115390. t3=t1;
  115391. t4=t2;
  115392. for(k=0;k<l1;k++){
  115393. ch[t3]=c1[t3]-c1[t4];
  115394. ch[t4]=c1[t3]+c1[t4];
  115395. t3+=ido;
  115396. t4+=ido;
  115397. }
  115398. }
  115399. if(ido==1)goto L132;
  115400. if(nbd<l1)goto L128;
  115401. t1=0;
  115402. t2=ipp2*t0;
  115403. for(j=1;j<ipph;j++){
  115404. t1+=t0;
  115405. t2-=t0;
  115406. t3=t1;
  115407. t4=t2;
  115408. for(k=0;k<l1;k++){
  115409. t5=t3;
  115410. t6=t4;
  115411. for(i=2;i<ido;i+=2){
  115412. t5+=2;
  115413. t6+=2;
  115414. ch[t5-1]=c1[t5-1]-c1[t6];
  115415. ch[t6-1]=c1[t5-1]+c1[t6];
  115416. ch[t5]=c1[t5]+c1[t6-1];
  115417. ch[t6]=c1[t5]-c1[t6-1];
  115418. }
  115419. t3+=ido;
  115420. t4+=ido;
  115421. }
  115422. }
  115423. goto L132;
  115424. L128:
  115425. t1=0;
  115426. t2=ipp2*t0;
  115427. for(j=1;j<ipph;j++){
  115428. t1+=t0;
  115429. t2-=t0;
  115430. t3=t1;
  115431. t4=t2;
  115432. for(i=2;i<ido;i+=2){
  115433. t3+=2;
  115434. t4+=2;
  115435. t5=t3;
  115436. t6=t4;
  115437. for(k=0;k<l1;k++){
  115438. ch[t5-1]=c1[t5-1]-c1[t6];
  115439. ch[t6-1]=c1[t5-1]+c1[t6];
  115440. ch[t5]=c1[t5]+c1[t6-1];
  115441. ch[t6]=c1[t5]-c1[t6-1];
  115442. t5+=ido;
  115443. t6+=ido;
  115444. }
  115445. }
  115446. }
  115447. L132:
  115448. if(ido==1)return;
  115449. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  115450. t1=0;
  115451. for(j=1;j<ip;j++){
  115452. t2=(t1+=t0);
  115453. for(k=0;k<l1;k++){
  115454. c1[t2]=ch[t2];
  115455. t2+=ido;
  115456. }
  115457. }
  115458. if(nbd>l1)goto L139;
  115459. is= -ido-1;
  115460. t1=0;
  115461. for(j=1;j<ip;j++){
  115462. is+=ido;
  115463. t1+=t0;
  115464. idij=is;
  115465. t2=t1;
  115466. for(i=2;i<ido;i+=2){
  115467. t2+=2;
  115468. idij+=2;
  115469. t3=t2;
  115470. for(k=0;k<l1;k++){
  115471. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  115472. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  115473. t3+=ido;
  115474. }
  115475. }
  115476. }
  115477. return;
  115478. L139:
  115479. is= -ido-1;
  115480. t1=0;
  115481. for(j=1;j<ip;j++){
  115482. is+=ido;
  115483. t1+=t0;
  115484. t2=t1;
  115485. for(k=0;k<l1;k++){
  115486. idij=is;
  115487. t3=t2;
  115488. for(i=2;i<ido;i+=2){
  115489. idij+=2;
  115490. t3+=2;
  115491. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  115492. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  115493. }
  115494. t2+=ido;
  115495. }
  115496. }
  115497. }
  115498. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  115499. int i,k1,l1,l2;
  115500. int na;
  115501. int nf,ip,iw,ix2,ix3,ido,idl1;
  115502. nf=ifac[1];
  115503. na=0;
  115504. l1=1;
  115505. iw=1;
  115506. for(k1=0;k1<nf;k1++){
  115507. ip=ifac[k1 + 2];
  115508. l2=ip*l1;
  115509. ido=n/l2;
  115510. idl1=ido*l1;
  115511. if(ip!=4)goto L103;
  115512. ix2=iw+ido;
  115513. ix3=ix2+ido;
  115514. if(na!=0)
  115515. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115516. else
  115517. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115518. na=1-na;
  115519. goto L115;
  115520. L103:
  115521. if(ip!=2)goto L106;
  115522. if(na!=0)
  115523. dradb2(ido,l1,ch,c,wa+iw-1);
  115524. else
  115525. dradb2(ido,l1,c,ch,wa+iw-1);
  115526. na=1-na;
  115527. goto L115;
  115528. L106:
  115529. if(ip!=3)goto L109;
  115530. ix2=iw+ido;
  115531. if(na!=0)
  115532. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  115533. else
  115534. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  115535. na=1-na;
  115536. goto L115;
  115537. L109:
  115538. /* The radix five case can be translated later..... */
  115539. /* if(ip!=5)goto L112;
  115540. ix2=iw+ido;
  115541. ix3=ix2+ido;
  115542. ix4=ix3+ido;
  115543. if(na!=0)
  115544. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  115545. else
  115546. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  115547. na=1-na;
  115548. goto L115;
  115549. L112:*/
  115550. if(na!=0)
  115551. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  115552. else
  115553. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  115554. if(ido==1)na=1-na;
  115555. L115:
  115556. l1=l2;
  115557. iw+=(ip-1)*ido;
  115558. }
  115559. if(na==0)return;
  115560. for(i=0;i<n;i++)c[i]=ch[i];
  115561. }
  115562. void drft_forward(drft_lookup *l,float *data){
  115563. if(l->n==1)return;
  115564. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  115565. }
  115566. void drft_backward(drft_lookup *l,float *data){
  115567. if (l->n==1)return;
  115568. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  115569. }
  115570. void drft_init(drft_lookup *l,int n){
  115571. l->n=n;
  115572. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  115573. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  115574. fdrffti(n, l->trigcache, l->splitcache);
  115575. }
  115576. void drft_clear(drft_lookup *l){
  115577. if(l){
  115578. if(l->trigcache)_ogg_free(l->trigcache);
  115579. if(l->splitcache)_ogg_free(l->splitcache);
  115580. memset(l,0,sizeof(*l));
  115581. }
  115582. }
  115583. #endif
  115584. /********* End of inlined file: smallft.c *********/
  115585. /********* Start of inlined file: synthesis.c *********/
  115586. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115587. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115588. // tasks..
  115589. #ifdef _MSC_VER
  115590. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115591. #endif
  115592. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115593. #if JUCE_USE_OGGVORBIS
  115594. #include <stdio.h>
  115595. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  115596. vorbis_dsp_state *vd=vb->vd;
  115597. private_state *b=(private_state*)vd->backend_state;
  115598. vorbis_info *vi=vd->vi;
  115599. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115600. oggpack_buffer *opb=&vb->opb;
  115601. int type,mode,i;
  115602. /* first things first. Make sure decode is ready */
  115603. _vorbis_block_ripcord(vb);
  115604. oggpack_readinit(opb,op->packet,op->bytes);
  115605. /* Check the packet type */
  115606. if(oggpack_read(opb,1)!=0){
  115607. /* Oops. This is not an audio data packet */
  115608. return(OV_ENOTAUDIO);
  115609. }
  115610. /* read our mode and pre/post windowsize */
  115611. mode=oggpack_read(opb,b->modebits);
  115612. if(mode==-1)return(OV_EBADPACKET);
  115613. vb->mode=mode;
  115614. vb->W=ci->mode_param[mode]->blockflag;
  115615. if(vb->W){
  115616. /* this doesn;t get mapped through mode selection as it's used
  115617. only for window selection */
  115618. vb->lW=oggpack_read(opb,1);
  115619. vb->nW=oggpack_read(opb,1);
  115620. if(vb->nW==-1) return(OV_EBADPACKET);
  115621. }else{
  115622. vb->lW=0;
  115623. vb->nW=0;
  115624. }
  115625. /* more setup */
  115626. vb->granulepos=op->granulepos;
  115627. vb->sequence=op->packetno;
  115628. vb->eofflag=op->e_o_s;
  115629. /* alloc pcm passback storage */
  115630. vb->pcmend=ci->blocksizes[vb->W];
  115631. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  115632. for(i=0;i<vi->channels;i++)
  115633. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  115634. /* unpack_header enforces range checking */
  115635. type=ci->map_type[ci->mode_param[mode]->mapping];
  115636. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  115637. mapping]));
  115638. }
  115639. /* used to track pcm position without actually performing decode.
  115640. Useful for sequential 'fast forward' */
  115641. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  115642. vorbis_dsp_state *vd=vb->vd;
  115643. private_state *b=(private_state*)vd->backend_state;
  115644. vorbis_info *vi=vd->vi;
  115645. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115646. oggpack_buffer *opb=&vb->opb;
  115647. int mode;
  115648. /* first things first. Make sure decode is ready */
  115649. _vorbis_block_ripcord(vb);
  115650. oggpack_readinit(opb,op->packet,op->bytes);
  115651. /* Check the packet type */
  115652. if(oggpack_read(opb,1)!=0){
  115653. /* Oops. This is not an audio data packet */
  115654. return(OV_ENOTAUDIO);
  115655. }
  115656. /* read our mode and pre/post windowsize */
  115657. mode=oggpack_read(opb,b->modebits);
  115658. if(mode==-1)return(OV_EBADPACKET);
  115659. vb->mode=mode;
  115660. vb->W=ci->mode_param[mode]->blockflag;
  115661. if(vb->W){
  115662. vb->lW=oggpack_read(opb,1);
  115663. vb->nW=oggpack_read(opb,1);
  115664. if(vb->nW==-1) return(OV_EBADPACKET);
  115665. }else{
  115666. vb->lW=0;
  115667. vb->nW=0;
  115668. }
  115669. /* more setup */
  115670. vb->granulepos=op->granulepos;
  115671. vb->sequence=op->packetno;
  115672. vb->eofflag=op->e_o_s;
  115673. /* no pcm */
  115674. vb->pcmend=0;
  115675. vb->pcm=NULL;
  115676. return(0);
  115677. }
  115678. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  115679. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115680. oggpack_buffer opb;
  115681. int mode;
  115682. oggpack_readinit(&opb,op->packet,op->bytes);
  115683. /* Check the packet type */
  115684. if(oggpack_read(&opb,1)!=0){
  115685. /* Oops. This is not an audio data packet */
  115686. return(OV_ENOTAUDIO);
  115687. }
  115688. {
  115689. int modebits=0;
  115690. int v=ci->modes;
  115691. while(v>1){
  115692. modebits++;
  115693. v>>=1;
  115694. }
  115695. /* read our mode and pre/post windowsize */
  115696. mode=oggpack_read(&opb,modebits);
  115697. }
  115698. if(mode==-1)return(OV_EBADPACKET);
  115699. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  115700. }
  115701. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  115702. /* set / clear half-sample-rate mode */
  115703. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115704. /* right now, our MDCT can't handle < 64 sample windows. */
  115705. if(ci->blocksizes[0]<=64 && flag)return -1;
  115706. ci->halfrate_flag=(flag?1:0);
  115707. return 0;
  115708. }
  115709. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  115710. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115711. return ci->halfrate_flag;
  115712. }
  115713. #endif
  115714. /********* End of inlined file: synthesis.c *********/
  115715. /********* Start of inlined file: vorbisenc.c *********/
  115716. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115717. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115718. // tasks..
  115719. #ifdef _MSC_VER
  115720. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115721. #endif
  115722. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115723. #if JUCE_USE_OGGVORBIS
  115724. #include <stdlib.h>
  115725. #include <string.h>
  115726. #include <math.h>
  115727. /* careful with this; it's using static array sizing to make managing
  115728. all the modes a little less annoying. If we use a residue backend
  115729. with > 12 partition types, or a different division of iteration,
  115730. this needs to be updated. */
  115731. typedef struct {
  115732. static_codebook *books[12][3];
  115733. } static_bookblock;
  115734. typedef struct {
  115735. int res_type;
  115736. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  115737. vorbis_info_residue0 *res;
  115738. static_codebook *book_aux;
  115739. static_codebook *book_aux_managed;
  115740. static_bookblock *books_base;
  115741. static_bookblock *books_base_managed;
  115742. } vorbis_residue_template;
  115743. typedef struct {
  115744. vorbis_info_mapping0 *map;
  115745. vorbis_residue_template *res;
  115746. } vorbis_mapping_template;
  115747. typedef struct vp_adjblock{
  115748. int block[P_BANDS];
  115749. } vp_adjblock;
  115750. typedef struct {
  115751. int data[NOISE_COMPAND_LEVELS];
  115752. } compandblock;
  115753. /* high level configuration information for setting things up
  115754. step-by-step with the detailed vorbis_encode_ctl interface.
  115755. There's a fair amount of redundancy such that interactive setup
  115756. does not directly deal with any vorbis_info or codec_setup_info
  115757. initialization; it's all stored (until full init) in this highlevel
  115758. setup, then flushed out to the real codec setup structs later. */
  115759. typedef struct {
  115760. int att[P_NOISECURVES];
  115761. float boost;
  115762. float decay;
  115763. } att3;
  115764. typedef struct { int data[P_NOISECURVES]; } adj3;
  115765. typedef struct {
  115766. int pre[PACKETBLOBS];
  115767. int post[PACKETBLOBS];
  115768. float kHz[PACKETBLOBS];
  115769. float lowpasskHz[PACKETBLOBS];
  115770. } adj_stereo;
  115771. typedef struct {
  115772. int lo;
  115773. int hi;
  115774. int fixed;
  115775. } noiseguard;
  115776. typedef struct {
  115777. int data[P_NOISECURVES][17];
  115778. } noise3;
  115779. typedef struct {
  115780. int mappings;
  115781. double *rate_mapping;
  115782. double *quality_mapping;
  115783. int coupling_restriction;
  115784. long samplerate_min_restriction;
  115785. long samplerate_max_restriction;
  115786. int *blocksize_short;
  115787. int *blocksize_long;
  115788. att3 *psy_tone_masteratt;
  115789. int *psy_tone_0dB;
  115790. int *psy_tone_dBsuppress;
  115791. vp_adjblock *psy_tone_adj_impulse;
  115792. vp_adjblock *psy_tone_adj_long;
  115793. vp_adjblock *psy_tone_adj_other;
  115794. noiseguard *psy_noiseguards;
  115795. noise3 *psy_noise_bias_impulse;
  115796. noise3 *psy_noise_bias_padding;
  115797. noise3 *psy_noise_bias_trans;
  115798. noise3 *psy_noise_bias_long;
  115799. int *psy_noise_dBsuppress;
  115800. compandblock *psy_noise_compand;
  115801. double *psy_noise_compand_short_mapping;
  115802. double *psy_noise_compand_long_mapping;
  115803. int *psy_noise_normal_start[2];
  115804. int *psy_noise_normal_partition[2];
  115805. double *psy_noise_normal_thresh;
  115806. int *psy_ath_float;
  115807. int *psy_ath_abs;
  115808. double *psy_lowpass;
  115809. vorbis_info_psy_global *global_params;
  115810. double *global_mapping;
  115811. adj_stereo *stereo_modes;
  115812. static_codebook ***floor_books;
  115813. vorbis_info_floor1 *floor_params;
  115814. int *floor_short_mapping;
  115815. int *floor_long_mapping;
  115816. vorbis_mapping_template *maps;
  115817. } ve_setup_data_template;
  115818. /* a few static coder conventions */
  115819. static vorbis_info_mode _mode_template[2]={
  115820. {0,0,0,0},
  115821. {1,0,0,1}
  115822. };
  115823. static vorbis_info_mapping0 _map_nominal[2]={
  115824. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  115825. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  115826. };
  115827. /********* Start of inlined file: setup_44.h *********/
  115828. /********* Start of inlined file: floor_all.h *********/
  115829. /********* Start of inlined file: floor_books.h *********/
  115830. static long _huff_lengthlist_line_256x7_0sub1[] = {
  115831. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  115832. };
  115833. static static_codebook _huff_book_line_256x7_0sub1 = {
  115834. 1, 9,
  115835. _huff_lengthlist_line_256x7_0sub1,
  115836. 0, 0, 0, 0, 0,
  115837. NULL,
  115838. NULL,
  115839. NULL,
  115840. NULL,
  115841. 0
  115842. };
  115843. static long _huff_lengthlist_line_256x7_0sub2[] = {
  115844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  115845. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  115846. };
  115847. static static_codebook _huff_book_line_256x7_0sub2 = {
  115848. 1, 25,
  115849. _huff_lengthlist_line_256x7_0sub2,
  115850. 0, 0, 0, 0, 0,
  115851. NULL,
  115852. NULL,
  115853. NULL,
  115854. NULL,
  115855. 0
  115856. };
  115857. static long _huff_lengthlist_line_256x7_0sub3[] = {
  115858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  115860. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  115861. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  115862. };
  115863. static static_codebook _huff_book_line_256x7_0sub3 = {
  115864. 1, 64,
  115865. _huff_lengthlist_line_256x7_0sub3,
  115866. 0, 0, 0, 0, 0,
  115867. NULL,
  115868. NULL,
  115869. NULL,
  115870. NULL,
  115871. 0
  115872. };
  115873. static long _huff_lengthlist_line_256x7_1sub1[] = {
  115874. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  115875. };
  115876. static static_codebook _huff_book_line_256x7_1sub1 = {
  115877. 1, 9,
  115878. _huff_lengthlist_line_256x7_1sub1,
  115879. 0, 0, 0, 0, 0,
  115880. NULL,
  115881. NULL,
  115882. NULL,
  115883. NULL,
  115884. 0
  115885. };
  115886. static long _huff_lengthlist_line_256x7_1sub2[] = {
  115887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  115888. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  115889. };
  115890. static static_codebook _huff_book_line_256x7_1sub2 = {
  115891. 1, 25,
  115892. _huff_lengthlist_line_256x7_1sub2,
  115893. 0, 0, 0, 0, 0,
  115894. NULL,
  115895. NULL,
  115896. NULL,
  115897. NULL,
  115898. 0
  115899. };
  115900. static long _huff_lengthlist_line_256x7_1sub3[] = {
  115901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  115903. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  115904. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  115905. };
  115906. static static_codebook _huff_book_line_256x7_1sub3 = {
  115907. 1, 64,
  115908. _huff_lengthlist_line_256x7_1sub3,
  115909. 0, 0, 0, 0, 0,
  115910. NULL,
  115911. NULL,
  115912. NULL,
  115913. NULL,
  115914. 0
  115915. };
  115916. static long _huff_lengthlist_line_256x7_class0[] = {
  115917. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  115918. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  115919. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  115920. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  115921. };
  115922. static static_codebook _huff_book_line_256x7_class0 = {
  115923. 1, 64,
  115924. _huff_lengthlist_line_256x7_class0,
  115925. 0, 0, 0, 0, 0,
  115926. NULL,
  115927. NULL,
  115928. NULL,
  115929. NULL,
  115930. 0
  115931. };
  115932. static long _huff_lengthlist_line_256x7_class1[] = {
  115933. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  115934. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  115935. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  115936. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  115937. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  115938. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  115939. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  115940. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  115941. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  115942. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  115943. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  115944. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  115945. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115946. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115947. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  115948. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  115949. };
  115950. static static_codebook _huff_book_line_256x7_class1 = {
  115951. 1, 256,
  115952. _huff_lengthlist_line_256x7_class1,
  115953. 0, 0, 0, 0, 0,
  115954. NULL,
  115955. NULL,
  115956. NULL,
  115957. NULL,
  115958. 0
  115959. };
  115960. static long _huff_lengthlist_line_512x17_0sub0[] = {
  115961. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  115962. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  115963. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  115964. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  115965. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  115966. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  115967. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  115968. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  115969. };
  115970. static static_codebook _huff_book_line_512x17_0sub0 = {
  115971. 1, 128,
  115972. _huff_lengthlist_line_512x17_0sub0,
  115973. 0, 0, 0, 0, 0,
  115974. NULL,
  115975. NULL,
  115976. NULL,
  115977. NULL,
  115978. 0
  115979. };
  115980. static long _huff_lengthlist_line_512x17_1sub0[] = {
  115981. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115982. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  115983. };
  115984. static static_codebook _huff_book_line_512x17_1sub0 = {
  115985. 1, 32,
  115986. _huff_lengthlist_line_512x17_1sub0,
  115987. 0, 0, 0, 0, 0,
  115988. NULL,
  115989. NULL,
  115990. NULL,
  115991. NULL,
  115992. 0
  115993. };
  115994. static long _huff_lengthlist_line_512x17_1sub1[] = {
  115995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115997. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  115998. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  115999. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  116000. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  116001. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  116002. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116003. };
  116004. static static_codebook _huff_book_line_512x17_1sub1 = {
  116005. 1, 128,
  116006. _huff_lengthlist_line_512x17_1sub1,
  116007. 0, 0, 0, 0, 0,
  116008. NULL,
  116009. NULL,
  116010. NULL,
  116011. NULL,
  116012. 0
  116013. };
  116014. static long _huff_lengthlist_line_512x17_2sub1[] = {
  116015. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  116016. 5, 3,
  116017. };
  116018. static static_codebook _huff_book_line_512x17_2sub1 = {
  116019. 1, 18,
  116020. _huff_lengthlist_line_512x17_2sub1,
  116021. 0, 0, 0, 0, 0,
  116022. NULL,
  116023. NULL,
  116024. NULL,
  116025. NULL,
  116026. 0
  116027. };
  116028. static long _huff_lengthlist_line_512x17_2sub2[] = {
  116029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116030. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  116031. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  116032. 9, 8,
  116033. };
  116034. static static_codebook _huff_book_line_512x17_2sub2 = {
  116035. 1, 50,
  116036. _huff_lengthlist_line_512x17_2sub2,
  116037. 0, 0, 0, 0, 0,
  116038. NULL,
  116039. NULL,
  116040. NULL,
  116041. NULL,
  116042. 0
  116043. };
  116044. static long _huff_lengthlist_line_512x17_2sub3[] = {
  116045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116048. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  116049. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  116050. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116051. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116052. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116053. };
  116054. static static_codebook _huff_book_line_512x17_2sub3 = {
  116055. 1, 128,
  116056. _huff_lengthlist_line_512x17_2sub3,
  116057. 0, 0, 0, 0, 0,
  116058. NULL,
  116059. NULL,
  116060. NULL,
  116061. NULL,
  116062. 0
  116063. };
  116064. static long _huff_lengthlist_line_512x17_3sub1[] = {
  116065. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  116066. 5, 5,
  116067. };
  116068. static static_codebook _huff_book_line_512x17_3sub1 = {
  116069. 1, 18,
  116070. _huff_lengthlist_line_512x17_3sub1,
  116071. 0, 0, 0, 0, 0,
  116072. NULL,
  116073. NULL,
  116074. NULL,
  116075. NULL,
  116076. 0
  116077. };
  116078. static long _huff_lengthlist_line_512x17_3sub2[] = {
  116079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116080. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  116081. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  116082. 11,14,
  116083. };
  116084. static static_codebook _huff_book_line_512x17_3sub2 = {
  116085. 1, 50,
  116086. _huff_lengthlist_line_512x17_3sub2,
  116087. 0, 0, 0, 0, 0,
  116088. NULL,
  116089. NULL,
  116090. NULL,
  116091. NULL,
  116092. 0
  116093. };
  116094. static long _huff_lengthlist_line_512x17_3sub3[] = {
  116095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116098. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  116099. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116100. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116101. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116102. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116103. };
  116104. static static_codebook _huff_book_line_512x17_3sub3 = {
  116105. 1, 128,
  116106. _huff_lengthlist_line_512x17_3sub3,
  116107. 0, 0, 0, 0, 0,
  116108. NULL,
  116109. NULL,
  116110. NULL,
  116111. NULL,
  116112. 0
  116113. };
  116114. static long _huff_lengthlist_line_512x17_class1[] = {
  116115. 1, 2, 3, 6, 5, 4, 7, 7,
  116116. };
  116117. static static_codebook _huff_book_line_512x17_class1 = {
  116118. 1, 8,
  116119. _huff_lengthlist_line_512x17_class1,
  116120. 0, 0, 0, 0, 0,
  116121. NULL,
  116122. NULL,
  116123. NULL,
  116124. NULL,
  116125. 0
  116126. };
  116127. static long _huff_lengthlist_line_512x17_class2[] = {
  116128. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  116129. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  116130. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  116131. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  116132. };
  116133. static static_codebook _huff_book_line_512x17_class2 = {
  116134. 1, 64,
  116135. _huff_lengthlist_line_512x17_class2,
  116136. 0, 0, 0, 0, 0,
  116137. NULL,
  116138. NULL,
  116139. NULL,
  116140. NULL,
  116141. 0
  116142. };
  116143. static long _huff_lengthlist_line_512x17_class3[] = {
  116144. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  116145. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  116146. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  116147. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  116148. };
  116149. static static_codebook _huff_book_line_512x17_class3 = {
  116150. 1, 64,
  116151. _huff_lengthlist_line_512x17_class3,
  116152. 0, 0, 0, 0, 0,
  116153. NULL,
  116154. NULL,
  116155. NULL,
  116156. NULL,
  116157. 0
  116158. };
  116159. static long _huff_lengthlist_line_128x4_class0[] = {
  116160. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  116161. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  116162. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  116163. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  116164. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  116165. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  116166. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  116167. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  116168. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  116169. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  116170. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  116171. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  116172. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  116173. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  116174. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  116175. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  116176. };
  116177. static static_codebook _huff_book_line_128x4_class0 = {
  116178. 1, 256,
  116179. _huff_lengthlist_line_128x4_class0,
  116180. 0, 0, 0, 0, 0,
  116181. NULL,
  116182. NULL,
  116183. NULL,
  116184. NULL,
  116185. 0
  116186. };
  116187. static long _huff_lengthlist_line_128x4_0sub0[] = {
  116188. 2, 2, 2, 2,
  116189. };
  116190. static static_codebook _huff_book_line_128x4_0sub0 = {
  116191. 1, 4,
  116192. _huff_lengthlist_line_128x4_0sub0,
  116193. 0, 0, 0, 0, 0,
  116194. NULL,
  116195. NULL,
  116196. NULL,
  116197. NULL,
  116198. 0
  116199. };
  116200. static long _huff_lengthlist_line_128x4_0sub1[] = {
  116201. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  116202. };
  116203. static static_codebook _huff_book_line_128x4_0sub1 = {
  116204. 1, 10,
  116205. _huff_lengthlist_line_128x4_0sub1,
  116206. 0, 0, 0, 0, 0,
  116207. NULL,
  116208. NULL,
  116209. NULL,
  116210. NULL,
  116211. 0
  116212. };
  116213. static long _huff_lengthlist_line_128x4_0sub2[] = {
  116214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  116215. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  116216. };
  116217. static static_codebook _huff_book_line_128x4_0sub2 = {
  116218. 1, 25,
  116219. _huff_lengthlist_line_128x4_0sub2,
  116220. 0, 0, 0, 0, 0,
  116221. NULL,
  116222. NULL,
  116223. NULL,
  116224. NULL,
  116225. 0
  116226. };
  116227. static long _huff_lengthlist_line_128x4_0sub3[] = {
  116228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116230. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  116231. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  116232. };
  116233. static static_codebook _huff_book_line_128x4_0sub3 = {
  116234. 1, 64,
  116235. _huff_lengthlist_line_128x4_0sub3,
  116236. 0, 0, 0, 0, 0,
  116237. NULL,
  116238. NULL,
  116239. NULL,
  116240. NULL,
  116241. 0
  116242. };
  116243. static long _huff_lengthlist_line_256x4_class0[] = {
  116244. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  116245. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  116246. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  116247. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  116248. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  116249. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  116250. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  116251. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  116252. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  116253. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  116254. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  116255. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  116256. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  116257. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  116258. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  116259. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  116260. };
  116261. static static_codebook _huff_book_line_256x4_class0 = {
  116262. 1, 256,
  116263. _huff_lengthlist_line_256x4_class0,
  116264. 0, 0, 0, 0, 0,
  116265. NULL,
  116266. NULL,
  116267. NULL,
  116268. NULL,
  116269. 0
  116270. };
  116271. static long _huff_lengthlist_line_256x4_0sub0[] = {
  116272. 2, 2, 2, 2,
  116273. };
  116274. static static_codebook _huff_book_line_256x4_0sub0 = {
  116275. 1, 4,
  116276. _huff_lengthlist_line_256x4_0sub0,
  116277. 0, 0, 0, 0, 0,
  116278. NULL,
  116279. NULL,
  116280. NULL,
  116281. NULL,
  116282. 0
  116283. };
  116284. static long _huff_lengthlist_line_256x4_0sub1[] = {
  116285. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  116286. };
  116287. static static_codebook _huff_book_line_256x4_0sub1 = {
  116288. 1, 10,
  116289. _huff_lengthlist_line_256x4_0sub1,
  116290. 0, 0, 0, 0, 0,
  116291. NULL,
  116292. NULL,
  116293. NULL,
  116294. NULL,
  116295. 0
  116296. };
  116297. static long _huff_lengthlist_line_256x4_0sub2[] = {
  116298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  116299. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  116300. };
  116301. static static_codebook _huff_book_line_256x4_0sub2 = {
  116302. 1, 25,
  116303. _huff_lengthlist_line_256x4_0sub2,
  116304. 0, 0, 0, 0, 0,
  116305. NULL,
  116306. NULL,
  116307. NULL,
  116308. NULL,
  116309. 0
  116310. };
  116311. static long _huff_lengthlist_line_256x4_0sub3[] = {
  116312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116314. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  116315. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  116316. };
  116317. static static_codebook _huff_book_line_256x4_0sub3 = {
  116318. 1, 64,
  116319. _huff_lengthlist_line_256x4_0sub3,
  116320. 0, 0, 0, 0, 0,
  116321. NULL,
  116322. NULL,
  116323. NULL,
  116324. NULL,
  116325. 0
  116326. };
  116327. static long _huff_lengthlist_line_128x7_class0[] = {
  116328. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  116329. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  116330. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  116331. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  116332. };
  116333. static static_codebook _huff_book_line_128x7_class0 = {
  116334. 1, 64,
  116335. _huff_lengthlist_line_128x7_class0,
  116336. 0, 0, 0, 0, 0,
  116337. NULL,
  116338. NULL,
  116339. NULL,
  116340. NULL,
  116341. 0
  116342. };
  116343. static long _huff_lengthlist_line_128x7_class1[] = {
  116344. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  116345. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  116346. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  116347. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  116348. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  116349. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  116350. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  116351. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  116352. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  116353. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  116354. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  116355. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  116356. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  116357. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  116358. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  116359. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  116360. };
  116361. static static_codebook _huff_book_line_128x7_class1 = {
  116362. 1, 256,
  116363. _huff_lengthlist_line_128x7_class1,
  116364. 0, 0, 0, 0, 0,
  116365. NULL,
  116366. NULL,
  116367. NULL,
  116368. NULL,
  116369. 0
  116370. };
  116371. static long _huff_lengthlist_line_128x7_0sub1[] = {
  116372. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  116373. };
  116374. static static_codebook _huff_book_line_128x7_0sub1 = {
  116375. 1, 9,
  116376. _huff_lengthlist_line_128x7_0sub1,
  116377. 0, 0, 0, 0, 0,
  116378. NULL,
  116379. NULL,
  116380. NULL,
  116381. NULL,
  116382. 0
  116383. };
  116384. static long _huff_lengthlist_line_128x7_0sub2[] = {
  116385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  116386. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  116387. };
  116388. static static_codebook _huff_book_line_128x7_0sub2 = {
  116389. 1, 25,
  116390. _huff_lengthlist_line_128x7_0sub2,
  116391. 0, 0, 0, 0, 0,
  116392. NULL,
  116393. NULL,
  116394. NULL,
  116395. NULL,
  116396. 0
  116397. };
  116398. static long _huff_lengthlist_line_128x7_0sub3[] = {
  116399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  116401. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116402. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  116403. };
  116404. static static_codebook _huff_book_line_128x7_0sub3 = {
  116405. 1, 64,
  116406. _huff_lengthlist_line_128x7_0sub3,
  116407. 0, 0, 0, 0, 0,
  116408. NULL,
  116409. NULL,
  116410. NULL,
  116411. NULL,
  116412. 0
  116413. };
  116414. static long _huff_lengthlist_line_128x7_1sub1[] = {
  116415. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  116416. };
  116417. static static_codebook _huff_book_line_128x7_1sub1 = {
  116418. 1, 9,
  116419. _huff_lengthlist_line_128x7_1sub1,
  116420. 0, 0, 0, 0, 0,
  116421. NULL,
  116422. NULL,
  116423. NULL,
  116424. NULL,
  116425. 0
  116426. };
  116427. static long _huff_lengthlist_line_128x7_1sub2[] = {
  116428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  116429. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  116430. };
  116431. static static_codebook _huff_book_line_128x7_1sub2 = {
  116432. 1, 25,
  116433. _huff_lengthlist_line_128x7_1sub2,
  116434. 0, 0, 0, 0, 0,
  116435. NULL,
  116436. NULL,
  116437. NULL,
  116438. NULL,
  116439. 0
  116440. };
  116441. static long _huff_lengthlist_line_128x7_1sub3[] = {
  116442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  116444. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  116445. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  116446. };
  116447. static static_codebook _huff_book_line_128x7_1sub3 = {
  116448. 1, 64,
  116449. _huff_lengthlist_line_128x7_1sub3,
  116450. 0, 0, 0, 0, 0,
  116451. NULL,
  116452. NULL,
  116453. NULL,
  116454. NULL,
  116455. 0
  116456. };
  116457. static long _huff_lengthlist_line_128x11_class1[] = {
  116458. 1, 6, 3, 7, 2, 4, 5, 7,
  116459. };
  116460. static static_codebook _huff_book_line_128x11_class1 = {
  116461. 1, 8,
  116462. _huff_lengthlist_line_128x11_class1,
  116463. 0, 0, 0, 0, 0,
  116464. NULL,
  116465. NULL,
  116466. NULL,
  116467. NULL,
  116468. 0
  116469. };
  116470. static long _huff_lengthlist_line_128x11_class2[] = {
  116471. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  116472. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  116473. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  116474. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  116475. };
  116476. static static_codebook _huff_book_line_128x11_class2 = {
  116477. 1, 64,
  116478. _huff_lengthlist_line_128x11_class2,
  116479. 0, 0, 0, 0, 0,
  116480. NULL,
  116481. NULL,
  116482. NULL,
  116483. NULL,
  116484. 0
  116485. };
  116486. static long _huff_lengthlist_line_128x11_class3[] = {
  116487. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  116488. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  116489. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  116490. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  116491. };
  116492. static static_codebook _huff_book_line_128x11_class3 = {
  116493. 1, 64,
  116494. _huff_lengthlist_line_128x11_class3,
  116495. 0, 0, 0, 0, 0,
  116496. NULL,
  116497. NULL,
  116498. NULL,
  116499. NULL,
  116500. 0
  116501. };
  116502. static long _huff_lengthlist_line_128x11_0sub0[] = {
  116503. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116504. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  116505. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  116506. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  116507. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  116508. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  116509. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  116510. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  116511. };
  116512. static static_codebook _huff_book_line_128x11_0sub0 = {
  116513. 1, 128,
  116514. _huff_lengthlist_line_128x11_0sub0,
  116515. 0, 0, 0, 0, 0,
  116516. NULL,
  116517. NULL,
  116518. NULL,
  116519. NULL,
  116520. 0
  116521. };
  116522. static long _huff_lengthlist_line_128x11_1sub0[] = {
  116523. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  116524. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  116525. };
  116526. static static_codebook _huff_book_line_128x11_1sub0 = {
  116527. 1, 32,
  116528. _huff_lengthlist_line_128x11_1sub0,
  116529. 0, 0, 0, 0, 0,
  116530. NULL,
  116531. NULL,
  116532. NULL,
  116533. NULL,
  116534. 0
  116535. };
  116536. static long _huff_lengthlist_line_128x11_1sub1[] = {
  116537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116539. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  116540. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  116541. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  116542. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  116543. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  116544. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  116545. };
  116546. static static_codebook _huff_book_line_128x11_1sub1 = {
  116547. 1, 128,
  116548. _huff_lengthlist_line_128x11_1sub1,
  116549. 0, 0, 0, 0, 0,
  116550. NULL,
  116551. NULL,
  116552. NULL,
  116553. NULL,
  116554. 0
  116555. };
  116556. static long _huff_lengthlist_line_128x11_2sub1[] = {
  116557. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  116558. 5, 5,
  116559. };
  116560. static static_codebook _huff_book_line_128x11_2sub1 = {
  116561. 1, 18,
  116562. _huff_lengthlist_line_128x11_2sub1,
  116563. 0, 0, 0, 0, 0,
  116564. NULL,
  116565. NULL,
  116566. NULL,
  116567. NULL,
  116568. 0
  116569. };
  116570. static long _huff_lengthlist_line_128x11_2sub2[] = {
  116571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116572. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  116573. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  116574. 8,11,
  116575. };
  116576. static static_codebook _huff_book_line_128x11_2sub2 = {
  116577. 1, 50,
  116578. _huff_lengthlist_line_128x11_2sub2,
  116579. 0, 0, 0, 0, 0,
  116580. NULL,
  116581. NULL,
  116582. NULL,
  116583. NULL,
  116584. 0
  116585. };
  116586. static long _huff_lengthlist_line_128x11_2sub3[] = {
  116587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116590. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  116591. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116592. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116593. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116594. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116595. };
  116596. static static_codebook _huff_book_line_128x11_2sub3 = {
  116597. 1, 128,
  116598. _huff_lengthlist_line_128x11_2sub3,
  116599. 0, 0, 0, 0, 0,
  116600. NULL,
  116601. NULL,
  116602. NULL,
  116603. NULL,
  116604. 0
  116605. };
  116606. static long _huff_lengthlist_line_128x11_3sub1[] = {
  116607. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  116608. 5, 4,
  116609. };
  116610. static static_codebook _huff_book_line_128x11_3sub1 = {
  116611. 1, 18,
  116612. _huff_lengthlist_line_128x11_3sub1,
  116613. 0, 0, 0, 0, 0,
  116614. NULL,
  116615. NULL,
  116616. NULL,
  116617. NULL,
  116618. 0
  116619. };
  116620. static long _huff_lengthlist_line_128x11_3sub2[] = {
  116621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116622. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  116623. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  116624. 12, 6,
  116625. };
  116626. static static_codebook _huff_book_line_128x11_3sub2 = {
  116627. 1, 50,
  116628. _huff_lengthlist_line_128x11_3sub2,
  116629. 0, 0, 0, 0, 0,
  116630. NULL,
  116631. NULL,
  116632. NULL,
  116633. NULL,
  116634. 0
  116635. };
  116636. static long _huff_lengthlist_line_128x11_3sub3[] = {
  116637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116640. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  116641. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  116642. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116643. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116644. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  116645. };
  116646. static static_codebook _huff_book_line_128x11_3sub3 = {
  116647. 1, 128,
  116648. _huff_lengthlist_line_128x11_3sub3,
  116649. 0, 0, 0, 0, 0,
  116650. NULL,
  116651. NULL,
  116652. NULL,
  116653. NULL,
  116654. 0
  116655. };
  116656. static long _huff_lengthlist_line_128x17_class1[] = {
  116657. 1, 3, 4, 7, 2, 5, 6, 7,
  116658. };
  116659. static static_codebook _huff_book_line_128x17_class1 = {
  116660. 1, 8,
  116661. _huff_lengthlist_line_128x17_class1,
  116662. 0, 0, 0, 0, 0,
  116663. NULL,
  116664. NULL,
  116665. NULL,
  116666. NULL,
  116667. 0
  116668. };
  116669. static long _huff_lengthlist_line_128x17_class2[] = {
  116670. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  116671. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  116672. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  116673. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  116674. };
  116675. static static_codebook _huff_book_line_128x17_class2 = {
  116676. 1, 64,
  116677. _huff_lengthlist_line_128x17_class2,
  116678. 0, 0, 0, 0, 0,
  116679. NULL,
  116680. NULL,
  116681. NULL,
  116682. NULL,
  116683. 0
  116684. };
  116685. static long _huff_lengthlist_line_128x17_class3[] = {
  116686. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  116687. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  116688. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  116689. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  116690. };
  116691. static static_codebook _huff_book_line_128x17_class3 = {
  116692. 1, 64,
  116693. _huff_lengthlist_line_128x17_class3,
  116694. 0, 0, 0, 0, 0,
  116695. NULL,
  116696. NULL,
  116697. NULL,
  116698. NULL,
  116699. 0
  116700. };
  116701. static long _huff_lengthlist_line_128x17_0sub0[] = {
  116702. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116703. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  116704. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  116705. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  116706. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  116707. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  116708. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  116709. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  116710. };
  116711. static static_codebook _huff_book_line_128x17_0sub0 = {
  116712. 1, 128,
  116713. _huff_lengthlist_line_128x17_0sub0,
  116714. 0, 0, 0, 0, 0,
  116715. NULL,
  116716. NULL,
  116717. NULL,
  116718. NULL,
  116719. 0
  116720. };
  116721. static long _huff_lengthlist_line_128x17_1sub0[] = {
  116722. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116723. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  116724. };
  116725. static static_codebook _huff_book_line_128x17_1sub0 = {
  116726. 1, 32,
  116727. _huff_lengthlist_line_128x17_1sub0,
  116728. 0, 0, 0, 0, 0,
  116729. NULL,
  116730. NULL,
  116731. NULL,
  116732. NULL,
  116733. 0
  116734. };
  116735. static long _huff_lengthlist_line_128x17_1sub1[] = {
  116736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116738. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  116739. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  116740. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  116741. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  116742. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  116743. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  116744. };
  116745. static static_codebook _huff_book_line_128x17_1sub1 = {
  116746. 1, 128,
  116747. _huff_lengthlist_line_128x17_1sub1,
  116748. 0, 0, 0, 0, 0,
  116749. NULL,
  116750. NULL,
  116751. NULL,
  116752. NULL,
  116753. 0
  116754. };
  116755. static long _huff_lengthlist_line_128x17_2sub1[] = {
  116756. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  116757. 9, 4,
  116758. };
  116759. static static_codebook _huff_book_line_128x17_2sub1 = {
  116760. 1, 18,
  116761. _huff_lengthlist_line_128x17_2sub1,
  116762. 0, 0, 0, 0, 0,
  116763. NULL,
  116764. NULL,
  116765. NULL,
  116766. NULL,
  116767. 0
  116768. };
  116769. static long _huff_lengthlist_line_128x17_2sub2[] = {
  116770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116771. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  116772. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  116773. 13,13,
  116774. };
  116775. static static_codebook _huff_book_line_128x17_2sub2 = {
  116776. 1, 50,
  116777. _huff_lengthlist_line_128x17_2sub2,
  116778. 0, 0, 0, 0, 0,
  116779. NULL,
  116780. NULL,
  116781. NULL,
  116782. NULL,
  116783. 0
  116784. };
  116785. static long _huff_lengthlist_line_128x17_2sub3[] = {
  116786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116789. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116790. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  116791. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116792. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116793. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116794. };
  116795. static static_codebook _huff_book_line_128x17_2sub3 = {
  116796. 1, 128,
  116797. _huff_lengthlist_line_128x17_2sub3,
  116798. 0, 0, 0, 0, 0,
  116799. NULL,
  116800. NULL,
  116801. NULL,
  116802. NULL,
  116803. 0
  116804. };
  116805. static long _huff_lengthlist_line_128x17_3sub1[] = {
  116806. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  116807. 6, 4,
  116808. };
  116809. static static_codebook _huff_book_line_128x17_3sub1 = {
  116810. 1, 18,
  116811. _huff_lengthlist_line_128x17_3sub1,
  116812. 0, 0, 0, 0, 0,
  116813. NULL,
  116814. NULL,
  116815. NULL,
  116816. NULL,
  116817. 0
  116818. };
  116819. static long _huff_lengthlist_line_128x17_3sub2[] = {
  116820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116821. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  116822. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  116823. 10, 8,
  116824. };
  116825. static static_codebook _huff_book_line_128x17_3sub2 = {
  116826. 1, 50,
  116827. _huff_lengthlist_line_128x17_3sub2,
  116828. 0, 0, 0, 0, 0,
  116829. NULL,
  116830. NULL,
  116831. NULL,
  116832. NULL,
  116833. 0
  116834. };
  116835. static long _huff_lengthlist_line_128x17_3sub3[] = {
  116836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116839. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  116840. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  116841. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116844. };
  116845. static static_codebook _huff_book_line_128x17_3sub3 = {
  116846. 1, 128,
  116847. _huff_lengthlist_line_128x17_3sub3,
  116848. 0, 0, 0, 0, 0,
  116849. NULL,
  116850. NULL,
  116851. NULL,
  116852. NULL,
  116853. 0
  116854. };
  116855. static long _huff_lengthlist_line_1024x27_class1[] = {
  116856. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  116857. };
  116858. static static_codebook _huff_book_line_1024x27_class1 = {
  116859. 1, 16,
  116860. _huff_lengthlist_line_1024x27_class1,
  116861. 0, 0, 0, 0, 0,
  116862. NULL,
  116863. NULL,
  116864. NULL,
  116865. NULL,
  116866. 0
  116867. };
  116868. static long _huff_lengthlist_line_1024x27_class2[] = {
  116869. 1, 4, 2, 6, 3, 7, 5, 7,
  116870. };
  116871. static static_codebook _huff_book_line_1024x27_class2 = {
  116872. 1, 8,
  116873. _huff_lengthlist_line_1024x27_class2,
  116874. 0, 0, 0, 0, 0,
  116875. NULL,
  116876. NULL,
  116877. NULL,
  116878. NULL,
  116879. 0
  116880. };
  116881. static long _huff_lengthlist_line_1024x27_class3[] = {
  116882. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  116883. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  116884. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  116885. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  116886. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  116887. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  116888. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  116889. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  116890. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  116891. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  116892. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  116893. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  116894. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  116895. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  116896. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  116897. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  116898. };
  116899. static static_codebook _huff_book_line_1024x27_class3 = {
  116900. 1, 256,
  116901. _huff_lengthlist_line_1024x27_class3,
  116902. 0, 0, 0, 0, 0,
  116903. NULL,
  116904. NULL,
  116905. NULL,
  116906. NULL,
  116907. 0
  116908. };
  116909. static long _huff_lengthlist_line_1024x27_class4[] = {
  116910. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  116911. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  116912. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  116913. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  116914. };
  116915. static static_codebook _huff_book_line_1024x27_class4 = {
  116916. 1, 64,
  116917. _huff_lengthlist_line_1024x27_class4,
  116918. 0, 0, 0, 0, 0,
  116919. NULL,
  116920. NULL,
  116921. NULL,
  116922. NULL,
  116923. 0
  116924. };
  116925. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  116926. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116927. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  116928. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  116929. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  116930. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  116931. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  116932. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  116933. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  116934. };
  116935. static static_codebook _huff_book_line_1024x27_0sub0 = {
  116936. 1, 128,
  116937. _huff_lengthlist_line_1024x27_0sub0,
  116938. 0, 0, 0, 0, 0,
  116939. NULL,
  116940. NULL,
  116941. NULL,
  116942. NULL,
  116943. 0
  116944. };
  116945. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  116946. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  116947. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  116948. };
  116949. static static_codebook _huff_book_line_1024x27_1sub0 = {
  116950. 1, 32,
  116951. _huff_lengthlist_line_1024x27_1sub0,
  116952. 0, 0, 0, 0, 0,
  116953. NULL,
  116954. NULL,
  116955. NULL,
  116956. NULL,
  116957. 0
  116958. };
  116959. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  116960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116962. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  116963. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  116964. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  116965. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  116966. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  116967. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  116968. };
  116969. static static_codebook _huff_book_line_1024x27_1sub1 = {
  116970. 1, 128,
  116971. _huff_lengthlist_line_1024x27_1sub1,
  116972. 0, 0, 0, 0, 0,
  116973. NULL,
  116974. NULL,
  116975. NULL,
  116976. NULL,
  116977. 0
  116978. };
  116979. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  116980. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116981. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  116982. };
  116983. static static_codebook _huff_book_line_1024x27_2sub0 = {
  116984. 1, 32,
  116985. _huff_lengthlist_line_1024x27_2sub0,
  116986. 0, 0, 0, 0, 0,
  116987. NULL,
  116988. NULL,
  116989. NULL,
  116990. NULL,
  116991. 0
  116992. };
  116993. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  116994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116996. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  116997. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  116998. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  116999. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  117000. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  117001. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  117002. };
  117003. static static_codebook _huff_book_line_1024x27_2sub1 = {
  117004. 1, 128,
  117005. _huff_lengthlist_line_1024x27_2sub1,
  117006. 0, 0, 0, 0, 0,
  117007. NULL,
  117008. NULL,
  117009. NULL,
  117010. NULL,
  117011. 0
  117012. };
  117013. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  117014. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  117015. 5, 5,
  117016. };
  117017. static static_codebook _huff_book_line_1024x27_3sub1 = {
  117018. 1, 18,
  117019. _huff_lengthlist_line_1024x27_3sub1,
  117020. 0, 0, 0, 0, 0,
  117021. NULL,
  117022. NULL,
  117023. NULL,
  117024. NULL,
  117025. 0
  117026. };
  117027. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  117028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117029. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  117030. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  117031. 9,11,
  117032. };
  117033. static static_codebook _huff_book_line_1024x27_3sub2 = {
  117034. 1, 50,
  117035. _huff_lengthlist_line_1024x27_3sub2,
  117036. 0, 0, 0, 0, 0,
  117037. NULL,
  117038. NULL,
  117039. NULL,
  117040. NULL,
  117041. 0
  117042. };
  117043. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  117044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117047. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  117048. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  117049. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117050. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117051. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117052. };
  117053. static static_codebook _huff_book_line_1024x27_3sub3 = {
  117054. 1, 128,
  117055. _huff_lengthlist_line_1024x27_3sub3,
  117056. 0, 0, 0, 0, 0,
  117057. NULL,
  117058. NULL,
  117059. NULL,
  117060. NULL,
  117061. 0
  117062. };
  117063. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  117064. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  117065. 5, 4,
  117066. };
  117067. static static_codebook _huff_book_line_1024x27_4sub1 = {
  117068. 1, 18,
  117069. _huff_lengthlist_line_1024x27_4sub1,
  117070. 0, 0, 0, 0, 0,
  117071. NULL,
  117072. NULL,
  117073. NULL,
  117074. NULL,
  117075. 0
  117076. };
  117077. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  117078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117079. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  117080. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  117081. 9,12,
  117082. };
  117083. static static_codebook _huff_book_line_1024x27_4sub2 = {
  117084. 1, 50,
  117085. _huff_lengthlist_line_1024x27_4sub2,
  117086. 0, 0, 0, 0, 0,
  117087. NULL,
  117088. NULL,
  117089. NULL,
  117090. NULL,
  117091. 0
  117092. };
  117093. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  117094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117097. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  117098. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  117099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117101. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  117102. };
  117103. static static_codebook _huff_book_line_1024x27_4sub3 = {
  117104. 1, 128,
  117105. _huff_lengthlist_line_1024x27_4sub3,
  117106. 0, 0, 0, 0, 0,
  117107. NULL,
  117108. NULL,
  117109. NULL,
  117110. NULL,
  117111. 0
  117112. };
  117113. static long _huff_lengthlist_line_2048x27_class1[] = {
  117114. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  117115. };
  117116. static static_codebook _huff_book_line_2048x27_class1 = {
  117117. 1, 16,
  117118. _huff_lengthlist_line_2048x27_class1,
  117119. 0, 0, 0, 0, 0,
  117120. NULL,
  117121. NULL,
  117122. NULL,
  117123. NULL,
  117124. 0
  117125. };
  117126. static long _huff_lengthlist_line_2048x27_class2[] = {
  117127. 1, 2, 3, 6, 4, 7, 5, 7,
  117128. };
  117129. static static_codebook _huff_book_line_2048x27_class2 = {
  117130. 1, 8,
  117131. _huff_lengthlist_line_2048x27_class2,
  117132. 0, 0, 0, 0, 0,
  117133. NULL,
  117134. NULL,
  117135. NULL,
  117136. NULL,
  117137. 0
  117138. };
  117139. static long _huff_lengthlist_line_2048x27_class3[] = {
  117140. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  117141. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  117142. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  117143. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  117144. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  117145. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  117146. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  117147. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  117148. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  117149. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  117150. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  117151. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117152. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  117153. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  117154. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117155. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117156. };
  117157. static static_codebook _huff_book_line_2048x27_class3 = {
  117158. 1, 256,
  117159. _huff_lengthlist_line_2048x27_class3,
  117160. 0, 0, 0, 0, 0,
  117161. NULL,
  117162. NULL,
  117163. NULL,
  117164. NULL,
  117165. 0
  117166. };
  117167. static long _huff_lengthlist_line_2048x27_class4[] = {
  117168. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  117169. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  117170. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  117171. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  117172. };
  117173. static static_codebook _huff_book_line_2048x27_class4 = {
  117174. 1, 64,
  117175. _huff_lengthlist_line_2048x27_class4,
  117176. 0, 0, 0, 0, 0,
  117177. NULL,
  117178. NULL,
  117179. NULL,
  117180. NULL,
  117181. 0
  117182. };
  117183. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  117184. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117185. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  117186. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  117187. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  117188. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  117189. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  117190. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  117191. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  117192. };
  117193. static static_codebook _huff_book_line_2048x27_0sub0 = {
  117194. 1, 128,
  117195. _huff_lengthlist_line_2048x27_0sub0,
  117196. 0, 0, 0, 0, 0,
  117197. NULL,
  117198. NULL,
  117199. NULL,
  117200. NULL,
  117201. 0
  117202. };
  117203. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  117204. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117205. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  117206. };
  117207. static static_codebook _huff_book_line_2048x27_1sub0 = {
  117208. 1, 32,
  117209. _huff_lengthlist_line_2048x27_1sub0,
  117210. 0, 0, 0, 0, 0,
  117211. NULL,
  117212. NULL,
  117213. NULL,
  117214. NULL,
  117215. 0
  117216. };
  117217. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  117218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117220. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  117221. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  117222. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  117223. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  117224. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  117225. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  117226. };
  117227. static static_codebook _huff_book_line_2048x27_1sub1 = {
  117228. 1, 128,
  117229. _huff_lengthlist_line_2048x27_1sub1,
  117230. 0, 0, 0, 0, 0,
  117231. NULL,
  117232. NULL,
  117233. NULL,
  117234. NULL,
  117235. 0
  117236. };
  117237. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  117238. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117239. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  117240. };
  117241. static static_codebook _huff_book_line_2048x27_2sub0 = {
  117242. 1, 32,
  117243. _huff_lengthlist_line_2048x27_2sub0,
  117244. 0, 0, 0, 0, 0,
  117245. NULL,
  117246. NULL,
  117247. NULL,
  117248. NULL,
  117249. 0
  117250. };
  117251. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  117252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117254. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  117255. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  117256. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  117257. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  117258. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  117259. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117260. };
  117261. static static_codebook _huff_book_line_2048x27_2sub1 = {
  117262. 1, 128,
  117263. _huff_lengthlist_line_2048x27_2sub1,
  117264. 0, 0, 0, 0, 0,
  117265. NULL,
  117266. NULL,
  117267. NULL,
  117268. NULL,
  117269. 0
  117270. };
  117271. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  117272. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  117273. 5, 5,
  117274. };
  117275. static static_codebook _huff_book_line_2048x27_3sub1 = {
  117276. 1, 18,
  117277. _huff_lengthlist_line_2048x27_3sub1,
  117278. 0, 0, 0, 0, 0,
  117279. NULL,
  117280. NULL,
  117281. NULL,
  117282. NULL,
  117283. 0
  117284. };
  117285. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  117286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117287. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  117288. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  117289. 10,12,
  117290. };
  117291. static static_codebook _huff_book_line_2048x27_3sub2 = {
  117292. 1, 50,
  117293. _huff_lengthlist_line_2048x27_3sub2,
  117294. 0, 0, 0, 0, 0,
  117295. NULL,
  117296. NULL,
  117297. NULL,
  117298. NULL,
  117299. 0
  117300. };
  117301. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  117302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117305. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  117306. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117307. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117308. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117309. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117310. };
  117311. static static_codebook _huff_book_line_2048x27_3sub3 = {
  117312. 1, 128,
  117313. _huff_lengthlist_line_2048x27_3sub3,
  117314. 0, 0, 0, 0, 0,
  117315. NULL,
  117316. NULL,
  117317. NULL,
  117318. NULL,
  117319. 0
  117320. };
  117321. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  117322. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  117323. 4, 5,
  117324. };
  117325. static static_codebook _huff_book_line_2048x27_4sub1 = {
  117326. 1, 18,
  117327. _huff_lengthlist_line_2048x27_4sub1,
  117328. 0, 0, 0, 0, 0,
  117329. NULL,
  117330. NULL,
  117331. NULL,
  117332. NULL,
  117333. 0
  117334. };
  117335. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  117336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117337. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  117338. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  117339. 10,10,
  117340. };
  117341. static static_codebook _huff_book_line_2048x27_4sub2 = {
  117342. 1, 50,
  117343. _huff_lengthlist_line_2048x27_4sub2,
  117344. 0, 0, 0, 0, 0,
  117345. NULL,
  117346. NULL,
  117347. NULL,
  117348. NULL,
  117349. 0
  117350. };
  117351. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  117352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117355. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  117356. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  117357. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117358. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117359. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117360. };
  117361. static static_codebook _huff_book_line_2048x27_4sub3 = {
  117362. 1, 128,
  117363. _huff_lengthlist_line_2048x27_4sub3,
  117364. 0, 0, 0, 0, 0,
  117365. NULL,
  117366. NULL,
  117367. NULL,
  117368. NULL,
  117369. 0
  117370. };
  117371. static long _huff_lengthlist_line_256x4low_class0[] = {
  117372. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  117373. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  117374. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  117375. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  117376. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  117377. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  117378. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  117379. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  117380. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  117381. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  117382. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  117383. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  117384. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  117385. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  117386. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  117387. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  117388. };
  117389. static static_codebook _huff_book_line_256x4low_class0 = {
  117390. 1, 256,
  117391. _huff_lengthlist_line_256x4low_class0,
  117392. 0, 0, 0, 0, 0,
  117393. NULL,
  117394. NULL,
  117395. NULL,
  117396. NULL,
  117397. 0
  117398. };
  117399. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  117400. 1, 3, 2, 3,
  117401. };
  117402. static static_codebook _huff_book_line_256x4low_0sub0 = {
  117403. 1, 4,
  117404. _huff_lengthlist_line_256x4low_0sub0,
  117405. 0, 0, 0, 0, 0,
  117406. NULL,
  117407. NULL,
  117408. NULL,
  117409. NULL,
  117410. 0
  117411. };
  117412. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  117413. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  117414. };
  117415. static static_codebook _huff_book_line_256x4low_0sub1 = {
  117416. 1, 10,
  117417. _huff_lengthlist_line_256x4low_0sub1,
  117418. 0, 0, 0, 0, 0,
  117419. NULL,
  117420. NULL,
  117421. NULL,
  117422. NULL,
  117423. 0
  117424. };
  117425. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  117426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  117427. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  117428. };
  117429. static static_codebook _huff_book_line_256x4low_0sub2 = {
  117430. 1, 25,
  117431. _huff_lengthlist_line_256x4low_0sub2,
  117432. 0, 0, 0, 0, 0,
  117433. NULL,
  117434. NULL,
  117435. NULL,
  117436. NULL,
  117437. 0
  117438. };
  117439. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  117440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  117442. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  117443. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  117444. };
  117445. static static_codebook _huff_book_line_256x4low_0sub3 = {
  117446. 1, 64,
  117447. _huff_lengthlist_line_256x4low_0sub3,
  117448. 0, 0, 0, 0, 0,
  117449. NULL,
  117450. NULL,
  117451. NULL,
  117452. NULL,
  117453. 0
  117454. };
  117455. /********* End of inlined file: floor_books.h *********/
  117456. static static_codebook *_floor_128x4_books[]={
  117457. &_huff_book_line_128x4_class0,
  117458. &_huff_book_line_128x4_0sub0,
  117459. &_huff_book_line_128x4_0sub1,
  117460. &_huff_book_line_128x4_0sub2,
  117461. &_huff_book_line_128x4_0sub3,
  117462. };
  117463. static static_codebook *_floor_256x4_books[]={
  117464. &_huff_book_line_256x4_class0,
  117465. &_huff_book_line_256x4_0sub0,
  117466. &_huff_book_line_256x4_0sub1,
  117467. &_huff_book_line_256x4_0sub2,
  117468. &_huff_book_line_256x4_0sub3,
  117469. };
  117470. static static_codebook *_floor_128x7_books[]={
  117471. &_huff_book_line_128x7_class0,
  117472. &_huff_book_line_128x7_class1,
  117473. &_huff_book_line_128x7_0sub1,
  117474. &_huff_book_line_128x7_0sub2,
  117475. &_huff_book_line_128x7_0sub3,
  117476. &_huff_book_line_128x7_1sub1,
  117477. &_huff_book_line_128x7_1sub2,
  117478. &_huff_book_line_128x7_1sub3,
  117479. };
  117480. static static_codebook *_floor_256x7_books[]={
  117481. &_huff_book_line_256x7_class0,
  117482. &_huff_book_line_256x7_class1,
  117483. &_huff_book_line_256x7_0sub1,
  117484. &_huff_book_line_256x7_0sub2,
  117485. &_huff_book_line_256x7_0sub3,
  117486. &_huff_book_line_256x7_1sub1,
  117487. &_huff_book_line_256x7_1sub2,
  117488. &_huff_book_line_256x7_1sub3,
  117489. };
  117490. static static_codebook *_floor_128x11_books[]={
  117491. &_huff_book_line_128x11_class1,
  117492. &_huff_book_line_128x11_class2,
  117493. &_huff_book_line_128x11_class3,
  117494. &_huff_book_line_128x11_0sub0,
  117495. &_huff_book_line_128x11_1sub0,
  117496. &_huff_book_line_128x11_1sub1,
  117497. &_huff_book_line_128x11_2sub1,
  117498. &_huff_book_line_128x11_2sub2,
  117499. &_huff_book_line_128x11_2sub3,
  117500. &_huff_book_line_128x11_3sub1,
  117501. &_huff_book_line_128x11_3sub2,
  117502. &_huff_book_line_128x11_3sub3,
  117503. };
  117504. static static_codebook *_floor_128x17_books[]={
  117505. &_huff_book_line_128x17_class1,
  117506. &_huff_book_line_128x17_class2,
  117507. &_huff_book_line_128x17_class3,
  117508. &_huff_book_line_128x17_0sub0,
  117509. &_huff_book_line_128x17_1sub0,
  117510. &_huff_book_line_128x17_1sub1,
  117511. &_huff_book_line_128x17_2sub1,
  117512. &_huff_book_line_128x17_2sub2,
  117513. &_huff_book_line_128x17_2sub3,
  117514. &_huff_book_line_128x17_3sub1,
  117515. &_huff_book_line_128x17_3sub2,
  117516. &_huff_book_line_128x17_3sub3,
  117517. };
  117518. static static_codebook *_floor_256x4low_books[]={
  117519. &_huff_book_line_256x4low_class0,
  117520. &_huff_book_line_256x4low_0sub0,
  117521. &_huff_book_line_256x4low_0sub1,
  117522. &_huff_book_line_256x4low_0sub2,
  117523. &_huff_book_line_256x4low_0sub3,
  117524. };
  117525. static static_codebook *_floor_1024x27_books[]={
  117526. &_huff_book_line_1024x27_class1,
  117527. &_huff_book_line_1024x27_class2,
  117528. &_huff_book_line_1024x27_class3,
  117529. &_huff_book_line_1024x27_class4,
  117530. &_huff_book_line_1024x27_0sub0,
  117531. &_huff_book_line_1024x27_1sub0,
  117532. &_huff_book_line_1024x27_1sub1,
  117533. &_huff_book_line_1024x27_2sub0,
  117534. &_huff_book_line_1024x27_2sub1,
  117535. &_huff_book_line_1024x27_3sub1,
  117536. &_huff_book_line_1024x27_3sub2,
  117537. &_huff_book_line_1024x27_3sub3,
  117538. &_huff_book_line_1024x27_4sub1,
  117539. &_huff_book_line_1024x27_4sub2,
  117540. &_huff_book_line_1024x27_4sub3,
  117541. };
  117542. static static_codebook *_floor_2048x27_books[]={
  117543. &_huff_book_line_2048x27_class1,
  117544. &_huff_book_line_2048x27_class2,
  117545. &_huff_book_line_2048x27_class3,
  117546. &_huff_book_line_2048x27_class4,
  117547. &_huff_book_line_2048x27_0sub0,
  117548. &_huff_book_line_2048x27_1sub0,
  117549. &_huff_book_line_2048x27_1sub1,
  117550. &_huff_book_line_2048x27_2sub0,
  117551. &_huff_book_line_2048x27_2sub1,
  117552. &_huff_book_line_2048x27_3sub1,
  117553. &_huff_book_line_2048x27_3sub2,
  117554. &_huff_book_line_2048x27_3sub3,
  117555. &_huff_book_line_2048x27_4sub1,
  117556. &_huff_book_line_2048x27_4sub2,
  117557. &_huff_book_line_2048x27_4sub3,
  117558. };
  117559. static static_codebook *_floor_512x17_books[]={
  117560. &_huff_book_line_512x17_class1,
  117561. &_huff_book_line_512x17_class2,
  117562. &_huff_book_line_512x17_class3,
  117563. &_huff_book_line_512x17_0sub0,
  117564. &_huff_book_line_512x17_1sub0,
  117565. &_huff_book_line_512x17_1sub1,
  117566. &_huff_book_line_512x17_2sub1,
  117567. &_huff_book_line_512x17_2sub2,
  117568. &_huff_book_line_512x17_2sub3,
  117569. &_huff_book_line_512x17_3sub1,
  117570. &_huff_book_line_512x17_3sub2,
  117571. &_huff_book_line_512x17_3sub3,
  117572. };
  117573. static static_codebook **_floor_books[10]={
  117574. _floor_128x4_books,
  117575. _floor_256x4_books,
  117576. _floor_128x7_books,
  117577. _floor_256x7_books,
  117578. _floor_128x11_books,
  117579. _floor_128x17_books,
  117580. _floor_256x4low_books,
  117581. _floor_1024x27_books,
  117582. _floor_2048x27_books,
  117583. _floor_512x17_books,
  117584. };
  117585. static vorbis_info_floor1 _floor[10]={
  117586. /* 128 x 4 */
  117587. {
  117588. 1,{0},{4},{2},{0},
  117589. {{1,2,3,4}},
  117590. 4,{0,128, 33,8,16,70},
  117591. 60,30,500, 1.,18., -1
  117592. },
  117593. /* 256 x 4 */
  117594. {
  117595. 1,{0},{4},{2},{0},
  117596. {{1,2,3,4}},
  117597. 4,{0,256, 66,16,32,140},
  117598. 60,30,500, 1.,18., -1
  117599. },
  117600. /* 128 x 7 */
  117601. {
  117602. 2,{0,1},{3,4},{2,2},{0,1},
  117603. {{-1,2,3,4},{-1,5,6,7}},
  117604. 4,{0,128, 14,4,58, 2,8,28,90},
  117605. 60,30,500, 1.,18., -1
  117606. },
  117607. /* 256 x 7 */
  117608. {
  117609. 2,{0,1},{3,4},{2,2},{0,1},
  117610. {{-1,2,3,4},{-1,5,6,7}},
  117611. 4,{0,256, 28,8,116, 4,16,56,180},
  117612. 60,30,500, 1.,18., -1
  117613. },
  117614. /* 128 x 11 */
  117615. {
  117616. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  117617. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  117618. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  117619. 60,30,500, 1,18., -1
  117620. },
  117621. /* 128 x 17 */
  117622. {
  117623. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  117624. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  117625. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  117626. 60,30,500, 1,18., -1
  117627. },
  117628. /* 256 x 4 (low bitrate version) */
  117629. {
  117630. 1,{0},{4},{2},{0},
  117631. {{1,2,3,4}},
  117632. 4,{0,256, 66,16,32,140},
  117633. 60,30,500, 1.,18., -1
  117634. },
  117635. /* 1024 x 27 */
  117636. {
  117637. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  117638. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  117639. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  117640. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  117641. 60,30,500, 3,18., -1 /* lowpass */
  117642. },
  117643. /* 2048 x 27 */
  117644. {
  117645. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  117646. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  117647. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  117648. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  117649. 60,30,500, 3,18., -1 /* lowpass */
  117650. },
  117651. /* 512 x 17 */
  117652. {
  117653. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  117654. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  117655. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  117656. 7,23,39, 55,79,110, 156,232,360},
  117657. 60,30,500, 1,18., -1 /* lowpass! */
  117658. },
  117659. };
  117660. /********* End of inlined file: floor_all.h *********/
  117661. /********* Start of inlined file: residue_44.h *********/
  117662. /********* Start of inlined file: res_books_stereo.h *********/
  117663. static long _vq_quantlist__16c0_s_p1_0[] = {
  117664. 1,
  117665. 0,
  117666. 2,
  117667. };
  117668. static long _vq_lengthlist__16c0_s_p1_0[] = {
  117669. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  117670. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117674. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  117675. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117679. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117680. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  117715. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  117716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  117720. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  117721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  117725. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  117726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117760. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  117761. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117765. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  117766. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  117767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117770. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  117771. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  117772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118079. 0,
  118080. };
  118081. static float _vq_quantthresh__16c0_s_p1_0[] = {
  118082. -0.5, 0.5,
  118083. };
  118084. static long _vq_quantmap__16c0_s_p1_0[] = {
  118085. 1, 0, 2,
  118086. };
  118087. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  118088. _vq_quantthresh__16c0_s_p1_0,
  118089. _vq_quantmap__16c0_s_p1_0,
  118090. 3,
  118091. 3
  118092. };
  118093. static static_codebook _16c0_s_p1_0 = {
  118094. 8, 6561,
  118095. _vq_lengthlist__16c0_s_p1_0,
  118096. 1, -535822336, 1611661312, 2, 0,
  118097. _vq_quantlist__16c0_s_p1_0,
  118098. NULL,
  118099. &_vq_auxt__16c0_s_p1_0,
  118100. NULL,
  118101. 0
  118102. };
  118103. static long _vq_quantlist__16c0_s_p2_0[] = {
  118104. 2,
  118105. 1,
  118106. 3,
  118107. 0,
  118108. 4,
  118109. };
  118110. static long _vq_lengthlist__16c0_s_p2_0[] = {
  118111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118150. 0,
  118151. };
  118152. static float _vq_quantthresh__16c0_s_p2_0[] = {
  118153. -1.5, -0.5, 0.5, 1.5,
  118154. };
  118155. static long _vq_quantmap__16c0_s_p2_0[] = {
  118156. 3, 1, 0, 2, 4,
  118157. };
  118158. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  118159. _vq_quantthresh__16c0_s_p2_0,
  118160. _vq_quantmap__16c0_s_p2_0,
  118161. 5,
  118162. 5
  118163. };
  118164. static static_codebook _16c0_s_p2_0 = {
  118165. 4, 625,
  118166. _vq_lengthlist__16c0_s_p2_0,
  118167. 1, -533725184, 1611661312, 3, 0,
  118168. _vq_quantlist__16c0_s_p2_0,
  118169. NULL,
  118170. &_vq_auxt__16c0_s_p2_0,
  118171. NULL,
  118172. 0
  118173. };
  118174. static long _vq_quantlist__16c0_s_p3_0[] = {
  118175. 2,
  118176. 1,
  118177. 3,
  118178. 0,
  118179. 4,
  118180. };
  118181. static long _vq_lengthlist__16c0_s_p3_0[] = {
  118182. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  118184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118185. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  118187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118188. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118221. 0,
  118222. };
  118223. static float _vq_quantthresh__16c0_s_p3_0[] = {
  118224. -1.5, -0.5, 0.5, 1.5,
  118225. };
  118226. static long _vq_quantmap__16c0_s_p3_0[] = {
  118227. 3, 1, 0, 2, 4,
  118228. };
  118229. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  118230. _vq_quantthresh__16c0_s_p3_0,
  118231. _vq_quantmap__16c0_s_p3_0,
  118232. 5,
  118233. 5
  118234. };
  118235. static static_codebook _16c0_s_p3_0 = {
  118236. 4, 625,
  118237. _vq_lengthlist__16c0_s_p3_0,
  118238. 1, -533725184, 1611661312, 3, 0,
  118239. _vq_quantlist__16c0_s_p3_0,
  118240. NULL,
  118241. &_vq_auxt__16c0_s_p3_0,
  118242. NULL,
  118243. 0
  118244. };
  118245. static long _vq_quantlist__16c0_s_p4_0[] = {
  118246. 4,
  118247. 3,
  118248. 5,
  118249. 2,
  118250. 6,
  118251. 1,
  118252. 7,
  118253. 0,
  118254. 8,
  118255. };
  118256. static long _vq_lengthlist__16c0_s_p4_0[] = {
  118257. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118258. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118259. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118260. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  118261. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118262. 0,
  118263. };
  118264. static float _vq_quantthresh__16c0_s_p4_0[] = {
  118265. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118266. };
  118267. static long _vq_quantmap__16c0_s_p4_0[] = {
  118268. 7, 5, 3, 1, 0, 2, 4, 6,
  118269. 8,
  118270. };
  118271. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  118272. _vq_quantthresh__16c0_s_p4_0,
  118273. _vq_quantmap__16c0_s_p4_0,
  118274. 9,
  118275. 9
  118276. };
  118277. static static_codebook _16c0_s_p4_0 = {
  118278. 2, 81,
  118279. _vq_lengthlist__16c0_s_p4_0,
  118280. 1, -531628032, 1611661312, 4, 0,
  118281. _vq_quantlist__16c0_s_p4_0,
  118282. NULL,
  118283. &_vq_auxt__16c0_s_p4_0,
  118284. NULL,
  118285. 0
  118286. };
  118287. static long _vq_quantlist__16c0_s_p5_0[] = {
  118288. 4,
  118289. 3,
  118290. 5,
  118291. 2,
  118292. 6,
  118293. 1,
  118294. 7,
  118295. 0,
  118296. 8,
  118297. };
  118298. static long _vq_lengthlist__16c0_s_p5_0[] = {
  118299. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118300. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  118301. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  118302. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  118303. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  118304. 10,
  118305. };
  118306. static float _vq_quantthresh__16c0_s_p5_0[] = {
  118307. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118308. };
  118309. static long _vq_quantmap__16c0_s_p5_0[] = {
  118310. 7, 5, 3, 1, 0, 2, 4, 6,
  118311. 8,
  118312. };
  118313. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  118314. _vq_quantthresh__16c0_s_p5_0,
  118315. _vq_quantmap__16c0_s_p5_0,
  118316. 9,
  118317. 9
  118318. };
  118319. static static_codebook _16c0_s_p5_0 = {
  118320. 2, 81,
  118321. _vq_lengthlist__16c0_s_p5_0,
  118322. 1, -531628032, 1611661312, 4, 0,
  118323. _vq_quantlist__16c0_s_p5_0,
  118324. NULL,
  118325. &_vq_auxt__16c0_s_p5_0,
  118326. NULL,
  118327. 0
  118328. };
  118329. static long _vq_quantlist__16c0_s_p6_0[] = {
  118330. 8,
  118331. 7,
  118332. 9,
  118333. 6,
  118334. 10,
  118335. 5,
  118336. 11,
  118337. 4,
  118338. 12,
  118339. 3,
  118340. 13,
  118341. 2,
  118342. 14,
  118343. 1,
  118344. 15,
  118345. 0,
  118346. 16,
  118347. };
  118348. static long _vq_lengthlist__16c0_s_p6_0[] = {
  118349. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  118350. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  118351. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  118352. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  118353. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  118354. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  118355. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  118356. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  118357. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  118358. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  118359. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  118360. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  118361. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  118362. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  118363. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  118364. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  118365. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  118366. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  118367. 14,
  118368. };
  118369. static float _vq_quantthresh__16c0_s_p6_0[] = {
  118370. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118371. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118372. };
  118373. static long _vq_quantmap__16c0_s_p6_0[] = {
  118374. 15, 13, 11, 9, 7, 5, 3, 1,
  118375. 0, 2, 4, 6, 8, 10, 12, 14,
  118376. 16,
  118377. };
  118378. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  118379. _vq_quantthresh__16c0_s_p6_0,
  118380. _vq_quantmap__16c0_s_p6_0,
  118381. 17,
  118382. 17
  118383. };
  118384. static static_codebook _16c0_s_p6_0 = {
  118385. 2, 289,
  118386. _vq_lengthlist__16c0_s_p6_0,
  118387. 1, -529530880, 1611661312, 5, 0,
  118388. _vq_quantlist__16c0_s_p6_0,
  118389. NULL,
  118390. &_vq_auxt__16c0_s_p6_0,
  118391. NULL,
  118392. 0
  118393. };
  118394. static long _vq_quantlist__16c0_s_p7_0[] = {
  118395. 1,
  118396. 0,
  118397. 2,
  118398. };
  118399. static long _vq_lengthlist__16c0_s_p7_0[] = {
  118400. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  118401. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  118402. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  118403. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  118404. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  118405. 13,
  118406. };
  118407. static float _vq_quantthresh__16c0_s_p7_0[] = {
  118408. -5.5, 5.5,
  118409. };
  118410. static long _vq_quantmap__16c0_s_p7_0[] = {
  118411. 1, 0, 2,
  118412. };
  118413. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  118414. _vq_quantthresh__16c0_s_p7_0,
  118415. _vq_quantmap__16c0_s_p7_0,
  118416. 3,
  118417. 3
  118418. };
  118419. static static_codebook _16c0_s_p7_0 = {
  118420. 4, 81,
  118421. _vq_lengthlist__16c0_s_p7_0,
  118422. 1, -529137664, 1618345984, 2, 0,
  118423. _vq_quantlist__16c0_s_p7_0,
  118424. NULL,
  118425. &_vq_auxt__16c0_s_p7_0,
  118426. NULL,
  118427. 0
  118428. };
  118429. static long _vq_quantlist__16c0_s_p7_1[] = {
  118430. 5,
  118431. 4,
  118432. 6,
  118433. 3,
  118434. 7,
  118435. 2,
  118436. 8,
  118437. 1,
  118438. 9,
  118439. 0,
  118440. 10,
  118441. };
  118442. static long _vq_lengthlist__16c0_s_p7_1[] = {
  118443. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  118444. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  118445. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  118446. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  118447. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  118448. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  118449. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  118450. 11,11,11, 9, 9, 9, 9,10,10,
  118451. };
  118452. static float _vq_quantthresh__16c0_s_p7_1[] = {
  118453. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118454. 3.5, 4.5,
  118455. };
  118456. static long _vq_quantmap__16c0_s_p7_1[] = {
  118457. 9, 7, 5, 3, 1, 0, 2, 4,
  118458. 6, 8, 10,
  118459. };
  118460. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  118461. _vq_quantthresh__16c0_s_p7_1,
  118462. _vq_quantmap__16c0_s_p7_1,
  118463. 11,
  118464. 11
  118465. };
  118466. static static_codebook _16c0_s_p7_1 = {
  118467. 2, 121,
  118468. _vq_lengthlist__16c0_s_p7_1,
  118469. 1, -531365888, 1611661312, 4, 0,
  118470. _vq_quantlist__16c0_s_p7_1,
  118471. NULL,
  118472. &_vq_auxt__16c0_s_p7_1,
  118473. NULL,
  118474. 0
  118475. };
  118476. static long _vq_quantlist__16c0_s_p8_0[] = {
  118477. 6,
  118478. 5,
  118479. 7,
  118480. 4,
  118481. 8,
  118482. 3,
  118483. 9,
  118484. 2,
  118485. 10,
  118486. 1,
  118487. 11,
  118488. 0,
  118489. 12,
  118490. };
  118491. static long _vq_lengthlist__16c0_s_p8_0[] = {
  118492. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  118493. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  118494. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  118495. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  118496. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  118497. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  118498. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  118499. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  118500. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  118501. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  118502. 0,12,13,13,12,13,14,14,14,
  118503. };
  118504. static float _vq_quantthresh__16c0_s_p8_0[] = {
  118505. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  118506. 12.5, 17.5, 22.5, 27.5,
  118507. };
  118508. static long _vq_quantmap__16c0_s_p8_0[] = {
  118509. 11, 9, 7, 5, 3, 1, 0, 2,
  118510. 4, 6, 8, 10, 12,
  118511. };
  118512. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  118513. _vq_quantthresh__16c0_s_p8_0,
  118514. _vq_quantmap__16c0_s_p8_0,
  118515. 13,
  118516. 13
  118517. };
  118518. static static_codebook _16c0_s_p8_0 = {
  118519. 2, 169,
  118520. _vq_lengthlist__16c0_s_p8_0,
  118521. 1, -526516224, 1616117760, 4, 0,
  118522. _vq_quantlist__16c0_s_p8_0,
  118523. NULL,
  118524. &_vq_auxt__16c0_s_p8_0,
  118525. NULL,
  118526. 0
  118527. };
  118528. static long _vq_quantlist__16c0_s_p8_1[] = {
  118529. 2,
  118530. 1,
  118531. 3,
  118532. 0,
  118533. 4,
  118534. };
  118535. static long _vq_lengthlist__16c0_s_p8_1[] = {
  118536. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  118537. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  118538. };
  118539. static float _vq_quantthresh__16c0_s_p8_1[] = {
  118540. -1.5, -0.5, 0.5, 1.5,
  118541. };
  118542. static long _vq_quantmap__16c0_s_p8_1[] = {
  118543. 3, 1, 0, 2, 4,
  118544. };
  118545. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  118546. _vq_quantthresh__16c0_s_p8_1,
  118547. _vq_quantmap__16c0_s_p8_1,
  118548. 5,
  118549. 5
  118550. };
  118551. static static_codebook _16c0_s_p8_1 = {
  118552. 2, 25,
  118553. _vq_lengthlist__16c0_s_p8_1,
  118554. 1, -533725184, 1611661312, 3, 0,
  118555. _vq_quantlist__16c0_s_p8_1,
  118556. NULL,
  118557. &_vq_auxt__16c0_s_p8_1,
  118558. NULL,
  118559. 0
  118560. };
  118561. static long _vq_quantlist__16c0_s_p9_0[] = {
  118562. 1,
  118563. 0,
  118564. 2,
  118565. };
  118566. static long _vq_lengthlist__16c0_s_p9_0[] = {
  118567. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118568. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118569. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118570. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118571. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118572. 7,
  118573. };
  118574. static float _vq_quantthresh__16c0_s_p9_0[] = {
  118575. -157.5, 157.5,
  118576. };
  118577. static long _vq_quantmap__16c0_s_p9_0[] = {
  118578. 1, 0, 2,
  118579. };
  118580. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  118581. _vq_quantthresh__16c0_s_p9_0,
  118582. _vq_quantmap__16c0_s_p9_0,
  118583. 3,
  118584. 3
  118585. };
  118586. static static_codebook _16c0_s_p9_0 = {
  118587. 4, 81,
  118588. _vq_lengthlist__16c0_s_p9_0,
  118589. 1, -518803456, 1628680192, 2, 0,
  118590. _vq_quantlist__16c0_s_p9_0,
  118591. NULL,
  118592. &_vq_auxt__16c0_s_p9_0,
  118593. NULL,
  118594. 0
  118595. };
  118596. static long _vq_quantlist__16c0_s_p9_1[] = {
  118597. 7,
  118598. 6,
  118599. 8,
  118600. 5,
  118601. 9,
  118602. 4,
  118603. 10,
  118604. 3,
  118605. 11,
  118606. 2,
  118607. 12,
  118608. 1,
  118609. 13,
  118610. 0,
  118611. 14,
  118612. };
  118613. static long _vq_lengthlist__16c0_s_p9_1[] = {
  118614. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  118615. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  118616. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  118617. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  118618. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118621. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118622. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118623. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118624. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118625. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118627. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118628. 10,
  118629. };
  118630. static float _vq_quantthresh__16c0_s_p9_1[] = {
  118631. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118632. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118633. };
  118634. static long _vq_quantmap__16c0_s_p9_1[] = {
  118635. 13, 11, 9, 7, 5, 3, 1, 0,
  118636. 2, 4, 6, 8, 10, 12, 14,
  118637. };
  118638. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  118639. _vq_quantthresh__16c0_s_p9_1,
  118640. _vq_quantmap__16c0_s_p9_1,
  118641. 15,
  118642. 15
  118643. };
  118644. static static_codebook _16c0_s_p9_1 = {
  118645. 2, 225,
  118646. _vq_lengthlist__16c0_s_p9_1,
  118647. 1, -520986624, 1620377600, 4, 0,
  118648. _vq_quantlist__16c0_s_p9_1,
  118649. NULL,
  118650. &_vq_auxt__16c0_s_p9_1,
  118651. NULL,
  118652. 0
  118653. };
  118654. static long _vq_quantlist__16c0_s_p9_2[] = {
  118655. 10,
  118656. 9,
  118657. 11,
  118658. 8,
  118659. 12,
  118660. 7,
  118661. 13,
  118662. 6,
  118663. 14,
  118664. 5,
  118665. 15,
  118666. 4,
  118667. 16,
  118668. 3,
  118669. 17,
  118670. 2,
  118671. 18,
  118672. 1,
  118673. 19,
  118674. 0,
  118675. 20,
  118676. };
  118677. static long _vq_lengthlist__16c0_s_p9_2[] = {
  118678. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  118679. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  118680. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  118681. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  118682. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  118683. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  118684. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  118685. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  118686. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  118687. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  118688. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  118689. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  118690. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  118691. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  118692. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  118693. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  118694. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  118695. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  118696. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  118697. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  118698. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  118699. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  118700. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  118701. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  118702. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  118703. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  118704. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  118705. 10,11,10,10,11, 9,10,10,10,
  118706. };
  118707. static float _vq_quantthresh__16c0_s_p9_2[] = {
  118708. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118709. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118710. 6.5, 7.5, 8.5, 9.5,
  118711. };
  118712. static long _vq_quantmap__16c0_s_p9_2[] = {
  118713. 19, 17, 15, 13, 11, 9, 7, 5,
  118714. 3, 1, 0, 2, 4, 6, 8, 10,
  118715. 12, 14, 16, 18, 20,
  118716. };
  118717. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  118718. _vq_quantthresh__16c0_s_p9_2,
  118719. _vq_quantmap__16c0_s_p9_2,
  118720. 21,
  118721. 21
  118722. };
  118723. static static_codebook _16c0_s_p9_2 = {
  118724. 2, 441,
  118725. _vq_lengthlist__16c0_s_p9_2,
  118726. 1, -529268736, 1611661312, 5, 0,
  118727. _vq_quantlist__16c0_s_p9_2,
  118728. NULL,
  118729. &_vq_auxt__16c0_s_p9_2,
  118730. NULL,
  118731. 0
  118732. };
  118733. static long _huff_lengthlist__16c0_s_single[] = {
  118734. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  118735. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  118736. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  118737. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  118738. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  118739. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  118740. 16,16,18,18,
  118741. };
  118742. static static_codebook _huff_book__16c0_s_single = {
  118743. 2, 100,
  118744. _huff_lengthlist__16c0_s_single,
  118745. 0, 0, 0, 0, 0,
  118746. NULL,
  118747. NULL,
  118748. NULL,
  118749. NULL,
  118750. 0
  118751. };
  118752. static long _huff_lengthlist__16c1_s_long[] = {
  118753. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  118754. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  118755. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  118756. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  118757. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  118758. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  118759. 12,11,11,13,
  118760. };
  118761. static static_codebook _huff_book__16c1_s_long = {
  118762. 2, 100,
  118763. _huff_lengthlist__16c1_s_long,
  118764. 0, 0, 0, 0, 0,
  118765. NULL,
  118766. NULL,
  118767. NULL,
  118768. NULL,
  118769. 0
  118770. };
  118771. static long _vq_quantlist__16c1_s_p1_0[] = {
  118772. 1,
  118773. 0,
  118774. 2,
  118775. };
  118776. static long _vq_lengthlist__16c1_s_p1_0[] = {
  118777. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  118778. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118782. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  118783. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118787. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  118788. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  118823. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  118828. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  118829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118833. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  118834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118868. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118869. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118873. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  118874. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  118875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118878. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  118879. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  118880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119187. 0,
  119188. };
  119189. static float _vq_quantthresh__16c1_s_p1_0[] = {
  119190. -0.5, 0.5,
  119191. };
  119192. static long _vq_quantmap__16c1_s_p1_0[] = {
  119193. 1, 0, 2,
  119194. };
  119195. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  119196. _vq_quantthresh__16c1_s_p1_0,
  119197. _vq_quantmap__16c1_s_p1_0,
  119198. 3,
  119199. 3
  119200. };
  119201. static static_codebook _16c1_s_p1_0 = {
  119202. 8, 6561,
  119203. _vq_lengthlist__16c1_s_p1_0,
  119204. 1, -535822336, 1611661312, 2, 0,
  119205. _vq_quantlist__16c1_s_p1_0,
  119206. NULL,
  119207. &_vq_auxt__16c1_s_p1_0,
  119208. NULL,
  119209. 0
  119210. };
  119211. static long _vq_quantlist__16c1_s_p2_0[] = {
  119212. 2,
  119213. 1,
  119214. 3,
  119215. 0,
  119216. 4,
  119217. };
  119218. static long _vq_lengthlist__16c1_s_p2_0[] = {
  119219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119258. 0,
  119259. };
  119260. static float _vq_quantthresh__16c1_s_p2_0[] = {
  119261. -1.5, -0.5, 0.5, 1.5,
  119262. };
  119263. static long _vq_quantmap__16c1_s_p2_0[] = {
  119264. 3, 1, 0, 2, 4,
  119265. };
  119266. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  119267. _vq_quantthresh__16c1_s_p2_0,
  119268. _vq_quantmap__16c1_s_p2_0,
  119269. 5,
  119270. 5
  119271. };
  119272. static static_codebook _16c1_s_p2_0 = {
  119273. 4, 625,
  119274. _vq_lengthlist__16c1_s_p2_0,
  119275. 1, -533725184, 1611661312, 3, 0,
  119276. _vq_quantlist__16c1_s_p2_0,
  119277. NULL,
  119278. &_vq_auxt__16c1_s_p2_0,
  119279. NULL,
  119280. 0
  119281. };
  119282. static long _vq_quantlist__16c1_s_p3_0[] = {
  119283. 2,
  119284. 1,
  119285. 3,
  119286. 0,
  119287. 4,
  119288. };
  119289. static long _vq_lengthlist__16c1_s_p3_0[] = {
  119290. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  119292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119293. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  119295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119296. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  119297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119329. 0,
  119330. };
  119331. static float _vq_quantthresh__16c1_s_p3_0[] = {
  119332. -1.5, -0.5, 0.5, 1.5,
  119333. };
  119334. static long _vq_quantmap__16c1_s_p3_0[] = {
  119335. 3, 1, 0, 2, 4,
  119336. };
  119337. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  119338. _vq_quantthresh__16c1_s_p3_0,
  119339. _vq_quantmap__16c1_s_p3_0,
  119340. 5,
  119341. 5
  119342. };
  119343. static static_codebook _16c1_s_p3_0 = {
  119344. 4, 625,
  119345. _vq_lengthlist__16c1_s_p3_0,
  119346. 1, -533725184, 1611661312, 3, 0,
  119347. _vq_quantlist__16c1_s_p3_0,
  119348. NULL,
  119349. &_vq_auxt__16c1_s_p3_0,
  119350. NULL,
  119351. 0
  119352. };
  119353. static long _vq_quantlist__16c1_s_p4_0[] = {
  119354. 4,
  119355. 3,
  119356. 5,
  119357. 2,
  119358. 6,
  119359. 1,
  119360. 7,
  119361. 0,
  119362. 8,
  119363. };
  119364. static long _vq_lengthlist__16c1_s_p4_0[] = {
  119365. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  119366. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  119367. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  119368. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  119369. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119370. 0,
  119371. };
  119372. static float _vq_quantthresh__16c1_s_p4_0[] = {
  119373. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119374. };
  119375. static long _vq_quantmap__16c1_s_p4_0[] = {
  119376. 7, 5, 3, 1, 0, 2, 4, 6,
  119377. 8,
  119378. };
  119379. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  119380. _vq_quantthresh__16c1_s_p4_0,
  119381. _vq_quantmap__16c1_s_p4_0,
  119382. 9,
  119383. 9
  119384. };
  119385. static static_codebook _16c1_s_p4_0 = {
  119386. 2, 81,
  119387. _vq_lengthlist__16c1_s_p4_0,
  119388. 1, -531628032, 1611661312, 4, 0,
  119389. _vq_quantlist__16c1_s_p4_0,
  119390. NULL,
  119391. &_vq_auxt__16c1_s_p4_0,
  119392. NULL,
  119393. 0
  119394. };
  119395. static long _vq_quantlist__16c1_s_p5_0[] = {
  119396. 4,
  119397. 3,
  119398. 5,
  119399. 2,
  119400. 6,
  119401. 1,
  119402. 7,
  119403. 0,
  119404. 8,
  119405. };
  119406. static long _vq_lengthlist__16c1_s_p5_0[] = {
  119407. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  119408. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  119409. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  119410. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  119411. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119412. 10,
  119413. };
  119414. static float _vq_quantthresh__16c1_s_p5_0[] = {
  119415. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119416. };
  119417. static long _vq_quantmap__16c1_s_p5_0[] = {
  119418. 7, 5, 3, 1, 0, 2, 4, 6,
  119419. 8,
  119420. };
  119421. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  119422. _vq_quantthresh__16c1_s_p5_0,
  119423. _vq_quantmap__16c1_s_p5_0,
  119424. 9,
  119425. 9
  119426. };
  119427. static static_codebook _16c1_s_p5_0 = {
  119428. 2, 81,
  119429. _vq_lengthlist__16c1_s_p5_0,
  119430. 1, -531628032, 1611661312, 4, 0,
  119431. _vq_quantlist__16c1_s_p5_0,
  119432. NULL,
  119433. &_vq_auxt__16c1_s_p5_0,
  119434. NULL,
  119435. 0
  119436. };
  119437. static long _vq_quantlist__16c1_s_p6_0[] = {
  119438. 8,
  119439. 7,
  119440. 9,
  119441. 6,
  119442. 10,
  119443. 5,
  119444. 11,
  119445. 4,
  119446. 12,
  119447. 3,
  119448. 13,
  119449. 2,
  119450. 14,
  119451. 1,
  119452. 15,
  119453. 0,
  119454. 16,
  119455. };
  119456. static long _vq_lengthlist__16c1_s_p6_0[] = {
  119457. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  119458. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  119459. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  119460. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  119461. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  119462. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  119463. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  119464. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  119465. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  119466. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119467. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  119468. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  119469. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  119470. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  119471. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  119472. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  119473. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  119474. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  119475. 14,
  119476. };
  119477. static float _vq_quantthresh__16c1_s_p6_0[] = {
  119478. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119479. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119480. };
  119481. static long _vq_quantmap__16c1_s_p6_0[] = {
  119482. 15, 13, 11, 9, 7, 5, 3, 1,
  119483. 0, 2, 4, 6, 8, 10, 12, 14,
  119484. 16,
  119485. };
  119486. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  119487. _vq_quantthresh__16c1_s_p6_0,
  119488. _vq_quantmap__16c1_s_p6_0,
  119489. 17,
  119490. 17
  119491. };
  119492. static static_codebook _16c1_s_p6_0 = {
  119493. 2, 289,
  119494. _vq_lengthlist__16c1_s_p6_0,
  119495. 1, -529530880, 1611661312, 5, 0,
  119496. _vq_quantlist__16c1_s_p6_0,
  119497. NULL,
  119498. &_vq_auxt__16c1_s_p6_0,
  119499. NULL,
  119500. 0
  119501. };
  119502. static long _vq_quantlist__16c1_s_p7_0[] = {
  119503. 1,
  119504. 0,
  119505. 2,
  119506. };
  119507. static long _vq_lengthlist__16c1_s_p7_0[] = {
  119508. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  119509. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  119510. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  119511. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  119512. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  119513. 11,
  119514. };
  119515. static float _vq_quantthresh__16c1_s_p7_0[] = {
  119516. -5.5, 5.5,
  119517. };
  119518. static long _vq_quantmap__16c1_s_p7_0[] = {
  119519. 1, 0, 2,
  119520. };
  119521. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  119522. _vq_quantthresh__16c1_s_p7_0,
  119523. _vq_quantmap__16c1_s_p7_0,
  119524. 3,
  119525. 3
  119526. };
  119527. static static_codebook _16c1_s_p7_0 = {
  119528. 4, 81,
  119529. _vq_lengthlist__16c1_s_p7_0,
  119530. 1, -529137664, 1618345984, 2, 0,
  119531. _vq_quantlist__16c1_s_p7_0,
  119532. NULL,
  119533. &_vq_auxt__16c1_s_p7_0,
  119534. NULL,
  119535. 0
  119536. };
  119537. static long _vq_quantlist__16c1_s_p7_1[] = {
  119538. 5,
  119539. 4,
  119540. 6,
  119541. 3,
  119542. 7,
  119543. 2,
  119544. 8,
  119545. 1,
  119546. 9,
  119547. 0,
  119548. 10,
  119549. };
  119550. static long _vq_lengthlist__16c1_s_p7_1[] = {
  119551. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  119552. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  119553. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  119554. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  119555. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  119556. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  119557. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  119558. 10,10,10, 8, 8, 8, 8, 9, 9,
  119559. };
  119560. static float _vq_quantthresh__16c1_s_p7_1[] = {
  119561. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119562. 3.5, 4.5,
  119563. };
  119564. static long _vq_quantmap__16c1_s_p7_1[] = {
  119565. 9, 7, 5, 3, 1, 0, 2, 4,
  119566. 6, 8, 10,
  119567. };
  119568. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  119569. _vq_quantthresh__16c1_s_p7_1,
  119570. _vq_quantmap__16c1_s_p7_1,
  119571. 11,
  119572. 11
  119573. };
  119574. static static_codebook _16c1_s_p7_1 = {
  119575. 2, 121,
  119576. _vq_lengthlist__16c1_s_p7_1,
  119577. 1, -531365888, 1611661312, 4, 0,
  119578. _vq_quantlist__16c1_s_p7_1,
  119579. NULL,
  119580. &_vq_auxt__16c1_s_p7_1,
  119581. NULL,
  119582. 0
  119583. };
  119584. static long _vq_quantlist__16c1_s_p8_0[] = {
  119585. 6,
  119586. 5,
  119587. 7,
  119588. 4,
  119589. 8,
  119590. 3,
  119591. 9,
  119592. 2,
  119593. 10,
  119594. 1,
  119595. 11,
  119596. 0,
  119597. 12,
  119598. };
  119599. static long _vq_lengthlist__16c1_s_p8_0[] = {
  119600. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  119601. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  119602. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  119603. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  119604. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  119605. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  119606. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  119607. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  119608. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  119609. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  119610. 0,12,12,12,12,13,13,14,15,
  119611. };
  119612. static float _vq_quantthresh__16c1_s_p8_0[] = {
  119613. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119614. 12.5, 17.5, 22.5, 27.5,
  119615. };
  119616. static long _vq_quantmap__16c1_s_p8_0[] = {
  119617. 11, 9, 7, 5, 3, 1, 0, 2,
  119618. 4, 6, 8, 10, 12,
  119619. };
  119620. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  119621. _vq_quantthresh__16c1_s_p8_0,
  119622. _vq_quantmap__16c1_s_p8_0,
  119623. 13,
  119624. 13
  119625. };
  119626. static static_codebook _16c1_s_p8_0 = {
  119627. 2, 169,
  119628. _vq_lengthlist__16c1_s_p8_0,
  119629. 1, -526516224, 1616117760, 4, 0,
  119630. _vq_quantlist__16c1_s_p8_0,
  119631. NULL,
  119632. &_vq_auxt__16c1_s_p8_0,
  119633. NULL,
  119634. 0
  119635. };
  119636. static long _vq_quantlist__16c1_s_p8_1[] = {
  119637. 2,
  119638. 1,
  119639. 3,
  119640. 0,
  119641. 4,
  119642. };
  119643. static long _vq_lengthlist__16c1_s_p8_1[] = {
  119644. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  119645. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  119646. };
  119647. static float _vq_quantthresh__16c1_s_p8_1[] = {
  119648. -1.5, -0.5, 0.5, 1.5,
  119649. };
  119650. static long _vq_quantmap__16c1_s_p8_1[] = {
  119651. 3, 1, 0, 2, 4,
  119652. };
  119653. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  119654. _vq_quantthresh__16c1_s_p8_1,
  119655. _vq_quantmap__16c1_s_p8_1,
  119656. 5,
  119657. 5
  119658. };
  119659. static static_codebook _16c1_s_p8_1 = {
  119660. 2, 25,
  119661. _vq_lengthlist__16c1_s_p8_1,
  119662. 1, -533725184, 1611661312, 3, 0,
  119663. _vq_quantlist__16c1_s_p8_1,
  119664. NULL,
  119665. &_vq_auxt__16c1_s_p8_1,
  119666. NULL,
  119667. 0
  119668. };
  119669. static long _vq_quantlist__16c1_s_p9_0[] = {
  119670. 6,
  119671. 5,
  119672. 7,
  119673. 4,
  119674. 8,
  119675. 3,
  119676. 9,
  119677. 2,
  119678. 10,
  119679. 1,
  119680. 11,
  119681. 0,
  119682. 12,
  119683. };
  119684. static long _vq_lengthlist__16c1_s_p9_0[] = {
  119685. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119686. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119687. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119688. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119689. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119690. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119691. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119692. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119693. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119694. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119695. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119696. };
  119697. static float _vq_quantthresh__16c1_s_p9_0[] = {
  119698. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  119699. 787.5, 1102.5, 1417.5, 1732.5,
  119700. };
  119701. static long _vq_quantmap__16c1_s_p9_0[] = {
  119702. 11, 9, 7, 5, 3, 1, 0, 2,
  119703. 4, 6, 8, 10, 12,
  119704. };
  119705. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  119706. _vq_quantthresh__16c1_s_p9_0,
  119707. _vq_quantmap__16c1_s_p9_0,
  119708. 13,
  119709. 13
  119710. };
  119711. static static_codebook _16c1_s_p9_0 = {
  119712. 2, 169,
  119713. _vq_lengthlist__16c1_s_p9_0,
  119714. 1, -513964032, 1628680192, 4, 0,
  119715. _vq_quantlist__16c1_s_p9_0,
  119716. NULL,
  119717. &_vq_auxt__16c1_s_p9_0,
  119718. NULL,
  119719. 0
  119720. };
  119721. static long _vq_quantlist__16c1_s_p9_1[] = {
  119722. 7,
  119723. 6,
  119724. 8,
  119725. 5,
  119726. 9,
  119727. 4,
  119728. 10,
  119729. 3,
  119730. 11,
  119731. 2,
  119732. 12,
  119733. 1,
  119734. 13,
  119735. 0,
  119736. 14,
  119737. };
  119738. static long _vq_lengthlist__16c1_s_p9_1[] = {
  119739. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  119740. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  119741. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  119742. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  119743. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  119744. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  119745. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  119746. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  119747. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  119748. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  119749. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  119750. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  119751. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  119752. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  119753. 13,
  119754. };
  119755. static float _vq_quantthresh__16c1_s_p9_1[] = {
  119756. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119757. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119758. };
  119759. static long _vq_quantmap__16c1_s_p9_1[] = {
  119760. 13, 11, 9, 7, 5, 3, 1, 0,
  119761. 2, 4, 6, 8, 10, 12, 14,
  119762. };
  119763. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  119764. _vq_quantthresh__16c1_s_p9_1,
  119765. _vq_quantmap__16c1_s_p9_1,
  119766. 15,
  119767. 15
  119768. };
  119769. static static_codebook _16c1_s_p9_1 = {
  119770. 2, 225,
  119771. _vq_lengthlist__16c1_s_p9_1,
  119772. 1, -520986624, 1620377600, 4, 0,
  119773. _vq_quantlist__16c1_s_p9_1,
  119774. NULL,
  119775. &_vq_auxt__16c1_s_p9_1,
  119776. NULL,
  119777. 0
  119778. };
  119779. static long _vq_quantlist__16c1_s_p9_2[] = {
  119780. 10,
  119781. 9,
  119782. 11,
  119783. 8,
  119784. 12,
  119785. 7,
  119786. 13,
  119787. 6,
  119788. 14,
  119789. 5,
  119790. 15,
  119791. 4,
  119792. 16,
  119793. 3,
  119794. 17,
  119795. 2,
  119796. 18,
  119797. 1,
  119798. 19,
  119799. 0,
  119800. 20,
  119801. };
  119802. static long _vq_lengthlist__16c1_s_p9_2[] = {
  119803. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  119804. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  119805. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  119806. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  119807. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  119808. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  119809. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  119810. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  119811. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  119812. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  119813. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  119814. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  119815. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  119816. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  119817. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  119818. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  119819. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  119820. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  119821. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  119822. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  119823. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  119824. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  119825. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  119826. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  119827. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  119828. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  119829. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  119830. 11,11,11,11,12,11,11,12,11,
  119831. };
  119832. static float _vq_quantthresh__16c1_s_p9_2[] = {
  119833. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119834. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119835. 6.5, 7.5, 8.5, 9.5,
  119836. };
  119837. static long _vq_quantmap__16c1_s_p9_2[] = {
  119838. 19, 17, 15, 13, 11, 9, 7, 5,
  119839. 3, 1, 0, 2, 4, 6, 8, 10,
  119840. 12, 14, 16, 18, 20,
  119841. };
  119842. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  119843. _vq_quantthresh__16c1_s_p9_2,
  119844. _vq_quantmap__16c1_s_p9_2,
  119845. 21,
  119846. 21
  119847. };
  119848. static static_codebook _16c1_s_p9_2 = {
  119849. 2, 441,
  119850. _vq_lengthlist__16c1_s_p9_2,
  119851. 1, -529268736, 1611661312, 5, 0,
  119852. _vq_quantlist__16c1_s_p9_2,
  119853. NULL,
  119854. &_vq_auxt__16c1_s_p9_2,
  119855. NULL,
  119856. 0
  119857. };
  119858. static long _huff_lengthlist__16c1_s_short[] = {
  119859. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  119860. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  119861. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  119862. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  119863. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  119864. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  119865. 9, 9,10,13,
  119866. };
  119867. static static_codebook _huff_book__16c1_s_short = {
  119868. 2, 100,
  119869. _huff_lengthlist__16c1_s_short,
  119870. 0, 0, 0, 0, 0,
  119871. NULL,
  119872. NULL,
  119873. NULL,
  119874. NULL,
  119875. 0
  119876. };
  119877. static long _huff_lengthlist__16c2_s_long[] = {
  119878. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  119879. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  119880. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  119881. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  119882. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  119883. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  119884. 14,14,16,18,
  119885. };
  119886. static static_codebook _huff_book__16c2_s_long = {
  119887. 2, 100,
  119888. _huff_lengthlist__16c2_s_long,
  119889. 0, 0, 0, 0, 0,
  119890. NULL,
  119891. NULL,
  119892. NULL,
  119893. NULL,
  119894. 0
  119895. };
  119896. static long _vq_quantlist__16c2_s_p1_0[] = {
  119897. 1,
  119898. 0,
  119899. 2,
  119900. };
  119901. static long _vq_lengthlist__16c2_s_p1_0[] = {
  119902. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  119903. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119907. 0,
  119908. };
  119909. static float _vq_quantthresh__16c2_s_p1_0[] = {
  119910. -0.5, 0.5,
  119911. };
  119912. static long _vq_quantmap__16c2_s_p1_0[] = {
  119913. 1, 0, 2,
  119914. };
  119915. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  119916. _vq_quantthresh__16c2_s_p1_0,
  119917. _vq_quantmap__16c2_s_p1_0,
  119918. 3,
  119919. 3
  119920. };
  119921. static static_codebook _16c2_s_p1_0 = {
  119922. 4, 81,
  119923. _vq_lengthlist__16c2_s_p1_0,
  119924. 1, -535822336, 1611661312, 2, 0,
  119925. _vq_quantlist__16c2_s_p1_0,
  119926. NULL,
  119927. &_vq_auxt__16c2_s_p1_0,
  119928. NULL,
  119929. 0
  119930. };
  119931. static long _vq_quantlist__16c2_s_p2_0[] = {
  119932. 2,
  119933. 1,
  119934. 3,
  119935. 0,
  119936. 4,
  119937. };
  119938. static long _vq_lengthlist__16c2_s_p2_0[] = {
  119939. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  119940. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  119941. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  119942. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  119943. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  119944. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  119945. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  119946. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  119947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119951. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  119952. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  119953. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  119954. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  119955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119959. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  119960. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  119961. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  119962. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119967. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  119968. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  119969. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  119970. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  119975. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  119976. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  119977. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  119978. 13,
  119979. };
  119980. static float _vq_quantthresh__16c2_s_p2_0[] = {
  119981. -1.5, -0.5, 0.5, 1.5,
  119982. };
  119983. static long _vq_quantmap__16c2_s_p2_0[] = {
  119984. 3, 1, 0, 2, 4,
  119985. };
  119986. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  119987. _vq_quantthresh__16c2_s_p2_0,
  119988. _vq_quantmap__16c2_s_p2_0,
  119989. 5,
  119990. 5
  119991. };
  119992. static static_codebook _16c2_s_p2_0 = {
  119993. 4, 625,
  119994. _vq_lengthlist__16c2_s_p2_0,
  119995. 1, -533725184, 1611661312, 3, 0,
  119996. _vq_quantlist__16c2_s_p2_0,
  119997. NULL,
  119998. &_vq_auxt__16c2_s_p2_0,
  119999. NULL,
  120000. 0
  120001. };
  120002. static long _vq_quantlist__16c2_s_p3_0[] = {
  120003. 4,
  120004. 3,
  120005. 5,
  120006. 2,
  120007. 6,
  120008. 1,
  120009. 7,
  120010. 0,
  120011. 8,
  120012. };
  120013. static long _vq_lengthlist__16c2_s_p3_0[] = {
  120014. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  120015. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  120016. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  120017. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  120018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120019. 0,
  120020. };
  120021. static float _vq_quantthresh__16c2_s_p3_0[] = {
  120022. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120023. };
  120024. static long _vq_quantmap__16c2_s_p3_0[] = {
  120025. 7, 5, 3, 1, 0, 2, 4, 6,
  120026. 8,
  120027. };
  120028. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  120029. _vq_quantthresh__16c2_s_p3_0,
  120030. _vq_quantmap__16c2_s_p3_0,
  120031. 9,
  120032. 9
  120033. };
  120034. static static_codebook _16c2_s_p3_0 = {
  120035. 2, 81,
  120036. _vq_lengthlist__16c2_s_p3_0,
  120037. 1, -531628032, 1611661312, 4, 0,
  120038. _vq_quantlist__16c2_s_p3_0,
  120039. NULL,
  120040. &_vq_auxt__16c2_s_p3_0,
  120041. NULL,
  120042. 0
  120043. };
  120044. static long _vq_quantlist__16c2_s_p4_0[] = {
  120045. 8,
  120046. 7,
  120047. 9,
  120048. 6,
  120049. 10,
  120050. 5,
  120051. 11,
  120052. 4,
  120053. 12,
  120054. 3,
  120055. 13,
  120056. 2,
  120057. 14,
  120058. 1,
  120059. 15,
  120060. 0,
  120061. 16,
  120062. };
  120063. static long _vq_lengthlist__16c2_s_p4_0[] = {
  120064. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  120065. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  120066. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  120067. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  120068. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  120069. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  120070. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  120071. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  120072. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  120073. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  120074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120082. 0,
  120083. };
  120084. static float _vq_quantthresh__16c2_s_p4_0[] = {
  120085. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120086. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120087. };
  120088. static long _vq_quantmap__16c2_s_p4_0[] = {
  120089. 15, 13, 11, 9, 7, 5, 3, 1,
  120090. 0, 2, 4, 6, 8, 10, 12, 14,
  120091. 16,
  120092. };
  120093. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  120094. _vq_quantthresh__16c2_s_p4_0,
  120095. _vq_quantmap__16c2_s_p4_0,
  120096. 17,
  120097. 17
  120098. };
  120099. static static_codebook _16c2_s_p4_0 = {
  120100. 2, 289,
  120101. _vq_lengthlist__16c2_s_p4_0,
  120102. 1, -529530880, 1611661312, 5, 0,
  120103. _vq_quantlist__16c2_s_p4_0,
  120104. NULL,
  120105. &_vq_auxt__16c2_s_p4_0,
  120106. NULL,
  120107. 0
  120108. };
  120109. static long _vq_quantlist__16c2_s_p5_0[] = {
  120110. 1,
  120111. 0,
  120112. 2,
  120113. };
  120114. static long _vq_lengthlist__16c2_s_p5_0[] = {
  120115. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  120116. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  120117. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  120118. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  120119. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  120120. 12,
  120121. };
  120122. static float _vq_quantthresh__16c2_s_p5_0[] = {
  120123. -5.5, 5.5,
  120124. };
  120125. static long _vq_quantmap__16c2_s_p5_0[] = {
  120126. 1, 0, 2,
  120127. };
  120128. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  120129. _vq_quantthresh__16c2_s_p5_0,
  120130. _vq_quantmap__16c2_s_p5_0,
  120131. 3,
  120132. 3
  120133. };
  120134. static static_codebook _16c2_s_p5_0 = {
  120135. 4, 81,
  120136. _vq_lengthlist__16c2_s_p5_0,
  120137. 1, -529137664, 1618345984, 2, 0,
  120138. _vq_quantlist__16c2_s_p5_0,
  120139. NULL,
  120140. &_vq_auxt__16c2_s_p5_0,
  120141. NULL,
  120142. 0
  120143. };
  120144. static long _vq_quantlist__16c2_s_p5_1[] = {
  120145. 5,
  120146. 4,
  120147. 6,
  120148. 3,
  120149. 7,
  120150. 2,
  120151. 8,
  120152. 1,
  120153. 9,
  120154. 0,
  120155. 10,
  120156. };
  120157. static long _vq_lengthlist__16c2_s_p5_1[] = {
  120158. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  120159. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  120160. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  120161. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  120162. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  120163. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  120164. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  120165. 11,11,11, 7, 7, 8, 8, 8, 8,
  120166. };
  120167. static float _vq_quantthresh__16c2_s_p5_1[] = {
  120168. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120169. 3.5, 4.5,
  120170. };
  120171. static long _vq_quantmap__16c2_s_p5_1[] = {
  120172. 9, 7, 5, 3, 1, 0, 2, 4,
  120173. 6, 8, 10,
  120174. };
  120175. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  120176. _vq_quantthresh__16c2_s_p5_1,
  120177. _vq_quantmap__16c2_s_p5_1,
  120178. 11,
  120179. 11
  120180. };
  120181. static static_codebook _16c2_s_p5_1 = {
  120182. 2, 121,
  120183. _vq_lengthlist__16c2_s_p5_1,
  120184. 1, -531365888, 1611661312, 4, 0,
  120185. _vq_quantlist__16c2_s_p5_1,
  120186. NULL,
  120187. &_vq_auxt__16c2_s_p5_1,
  120188. NULL,
  120189. 0
  120190. };
  120191. static long _vq_quantlist__16c2_s_p6_0[] = {
  120192. 6,
  120193. 5,
  120194. 7,
  120195. 4,
  120196. 8,
  120197. 3,
  120198. 9,
  120199. 2,
  120200. 10,
  120201. 1,
  120202. 11,
  120203. 0,
  120204. 12,
  120205. };
  120206. static long _vq_lengthlist__16c2_s_p6_0[] = {
  120207. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120208. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  120209. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  120210. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  120211. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  120212. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  120213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120217. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120218. };
  120219. static float _vq_quantthresh__16c2_s_p6_0[] = {
  120220. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120221. 12.5, 17.5, 22.5, 27.5,
  120222. };
  120223. static long _vq_quantmap__16c2_s_p6_0[] = {
  120224. 11, 9, 7, 5, 3, 1, 0, 2,
  120225. 4, 6, 8, 10, 12,
  120226. };
  120227. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  120228. _vq_quantthresh__16c2_s_p6_0,
  120229. _vq_quantmap__16c2_s_p6_0,
  120230. 13,
  120231. 13
  120232. };
  120233. static static_codebook _16c2_s_p6_0 = {
  120234. 2, 169,
  120235. _vq_lengthlist__16c2_s_p6_0,
  120236. 1, -526516224, 1616117760, 4, 0,
  120237. _vq_quantlist__16c2_s_p6_0,
  120238. NULL,
  120239. &_vq_auxt__16c2_s_p6_0,
  120240. NULL,
  120241. 0
  120242. };
  120243. static long _vq_quantlist__16c2_s_p6_1[] = {
  120244. 2,
  120245. 1,
  120246. 3,
  120247. 0,
  120248. 4,
  120249. };
  120250. static long _vq_lengthlist__16c2_s_p6_1[] = {
  120251. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120252. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120253. };
  120254. static float _vq_quantthresh__16c2_s_p6_1[] = {
  120255. -1.5, -0.5, 0.5, 1.5,
  120256. };
  120257. static long _vq_quantmap__16c2_s_p6_1[] = {
  120258. 3, 1, 0, 2, 4,
  120259. };
  120260. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  120261. _vq_quantthresh__16c2_s_p6_1,
  120262. _vq_quantmap__16c2_s_p6_1,
  120263. 5,
  120264. 5
  120265. };
  120266. static static_codebook _16c2_s_p6_1 = {
  120267. 2, 25,
  120268. _vq_lengthlist__16c2_s_p6_1,
  120269. 1, -533725184, 1611661312, 3, 0,
  120270. _vq_quantlist__16c2_s_p6_1,
  120271. NULL,
  120272. &_vq_auxt__16c2_s_p6_1,
  120273. NULL,
  120274. 0
  120275. };
  120276. static long _vq_quantlist__16c2_s_p7_0[] = {
  120277. 6,
  120278. 5,
  120279. 7,
  120280. 4,
  120281. 8,
  120282. 3,
  120283. 9,
  120284. 2,
  120285. 10,
  120286. 1,
  120287. 11,
  120288. 0,
  120289. 12,
  120290. };
  120291. static long _vq_lengthlist__16c2_s_p7_0[] = {
  120292. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120293. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  120294. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  120295. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  120296. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  120297. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  120298. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  120299. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  120300. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  120301. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  120302. 18,13,14,13,13,14,13,15,14,
  120303. };
  120304. static float _vq_quantthresh__16c2_s_p7_0[] = {
  120305. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  120306. 27.5, 38.5, 49.5, 60.5,
  120307. };
  120308. static long _vq_quantmap__16c2_s_p7_0[] = {
  120309. 11, 9, 7, 5, 3, 1, 0, 2,
  120310. 4, 6, 8, 10, 12,
  120311. };
  120312. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  120313. _vq_quantthresh__16c2_s_p7_0,
  120314. _vq_quantmap__16c2_s_p7_0,
  120315. 13,
  120316. 13
  120317. };
  120318. static static_codebook _16c2_s_p7_0 = {
  120319. 2, 169,
  120320. _vq_lengthlist__16c2_s_p7_0,
  120321. 1, -523206656, 1618345984, 4, 0,
  120322. _vq_quantlist__16c2_s_p7_0,
  120323. NULL,
  120324. &_vq_auxt__16c2_s_p7_0,
  120325. NULL,
  120326. 0
  120327. };
  120328. static long _vq_quantlist__16c2_s_p7_1[] = {
  120329. 5,
  120330. 4,
  120331. 6,
  120332. 3,
  120333. 7,
  120334. 2,
  120335. 8,
  120336. 1,
  120337. 9,
  120338. 0,
  120339. 10,
  120340. };
  120341. static long _vq_lengthlist__16c2_s_p7_1[] = {
  120342. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  120343. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  120344. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  120345. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  120346. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  120347. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  120348. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  120349. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  120350. };
  120351. static float _vq_quantthresh__16c2_s_p7_1[] = {
  120352. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120353. 3.5, 4.5,
  120354. };
  120355. static long _vq_quantmap__16c2_s_p7_1[] = {
  120356. 9, 7, 5, 3, 1, 0, 2, 4,
  120357. 6, 8, 10,
  120358. };
  120359. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  120360. _vq_quantthresh__16c2_s_p7_1,
  120361. _vq_quantmap__16c2_s_p7_1,
  120362. 11,
  120363. 11
  120364. };
  120365. static static_codebook _16c2_s_p7_1 = {
  120366. 2, 121,
  120367. _vq_lengthlist__16c2_s_p7_1,
  120368. 1, -531365888, 1611661312, 4, 0,
  120369. _vq_quantlist__16c2_s_p7_1,
  120370. NULL,
  120371. &_vq_auxt__16c2_s_p7_1,
  120372. NULL,
  120373. 0
  120374. };
  120375. static long _vq_quantlist__16c2_s_p8_0[] = {
  120376. 7,
  120377. 6,
  120378. 8,
  120379. 5,
  120380. 9,
  120381. 4,
  120382. 10,
  120383. 3,
  120384. 11,
  120385. 2,
  120386. 12,
  120387. 1,
  120388. 13,
  120389. 0,
  120390. 14,
  120391. };
  120392. static long _vq_lengthlist__16c2_s_p8_0[] = {
  120393. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  120394. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  120395. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  120396. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  120397. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  120398. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  120399. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  120400. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  120401. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  120402. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  120403. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  120404. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  120405. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  120406. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  120407. 13,
  120408. };
  120409. static float _vq_quantthresh__16c2_s_p8_0[] = {
  120410. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120411. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120412. };
  120413. static long _vq_quantmap__16c2_s_p8_0[] = {
  120414. 13, 11, 9, 7, 5, 3, 1, 0,
  120415. 2, 4, 6, 8, 10, 12, 14,
  120416. };
  120417. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  120418. _vq_quantthresh__16c2_s_p8_0,
  120419. _vq_quantmap__16c2_s_p8_0,
  120420. 15,
  120421. 15
  120422. };
  120423. static static_codebook _16c2_s_p8_0 = {
  120424. 2, 225,
  120425. _vq_lengthlist__16c2_s_p8_0,
  120426. 1, -520986624, 1620377600, 4, 0,
  120427. _vq_quantlist__16c2_s_p8_0,
  120428. NULL,
  120429. &_vq_auxt__16c2_s_p8_0,
  120430. NULL,
  120431. 0
  120432. };
  120433. static long _vq_quantlist__16c2_s_p8_1[] = {
  120434. 10,
  120435. 9,
  120436. 11,
  120437. 8,
  120438. 12,
  120439. 7,
  120440. 13,
  120441. 6,
  120442. 14,
  120443. 5,
  120444. 15,
  120445. 4,
  120446. 16,
  120447. 3,
  120448. 17,
  120449. 2,
  120450. 18,
  120451. 1,
  120452. 19,
  120453. 0,
  120454. 20,
  120455. };
  120456. static long _vq_lengthlist__16c2_s_p8_1[] = {
  120457. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  120458. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  120459. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  120460. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  120461. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  120462. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  120463. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  120464. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  120465. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  120466. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  120467. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  120468. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  120469. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  120470. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  120471. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  120472. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  120473. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  120474. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  120475. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  120476. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  120477. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  120478. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  120479. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  120480. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  120481. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  120482. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  120483. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  120484. 10,11,10,10,10,10,10,10,10,
  120485. };
  120486. static float _vq_quantthresh__16c2_s_p8_1[] = {
  120487. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120488. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120489. 6.5, 7.5, 8.5, 9.5,
  120490. };
  120491. static long _vq_quantmap__16c2_s_p8_1[] = {
  120492. 19, 17, 15, 13, 11, 9, 7, 5,
  120493. 3, 1, 0, 2, 4, 6, 8, 10,
  120494. 12, 14, 16, 18, 20,
  120495. };
  120496. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  120497. _vq_quantthresh__16c2_s_p8_1,
  120498. _vq_quantmap__16c2_s_p8_1,
  120499. 21,
  120500. 21
  120501. };
  120502. static static_codebook _16c2_s_p8_1 = {
  120503. 2, 441,
  120504. _vq_lengthlist__16c2_s_p8_1,
  120505. 1, -529268736, 1611661312, 5, 0,
  120506. _vq_quantlist__16c2_s_p8_1,
  120507. NULL,
  120508. &_vq_auxt__16c2_s_p8_1,
  120509. NULL,
  120510. 0
  120511. };
  120512. static long _vq_quantlist__16c2_s_p9_0[] = {
  120513. 6,
  120514. 5,
  120515. 7,
  120516. 4,
  120517. 8,
  120518. 3,
  120519. 9,
  120520. 2,
  120521. 10,
  120522. 1,
  120523. 11,
  120524. 0,
  120525. 12,
  120526. };
  120527. static long _vq_lengthlist__16c2_s_p9_0[] = {
  120528. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120529. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120530. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120531. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120532. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120533. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120534. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120535. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120536. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120537. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120538. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120539. };
  120540. static float _vq_quantthresh__16c2_s_p9_0[] = {
  120541. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  120542. 2327.5, 3258.5, 4189.5, 5120.5,
  120543. };
  120544. static long _vq_quantmap__16c2_s_p9_0[] = {
  120545. 11, 9, 7, 5, 3, 1, 0, 2,
  120546. 4, 6, 8, 10, 12,
  120547. };
  120548. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  120549. _vq_quantthresh__16c2_s_p9_0,
  120550. _vq_quantmap__16c2_s_p9_0,
  120551. 13,
  120552. 13
  120553. };
  120554. static static_codebook _16c2_s_p9_0 = {
  120555. 2, 169,
  120556. _vq_lengthlist__16c2_s_p9_0,
  120557. 1, -510275072, 1631393792, 4, 0,
  120558. _vq_quantlist__16c2_s_p9_0,
  120559. NULL,
  120560. &_vq_auxt__16c2_s_p9_0,
  120561. NULL,
  120562. 0
  120563. };
  120564. static long _vq_quantlist__16c2_s_p9_1[] = {
  120565. 8,
  120566. 7,
  120567. 9,
  120568. 6,
  120569. 10,
  120570. 5,
  120571. 11,
  120572. 4,
  120573. 12,
  120574. 3,
  120575. 13,
  120576. 2,
  120577. 14,
  120578. 1,
  120579. 15,
  120580. 0,
  120581. 16,
  120582. };
  120583. static long _vq_lengthlist__16c2_s_p9_1[] = {
  120584. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  120585. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  120586. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  120587. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  120588. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  120589. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  120590. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  120591. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  120592. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  120593. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  120594. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120595. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120596. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120597. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120598. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120599. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  120600. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  120601. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120602. 10,
  120603. };
  120604. static float _vq_quantthresh__16c2_s_p9_1[] = {
  120605. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  120606. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  120607. };
  120608. static long _vq_quantmap__16c2_s_p9_1[] = {
  120609. 15, 13, 11, 9, 7, 5, 3, 1,
  120610. 0, 2, 4, 6, 8, 10, 12, 14,
  120611. 16,
  120612. };
  120613. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  120614. _vq_quantthresh__16c2_s_p9_1,
  120615. _vq_quantmap__16c2_s_p9_1,
  120616. 17,
  120617. 17
  120618. };
  120619. static static_codebook _16c2_s_p9_1 = {
  120620. 2, 289,
  120621. _vq_lengthlist__16c2_s_p9_1,
  120622. 1, -518488064, 1622704128, 5, 0,
  120623. _vq_quantlist__16c2_s_p9_1,
  120624. NULL,
  120625. &_vq_auxt__16c2_s_p9_1,
  120626. NULL,
  120627. 0
  120628. };
  120629. static long _vq_quantlist__16c2_s_p9_2[] = {
  120630. 13,
  120631. 12,
  120632. 14,
  120633. 11,
  120634. 15,
  120635. 10,
  120636. 16,
  120637. 9,
  120638. 17,
  120639. 8,
  120640. 18,
  120641. 7,
  120642. 19,
  120643. 6,
  120644. 20,
  120645. 5,
  120646. 21,
  120647. 4,
  120648. 22,
  120649. 3,
  120650. 23,
  120651. 2,
  120652. 24,
  120653. 1,
  120654. 25,
  120655. 0,
  120656. 26,
  120657. };
  120658. static long _vq_lengthlist__16c2_s_p9_2[] = {
  120659. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  120660. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  120661. };
  120662. static float _vq_quantthresh__16c2_s_p9_2[] = {
  120663. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  120664. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120665. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  120666. 11.5, 12.5,
  120667. };
  120668. static long _vq_quantmap__16c2_s_p9_2[] = {
  120669. 25, 23, 21, 19, 17, 15, 13, 11,
  120670. 9, 7, 5, 3, 1, 0, 2, 4,
  120671. 6, 8, 10, 12, 14, 16, 18, 20,
  120672. 22, 24, 26,
  120673. };
  120674. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  120675. _vq_quantthresh__16c2_s_p9_2,
  120676. _vq_quantmap__16c2_s_p9_2,
  120677. 27,
  120678. 27
  120679. };
  120680. static static_codebook _16c2_s_p9_2 = {
  120681. 1, 27,
  120682. _vq_lengthlist__16c2_s_p9_2,
  120683. 1, -528875520, 1611661312, 5, 0,
  120684. _vq_quantlist__16c2_s_p9_2,
  120685. NULL,
  120686. &_vq_auxt__16c2_s_p9_2,
  120687. NULL,
  120688. 0
  120689. };
  120690. static long _huff_lengthlist__16c2_s_short[] = {
  120691. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  120692. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  120693. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  120694. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  120695. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  120696. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  120697. 15,12,14,14,
  120698. };
  120699. static static_codebook _huff_book__16c2_s_short = {
  120700. 2, 100,
  120701. _huff_lengthlist__16c2_s_short,
  120702. 0, 0, 0, 0, 0,
  120703. NULL,
  120704. NULL,
  120705. NULL,
  120706. NULL,
  120707. 0
  120708. };
  120709. static long _vq_quantlist__8c0_s_p1_0[] = {
  120710. 1,
  120711. 0,
  120712. 2,
  120713. };
  120714. static long _vq_lengthlist__8c0_s_p1_0[] = {
  120715. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120716. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120720. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  120721. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120725. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120726. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  120761. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  120766. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  120767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  120771. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  120772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120806. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120807. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120811. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  120812. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  120813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120816. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  120817. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  120818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121125. 0,
  121126. };
  121127. static float _vq_quantthresh__8c0_s_p1_0[] = {
  121128. -0.5, 0.5,
  121129. };
  121130. static long _vq_quantmap__8c0_s_p1_0[] = {
  121131. 1, 0, 2,
  121132. };
  121133. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  121134. _vq_quantthresh__8c0_s_p1_0,
  121135. _vq_quantmap__8c0_s_p1_0,
  121136. 3,
  121137. 3
  121138. };
  121139. static static_codebook _8c0_s_p1_0 = {
  121140. 8, 6561,
  121141. _vq_lengthlist__8c0_s_p1_0,
  121142. 1, -535822336, 1611661312, 2, 0,
  121143. _vq_quantlist__8c0_s_p1_0,
  121144. NULL,
  121145. &_vq_auxt__8c0_s_p1_0,
  121146. NULL,
  121147. 0
  121148. };
  121149. static long _vq_quantlist__8c0_s_p2_0[] = {
  121150. 2,
  121151. 1,
  121152. 3,
  121153. 0,
  121154. 4,
  121155. };
  121156. static long _vq_lengthlist__8c0_s_p2_0[] = {
  121157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121196. 0,
  121197. };
  121198. static float _vq_quantthresh__8c0_s_p2_0[] = {
  121199. -1.5, -0.5, 0.5, 1.5,
  121200. };
  121201. static long _vq_quantmap__8c0_s_p2_0[] = {
  121202. 3, 1, 0, 2, 4,
  121203. };
  121204. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  121205. _vq_quantthresh__8c0_s_p2_0,
  121206. _vq_quantmap__8c0_s_p2_0,
  121207. 5,
  121208. 5
  121209. };
  121210. static static_codebook _8c0_s_p2_0 = {
  121211. 4, 625,
  121212. _vq_lengthlist__8c0_s_p2_0,
  121213. 1, -533725184, 1611661312, 3, 0,
  121214. _vq_quantlist__8c0_s_p2_0,
  121215. NULL,
  121216. &_vq_auxt__8c0_s_p2_0,
  121217. NULL,
  121218. 0
  121219. };
  121220. static long _vq_quantlist__8c0_s_p3_0[] = {
  121221. 2,
  121222. 1,
  121223. 3,
  121224. 0,
  121225. 4,
  121226. };
  121227. static long _vq_lengthlist__8c0_s_p3_0[] = {
  121228. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  121230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121231. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  121233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121234. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121267. 0,
  121268. };
  121269. static float _vq_quantthresh__8c0_s_p3_0[] = {
  121270. -1.5, -0.5, 0.5, 1.5,
  121271. };
  121272. static long _vq_quantmap__8c0_s_p3_0[] = {
  121273. 3, 1, 0, 2, 4,
  121274. };
  121275. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  121276. _vq_quantthresh__8c0_s_p3_0,
  121277. _vq_quantmap__8c0_s_p3_0,
  121278. 5,
  121279. 5
  121280. };
  121281. static static_codebook _8c0_s_p3_0 = {
  121282. 4, 625,
  121283. _vq_lengthlist__8c0_s_p3_0,
  121284. 1, -533725184, 1611661312, 3, 0,
  121285. _vq_quantlist__8c0_s_p3_0,
  121286. NULL,
  121287. &_vq_auxt__8c0_s_p3_0,
  121288. NULL,
  121289. 0
  121290. };
  121291. static long _vq_quantlist__8c0_s_p4_0[] = {
  121292. 4,
  121293. 3,
  121294. 5,
  121295. 2,
  121296. 6,
  121297. 1,
  121298. 7,
  121299. 0,
  121300. 8,
  121301. };
  121302. static long _vq_lengthlist__8c0_s_p4_0[] = {
  121303. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121304. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121305. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121306. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  121307. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121308. 0,
  121309. };
  121310. static float _vq_quantthresh__8c0_s_p4_0[] = {
  121311. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121312. };
  121313. static long _vq_quantmap__8c0_s_p4_0[] = {
  121314. 7, 5, 3, 1, 0, 2, 4, 6,
  121315. 8,
  121316. };
  121317. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  121318. _vq_quantthresh__8c0_s_p4_0,
  121319. _vq_quantmap__8c0_s_p4_0,
  121320. 9,
  121321. 9
  121322. };
  121323. static static_codebook _8c0_s_p4_0 = {
  121324. 2, 81,
  121325. _vq_lengthlist__8c0_s_p4_0,
  121326. 1, -531628032, 1611661312, 4, 0,
  121327. _vq_quantlist__8c0_s_p4_0,
  121328. NULL,
  121329. &_vq_auxt__8c0_s_p4_0,
  121330. NULL,
  121331. 0
  121332. };
  121333. static long _vq_quantlist__8c0_s_p5_0[] = {
  121334. 4,
  121335. 3,
  121336. 5,
  121337. 2,
  121338. 6,
  121339. 1,
  121340. 7,
  121341. 0,
  121342. 8,
  121343. };
  121344. static long _vq_lengthlist__8c0_s_p5_0[] = {
  121345. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  121346. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  121347. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  121348. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  121349. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121350. 10,
  121351. };
  121352. static float _vq_quantthresh__8c0_s_p5_0[] = {
  121353. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121354. };
  121355. static long _vq_quantmap__8c0_s_p5_0[] = {
  121356. 7, 5, 3, 1, 0, 2, 4, 6,
  121357. 8,
  121358. };
  121359. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  121360. _vq_quantthresh__8c0_s_p5_0,
  121361. _vq_quantmap__8c0_s_p5_0,
  121362. 9,
  121363. 9
  121364. };
  121365. static static_codebook _8c0_s_p5_0 = {
  121366. 2, 81,
  121367. _vq_lengthlist__8c0_s_p5_0,
  121368. 1, -531628032, 1611661312, 4, 0,
  121369. _vq_quantlist__8c0_s_p5_0,
  121370. NULL,
  121371. &_vq_auxt__8c0_s_p5_0,
  121372. NULL,
  121373. 0
  121374. };
  121375. static long _vq_quantlist__8c0_s_p6_0[] = {
  121376. 8,
  121377. 7,
  121378. 9,
  121379. 6,
  121380. 10,
  121381. 5,
  121382. 11,
  121383. 4,
  121384. 12,
  121385. 3,
  121386. 13,
  121387. 2,
  121388. 14,
  121389. 1,
  121390. 15,
  121391. 0,
  121392. 16,
  121393. };
  121394. static long _vq_lengthlist__8c0_s_p6_0[] = {
  121395. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  121396. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121397. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  121398. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  121399. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  121400. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  121401. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  121402. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  121403. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  121404. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121405. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  121406. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  121407. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  121408. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  121409. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  121410. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  121411. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  121412. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  121413. 14,
  121414. };
  121415. static float _vq_quantthresh__8c0_s_p6_0[] = {
  121416. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121417. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121418. };
  121419. static long _vq_quantmap__8c0_s_p6_0[] = {
  121420. 15, 13, 11, 9, 7, 5, 3, 1,
  121421. 0, 2, 4, 6, 8, 10, 12, 14,
  121422. 16,
  121423. };
  121424. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  121425. _vq_quantthresh__8c0_s_p6_0,
  121426. _vq_quantmap__8c0_s_p6_0,
  121427. 17,
  121428. 17
  121429. };
  121430. static static_codebook _8c0_s_p6_0 = {
  121431. 2, 289,
  121432. _vq_lengthlist__8c0_s_p6_0,
  121433. 1, -529530880, 1611661312, 5, 0,
  121434. _vq_quantlist__8c0_s_p6_0,
  121435. NULL,
  121436. &_vq_auxt__8c0_s_p6_0,
  121437. NULL,
  121438. 0
  121439. };
  121440. static long _vq_quantlist__8c0_s_p7_0[] = {
  121441. 1,
  121442. 0,
  121443. 2,
  121444. };
  121445. static long _vq_lengthlist__8c0_s_p7_0[] = {
  121446. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  121447. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  121448. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  121449. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  121450. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  121451. 10,
  121452. };
  121453. static float _vq_quantthresh__8c0_s_p7_0[] = {
  121454. -5.5, 5.5,
  121455. };
  121456. static long _vq_quantmap__8c0_s_p7_0[] = {
  121457. 1, 0, 2,
  121458. };
  121459. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  121460. _vq_quantthresh__8c0_s_p7_0,
  121461. _vq_quantmap__8c0_s_p7_0,
  121462. 3,
  121463. 3
  121464. };
  121465. static static_codebook _8c0_s_p7_0 = {
  121466. 4, 81,
  121467. _vq_lengthlist__8c0_s_p7_0,
  121468. 1, -529137664, 1618345984, 2, 0,
  121469. _vq_quantlist__8c0_s_p7_0,
  121470. NULL,
  121471. &_vq_auxt__8c0_s_p7_0,
  121472. NULL,
  121473. 0
  121474. };
  121475. static long _vq_quantlist__8c0_s_p7_1[] = {
  121476. 5,
  121477. 4,
  121478. 6,
  121479. 3,
  121480. 7,
  121481. 2,
  121482. 8,
  121483. 1,
  121484. 9,
  121485. 0,
  121486. 10,
  121487. };
  121488. static long _vq_lengthlist__8c0_s_p7_1[] = {
  121489. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  121490. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  121491. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  121492. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  121493. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  121494. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  121495. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  121496. 10,10,10, 9, 9, 9,10,10,10,
  121497. };
  121498. static float _vq_quantthresh__8c0_s_p7_1[] = {
  121499. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121500. 3.5, 4.5,
  121501. };
  121502. static long _vq_quantmap__8c0_s_p7_1[] = {
  121503. 9, 7, 5, 3, 1, 0, 2, 4,
  121504. 6, 8, 10,
  121505. };
  121506. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  121507. _vq_quantthresh__8c0_s_p7_1,
  121508. _vq_quantmap__8c0_s_p7_1,
  121509. 11,
  121510. 11
  121511. };
  121512. static static_codebook _8c0_s_p7_1 = {
  121513. 2, 121,
  121514. _vq_lengthlist__8c0_s_p7_1,
  121515. 1, -531365888, 1611661312, 4, 0,
  121516. _vq_quantlist__8c0_s_p7_1,
  121517. NULL,
  121518. &_vq_auxt__8c0_s_p7_1,
  121519. NULL,
  121520. 0
  121521. };
  121522. static long _vq_quantlist__8c0_s_p8_0[] = {
  121523. 6,
  121524. 5,
  121525. 7,
  121526. 4,
  121527. 8,
  121528. 3,
  121529. 9,
  121530. 2,
  121531. 10,
  121532. 1,
  121533. 11,
  121534. 0,
  121535. 12,
  121536. };
  121537. static long _vq_lengthlist__8c0_s_p8_0[] = {
  121538. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  121539. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  121540. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  121541. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  121542. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  121543. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  121544. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  121545. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  121546. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  121547. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  121548. 0, 0,13,13,11,13,13,11,12,
  121549. };
  121550. static float _vq_quantthresh__8c0_s_p8_0[] = {
  121551. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121552. 12.5, 17.5, 22.5, 27.5,
  121553. };
  121554. static long _vq_quantmap__8c0_s_p8_0[] = {
  121555. 11, 9, 7, 5, 3, 1, 0, 2,
  121556. 4, 6, 8, 10, 12,
  121557. };
  121558. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  121559. _vq_quantthresh__8c0_s_p8_0,
  121560. _vq_quantmap__8c0_s_p8_0,
  121561. 13,
  121562. 13
  121563. };
  121564. static static_codebook _8c0_s_p8_0 = {
  121565. 2, 169,
  121566. _vq_lengthlist__8c0_s_p8_0,
  121567. 1, -526516224, 1616117760, 4, 0,
  121568. _vq_quantlist__8c0_s_p8_0,
  121569. NULL,
  121570. &_vq_auxt__8c0_s_p8_0,
  121571. NULL,
  121572. 0
  121573. };
  121574. static long _vq_quantlist__8c0_s_p8_1[] = {
  121575. 2,
  121576. 1,
  121577. 3,
  121578. 0,
  121579. 4,
  121580. };
  121581. static long _vq_lengthlist__8c0_s_p8_1[] = {
  121582. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  121583. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  121584. };
  121585. static float _vq_quantthresh__8c0_s_p8_1[] = {
  121586. -1.5, -0.5, 0.5, 1.5,
  121587. };
  121588. static long _vq_quantmap__8c0_s_p8_1[] = {
  121589. 3, 1, 0, 2, 4,
  121590. };
  121591. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  121592. _vq_quantthresh__8c0_s_p8_1,
  121593. _vq_quantmap__8c0_s_p8_1,
  121594. 5,
  121595. 5
  121596. };
  121597. static static_codebook _8c0_s_p8_1 = {
  121598. 2, 25,
  121599. _vq_lengthlist__8c0_s_p8_1,
  121600. 1, -533725184, 1611661312, 3, 0,
  121601. _vq_quantlist__8c0_s_p8_1,
  121602. NULL,
  121603. &_vq_auxt__8c0_s_p8_1,
  121604. NULL,
  121605. 0
  121606. };
  121607. static long _vq_quantlist__8c0_s_p9_0[] = {
  121608. 1,
  121609. 0,
  121610. 2,
  121611. };
  121612. static long _vq_lengthlist__8c0_s_p9_0[] = {
  121613. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121614. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121615. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121616. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121617. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121618. 7,
  121619. };
  121620. static float _vq_quantthresh__8c0_s_p9_0[] = {
  121621. -157.5, 157.5,
  121622. };
  121623. static long _vq_quantmap__8c0_s_p9_0[] = {
  121624. 1, 0, 2,
  121625. };
  121626. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  121627. _vq_quantthresh__8c0_s_p9_0,
  121628. _vq_quantmap__8c0_s_p9_0,
  121629. 3,
  121630. 3
  121631. };
  121632. static static_codebook _8c0_s_p9_0 = {
  121633. 4, 81,
  121634. _vq_lengthlist__8c0_s_p9_0,
  121635. 1, -518803456, 1628680192, 2, 0,
  121636. _vq_quantlist__8c0_s_p9_0,
  121637. NULL,
  121638. &_vq_auxt__8c0_s_p9_0,
  121639. NULL,
  121640. 0
  121641. };
  121642. static long _vq_quantlist__8c0_s_p9_1[] = {
  121643. 7,
  121644. 6,
  121645. 8,
  121646. 5,
  121647. 9,
  121648. 4,
  121649. 10,
  121650. 3,
  121651. 11,
  121652. 2,
  121653. 12,
  121654. 1,
  121655. 13,
  121656. 0,
  121657. 14,
  121658. };
  121659. static long _vq_lengthlist__8c0_s_p9_1[] = {
  121660. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  121661. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  121662. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  121663. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  121664. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  121665. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  121666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121667. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121668. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121670. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121674. 11,
  121675. };
  121676. static float _vq_quantthresh__8c0_s_p9_1[] = {
  121677. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121678. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121679. };
  121680. static long _vq_quantmap__8c0_s_p9_1[] = {
  121681. 13, 11, 9, 7, 5, 3, 1, 0,
  121682. 2, 4, 6, 8, 10, 12, 14,
  121683. };
  121684. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  121685. _vq_quantthresh__8c0_s_p9_1,
  121686. _vq_quantmap__8c0_s_p9_1,
  121687. 15,
  121688. 15
  121689. };
  121690. static static_codebook _8c0_s_p9_1 = {
  121691. 2, 225,
  121692. _vq_lengthlist__8c0_s_p9_1,
  121693. 1, -520986624, 1620377600, 4, 0,
  121694. _vq_quantlist__8c0_s_p9_1,
  121695. NULL,
  121696. &_vq_auxt__8c0_s_p9_1,
  121697. NULL,
  121698. 0
  121699. };
  121700. static long _vq_quantlist__8c0_s_p9_2[] = {
  121701. 10,
  121702. 9,
  121703. 11,
  121704. 8,
  121705. 12,
  121706. 7,
  121707. 13,
  121708. 6,
  121709. 14,
  121710. 5,
  121711. 15,
  121712. 4,
  121713. 16,
  121714. 3,
  121715. 17,
  121716. 2,
  121717. 18,
  121718. 1,
  121719. 19,
  121720. 0,
  121721. 20,
  121722. };
  121723. static long _vq_lengthlist__8c0_s_p9_2[] = {
  121724. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  121725. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  121726. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  121727. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  121728. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  121729. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  121730. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  121731. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  121732. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  121733. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  121734. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  121735. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  121736. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  121737. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  121738. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  121739. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  121740. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  121741. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  121742. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  121743. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  121744. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  121745. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  121746. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  121747. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  121748. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  121749. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  121750. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  121751. 10,11, 9,11,10, 9,10, 9,10,
  121752. };
  121753. static float _vq_quantthresh__8c0_s_p9_2[] = {
  121754. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121755. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121756. 6.5, 7.5, 8.5, 9.5,
  121757. };
  121758. static long _vq_quantmap__8c0_s_p9_2[] = {
  121759. 19, 17, 15, 13, 11, 9, 7, 5,
  121760. 3, 1, 0, 2, 4, 6, 8, 10,
  121761. 12, 14, 16, 18, 20,
  121762. };
  121763. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  121764. _vq_quantthresh__8c0_s_p9_2,
  121765. _vq_quantmap__8c0_s_p9_2,
  121766. 21,
  121767. 21
  121768. };
  121769. static static_codebook _8c0_s_p9_2 = {
  121770. 2, 441,
  121771. _vq_lengthlist__8c0_s_p9_2,
  121772. 1, -529268736, 1611661312, 5, 0,
  121773. _vq_quantlist__8c0_s_p9_2,
  121774. NULL,
  121775. &_vq_auxt__8c0_s_p9_2,
  121776. NULL,
  121777. 0
  121778. };
  121779. static long _huff_lengthlist__8c0_s_single[] = {
  121780. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  121781. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  121782. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  121783. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  121784. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  121785. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  121786. 17,16,17,17,
  121787. };
  121788. static static_codebook _huff_book__8c0_s_single = {
  121789. 2, 100,
  121790. _huff_lengthlist__8c0_s_single,
  121791. 0, 0, 0, 0, 0,
  121792. NULL,
  121793. NULL,
  121794. NULL,
  121795. NULL,
  121796. 0
  121797. };
  121798. static long _vq_quantlist__8c1_s_p1_0[] = {
  121799. 1,
  121800. 0,
  121801. 2,
  121802. };
  121803. static long _vq_lengthlist__8c1_s_p1_0[] = {
  121804. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121805. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121809. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  121810. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  121815. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121850. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  121855. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  121856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121860. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  121861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121868. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121873. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121878. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121896. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  121901. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  121906. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  121913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  121918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  121923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  122215. };
  122216. static float _vq_quantthresh__8c1_s_p1_0[] = {
  122217. -0.5, 0.5,
  122218. };
  122219. static long _vq_quantmap__8c1_s_p1_0[] = {
  122220. 1, 0, 2,
  122221. };
  122222. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  122223. _vq_quantthresh__8c1_s_p1_0,
  122224. _vq_quantmap__8c1_s_p1_0,
  122225. 3,
  122226. 3
  122227. };
  122228. static static_codebook _8c1_s_p1_0 = {
  122229. 8, 6561,
  122230. _vq_lengthlist__8c1_s_p1_0,
  122231. 1, -535822336, 1611661312, 2, 0,
  122232. _vq_quantlist__8c1_s_p1_0,
  122233. NULL,
  122234. &_vq_auxt__8c1_s_p1_0,
  122235. NULL,
  122236. 0
  122237. };
  122238. static long _vq_quantlist__8c1_s_p2_0[] = {
  122239. 2,
  122240. 1,
  122241. 3,
  122242. 0,
  122243. 4,
  122244. };
  122245. static long _vq_lengthlist__8c1_s_p2_0[] = {
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0,
  122286. };
  122287. static float _vq_quantthresh__8c1_s_p2_0[] = {
  122288. -1.5, -0.5, 0.5, 1.5,
  122289. };
  122290. static long _vq_quantmap__8c1_s_p2_0[] = {
  122291. 3, 1, 0, 2, 4,
  122292. };
  122293. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  122294. _vq_quantthresh__8c1_s_p2_0,
  122295. _vq_quantmap__8c1_s_p2_0,
  122296. 5,
  122297. 5
  122298. };
  122299. static static_codebook _8c1_s_p2_0 = {
  122300. 4, 625,
  122301. _vq_lengthlist__8c1_s_p2_0,
  122302. 1, -533725184, 1611661312, 3, 0,
  122303. _vq_quantlist__8c1_s_p2_0,
  122304. NULL,
  122305. &_vq_auxt__8c1_s_p2_0,
  122306. NULL,
  122307. 0
  122308. };
  122309. static long _vq_quantlist__8c1_s_p3_0[] = {
  122310. 2,
  122311. 1,
  122312. 3,
  122313. 0,
  122314. 4,
  122315. };
  122316. static long _vq_lengthlist__8c1_s_p3_0[] = {
  122317. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0,
  122357. };
  122358. static float _vq_quantthresh__8c1_s_p3_0[] = {
  122359. -1.5, -0.5, 0.5, 1.5,
  122360. };
  122361. static long _vq_quantmap__8c1_s_p3_0[] = {
  122362. 3, 1, 0, 2, 4,
  122363. };
  122364. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  122365. _vq_quantthresh__8c1_s_p3_0,
  122366. _vq_quantmap__8c1_s_p3_0,
  122367. 5,
  122368. 5
  122369. };
  122370. static static_codebook _8c1_s_p3_0 = {
  122371. 4, 625,
  122372. _vq_lengthlist__8c1_s_p3_0,
  122373. 1, -533725184, 1611661312, 3, 0,
  122374. _vq_quantlist__8c1_s_p3_0,
  122375. NULL,
  122376. &_vq_auxt__8c1_s_p3_0,
  122377. NULL,
  122378. 0
  122379. };
  122380. static long _vq_quantlist__8c1_s_p4_0[] = {
  122381. 4,
  122382. 3,
  122383. 5,
  122384. 2,
  122385. 6,
  122386. 1,
  122387. 7,
  122388. 0,
  122389. 8,
  122390. };
  122391. static long _vq_lengthlist__8c1_s_p4_0[] = {
  122392. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122393. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122394. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122395. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  122396. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0,
  122398. };
  122399. static float _vq_quantthresh__8c1_s_p4_0[] = {
  122400. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122401. };
  122402. static long _vq_quantmap__8c1_s_p4_0[] = {
  122403. 7, 5, 3, 1, 0, 2, 4, 6,
  122404. 8,
  122405. };
  122406. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  122407. _vq_quantthresh__8c1_s_p4_0,
  122408. _vq_quantmap__8c1_s_p4_0,
  122409. 9,
  122410. 9
  122411. };
  122412. static static_codebook _8c1_s_p4_0 = {
  122413. 2, 81,
  122414. _vq_lengthlist__8c1_s_p4_0,
  122415. 1, -531628032, 1611661312, 4, 0,
  122416. _vq_quantlist__8c1_s_p4_0,
  122417. NULL,
  122418. &_vq_auxt__8c1_s_p4_0,
  122419. NULL,
  122420. 0
  122421. };
  122422. static long _vq_quantlist__8c1_s_p5_0[] = {
  122423. 4,
  122424. 3,
  122425. 5,
  122426. 2,
  122427. 6,
  122428. 1,
  122429. 7,
  122430. 0,
  122431. 8,
  122432. };
  122433. static long _vq_lengthlist__8c1_s_p5_0[] = {
  122434. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  122435. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  122436. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  122437. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  122438. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122439. 10,
  122440. };
  122441. static float _vq_quantthresh__8c1_s_p5_0[] = {
  122442. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122443. };
  122444. static long _vq_quantmap__8c1_s_p5_0[] = {
  122445. 7, 5, 3, 1, 0, 2, 4, 6,
  122446. 8,
  122447. };
  122448. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  122449. _vq_quantthresh__8c1_s_p5_0,
  122450. _vq_quantmap__8c1_s_p5_0,
  122451. 9,
  122452. 9
  122453. };
  122454. static static_codebook _8c1_s_p5_0 = {
  122455. 2, 81,
  122456. _vq_lengthlist__8c1_s_p5_0,
  122457. 1, -531628032, 1611661312, 4, 0,
  122458. _vq_quantlist__8c1_s_p5_0,
  122459. NULL,
  122460. &_vq_auxt__8c1_s_p5_0,
  122461. NULL,
  122462. 0
  122463. };
  122464. static long _vq_quantlist__8c1_s_p6_0[] = {
  122465. 8,
  122466. 7,
  122467. 9,
  122468. 6,
  122469. 10,
  122470. 5,
  122471. 11,
  122472. 4,
  122473. 12,
  122474. 3,
  122475. 13,
  122476. 2,
  122477. 14,
  122478. 1,
  122479. 15,
  122480. 0,
  122481. 16,
  122482. };
  122483. static long _vq_lengthlist__8c1_s_p6_0[] = {
  122484. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  122485. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122486. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122487. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  122488. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  122489. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  122490. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  122491. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  122492. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  122493. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122494. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  122495. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  122496. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  122497. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  122498. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  122499. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  122500. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  122502. 14,
  122503. };
  122504. static float _vq_quantthresh__8c1_s_p6_0[] = {
  122505. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122506. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122507. };
  122508. static long _vq_quantmap__8c1_s_p6_0[] = {
  122509. 15, 13, 11, 9, 7, 5, 3, 1,
  122510. 0, 2, 4, 6, 8, 10, 12, 14,
  122511. 16,
  122512. };
  122513. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  122514. _vq_quantthresh__8c1_s_p6_0,
  122515. _vq_quantmap__8c1_s_p6_0,
  122516. 17,
  122517. 17
  122518. };
  122519. static static_codebook _8c1_s_p6_0 = {
  122520. 2, 289,
  122521. _vq_lengthlist__8c1_s_p6_0,
  122522. 1, -529530880, 1611661312, 5, 0,
  122523. _vq_quantlist__8c1_s_p6_0,
  122524. NULL,
  122525. &_vq_auxt__8c1_s_p6_0,
  122526. NULL,
  122527. 0
  122528. };
  122529. static long _vq_quantlist__8c1_s_p7_0[] = {
  122530. 1,
  122531. 0,
  122532. 2,
  122533. };
  122534. static long _vq_lengthlist__8c1_s_p7_0[] = {
  122535. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  122536. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  122537. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  122538. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  122539. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  122540. 9,
  122541. };
  122542. static float _vq_quantthresh__8c1_s_p7_0[] = {
  122543. -5.5, 5.5,
  122544. };
  122545. static long _vq_quantmap__8c1_s_p7_0[] = {
  122546. 1, 0, 2,
  122547. };
  122548. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  122549. _vq_quantthresh__8c1_s_p7_0,
  122550. _vq_quantmap__8c1_s_p7_0,
  122551. 3,
  122552. 3
  122553. };
  122554. static static_codebook _8c1_s_p7_0 = {
  122555. 4, 81,
  122556. _vq_lengthlist__8c1_s_p7_0,
  122557. 1, -529137664, 1618345984, 2, 0,
  122558. _vq_quantlist__8c1_s_p7_0,
  122559. NULL,
  122560. &_vq_auxt__8c1_s_p7_0,
  122561. NULL,
  122562. 0
  122563. };
  122564. static long _vq_quantlist__8c1_s_p7_1[] = {
  122565. 5,
  122566. 4,
  122567. 6,
  122568. 3,
  122569. 7,
  122570. 2,
  122571. 8,
  122572. 1,
  122573. 9,
  122574. 0,
  122575. 10,
  122576. };
  122577. static long _vq_lengthlist__8c1_s_p7_1[] = {
  122578. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  122579. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  122580. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  122581. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  122582. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  122583. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  122584. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  122585. 10,10,10, 8, 8, 8, 8, 8, 8,
  122586. };
  122587. static float _vq_quantthresh__8c1_s_p7_1[] = {
  122588. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122589. 3.5, 4.5,
  122590. };
  122591. static long _vq_quantmap__8c1_s_p7_1[] = {
  122592. 9, 7, 5, 3, 1, 0, 2, 4,
  122593. 6, 8, 10,
  122594. };
  122595. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  122596. _vq_quantthresh__8c1_s_p7_1,
  122597. _vq_quantmap__8c1_s_p7_1,
  122598. 11,
  122599. 11
  122600. };
  122601. static static_codebook _8c1_s_p7_1 = {
  122602. 2, 121,
  122603. _vq_lengthlist__8c1_s_p7_1,
  122604. 1, -531365888, 1611661312, 4, 0,
  122605. _vq_quantlist__8c1_s_p7_1,
  122606. NULL,
  122607. &_vq_auxt__8c1_s_p7_1,
  122608. NULL,
  122609. 0
  122610. };
  122611. static long _vq_quantlist__8c1_s_p8_0[] = {
  122612. 6,
  122613. 5,
  122614. 7,
  122615. 4,
  122616. 8,
  122617. 3,
  122618. 9,
  122619. 2,
  122620. 10,
  122621. 1,
  122622. 11,
  122623. 0,
  122624. 12,
  122625. };
  122626. static long _vq_lengthlist__8c1_s_p8_0[] = {
  122627. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  122628. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  122629. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  122630. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122631. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  122632. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  122633. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  122634. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  122635. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  122636. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  122637. 0,12,12,11,10,12,11,13,12,
  122638. };
  122639. static float _vq_quantthresh__8c1_s_p8_0[] = {
  122640. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122641. 12.5, 17.5, 22.5, 27.5,
  122642. };
  122643. static long _vq_quantmap__8c1_s_p8_0[] = {
  122644. 11, 9, 7, 5, 3, 1, 0, 2,
  122645. 4, 6, 8, 10, 12,
  122646. };
  122647. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  122648. _vq_quantthresh__8c1_s_p8_0,
  122649. _vq_quantmap__8c1_s_p8_0,
  122650. 13,
  122651. 13
  122652. };
  122653. static static_codebook _8c1_s_p8_0 = {
  122654. 2, 169,
  122655. _vq_lengthlist__8c1_s_p8_0,
  122656. 1, -526516224, 1616117760, 4, 0,
  122657. _vq_quantlist__8c1_s_p8_0,
  122658. NULL,
  122659. &_vq_auxt__8c1_s_p8_0,
  122660. NULL,
  122661. 0
  122662. };
  122663. static long _vq_quantlist__8c1_s_p8_1[] = {
  122664. 2,
  122665. 1,
  122666. 3,
  122667. 0,
  122668. 4,
  122669. };
  122670. static long _vq_lengthlist__8c1_s_p8_1[] = {
  122671. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  122672. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  122673. };
  122674. static float _vq_quantthresh__8c1_s_p8_1[] = {
  122675. -1.5, -0.5, 0.5, 1.5,
  122676. };
  122677. static long _vq_quantmap__8c1_s_p8_1[] = {
  122678. 3, 1, 0, 2, 4,
  122679. };
  122680. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  122681. _vq_quantthresh__8c1_s_p8_1,
  122682. _vq_quantmap__8c1_s_p8_1,
  122683. 5,
  122684. 5
  122685. };
  122686. static static_codebook _8c1_s_p8_1 = {
  122687. 2, 25,
  122688. _vq_lengthlist__8c1_s_p8_1,
  122689. 1, -533725184, 1611661312, 3, 0,
  122690. _vq_quantlist__8c1_s_p8_1,
  122691. NULL,
  122692. &_vq_auxt__8c1_s_p8_1,
  122693. NULL,
  122694. 0
  122695. };
  122696. static long _vq_quantlist__8c1_s_p9_0[] = {
  122697. 6,
  122698. 5,
  122699. 7,
  122700. 4,
  122701. 8,
  122702. 3,
  122703. 9,
  122704. 2,
  122705. 10,
  122706. 1,
  122707. 11,
  122708. 0,
  122709. 12,
  122710. };
  122711. static long _vq_lengthlist__8c1_s_p9_0[] = {
  122712. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  122713. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  122714. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122715. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122716. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122717. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122718. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122719. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122720. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122721. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122722. 10,10,10,10,10, 9, 9, 9, 9,
  122723. };
  122724. static float _vq_quantthresh__8c1_s_p9_0[] = {
  122725. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  122726. 787.5, 1102.5, 1417.5, 1732.5,
  122727. };
  122728. static long _vq_quantmap__8c1_s_p9_0[] = {
  122729. 11, 9, 7, 5, 3, 1, 0, 2,
  122730. 4, 6, 8, 10, 12,
  122731. };
  122732. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  122733. _vq_quantthresh__8c1_s_p9_0,
  122734. _vq_quantmap__8c1_s_p9_0,
  122735. 13,
  122736. 13
  122737. };
  122738. static static_codebook _8c1_s_p9_0 = {
  122739. 2, 169,
  122740. _vq_lengthlist__8c1_s_p9_0,
  122741. 1, -513964032, 1628680192, 4, 0,
  122742. _vq_quantlist__8c1_s_p9_0,
  122743. NULL,
  122744. &_vq_auxt__8c1_s_p9_0,
  122745. NULL,
  122746. 0
  122747. };
  122748. static long _vq_quantlist__8c1_s_p9_1[] = {
  122749. 7,
  122750. 6,
  122751. 8,
  122752. 5,
  122753. 9,
  122754. 4,
  122755. 10,
  122756. 3,
  122757. 11,
  122758. 2,
  122759. 12,
  122760. 1,
  122761. 13,
  122762. 0,
  122763. 14,
  122764. };
  122765. static long _vq_lengthlist__8c1_s_p9_1[] = {
  122766. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  122767. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  122768. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  122769. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  122770. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  122771. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  122772. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  122773. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  122774. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  122775. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  122776. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  122777. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  122778. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  122779. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  122780. 15,
  122781. };
  122782. static float _vq_quantthresh__8c1_s_p9_1[] = {
  122783. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122784. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122785. };
  122786. static long _vq_quantmap__8c1_s_p9_1[] = {
  122787. 13, 11, 9, 7, 5, 3, 1, 0,
  122788. 2, 4, 6, 8, 10, 12, 14,
  122789. };
  122790. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  122791. _vq_quantthresh__8c1_s_p9_1,
  122792. _vq_quantmap__8c1_s_p9_1,
  122793. 15,
  122794. 15
  122795. };
  122796. static static_codebook _8c1_s_p9_1 = {
  122797. 2, 225,
  122798. _vq_lengthlist__8c1_s_p9_1,
  122799. 1, -520986624, 1620377600, 4, 0,
  122800. _vq_quantlist__8c1_s_p9_1,
  122801. NULL,
  122802. &_vq_auxt__8c1_s_p9_1,
  122803. NULL,
  122804. 0
  122805. };
  122806. static long _vq_quantlist__8c1_s_p9_2[] = {
  122807. 10,
  122808. 9,
  122809. 11,
  122810. 8,
  122811. 12,
  122812. 7,
  122813. 13,
  122814. 6,
  122815. 14,
  122816. 5,
  122817. 15,
  122818. 4,
  122819. 16,
  122820. 3,
  122821. 17,
  122822. 2,
  122823. 18,
  122824. 1,
  122825. 19,
  122826. 0,
  122827. 20,
  122828. };
  122829. static long _vq_lengthlist__8c1_s_p9_2[] = {
  122830. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  122831. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  122832. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  122833. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  122834. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  122835. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  122836. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  122837. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  122838. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  122839. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  122840. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  122841. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  122842. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  122843. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  122844. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  122845. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  122846. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122847. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  122848. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  122849. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  122850. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122851. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  122852. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  122853. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  122854. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  122855. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  122856. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  122857. 10,10,10,10,10,10,10,10,10,
  122858. };
  122859. static float _vq_quantthresh__8c1_s_p9_2[] = {
  122860. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122861. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122862. 6.5, 7.5, 8.5, 9.5,
  122863. };
  122864. static long _vq_quantmap__8c1_s_p9_2[] = {
  122865. 19, 17, 15, 13, 11, 9, 7, 5,
  122866. 3, 1, 0, 2, 4, 6, 8, 10,
  122867. 12, 14, 16, 18, 20,
  122868. };
  122869. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  122870. _vq_quantthresh__8c1_s_p9_2,
  122871. _vq_quantmap__8c1_s_p9_2,
  122872. 21,
  122873. 21
  122874. };
  122875. static static_codebook _8c1_s_p9_2 = {
  122876. 2, 441,
  122877. _vq_lengthlist__8c1_s_p9_2,
  122878. 1, -529268736, 1611661312, 5, 0,
  122879. _vq_quantlist__8c1_s_p9_2,
  122880. NULL,
  122881. &_vq_auxt__8c1_s_p9_2,
  122882. NULL,
  122883. 0
  122884. };
  122885. static long _huff_lengthlist__8c1_s_single[] = {
  122886. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  122887. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  122888. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  122889. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  122890. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  122891. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  122892. 9, 7, 7, 8,
  122893. };
  122894. static static_codebook _huff_book__8c1_s_single = {
  122895. 2, 100,
  122896. _huff_lengthlist__8c1_s_single,
  122897. 0, 0, 0, 0, 0,
  122898. NULL,
  122899. NULL,
  122900. NULL,
  122901. NULL,
  122902. 0
  122903. };
  122904. static long _huff_lengthlist__44c2_s_long[] = {
  122905. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  122906. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  122907. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  122908. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  122909. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  122910. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  122911. 10, 8, 8, 9,
  122912. };
  122913. static static_codebook _huff_book__44c2_s_long = {
  122914. 2, 100,
  122915. _huff_lengthlist__44c2_s_long,
  122916. 0, 0, 0, 0, 0,
  122917. NULL,
  122918. NULL,
  122919. NULL,
  122920. NULL,
  122921. 0
  122922. };
  122923. static long _vq_quantlist__44c2_s_p1_0[] = {
  122924. 1,
  122925. 0,
  122926. 2,
  122927. };
  122928. static long _vq_lengthlist__44c2_s_p1_0[] = {
  122929. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  122930. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  122935. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  122940. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122975. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  122980. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  122985. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123021. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123026. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123031. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 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,
  123340. };
  123341. static float _vq_quantthresh__44c2_s_p1_0[] = {
  123342. -0.5, 0.5,
  123343. };
  123344. static long _vq_quantmap__44c2_s_p1_0[] = {
  123345. 1, 0, 2,
  123346. };
  123347. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  123348. _vq_quantthresh__44c2_s_p1_0,
  123349. _vq_quantmap__44c2_s_p1_0,
  123350. 3,
  123351. 3
  123352. };
  123353. static static_codebook _44c2_s_p1_0 = {
  123354. 8, 6561,
  123355. _vq_lengthlist__44c2_s_p1_0,
  123356. 1, -535822336, 1611661312, 2, 0,
  123357. _vq_quantlist__44c2_s_p1_0,
  123358. NULL,
  123359. &_vq_auxt__44c2_s_p1_0,
  123360. NULL,
  123361. 0
  123362. };
  123363. static long _vq_quantlist__44c2_s_p2_0[] = {
  123364. 2,
  123365. 1,
  123366. 3,
  123367. 0,
  123368. 4,
  123369. };
  123370. static long _vq_lengthlist__44c2_s_p2_0[] = {
  123371. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  123372. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  123373. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  123374. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  123375. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  123381. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  123382. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  123383. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  123389. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  123390. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  123397. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  123398. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0,
  123411. };
  123412. static float _vq_quantthresh__44c2_s_p2_0[] = {
  123413. -1.5, -0.5, 0.5, 1.5,
  123414. };
  123415. static long _vq_quantmap__44c2_s_p2_0[] = {
  123416. 3, 1, 0, 2, 4,
  123417. };
  123418. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  123419. _vq_quantthresh__44c2_s_p2_0,
  123420. _vq_quantmap__44c2_s_p2_0,
  123421. 5,
  123422. 5
  123423. };
  123424. static static_codebook _44c2_s_p2_0 = {
  123425. 4, 625,
  123426. _vq_lengthlist__44c2_s_p2_0,
  123427. 1, -533725184, 1611661312, 3, 0,
  123428. _vq_quantlist__44c2_s_p2_0,
  123429. NULL,
  123430. &_vq_auxt__44c2_s_p2_0,
  123431. NULL,
  123432. 0
  123433. };
  123434. static long _vq_quantlist__44c2_s_p3_0[] = {
  123435. 2,
  123436. 1,
  123437. 3,
  123438. 0,
  123439. 4,
  123440. };
  123441. static long _vq_lengthlist__44c2_s_p3_0[] = {
  123442. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0,
  123482. };
  123483. static float _vq_quantthresh__44c2_s_p3_0[] = {
  123484. -1.5, -0.5, 0.5, 1.5,
  123485. };
  123486. static long _vq_quantmap__44c2_s_p3_0[] = {
  123487. 3, 1, 0, 2, 4,
  123488. };
  123489. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  123490. _vq_quantthresh__44c2_s_p3_0,
  123491. _vq_quantmap__44c2_s_p3_0,
  123492. 5,
  123493. 5
  123494. };
  123495. static static_codebook _44c2_s_p3_0 = {
  123496. 4, 625,
  123497. _vq_lengthlist__44c2_s_p3_0,
  123498. 1, -533725184, 1611661312, 3, 0,
  123499. _vq_quantlist__44c2_s_p3_0,
  123500. NULL,
  123501. &_vq_auxt__44c2_s_p3_0,
  123502. NULL,
  123503. 0
  123504. };
  123505. static long _vq_quantlist__44c2_s_p4_0[] = {
  123506. 4,
  123507. 3,
  123508. 5,
  123509. 2,
  123510. 6,
  123511. 1,
  123512. 7,
  123513. 0,
  123514. 8,
  123515. };
  123516. static long _vq_lengthlist__44c2_s_p4_0[] = {
  123517. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  123518. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  123519. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  123520. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123521. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0,
  123523. };
  123524. static float _vq_quantthresh__44c2_s_p4_0[] = {
  123525. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123526. };
  123527. static long _vq_quantmap__44c2_s_p4_0[] = {
  123528. 7, 5, 3, 1, 0, 2, 4, 6,
  123529. 8,
  123530. };
  123531. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  123532. _vq_quantthresh__44c2_s_p4_0,
  123533. _vq_quantmap__44c2_s_p4_0,
  123534. 9,
  123535. 9
  123536. };
  123537. static static_codebook _44c2_s_p4_0 = {
  123538. 2, 81,
  123539. _vq_lengthlist__44c2_s_p4_0,
  123540. 1, -531628032, 1611661312, 4, 0,
  123541. _vq_quantlist__44c2_s_p4_0,
  123542. NULL,
  123543. &_vq_auxt__44c2_s_p4_0,
  123544. NULL,
  123545. 0
  123546. };
  123547. static long _vq_quantlist__44c2_s_p5_0[] = {
  123548. 4,
  123549. 3,
  123550. 5,
  123551. 2,
  123552. 6,
  123553. 1,
  123554. 7,
  123555. 0,
  123556. 8,
  123557. };
  123558. static long _vq_lengthlist__44c2_s_p5_0[] = {
  123559. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  123560. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  123561. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  123562. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123563. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  123564. 11,
  123565. };
  123566. static float _vq_quantthresh__44c2_s_p5_0[] = {
  123567. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123568. };
  123569. static long _vq_quantmap__44c2_s_p5_0[] = {
  123570. 7, 5, 3, 1, 0, 2, 4, 6,
  123571. 8,
  123572. };
  123573. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  123574. _vq_quantthresh__44c2_s_p5_0,
  123575. _vq_quantmap__44c2_s_p5_0,
  123576. 9,
  123577. 9
  123578. };
  123579. static static_codebook _44c2_s_p5_0 = {
  123580. 2, 81,
  123581. _vq_lengthlist__44c2_s_p5_0,
  123582. 1, -531628032, 1611661312, 4, 0,
  123583. _vq_quantlist__44c2_s_p5_0,
  123584. NULL,
  123585. &_vq_auxt__44c2_s_p5_0,
  123586. NULL,
  123587. 0
  123588. };
  123589. static long _vq_quantlist__44c2_s_p6_0[] = {
  123590. 8,
  123591. 7,
  123592. 9,
  123593. 6,
  123594. 10,
  123595. 5,
  123596. 11,
  123597. 4,
  123598. 12,
  123599. 3,
  123600. 13,
  123601. 2,
  123602. 14,
  123603. 1,
  123604. 15,
  123605. 0,
  123606. 16,
  123607. };
  123608. static long _vq_lengthlist__44c2_s_p6_0[] = {
  123609. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  123610. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123611. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123612. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  123613. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  123614. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123615. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123616. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  123617. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  123618. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123619. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123620. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  123621. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  123622. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123623. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  123624. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  123625. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123627. 14,
  123628. };
  123629. static float _vq_quantthresh__44c2_s_p6_0[] = {
  123630. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123631. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123632. };
  123633. static long _vq_quantmap__44c2_s_p6_0[] = {
  123634. 15, 13, 11, 9, 7, 5, 3, 1,
  123635. 0, 2, 4, 6, 8, 10, 12, 14,
  123636. 16,
  123637. };
  123638. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  123639. _vq_quantthresh__44c2_s_p6_0,
  123640. _vq_quantmap__44c2_s_p6_0,
  123641. 17,
  123642. 17
  123643. };
  123644. static static_codebook _44c2_s_p6_0 = {
  123645. 2, 289,
  123646. _vq_lengthlist__44c2_s_p6_0,
  123647. 1, -529530880, 1611661312, 5, 0,
  123648. _vq_quantlist__44c2_s_p6_0,
  123649. NULL,
  123650. &_vq_auxt__44c2_s_p6_0,
  123651. NULL,
  123652. 0
  123653. };
  123654. static long _vq_quantlist__44c2_s_p7_0[] = {
  123655. 1,
  123656. 0,
  123657. 2,
  123658. };
  123659. static long _vq_lengthlist__44c2_s_p7_0[] = {
  123660. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  123661. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  123662. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  123663. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  123664. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  123665. 11,
  123666. };
  123667. static float _vq_quantthresh__44c2_s_p7_0[] = {
  123668. -5.5, 5.5,
  123669. };
  123670. static long _vq_quantmap__44c2_s_p7_0[] = {
  123671. 1, 0, 2,
  123672. };
  123673. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  123674. _vq_quantthresh__44c2_s_p7_0,
  123675. _vq_quantmap__44c2_s_p7_0,
  123676. 3,
  123677. 3
  123678. };
  123679. static static_codebook _44c2_s_p7_0 = {
  123680. 4, 81,
  123681. _vq_lengthlist__44c2_s_p7_0,
  123682. 1, -529137664, 1618345984, 2, 0,
  123683. _vq_quantlist__44c2_s_p7_0,
  123684. NULL,
  123685. &_vq_auxt__44c2_s_p7_0,
  123686. NULL,
  123687. 0
  123688. };
  123689. static long _vq_quantlist__44c2_s_p7_1[] = {
  123690. 5,
  123691. 4,
  123692. 6,
  123693. 3,
  123694. 7,
  123695. 2,
  123696. 8,
  123697. 1,
  123698. 9,
  123699. 0,
  123700. 10,
  123701. };
  123702. static long _vq_lengthlist__44c2_s_p7_1[] = {
  123703. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  123704. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  123705. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123706. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123707. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123708. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123709. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  123710. 10,10,10, 8, 8, 8, 8, 8, 8,
  123711. };
  123712. static float _vq_quantthresh__44c2_s_p7_1[] = {
  123713. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123714. 3.5, 4.5,
  123715. };
  123716. static long _vq_quantmap__44c2_s_p7_1[] = {
  123717. 9, 7, 5, 3, 1, 0, 2, 4,
  123718. 6, 8, 10,
  123719. };
  123720. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  123721. _vq_quantthresh__44c2_s_p7_1,
  123722. _vq_quantmap__44c2_s_p7_1,
  123723. 11,
  123724. 11
  123725. };
  123726. static static_codebook _44c2_s_p7_1 = {
  123727. 2, 121,
  123728. _vq_lengthlist__44c2_s_p7_1,
  123729. 1, -531365888, 1611661312, 4, 0,
  123730. _vq_quantlist__44c2_s_p7_1,
  123731. NULL,
  123732. &_vq_auxt__44c2_s_p7_1,
  123733. NULL,
  123734. 0
  123735. };
  123736. static long _vq_quantlist__44c2_s_p8_0[] = {
  123737. 6,
  123738. 5,
  123739. 7,
  123740. 4,
  123741. 8,
  123742. 3,
  123743. 9,
  123744. 2,
  123745. 10,
  123746. 1,
  123747. 11,
  123748. 0,
  123749. 12,
  123750. };
  123751. static long _vq_lengthlist__44c2_s_p8_0[] = {
  123752. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123753. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  123754. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123755. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123756. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  123757. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123758. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  123759. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  123760. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  123761. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  123762. 0,12,12,12,12,13,12,14,14,
  123763. };
  123764. static float _vq_quantthresh__44c2_s_p8_0[] = {
  123765. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123766. 12.5, 17.5, 22.5, 27.5,
  123767. };
  123768. static long _vq_quantmap__44c2_s_p8_0[] = {
  123769. 11, 9, 7, 5, 3, 1, 0, 2,
  123770. 4, 6, 8, 10, 12,
  123771. };
  123772. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  123773. _vq_quantthresh__44c2_s_p8_0,
  123774. _vq_quantmap__44c2_s_p8_0,
  123775. 13,
  123776. 13
  123777. };
  123778. static static_codebook _44c2_s_p8_0 = {
  123779. 2, 169,
  123780. _vq_lengthlist__44c2_s_p8_0,
  123781. 1, -526516224, 1616117760, 4, 0,
  123782. _vq_quantlist__44c2_s_p8_0,
  123783. NULL,
  123784. &_vq_auxt__44c2_s_p8_0,
  123785. NULL,
  123786. 0
  123787. };
  123788. static long _vq_quantlist__44c2_s_p8_1[] = {
  123789. 2,
  123790. 1,
  123791. 3,
  123792. 0,
  123793. 4,
  123794. };
  123795. static long _vq_lengthlist__44c2_s_p8_1[] = {
  123796. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  123797. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  123798. };
  123799. static float _vq_quantthresh__44c2_s_p8_1[] = {
  123800. -1.5, -0.5, 0.5, 1.5,
  123801. };
  123802. static long _vq_quantmap__44c2_s_p8_1[] = {
  123803. 3, 1, 0, 2, 4,
  123804. };
  123805. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  123806. _vq_quantthresh__44c2_s_p8_1,
  123807. _vq_quantmap__44c2_s_p8_1,
  123808. 5,
  123809. 5
  123810. };
  123811. static static_codebook _44c2_s_p8_1 = {
  123812. 2, 25,
  123813. _vq_lengthlist__44c2_s_p8_1,
  123814. 1, -533725184, 1611661312, 3, 0,
  123815. _vq_quantlist__44c2_s_p8_1,
  123816. NULL,
  123817. &_vq_auxt__44c2_s_p8_1,
  123818. NULL,
  123819. 0
  123820. };
  123821. static long _vq_quantlist__44c2_s_p9_0[] = {
  123822. 6,
  123823. 5,
  123824. 7,
  123825. 4,
  123826. 8,
  123827. 3,
  123828. 9,
  123829. 2,
  123830. 10,
  123831. 1,
  123832. 11,
  123833. 0,
  123834. 12,
  123835. };
  123836. static long _vq_lengthlist__44c2_s_p9_0[] = {
  123837. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  123838. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  123839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123840. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  123841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123847. 11,11,11,11,11,11,11,11,11,
  123848. };
  123849. static float _vq_quantthresh__44c2_s_p9_0[] = {
  123850. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  123851. 552.5, 773.5, 994.5, 1215.5,
  123852. };
  123853. static long _vq_quantmap__44c2_s_p9_0[] = {
  123854. 11, 9, 7, 5, 3, 1, 0, 2,
  123855. 4, 6, 8, 10, 12,
  123856. };
  123857. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  123858. _vq_quantthresh__44c2_s_p9_0,
  123859. _vq_quantmap__44c2_s_p9_0,
  123860. 13,
  123861. 13
  123862. };
  123863. static static_codebook _44c2_s_p9_0 = {
  123864. 2, 169,
  123865. _vq_lengthlist__44c2_s_p9_0,
  123866. 1, -514541568, 1627103232, 4, 0,
  123867. _vq_quantlist__44c2_s_p9_0,
  123868. NULL,
  123869. &_vq_auxt__44c2_s_p9_0,
  123870. NULL,
  123871. 0
  123872. };
  123873. static long _vq_quantlist__44c2_s_p9_1[] = {
  123874. 6,
  123875. 5,
  123876. 7,
  123877. 4,
  123878. 8,
  123879. 3,
  123880. 9,
  123881. 2,
  123882. 10,
  123883. 1,
  123884. 11,
  123885. 0,
  123886. 12,
  123887. };
  123888. static long _vq_lengthlist__44c2_s_p9_1[] = {
  123889. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  123890. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  123891. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  123892. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  123893. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  123894. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  123895. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  123896. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  123897. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  123898. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  123899. 17,13,12,12,10,13,11,14,14,
  123900. };
  123901. static float _vq_quantthresh__44c2_s_p9_1[] = {
  123902. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  123903. 42.5, 59.5, 76.5, 93.5,
  123904. };
  123905. static long _vq_quantmap__44c2_s_p9_1[] = {
  123906. 11, 9, 7, 5, 3, 1, 0, 2,
  123907. 4, 6, 8, 10, 12,
  123908. };
  123909. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  123910. _vq_quantthresh__44c2_s_p9_1,
  123911. _vq_quantmap__44c2_s_p9_1,
  123912. 13,
  123913. 13
  123914. };
  123915. static static_codebook _44c2_s_p9_1 = {
  123916. 2, 169,
  123917. _vq_lengthlist__44c2_s_p9_1,
  123918. 1, -522616832, 1620115456, 4, 0,
  123919. _vq_quantlist__44c2_s_p9_1,
  123920. NULL,
  123921. &_vq_auxt__44c2_s_p9_1,
  123922. NULL,
  123923. 0
  123924. };
  123925. static long _vq_quantlist__44c2_s_p9_2[] = {
  123926. 8,
  123927. 7,
  123928. 9,
  123929. 6,
  123930. 10,
  123931. 5,
  123932. 11,
  123933. 4,
  123934. 12,
  123935. 3,
  123936. 13,
  123937. 2,
  123938. 14,
  123939. 1,
  123940. 15,
  123941. 0,
  123942. 16,
  123943. };
  123944. static long _vq_lengthlist__44c2_s_p9_2[] = {
  123945. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  123946. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  123947. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  123948. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  123949. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  123950. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  123951. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  123952. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  123953. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  123954. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  123955. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  123956. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  123957. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  123958. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  123959. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  123960. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  123961. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  123962. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  123963. 10,
  123964. };
  123965. static float _vq_quantthresh__44c2_s_p9_2[] = {
  123966. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123967. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123968. };
  123969. static long _vq_quantmap__44c2_s_p9_2[] = {
  123970. 15, 13, 11, 9, 7, 5, 3, 1,
  123971. 0, 2, 4, 6, 8, 10, 12, 14,
  123972. 16,
  123973. };
  123974. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  123975. _vq_quantthresh__44c2_s_p9_2,
  123976. _vq_quantmap__44c2_s_p9_2,
  123977. 17,
  123978. 17
  123979. };
  123980. static static_codebook _44c2_s_p9_2 = {
  123981. 2, 289,
  123982. _vq_lengthlist__44c2_s_p9_2,
  123983. 1, -529530880, 1611661312, 5, 0,
  123984. _vq_quantlist__44c2_s_p9_2,
  123985. NULL,
  123986. &_vq_auxt__44c2_s_p9_2,
  123987. NULL,
  123988. 0
  123989. };
  123990. static long _huff_lengthlist__44c2_s_short[] = {
  123991. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  123992. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  123993. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  123994. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  123995. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  123996. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  123997. 6, 8, 9,12,
  123998. };
  123999. static static_codebook _huff_book__44c2_s_short = {
  124000. 2, 100,
  124001. _huff_lengthlist__44c2_s_short,
  124002. 0, 0, 0, 0, 0,
  124003. NULL,
  124004. NULL,
  124005. NULL,
  124006. NULL,
  124007. 0
  124008. };
  124009. static long _huff_lengthlist__44c3_s_long[] = {
  124010. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  124011. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  124012. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  124013. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  124014. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  124015. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  124016. 9, 8, 8, 8,
  124017. };
  124018. static static_codebook _huff_book__44c3_s_long = {
  124019. 2, 100,
  124020. _huff_lengthlist__44c3_s_long,
  124021. 0, 0, 0, 0, 0,
  124022. NULL,
  124023. NULL,
  124024. NULL,
  124025. NULL,
  124026. 0
  124027. };
  124028. static long _vq_quantlist__44c3_s_p1_0[] = {
  124029. 1,
  124030. 0,
  124031. 2,
  124032. };
  124033. static long _vq_lengthlist__44c3_s_p1_0[] = {
  124034. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124035. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124040. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124045. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124080. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124085. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  124090. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124126. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124131. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124136. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124444. 0,
  124445. };
  124446. static float _vq_quantthresh__44c3_s_p1_0[] = {
  124447. -0.5, 0.5,
  124448. };
  124449. static long _vq_quantmap__44c3_s_p1_0[] = {
  124450. 1, 0, 2,
  124451. };
  124452. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  124453. _vq_quantthresh__44c3_s_p1_0,
  124454. _vq_quantmap__44c3_s_p1_0,
  124455. 3,
  124456. 3
  124457. };
  124458. static static_codebook _44c3_s_p1_0 = {
  124459. 8, 6561,
  124460. _vq_lengthlist__44c3_s_p1_0,
  124461. 1, -535822336, 1611661312, 2, 0,
  124462. _vq_quantlist__44c3_s_p1_0,
  124463. NULL,
  124464. &_vq_auxt__44c3_s_p1_0,
  124465. NULL,
  124466. 0
  124467. };
  124468. static long _vq_quantlist__44c3_s_p2_0[] = {
  124469. 2,
  124470. 1,
  124471. 3,
  124472. 0,
  124473. 4,
  124474. };
  124475. static long _vq_lengthlist__44c3_s_p2_0[] = {
  124476. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  124477. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  124478. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124479. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  124480. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124485. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  124486. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  124487. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  124488. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124493. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  124494. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  124495. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  124496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124501. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  124502. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  124503. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124515. 0,
  124516. };
  124517. static float _vq_quantthresh__44c3_s_p2_0[] = {
  124518. -1.5, -0.5, 0.5, 1.5,
  124519. };
  124520. static long _vq_quantmap__44c3_s_p2_0[] = {
  124521. 3, 1, 0, 2, 4,
  124522. };
  124523. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  124524. _vq_quantthresh__44c3_s_p2_0,
  124525. _vq_quantmap__44c3_s_p2_0,
  124526. 5,
  124527. 5
  124528. };
  124529. static static_codebook _44c3_s_p2_0 = {
  124530. 4, 625,
  124531. _vq_lengthlist__44c3_s_p2_0,
  124532. 1, -533725184, 1611661312, 3, 0,
  124533. _vq_quantlist__44c3_s_p2_0,
  124534. NULL,
  124535. &_vq_auxt__44c3_s_p2_0,
  124536. NULL,
  124537. 0
  124538. };
  124539. static long _vq_quantlist__44c3_s_p3_0[] = {
  124540. 2,
  124541. 1,
  124542. 3,
  124543. 0,
  124544. 4,
  124545. };
  124546. static long _vq_lengthlist__44c3_s_p3_0[] = {
  124547. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  124549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124550. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124553. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124586. 0,
  124587. };
  124588. static float _vq_quantthresh__44c3_s_p3_0[] = {
  124589. -1.5, -0.5, 0.5, 1.5,
  124590. };
  124591. static long _vq_quantmap__44c3_s_p3_0[] = {
  124592. 3, 1, 0, 2, 4,
  124593. };
  124594. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  124595. _vq_quantthresh__44c3_s_p3_0,
  124596. _vq_quantmap__44c3_s_p3_0,
  124597. 5,
  124598. 5
  124599. };
  124600. static static_codebook _44c3_s_p3_0 = {
  124601. 4, 625,
  124602. _vq_lengthlist__44c3_s_p3_0,
  124603. 1, -533725184, 1611661312, 3, 0,
  124604. _vq_quantlist__44c3_s_p3_0,
  124605. NULL,
  124606. &_vq_auxt__44c3_s_p3_0,
  124607. NULL,
  124608. 0
  124609. };
  124610. static long _vq_quantlist__44c3_s_p4_0[] = {
  124611. 4,
  124612. 3,
  124613. 5,
  124614. 2,
  124615. 6,
  124616. 1,
  124617. 7,
  124618. 0,
  124619. 8,
  124620. };
  124621. static long _vq_lengthlist__44c3_s_p4_0[] = {
  124622. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  124623. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  124624. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  124625. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  124626. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124627. 0,
  124628. };
  124629. static float _vq_quantthresh__44c3_s_p4_0[] = {
  124630. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124631. };
  124632. static long _vq_quantmap__44c3_s_p4_0[] = {
  124633. 7, 5, 3, 1, 0, 2, 4, 6,
  124634. 8,
  124635. };
  124636. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  124637. _vq_quantthresh__44c3_s_p4_0,
  124638. _vq_quantmap__44c3_s_p4_0,
  124639. 9,
  124640. 9
  124641. };
  124642. static static_codebook _44c3_s_p4_0 = {
  124643. 2, 81,
  124644. _vq_lengthlist__44c3_s_p4_0,
  124645. 1, -531628032, 1611661312, 4, 0,
  124646. _vq_quantlist__44c3_s_p4_0,
  124647. NULL,
  124648. &_vq_auxt__44c3_s_p4_0,
  124649. NULL,
  124650. 0
  124651. };
  124652. static long _vq_quantlist__44c3_s_p5_0[] = {
  124653. 4,
  124654. 3,
  124655. 5,
  124656. 2,
  124657. 6,
  124658. 1,
  124659. 7,
  124660. 0,
  124661. 8,
  124662. };
  124663. static long _vq_lengthlist__44c3_s_p5_0[] = {
  124664. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  124665. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  124666. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124667. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  124668. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  124669. 11,
  124670. };
  124671. static float _vq_quantthresh__44c3_s_p5_0[] = {
  124672. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124673. };
  124674. static long _vq_quantmap__44c3_s_p5_0[] = {
  124675. 7, 5, 3, 1, 0, 2, 4, 6,
  124676. 8,
  124677. };
  124678. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  124679. _vq_quantthresh__44c3_s_p5_0,
  124680. _vq_quantmap__44c3_s_p5_0,
  124681. 9,
  124682. 9
  124683. };
  124684. static static_codebook _44c3_s_p5_0 = {
  124685. 2, 81,
  124686. _vq_lengthlist__44c3_s_p5_0,
  124687. 1, -531628032, 1611661312, 4, 0,
  124688. _vq_quantlist__44c3_s_p5_0,
  124689. NULL,
  124690. &_vq_auxt__44c3_s_p5_0,
  124691. NULL,
  124692. 0
  124693. };
  124694. static long _vq_quantlist__44c3_s_p6_0[] = {
  124695. 8,
  124696. 7,
  124697. 9,
  124698. 6,
  124699. 10,
  124700. 5,
  124701. 11,
  124702. 4,
  124703. 12,
  124704. 3,
  124705. 13,
  124706. 2,
  124707. 14,
  124708. 1,
  124709. 15,
  124710. 0,
  124711. 16,
  124712. };
  124713. static long _vq_lengthlist__44c3_s_p6_0[] = {
  124714. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  124715. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  124716. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  124717. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  124718. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  124719. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124720. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  124721. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124722. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124723. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  124724. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  124725. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  124726. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  124727. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  124728. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  124729. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  124730. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  124732. 13,
  124733. };
  124734. static float _vq_quantthresh__44c3_s_p6_0[] = {
  124735. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124736. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124737. };
  124738. static long _vq_quantmap__44c3_s_p6_0[] = {
  124739. 15, 13, 11, 9, 7, 5, 3, 1,
  124740. 0, 2, 4, 6, 8, 10, 12, 14,
  124741. 16,
  124742. };
  124743. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  124744. _vq_quantthresh__44c3_s_p6_0,
  124745. _vq_quantmap__44c3_s_p6_0,
  124746. 17,
  124747. 17
  124748. };
  124749. static static_codebook _44c3_s_p6_0 = {
  124750. 2, 289,
  124751. _vq_lengthlist__44c3_s_p6_0,
  124752. 1, -529530880, 1611661312, 5, 0,
  124753. _vq_quantlist__44c3_s_p6_0,
  124754. NULL,
  124755. &_vq_auxt__44c3_s_p6_0,
  124756. NULL,
  124757. 0
  124758. };
  124759. static long _vq_quantlist__44c3_s_p7_0[] = {
  124760. 1,
  124761. 0,
  124762. 2,
  124763. };
  124764. static long _vq_lengthlist__44c3_s_p7_0[] = {
  124765. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124766. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  124767. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124768. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  124769. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  124770. 10,
  124771. };
  124772. static float _vq_quantthresh__44c3_s_p7_0[] = {
  124773. -5.5, 5.5,
  124774. };
  124775. static long _vq_quantmap__44c3_s_p7_0[] = {
  124776. 1, 0, 2,
  124777. };
  124778. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  124779. _vq_quantthresh__44c3_s_p7_0,
  124780. _vq_quantmap__44c3_s_p7_0,
  124781. 3,
  124782. 3
  124783. };
  124784. static static_codebook _44c3_s_p7_0 = {
  124785. 4, 81,
  124786. _vq_lengthlist__44c3_s_p7_0,
  124787. 1, -529137664, 1618345984, 2, 0,
  124788. _vq_quantlist__44c3_s_p7_0,
  124789. NULL,
  124790. &_vq_auxt__44c3_s_p7_0,
  124791. NULL,
  124792. 0
  124793. };
  124794. static long _vq_quantlist__44c3_s_p7_1[] = {
  124795. 5,
  124796. 4,
  124797. 6,
  124798. 3,
  124799. 7,
  124800. 2,
  124801. 8,
  124802. 1,
  124803. 9,
  124804. 0,
  124805. 10,
  124806. };
  124807. static long _vq_lengthlist__44c3_s_p7_1[] = {
  124808. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  124809. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  124810. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  124811. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  124812. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124813. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124814. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  124815. 10,10,10, 8, 8, 8, 8, 8, 8,
  124816. };
  124817. static float _vq_quantthresh__44c3_s_p7_1[] = {
  124818. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124819. 3.5, 4.5,
  124820. };
  124821. static long _vq_quantmap__44c3_s_p7_1[] = {
  124822. 9, 7, 5, 3, 1, 0, 2, 4,
  124823. 6, 8, 10,
  124824. };
  124825. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  124826. _vq_quantthresh__44c3_s_p7_1,
  124827. _vq_quantmap__44c3_s_p7_1,
  124828. 11,
  124829. 11
  124830. };
  124831. static static_codebook _44c3_s_p7_1 = {
  124832. 2, 121,
  124833. _vq_lengthlist__44c3_s_p7_1,
  124834. 1, -531365888, 1611661312, 4, 0,
  124835. _vq_quantlist__44c3_s_p7_1,
  124836. NULL,
  124837. &_vq_auxt__44c3_s_p7_1,
  124838. NULL,
  124839. 0
  124840. };
  124841. static long _vq_quantlist__44c3_s_p8_0[] = {
  124842. 6,
  124843. 5,
  124844. 7,
  124845. 4,
  124846. 8,
  124847. 3,
  124848. 9,
  124849. 2,
  124850. 10,
  124851. 1,
  124852. 11,
  124853. 0,
  124854. 12,
  124855. };
  124856. static long _vq_lengthlist__44c3_s_p8_0[] = {
  124857. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  124858. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  124859. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124860. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124861. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  124862. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124863. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  124864. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  124865. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  124866. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  124867. 0,13,13,12,12,13,12,14,13,
  124868. };
  124869. static float _vq_quantthresh__44c3_s_p8_0[] = {
  124870. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124871. 12.5, 17.5, 22.5, 27.5,
  124872. };
  124873. static long _vq_quantmap__44c3_s_p8_0[] = {
  124874. 11, 9, 7, 5, 3, 1, 0, 2,
  124875. 4, 6, 8, 10, 12,
  124876. };
  124877. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  124878. _vq_quantthresh__44c3_s_p8_0,
  124879. _vq_quantmap__44c3_s_p8_0,
  124880. 13,
  124881. 13
  124882. };
  124883. static static_codebook _44c3_s_p8_0 = {
  124884. 2, 169,
  124885. _vq_lengthlist__44c3_s_p8_0,
  124886. 1, -526516224, 1616117760, 4, 0,
  124887. _vq_quantlist__44c3_s_p8_0,
  124888. NULL,
  124889. &_vq_auxt__44c3_s_p8_0,
  124890. NULL,
  124891. 0
  124892. };
  124893. static long _vq_quantlist__44c3_s_p8_1[] = {
  124894. 2,
  124895. 1,
  124896. 3,
  124897. 0,
  124898. 4,
  124899. };
  124900. static long _vq_lengthlist__44c3_s_p8_1[] = {
  124901. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  124902. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124903. };
  124904. static float _vq_quantthresh__44c3_s_p8_1[] = {
  124905. -1.5, -0.5, 0.5, 1.5,
  124906. };
  124907. static long _vq_quantmap__44c3_s_p8_1[] = {
  124908. 3, 1, 0, 2, 4,
  124909. };
  124910. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  124911. _vq_quantthresh__44c3_s_p8_1,
  124912. _vq_quantmap__44c3_s_p8_1,
  124913. 5,
  124914. 5
  124915. };
  124916. static static_codebook _44c3_s_p8_1 = {
  124917. 2, 25,
  124918. _vq_lengthlist__44c3_s_p8_1,
  124919. 1, -533725184, 1611661312, 3, 0,
  124920. _vq_quantlist__44c3_s_p8_1,
  124921. NULL,
  124922. &_vq_auxt__44c3_s_p8_1,
  124923. NULL,
  124924. 0
  124925. };
  124926. static long _vq_quantlist__44c3_s_p9_0[] = {
  124927. 6,
  124928. 5,
  124929. 7,
  124930. 4,
  124931. 8,
  124932. 3,
  124933. 9,
  124934. 2,
  124935. 10,
  124936. 1,
  124937. 11,
  124938. 0,
  124939. 12,
  124940. };
  124941. static long _vq_lengthlist__44c3_s_p9_0[] = {
  124942. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  124943. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  124944. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124945. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  124946. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124947. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124948. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124949. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124950. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  124951. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124952. 11,11,11,11,11,11,11,11,11,
  124953. };
  124954. static float _vq_quantthresh__44c3_s_p9_0[] = {
  124955. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  124956. 637.5, 892.5, 1147.5, 1402.5,
  124957. };
  124958. static long _vq_quantmap__44c3_s_p9_0[] = {
  124959. 11, 9, 7, 5, 3, 1, 0, 2,
  124960. 4, 6, 8, 10, 12,
  124961. };
  124962. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  124963. _vq_quantthresh__44c3_s_p9_0,
  124964. _vq_quantmap__44c3_s_p9_0,
  124965. 13,
  124966. 13
  124967. };
  124968. static static_codebook _44c3_s_p9_0 = {
  124969. 2, 169,
  124970. _vq_lengthlist__44c3_s_p9_0,
  124971. 1, -514332672, 1627381760, 4, 0,
  124972. _vq_quantlist__44c3_s_p9_0,
  124973. NULL,
  124974. &_vq_auxt__44c3_s_p9_0,
  124975. NULL,
  124976. 0
  124977. };
  124978. static long _vq_quantlist__44c3_s_p9_1[] = {
  124979. 7,
  124980. 6,
  124981. 8,
  124982. 5,
  124983. 9,
  124984. 4,
  124985. 10,
  124986. 3,
  124987. 11,
  124988. 2,
  124989. 12,
  124990. 1,
  124991. 13,
  124992. 0,
  124993. 14,
  124994. };
  124995. static long _vq_lengthlist__44c3_s_p9_1[] = {
  124996. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  124997. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  124998. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  124999. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  125000. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  125001. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  125002. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  125003. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  125004. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  125005. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  125006. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  125007. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  125008. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  125009. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  125010. 15,
  125011. };
  125012. static float _vq_quantthresh__44c3_s_p9_1[] = {
  125013. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  125014. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  125015. };
  125016. static long _vq_quantmap__44c3_s_p9_1[] = {
  125017. 13, 11, 9, 7, 5, 3, 1, 0,
  125018. 2, 4, 6, 8, 10, 12, 14,
  125019. };
  125020. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  125021. _vq_quantthresh__44c3_s_p9_1,
  125022. _vq_quantmap__44c3_s_p9_1,
  125023. 15,
  125024. 15
  125025. };
  125026. static static_codebook _44c3_s_p9_1 = {
  125027. 2, 225,
  125028. _vq_lengthlist__44c3_s_p9_1,
  125029. 1, -522338304, 1620115456, 4, 0,
  125030. _vq_quantlist__44c3_s_p9_1,
  125031. NULL,
  125032. &_vq_auxt__44c3_s_p9_1,
  125033. NULL,
  125034. 0
  125035. };
  125036. static long _vq_quantlist__44c3_s_p9_2[] = {
  125037. 8,
  125038. 7,
  125039. 9,
  125040. 6,
  125041. 10,
  125042. 5,
  125043. 11,
  125044. 4,
  125045. 12,
  125046. 3,
  125047. 13,
  125048. 2,
  125049. 14,
  125050. 1,
  125051. 15,
  125052. 0,
  125053. 16,
  125054. };
  125055. static long _vq_lengthlist__44c3_s_p9_2[] = {
  125056. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  125057. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  125058. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  125059. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  125060. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  125061. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  125062. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  125063. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  125064. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  125065. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  125066. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  125067. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  125068. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  125069. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  125070. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  125071. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  125072. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  125073. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  125074. 10,
  125075. };
  125076. static float _vq_quantthresh__44c3_s_p9_2[] = {
  125077. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125078. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125079. };
  125080. static long _vq_quantmap__44c3_s_p9_2[] = {
  125081. 15, 13, 11, 9, 7, 5, 3, 1,
  125082. 0, 2, 4, 6, 8, 10, 12, 14,
  125083. 16,
  125084. };
  125085. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  125086. _vq_quantthresh__44c3_s_p9_2,
  125087. _vq_quantmap__44c3_s_p9_2,
  125088. 17,
  125089. 17
  125090. };
  125091. static static_codebook _44c3_s_p9_2 = {
  125092. 2, 289,
  125093. _vq_lengthlist__44c3_s_p9_2,
  125094. 1, -529530880, 1611661312, 5, 0,
  125095. _vq_quantlist__44c3_s_p9_2,
  125096. NULL,
  125097. &_vq_auxt__44c3_s_p9_2,
  125098. NULL,
  125099. 0
  125100. };
  125101. static long _huff_lengthlist__44c3_s_short[] = {
  125102. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  125103. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  125104. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  125105. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  125106. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  125107. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  125108. 6, 8, 9,11,
  125109. };
  125110. static static_codebook _huff_book__44c3_s_short = {
  125111. 2, 100,
  125112. _huff_lengthlist__44c3_s_short,
  125113. 0, 0, 0, 0, 0,
  125114. NULL,
  125115. NULL,
  125116. NULL,
  125117. NULL,
  125118. 0
  125119. };
  125120. static long _huff_lengthlist__44c4_s_long[] = {
  125121. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  125122. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  125123. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  125124. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  125125. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  125126. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  125127. 9, 8, 7, 7,
  125128. };
  125129. static static_codebook _huff_book__44c4_s_long = {
  125130. 2, 100,
  125131. _huff_lengthlist__44c4_s_long,
  125132. 0, 0, 0, 0, 0,
  125133. NULL,
  125134. NULL,
  125135. NULL,
  125136. NULL,
  125137. 0
  125138. };
  125139. static long _vq_quantlist__44c4_s_p1_0[] = {
  125140. 1,
  125141. 0,
  125142. 2,
  125143. };
  125144. static long _vq_lengthlist__44c4_s_p1_0[] = {
  125145. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  125146. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125151. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125156. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  125191. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  125196. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  125201. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125237. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125242. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125247. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0,
  125556. };
  125557. static float _vq_quantthresh__44c4_s_p1_0[] = {
  125558. -0.5, 0.5,
  125559. };
  125560. static long _vq_quantmap__44c4_s_p1_0[] = {
  125561. 1, 0, 2,
  125562. };
  125563. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  125564. _vq_quantthresh__44c4_s_p1_0,
  125565. _vq_quantmap__44c4_s_p1_0,
  125566. 3,
  125567. 3
  125568. };
  125569. static static_codebook _44c4_s_p1_0 = {
  125570. 8, 6561,
  125571. _vq_lengthlist__44c4_s_p1_0,
  125572. 1, -535822336, 1611661312, 2, 0,
  125573. _vq_quantlist__44c4_s_p1_0,
  125574. NULL,
  125575. &_vq_auxt__44c4_s_p1_0,
  125576. NULL,
  125577. 0
  125578. };
  125579. static long _vq_quantlist__44c4_s_p2_0[] = {
  125580. 2,
  125581. 1,
  125582. 3,
  125583. 0,
  125584. 4,
  125585. };
  125586. static long _vq_lengthlist__44c4_s_p2_0[] = {
  125587. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125588. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  125589. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125590. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  125591. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  125597. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  125598. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  125599. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  125605. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  125606. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  125613. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  125614. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0,
  125627. };
  125628. static float _vq_quantthresh__44c4_s_p2_0[] = {
  125629. -1.5, -0.5, 0.5, 1.5,
  125630. };
  125631. static long _vq_quantmap__44c4_s_p2_0[] = {
  125632. 3, 1, 0, 2, 4,
  125633. };
  125634. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  125635. _vq_quantthresh__44c4_s_p2_0,
  125636. _vq_quantmap__44c4_s_p2_0,
  125637. 5,
  125638. 5
  125639. };
  125640. static static_codebook _44c4_s_p2_0 = {
  125641. 4, 625,
  125642. _vq_lengthlist__44c4_s_p2_0,
  125643. 1, -533725184, 1611661312, 3, 0,
  125644. _vq_quantlist__44c4_s_p2_0,
  125645. NULL,
  125646. &_vq_auxt__44c4_s_p2_0,
  125647. NULL,
  125648. 0
  125649. };
  125650. static long _vq_quantlist__44c4_s_p3_0[] = {
  125651. 2,
  125652. 1,
  125653. 3,
  125654. 0,
  125655. 4,
  125656. };
  125657. static long _vq_lengthlist__44c4_s_p3_0[] = {
  125658. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0,
  125698. };
  125699. static float _vq_quantthresh__44c4_s_p3_0[] = {
  125700. -1.5, -0.5, 0.5, 1.5,
  125701. };
  125702. static long _vq_quantmap__44c4_s_p3_0[] = {
  125703. 3, 1, 0, 2, 4,
  125704. };
  125705. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  125706. _vq_quantthresh__44c4_s_p3_0,
  125707. _vq_quantmap__44c4_s_p3_0,
  125708. 5,
  125709. 5
  125710. };
  125711. static static_codebook _44c4_s_p3_0 = {
  125712. 4, 625,
  125713. _vq_lengthlist__44c4_s_p3_0,
  125714. 1, -533725184, 1611661312, 3, 0,
  125715. _vq_quantlist__44c4_s_p3_0,
  125716. NULL,
  125717. &_vq_auxt__44c4_s_p3_0,
  125718. NULL,
  125719. 0
  125720. };
  125721. static long _vq_quantlist__44c4_s_p4_0[] = {
  125722. 4,
  125723. 3,
  125724. 5,
  125725. 2,
  125726. 6,
  125727. 1,
  125728. 7,
  125729. 0,
  125730. 8,
  125731. };
  125732. static long _vq_lengthlist__44c4_s_p4_0[] = {
  125733. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125734. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125735. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125736. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  125737. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0,
  125739. };
  125740. static float _vq_quantthresh__44c4_s_p4_0[] = {
  125741. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125742. };
  125743. static long _vq_quantmap__44c4_s_p4_0[] = {
  125744. 7, 5, 3, 1, 0, 2, 4, 6,
  125745. 8,
  125746. };
  125747. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  125748. _vq_quantthresh__44c4_s_p4_0,
  125749. _vq_quantmap__44c4_s_p4_0,
  125750. 9,
  125751. 9
  125752. };
  125753. static static_codebook _44c4_s_p4_0 = {
  125754. 2, 81,
  125755. _vq_lengthlist__44c4_s_p4_0,
  125756. 1, -531628032, 1611661312, 4, 0,
  125757. _vq_quantlist__44c4_s_p4_0,
  125758. NULL,
  125759. &_vq_auxt__44c4_s_p4_0,
  125760. NULL,
  125761. 0
  125762. };
  125763. static long _vq_quantlist__44c4_s_p5_0[] = {
  125764. 4,
  125765. 3,
  125766. 5,
  125767. 2,
  125768. 6,
  125769. 1,
  125770. 7,
  125771. 0,
  125772. 8,
  125773. };
  125774. static long _vq_lengthlist__44c4_s_p5_0[] = {
  125775. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125776. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  125777. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  125778. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  125779. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  125780. 10,
  125781. };
  125782. static float _vq_quantthresh__44c4_s_p5_0[] = {
  125783. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125784. };
  125785. static long _vq_quantmap__44c4_s_p5_0[] = {
  125786. 7, 5, 3, 1, 0, 2, 4, 6,
  125787. 8,
  125788. };
  125789. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  125790. _vq_quantthresh__44c4_s_p5_0,
  125791. _vq_quantmap__44c4_s_p5_0,
  125792. 9,
  125793. 9
  125794. };
  125795. static static_codebook _44c4_s_p5_0 = {
  125796. 2, 81,
  125797. _vq_lengthlist__44c4_s_p5_0,
  125798. 1, -531628032, 1611661312, 4, 0,
  125799. _vq_quantlist__44c4_s_p5_0,
  125800. NULL,
  125801. &_vq_auxt__44c4_s_p5_0,
  125802. NULL,
  125803. 0
  125804. };
  125805. static long _vq_quantlist__44c4_s_p6_0[] = {
  125806. 8,
  125807. 7,
  125808. 9,
  125809. 6,
  125810. 10,
  125811. 5,
  125812. 11,
  125813. 4,
  125814. 12,
  125815. 3,
  125816. 13,
  125817. 2,
  125818. 14,
  125819. 1,
  125820. 15,
  125821. 0,
  125822. 16,
  125823. };
  125824. static long _vq_lengthlist__44c4_s_p6_0[] = {
  125825. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  125826. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125827. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  125828. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125829. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125830. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125831. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  125832. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125833. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125834. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  125835. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  125836. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  125837. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  125838. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  125839. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  125840. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125841. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  125843. 13,
  125844. };
  125845. static float _vq_quantthresh__44c4_s_p6_0[] = {
  125846. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125847. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125848. };
  125849. static long _vq_quantmap__44c4_s_p6_0[] = {
  125850. 15, 13, 11, 9, 7, 5, 3, 1,
  125851. 0, 2, 4, 6, 8, 10, 12, 14,
  125852. 16,
  125853. };
  125854. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  125855. _vq_quantthresh__44c4_s_p6_0,
  125856. _vq_quantmap__44c4_s_p6_0,
  125857. 17,
  125858. 17
  125859. };
  125860. static static_codebook _44c4_s_p6_0 = {
  125861. 2, 289,
  125862. _vq_lengthlist__44c4_s_p6_0,
  125863. 1, -529530880, 1611661312, 5, 0,
  125864. _vq_quantlist__44c4_s_p6_0,
  125865. NULL,
  125866. &_vq_auxt__44c4_s_p6_0,
  125867. NULL,
  125868. 0
  125869. };
  125870. static long _vq_quantlist__44c4_s_p7_0[] = {
  125871. 1,
  125872. 0,
  125873. 2,
  125874. };
  125875. static long _vq_lengthlist__44c4_s_p7_0[] = {
  125876. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125877. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125878. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125879. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  125880. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125881. 10,
  125882. };
  125883. static float _vq_quantthresh__44c4_s_p7_0[] = {
  125884. -5.5, 5.5,
  125885. };
  125886. static long _vq_quantmap__44c4_s_p7_0[] = {
  125887. 1, 0, 2,
  125888. };
  125889. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  125890. _vq_quantthresh__44c4_s_p7_0,
  125891. _vq_quantmap__44c4_s_p7_0,
  125892. 3,
  125893. 3
  125894. };
  125895. static static_codebook _44c4_s_p7_0 = {
  125896. 4, 81,
  125897. _vq_lengthlist__44c4_s_p7_0,
  125898. 1, -529137664, 1618345984, 2, 0,
  125899. _vq_quantlist__44c4_s_p7_0,
  125900. NULL,
  125901. &_vq_auxt__44c4_s_p7_0,
  125902. NULL,
  125903. 0
  125904. };
  125905. static long _vq_quantlist__44c4_s_p7_1[] = {
  125906. 5,
  125907. 4,
  125908. 6,
  125909. 3,
  125910. 7,
  125911. 2,
  125912. 8,
  125913. 1,
  125914. 9,
  125915. 0,
  125916. 10,
  125917. };
  125918. static long _vq_lengthlist__44c4_s_p7_1[] = {
  125919. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  125920. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  125921. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  125922. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  125923. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  125924. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125925. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  125926. 10,10,10, 8, 8, 8, 8, 9, 9,
  125927. };
  125928. static float _vq_quantthresh__44c4_s_p7_1[] = {
  125929. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125930. 3.5, 4.5,
  125931. };
  125932. static long _vq_quantmap__44c4_s_p7_1[] = {
  125933. 9, 7, 5, 3, 1, 0, 2, 4,
  125934. 6, 8, 10,
  125935. };
  125936. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  125937. _vq_quantthresh__44c4_s_p7_1,
  125938. _vq_quantmap__44c4_s_p7_1,
  125939. 11,
  125940. 11
  125941. };
  125942. static static_codebook _44c4_s_p7_1 = {
  125943. 2, 121,
  125944. _vq_lengthlist__44c4_s_p7_1,
  125945. 1, -531365888, 1611661312, 4, 0,
  125946. _vq_quantlist__44c4_s_p7_1,
  125947. NULL,
  125948. &_vq_auxt__44c4_s_p7_1,
  125949. NULL,
  125950. 0
  125951. };
  125952. static long _vq_quantlist__44c4_s_p8_0[] = {
  125953. 6,
  125954. 5,
  125955. 7,
  125956. 4,
  125957. 8,
  125958. 3,
  125959. 9,
  125960. 2,
  125961. 10,
  125962. 1,
  125963. 11,
  125964. 0,
  125965. 12,
  125966. };
  125967. static long _vq_lengthlist__44c4_s_p8_0[] = {
  125968. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125969. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  125970. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125971. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125972. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  125973. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  125974. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  125975. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125976. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  125977. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  125978. 0,13,12,12,12,12,12,13,13,
  125979. };
  125980. static float _vq_quantthresh__44c4_s_p8_0[] = {
  125981. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125982. 12.5, 17.5, 22.5, 27.5,
  125983. };
  125984. static long _vq_quantmap__44c4_s_p8_0[] = {
  125985. 11, 9, 7, 5, 3, 1, 0, 2,
  125986. 4, 6, 8, 10, 12,
  125987. };
  125988. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  125989. _vq_quantthresh__44c4_s_p8_0,
  125990. _vq_quantmap__44c4_s_p8_0,
  125991. 13,
  125992. 13
  125993. };
  125994. static static_codebook _44c4_s_p8_0 = {
  125995. 2, 169,
  125996. _vq_lengthlist__44c4_s_p8_0,
  125997. 1, -526516224, 1616117760, 4, 0,
  125998. _vq_quantlist__44c4_s_p8_0,
  125999. NULL,
  126000. &_vq_auxt__44c4_s_p8_0,
  126001. NULL,
  126002. 0
  126003. };
  126004. static long _vq_quantlist__44c4_s_p8_1[] = {
  126005. 2,
  126006. 1,
  126007. 3,
  126008. 0,
  126009. 4,
  126010. };
  126011. static long _vq_lengthlist__44c4_s_p8_1[] = {
  126012. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  126013. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126014. };
  126015. static float _vq_quantthresh__44c4_s_p8_1[] = {
  126016. -1.5, -0.5, 0.5, 1.5,
  126017. };
  126018. static long _vq_quantmap__44c4_s_p8_1[] = {
  126019. 3, 1, 0, 2, 4,
  126020. };
  126021. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  126022. _vq_quantthresh__44c4_s_p8_1,
  126023. _vq_quantmap__44c4_s_p8_1,
  126024. 5,
  126025. 5
  126026. };
  126027. static static_codebook _44c4_s_p8_1 = {
  126028. 2, 25,
  126029. _vq_lengthlist__44c4_s_p8_1,
  126030. 1, -533725184, 1611661312, 3, 0,
  126031. _vq_quantlist__44c4_s_p8_1,
  126032. NULL,
  126033. &_vq_auxt__44c4_s_p8_1,
  126034. NULL,
  126035. 0
  126036. };
  126037. static long _vq_quantlist__44c4_s_p9_0[] = {
  126038. 6,
  126039. 5,
  126040. 7,
  126041. 4,
  126042. 8,
  126043. 3,
  126044. 9,
  126045. 2,
  126046. 10,
  126047. 1,
  126048. 11,
  126049. 0,
  126050. 12,
  126051. };
  126052. static long _vq_lengthlist__44c4_s_p9_0[] = {
  126053. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  126054. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  126055. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126056. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126057. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126058. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126059. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126060. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126061. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126062. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126063. 12,12,12,12,12,12,12,12,12,
  126064. };
  126065. static float _vq_quantthresh__44c4_s_p9_0[] = {
  126066. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126067. 787.5, 1102.5, 1417.5, 1732.5,
  126068. };
  126069. static long _vq_quantmap__44c4_s_p9_0[] = {
  126070. 11, 9, 7, 5, 3, 1, 0, 2,
  126071. 4, 6, 8, 10, 12,
  126072. };
  126073. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  126074. _vq_quantthresh__44c4_s_p9_0,
  126075. _vq_quantmap__44c4_s_p9_0,
  126076. 13,
  126077. 13
  126078. };
  126079. static static_codebook _44c4_s_p9_0 = {
  126080. 2, 169,
  126081. _vq_lengthlist__44c4_s_p9_0,
  126082. 1, -513964032, 1628680192, 4, 0,
  126083. _vq_quantlist__44c4_s_p9_0,
  126084. NULL,
  126085. &_vq_auxt__44c4_s_p9_0,
  126086. NULL,
  126087. 0
  126088. };
  126089. static long _vq_quantlist__44c4_s_p9_1[] = {
  126090. 7,
  126091. 6,
  126092. 8,
  126093. 5,
  126094. 9,
  126095. 4,
  126096. 10,
  126097. 3,
  126098. 11,
  126099. 2,
  126100. 12,
  126101. 1,
  126102. 13,
  126103. 0,
  126104. 14,
  126105. };
  126106. static long _vq_lengthlist__44c4_s_p9_1[] = {
  126107. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  126108. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  126109. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  126110. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  126111. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  126112. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  126113. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  126114. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  126115. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  126116. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  126117. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  126118. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  126119. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  126120. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  126121. 15,
  126122. };
  126123. static float _vq_quantthresh__44c4_s_p9_1[] = {
  126124. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126125. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126126. };
  126127. static long _vq_quantmap__44c4_s_p9_1[] = {
  126128. 13, 11, 9, 7, 5, 3, 1, 0,
  126129. 2, 4, 6, 8, 10, 12, 14,
  126130. };
  126131. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  126132. _vq_quantthresh__44c4_s_p9_1,
  126133. _vq_quantmap__44c4_s_p9_1,
  126134. 15,
  126135. 15
  126136. };
  126137. static static_codebook _44c4_s_p9_1 = {
  126138. 2, 225,
  126139. _vq_lengthlist__44c4_s_p9_1,
  126140. 1, -520986624, 1620377600, 4, 0,
  126141. _vq_quantlist__44c4_s_p9_1,
  126142. NULL,
  126143. &_vq_auxt__44c4_s_p9_1,
  126144. NULL,
  126145. 0
  126146. };
  126147. static long _vq_quantlist__44c4_s_p9_2[] = {
  126148. 10,
  126149. 9,
  126150. 11,
  126151. 8,
  126152. 12,
  126153. 7,
  126154. 13,
  126155. 6,
  126156. 14,
  126157. 5,
  126158. 15,
  126159. 4,
  126160. 16,
  126161. 3,
  126162. 17,
  126163. 2,
  126164. 18,
  126165. 1,
  126166. 19,
  126167. 0,
  126168. 20,
  126169. };
  126170. static long _vq_lengthlist__44c4_s_p9_2[] = {
  126171. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  126172. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  126173. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  126174. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  126175. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  126176. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  126177. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  126178. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  126179. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  126180. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  126181. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126182. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126183. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126184. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126185. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  126186. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  126187. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  126188. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126189. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  126190. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  126191. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126192. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126193. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  126194. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  126195. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  126196. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  126197. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  126198. 10,10,10,10,10,10,10,10,10,
  126199. };
  126200. static float _vq_quantthresh__44c4_s_p9_2[] = {
  126201. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126202. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126203. 6.5, 7.5, 8.5, 9.5,
  126204. };
  126205. static long _vq_quantmap__44c4_s_p9_2[] = {
  126206. 19, 17, 15, 13, 11, 9, 7, 5,
  126207. 3, 1, 0, 2, 4, 6, 8, 10,
  126208. 12, 14, 16, 18, 20,
  126209. };
  126210. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  126211. _vq_quantthresh__44c4_s_p9_2,
  126212. _vq_quantmap__44c4_s_p9_2,
  126213. 21,
  126214. 21
  126215. };
  126216. static static_codebook _44c4_s_p9_2 = {
  126217. 2, 441,
  126218. _vq_lengthlist__44c4_s_p9_2,
  126219. 1, -529268736, 1611661312, 5, 0,
  126220. _vq_quantlist__44c4_s_p9_2,
  126221. NULL,
  126222. &_vq_auxt__44c4_s_p9_2,
  126223. NULL,
  126224. 0
  126225. };
  126226. static long _huff_lengthlist__44c4_s_short[] = {
  126227. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  126228. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  126229. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  126230. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  126231. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  126232. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  126233. 7, 9,12,17,
  126234. };
  126235. static static_codebook _huff_book__44c4_s_short = {
  126236. 2, 100,
  126237. _huff_lengthlist__44c4_s_short,
  126238. 0, 0, 0, 0, 0,
  126239. NULL,
  126240. NULL,
  126241. NULL,
  126242. NULL,
  126243. 0
  126244. };
  126245. static long _huff_lengthlist__44c5_s_long[] = {
  126246. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  126247. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  126248. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  126249. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  126250. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  126251. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  126252. 9, 8, 7, 7,
  126253. };
  126254. static static_codebook _huff_book__44c5_s_long = {
  126255. 2, 100,
  126256. _huff_lengthlist__44c5_s_long,
  126257. 0, 0, 0, 0, 0,
  126258. NULL,
  126259. NULL,
  126260. NULL,
  126261. NULL,
  126262. 0
  126263. };
  126264. static long _vq_quantlist__44c5_s_p1_0[] = {
  126265. 1,
  126266. 0,
  126267. 2,
  126268. };
  126269. static long _vq_lengthlist__44c5_s_p1_0[] = {
  126270. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126271. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126276. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126281. 0, 0, 0, 0, 7, 9, 9, 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, 4, 7, 7, 0, 0, 0, 0,
  126316. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126321. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126326. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126362. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  126367. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126372. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0,
  126681. };
  126682. static float _vq_quantthresh__44c5_s_p1_0[] = {
  126683. -0.5, 0.5,
  126684. };
  126685. static long _vq_quantmap__44c5_s_p1_0[] = {
  126686. 1, 0, 2,
  126687. };
  126688. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  126689. _vq_quantthresh__44c5_s_p1_0,
  126690. _vq_quantmap__44c5_s_p1_0,
  126691. 3,
  126692. 3
  126693. };
  126694. static static_codebook _44c5_s_p1_0 = {
  126695. 8, 6561,
  126696. _vq_lengthlist__44c5_s_p1_0,
  126697. 1, -535822336, 1611661312, 2, 0,
  126698. _vq_quantlist__44c5_s_p1_0,
  126699. NULL,
  126700. &_vq_auxt__44c5_s_p1_0,
  126701. NULL,
  126702. 0
  126703. };
  126704. static long _vq_quantlist__44c5_s_p2_0[] = {
  126705. 2,
  126706. 1,
  126707. 3,
  126708. 0,
  126709. 4,
  126710. };
  126711. static long _vq_lengthlist__44c5_s_p2_0[] = {
  126712. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126713. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  126714. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126715. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  126716. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  126722. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  126723. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  126724. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  126730. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  126731. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  126738. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  126739. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0,
  126752. };
  126753. static float _vq_quantthresh__44c5_s_p2_0[] = {
  126754. -1.5, -0.5, 0.5, 1.5,
  126755. };
  126756. static long _vq_quantmap__44c5_s_p2_0[] = {
  126757. 3, 1, 0, 2, 4,
  126758. };
  126759. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  126760. _vq_quantthresh__44c5_s_p2_0,
  126761. _vq_quantmap__44c5_s_p2_0,
  126762. 5,
  126763. 5
  126764. };
  126765. static static_codebook _44c5_s_p2_0 = {
  126766. 4, 625,
  126767. _vq_lengthlist__44c5_s_p2_0,
  126768. 1, -533725184, 1611661312, 3, 0,
  126769. _vq_quantlist__44c5_s_p2_0,
  126770. NULL,
  126771. &_vq_auxt__44c5_s_p2_0,
  126772. NULL,
  126773. 0
  126774. };
  126775. static long _vq_quantlist__44c5_s_p3_0[] = {
  126776. 2,
  126777. 1,
  126778. 3,
  126779. 0,
  126780. 4,
  126781. };
  126782. static long _vq_lengthlist__44c5_s_p3_0[] = {
  126783. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0,
  126823. };
  126824. static float _vq_quantthresh__44c5_s_p3_0[] = {
  126825. -1.5, -0.5, 0.5, 1.5,
  126826. };
  126827. static long _vq_quantmap__44c5_s_p3_0[] = {
  126828. 3, 1, 0, 2, 4,
  126829. };
  126830. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  126831. _vq_quantthresh__44c5_s_p3_0,
  126832. _vq_quantmap__44c5_s_p3_0,
  126833. 5,
  126834. 5
  126835. };
  126836. static static_codebook _44c5_s_p3_0 = {
  126837. 4, 625,
  126838. _vq_lengthlist__44c5_s_p3_0,
  126839. 1, -533725184, 1611661312, 3, 0,
  126840. _vq_quantlist__44c5_s_p3_0,
  126841. NULL,
  126842. &_vq_auxt__44c5_s_p3_0,
  126843. NULL,
  126844. 0
  126845. };
  126846. static long _vq_quantlist__44c5_s_p4_0[] = {
  126847. 4,
  126848. 3,
  126849. 5,
  126850. 2,
  126851. 6,
  126852. 1,
  126853. 7,
  126854. 0,
  126855. 8,
  126856. };
  126857. static long _vq_lengthlist__44c5_s_p4_0[] = {
  126858. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126859. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126860. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126861. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  126862. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0,
  126864. };
  126865. static float _vq_quantthresh__44c5_s_p4_0[] = {
  126866. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126867. };
  126868. static long _vq_quantmap__44c5_s_p4_0[] = {
  126869. 7, 5, 3, 1, 0, 2, 4, 6,
  126870. 8,
  126871. };
  126872. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  126873. _vq_quantthresh__44c5_s_p4_0,
  126874. _vq_quantmap__44c5_s_p4_0,
  126875. 9,
  126876. 9
  126877. };
  126878. static static_codebook _44c5_s_p4_0 = {
  126879. 2, 81,
  126880. _vq_lengthlist__44c5_s_p4_0,
  126881. 1, -531628032, 1611661312, 4, 0,
  126882. _vq_quantlist__44c5_s_p4_0,
  126883. NULL,
  126884. &_vq_auxt__44c5_s_p4_0,
  126885. NULL,
  126886. 0
  126887. };
  126888. static long _vq_quantlist__44c5_s_p5_0[] = {
  126889. 4,
  126890. 3,
  126891. 5,
  126892. 2,
  126893. 6,
  126894. 1,
  126895. 7,
  126896. 0,
  126897. 8,
  126898. };
  126899. static long _vq_lengthlist__44c5_s_p5_0[] = {
  126900. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126901. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  126902. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  126903. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  126904. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126905. 10,
  126906. };
  126907. static float _vq_quantthresh__44c5_s_p5_0[] = {
  126908. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126909. };
  126910. static long _vq_quantmap__44c5_s_p5_0[] = {
  126911. 7, 5, 3, 1, 0, 2, 4, 6,
  126912. 8,
  126913. };
  126914. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  126915. _vq_quantthresh__44c5_s_p5_0,
  126916. _vq_quantmap__44c5_s_p5_0,
  126917. 9,
  126918. 9
  126919. };
  126920. static static_codebook _44c5_s_p5_0 = {
  126921. 2, 81,
  126922. _vq_lengthlist__44c5_s_p5_0,
  126923. 1, -531628032, 1611661312, 4, 0,
  126924. _vq_quantlist__44c5_s_p5_0,
  126925. NULL,
  126926. &_vq_auxt__44c5_s_p5_0,
  126927. NULL,
  126928. 0
  126929. };
  126930. static long _vq_quantlist__44c5_s_p6_0[] = {
  126931. 8,
  126932. 7,
  126933. 9,
  126934. 6,
  126935. 10,
  126936. 5,
  126937. 11,
  126938. 4,
  126939. 12,
  126940. 3,
  126941. 13,
  126942. 2,
  126943. 14,
  126944. 1,
  126945. 15,
  126946. 0,
  126947. 16,
  126948. };
  126949. static long _vq_lengthlist__44c5_s_p6_0[] = {
  126950. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  126951. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126952. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  126953. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126954. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126955. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  126956. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  126957. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  126958. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126959. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  126960. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  126961. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  126962. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  126963. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  126964. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  126965. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126966. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  126968. 13,
  126969. };
  126970. static float _vq_quantthresh__44c5_s_p6_0[] = {
  126971. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126972. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126973. };
  126974. static long _vq_quantmap__44c5_s_p6_0[] = {
  126975. 15, 13, 11, 9, 7, 5, 3, 1,
  126976. 0, 2, 4, 6, 8, 10, 12, 14,
  126977. 16,
  126978. };
  126979. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  126980. _vq_quantthresh__44c5_s_p6_0,
  126981. _vq_quantmap__44c5_s_p6_0,
  126982. 17,
  126983. 17
  126984. };
  126985. static static_codebook _44c5_s_p6_0 = {
  126986. 2, 289,
  126987. _vq_lengthlist__44c5_s_p6_0,
  126988. 1, -529530880, 1611661312, 5, 0,
  126989. _vq_quantlist__44c5_s_p6_0,
  126990. NULL,
  126991. &_vq_auxt__44c5_s_p6_0,
  126992. NULL,
  126993. 0
  126994. };
  126995. static long _vq_quantlist__44c5_s_p7_0[] = {
  126996. 1,
  126997. 0,
  126998. 2,
  126999. };
  127000. static long _vq_lengthlist__44c5_s_p7_0[] = {
  127001. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127002. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127003. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127004. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127005. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127006. 10,
  127007. };
  127008. static float _vq_quantthresh__44c5_s_p7_0[] = {
  127009. -5.5, 5.5,
  127010. };
  127011. static long _vq_quantmap__44c5_s_p7_0[] = {
  127012. 1, 0, 2,
  127013. };
  127014. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  127015. _vq_quantthresh__44c5_s_p7_0,
  127016. _vq_quantmap__44c5_s_p7_0,
  127017. 3,
  127018. 3
  127019. };
  127020. static static_codebook _44c5_s_p7_0 = {
  127021. 4, 81,
  127022. _vq_lengthlist__44c5_s_p7_0,
  127023. 1, -529137664, 1618345984, 2, 0,
  127024. _vq_quantlist__44c5_s_p7_0,
  127025. NULL,
  127026. &_vq_auxt__44c5_s_p7_0,
  127027. NULL,
  127028. 0
  127029. };
  127030. static long _vq_quantlist__44c5_s_p7_1[] = {
  127031. 5,
  127032. 4,
  127033. 6,
  127034. 3,
  127035. 7,
  127036. 2,
  127037. 8,
  127038. 1,
  127039. 9,
  127040. 0,
  127041. 10,
  127042. };
  127043. static long _vq_lengthlist__44c5_s_p7_1[] = {
  127044. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  127045. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127046. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127047. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127048. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127049. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  127050. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127051. 10,10,10, 8, 8, 8, 8, 8, 8,
  127052. };
  127053. static float _vq_quantthresh__44c5_s_p7_1[] = {
  127054. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127055. 3.5, 4.5,
  127056. };
  127057. static long _vq_quantmap__44c5_s_p7_1[] = {
  127058. 9, 7, 5, 3, 1, 0, 2, 4,
  127059. 6, 8, 10,
  127060. };
  127061. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  127062. _vq_quantthresh__44c5_s_p7_1,
  127063. _vq_quantmap__44c5_s_p7_1,
  127064. 11,
  127065. 11
  127066. };
  127067. static static_codebook _44c5_s_p7_1 = {
  127068. 2, 121,
  127069. _vq_lengthlist__44c5_s_p7_1,
  127070. 1, -531365888, 1611661312, 4, 0,
  127071. _vq_quantlist__44c5_s_p7_1,
  127072. NULL,
  127073. &_vq_auxt__44c5_s_p7_1,
  127074. NULL,
  127075. 0
  127076. };
  127077. static long _vq_quantlist__44c5_s_p8_0[] = {
  127078. 6,
  127079. 5,
  127080. 7,
  127081. 4,
  127082. 8,
  127083. 3,
  127084. 9,
  127085. 2,
  127086. 10,
  127087. 1,
  127088. 11,
  127089. 0,
  127090. 12,
  127091. };
  127092. static long _vq_lengthlist__44c5_s_p8_0[] = {
  127093. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127094. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  127095. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127096. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127097. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  127098. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  127099. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  127100. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  127101. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  127102. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  127103. 0,12,12,12,12,12,12,13,13,
  127104. };
  127105. static float _vq_quantthresh__44c5_s_p8_0[] = {
  127106. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127107. 12.5, 17.5, 22.5, 27.5,
  127108. };
  127109. static long _vq_quantmap__44c5_s_p8_0[] = {
  127110. 11, 9, 7, 5, 3, 1, 0, 2,
  127111. 4, 6, 8, 10, 12,
  127112. };
  127113. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  127114. _vq_quantthresh__44c5_s_p8_0,
  127115. _vq_quantmap__44c5_s_p8_0,
  127116. 13,
  127117. 13
  127118. };
  127119. static static_codebook _44c5_s_p8_0 = {
  127120. 2, 169,
  127121. _vq_lengthlist__44c5_s_p8_0,
  127122. 1, -526516224, 1616117760, 4, 0,
  127123. _vq_quantlist__44c5_s_p8_0,
  127124. NULL,
  127125. &_vq_auxt__44c5_s_p8_0,
  127126. NULL,
  127127. 0
  127128. };
  127129. static long _vq_quantlist__44c5_s_p8_1[] = {
  127130. 2,
  127131. 1,
  127132. 3,
  127133. 0,
  127134. 4,
  127135. };
  127136. static long _vq_lengthlist__44c5_s_p8_1[] = {
  127137. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  127138. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127139. };
  127140. static float _vq_quantthresh__44c5_s_p8_1[] = {
  127141. -1.5, -0.5, 0.5, 1.5,
  127142. };
  127143. static long _vq_quantmap__44c5_s_p8_1[] = {
  127144. 3, 1, 0, 2, 4,
  127145. };
  127146. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  127147. _vq_quantthresh__44c5_s_p8_1,
  127148. _vq_quantmap__44c5_s_p8_1,
  127149. 5,
  127150. 5
  127151. };
  127152. static static_codebook _44c5_s_p8_1 = {
  127153. 2, 25,
  127154. _vq_lengthlist__44c5_s_p8_1,
  127155. 1, -533725184, 1611661312, 3, 0,
  127156. _vq_quantlist__44c5_s_p8_1,
  127157. NULL,
  127158. &_vq_auxt__44c5_s_p8_1,
  127159. NULL,
  127160. 0
  127161. };
  127162. static long _vq_quantlist__44c5_s_p9_0[] = {
  127163. 7,
  127164. 6,
  127165. 8,
  127166. 5,
  127167. 9,
  127168. 4,
  127169. 10,
  127170. 3,
  127171. 11,
  127172. 2,
  127173. 12,
  127174. 1,
  127175. 13,
  127176. 0,
  127177. 14,
  127178. };
  127179. static long _vq_lengthlist__44c5_s_p9_0[] = {
  127180. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  127181. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  127182. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127183. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127184. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127185. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127186. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127187. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127188. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127189. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127190. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127191. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127192. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127193. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  127194. 12,
  127195. };
  127196. static float _vq_quantthresh__44c5_s_p9_0[] = {
  127197. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  127198. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  127199. };
  127200. static long _vq_quantmap__44c5_s_p9_0[] = {
  127201. 13, 11, 9, 7, 5, 3, 1, 0,
  127202. 2, 4, 6, 8, 10, 12, 14,
  127203. };
  127204. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  127205. _vq_quantthresh__44c5_s_p9_0,
  127206. _vq_quantmap__44c5_s_p9_0,
  127207. 15,
  127208. 15
  127209. };
  127210. static static_codebook _44c5_s_p9_0 = {
  127211. 2, 225,
  127212. _vq_lengthlist__44c5_s_p9_0,
  127213. 1, -512522752, 1628852224, 4, 0,
  127214. _vq_quantlist__44c5_s_p9_0,
  127215. NULL,
  127216. &_vq_auxt__44c5_s_p9_0,
  127217. NULL,
  127218. 0
  127219. };
  127220. static long _vq_quantlist__44c5_s_p9_1[] = {
  127221. 8,
  127222. 7,
  127223. 9,
  127224. 6,
  127225. 10,
  127226. 5,
  127227. 11,
  127228. 4,
  127229. 12,
  127230. 3,
  127231. 13,
  127232. 2,
  127233. 14,
  127234. 1,
  127235. 15,
  127236. 0,
  127237. 16,
  127238. };
  127239. static long _vq_lengthlist__44c5_s_p9_1[] = {
  127240. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  127241. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  127242. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  127243. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  127244. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  127245. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  127246. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  127247. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  127248. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  127249. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  127250. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  127251. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  127252. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  127253. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  127254. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  127255. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  127256. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  127257. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  127258. 15,
  127259. };
  127260. static float _vq_quantthresh__44c5_s_p9_1[] = {
  127261. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  127262. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  127263. };
  127264. static long _vq_quantmap__44c5_s_p9_1[] = {
  127265. 15, 13, 11, 9, 7, 5, 3, 1,
  127266. 0, 2, 4, 6, 8, 10, 12, 14,
  127267. 16,
  127268. };
  127269. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  127270. _vq_quantthresh__44c5_s_p9_1,
  127271. _vq_quantmap__44c5_s_p9_1,
  127272. 17,
  127273. 17
  127274. };
  127275. static static_codebook _44c5_s_p9_1 = {
  127276. 2, 289,
  127277. _vq_lengthlist__44c5_s_p9_1,
  127278. 1, -520814592, 1620377600, 5, 0,
  127279. _vq_quantlist__44c5_s_p9_1,
  127280. NULL,
  127281. &_vq_auxt__44c5_s_p9_1,
  127282. NULL,
  127283. 0
  127284. };
  127285. static long _vq_quantlist__44c5_s_p9_2[] = {
  127286. 10,
  127287. 9,
  127288. 11,
  127289. 8,
  127290. 12,
  127291. 7,
  127292. 13,
  127293. 6,
  127294. 14,
  127295. 5,
  127296. 15,
  127297. 4,
  127298. 16,
  127299. 3,
  127300. 17,
  127301. 2,
  127302. 18,
  127303. 1,
  127304. 19,
  127305. 0,
  127306. 20,
  127307. };
  127308. static long _vq_lengthlist__44c5_s_p9_2[] = {
  127309. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  127310. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  127311. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  127312. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  127313. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  127314. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127315. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127316. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  127317. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127318. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127319. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  127320. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  127321. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  127322. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  127323. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  127324. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  127325. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  127326. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127327. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  127328. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  127329. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127330. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127331. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  127332. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127333. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  127334. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127335. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  127336. 10,10,10,10,10,10,10,10,10,
  127337. };
  127338. static float _vq_quantthresh__44c5_s_p9_2[] = {
  127339. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127340. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127341. 6.5, 7.5, 8.5, 9.5,
  127342. };
  127343. static long _vq_quantmap__44c5_s_p9_2[] = {
  127344. 19, 17, 15, 13, 11, 9, 7, 5,
  127345. 3, 1, 0, 2, 4, 6, 8, 10,
  127346. 12, 14, 16, 18, 20,
  127347. };
  127348. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  127349. _vq_quantthresh__44c5_s_p9_2,
  127350. _vq_quantmap__44c5_s_p9_2,
  127351. 21,
  127352. 21
  127353. };
  127354. static static_codebook _44c5_s_p9_2 = {
  127355. 2, 441,
  127356. _vq_lengthlist__44c5_s_p9_2,
  127357. 1, -529268736, 1611661312, 5, 0,
  127358. _vq_quantlist__44c5_s_p9_2,
  127359. NULL,
  127360. &_vq_auxt__44c5_s_p9_2,
  127361. NULL,
  127362. 0
  127363. };
  127364. static long _huff_lengthlist__44c5_s_short[] = {
  127365. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  127366. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  127367. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  127368. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  127369. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  127370. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  127371. 6, 8,11,16,
  127372. };
  127373. static static_codebook _huff_book__44c5_s_short = {
  127374. 2, 100,
  127375. _huff_lengthlist__44c5_s_short,
  127376. 0, 0, 0, 0, 0,
  127377. NULL,
  127378. NULL,
  127379. NULL,
  127380. NULL,
  127381. 0
  127382. };
  127383. static long _huff_lengthlist__44c6_s_long[] = {
  127384. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  127385. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  127386. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  127387. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  127388. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  127389. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  127390. 11,10,10,12,
  127391. };
  127392. static static_codebook _huff_book__44c6_s_long = {
  127393. 2, 100,
  127394. _huff_lengthlist__44c6_s_long,
  127395. 0, 0, 0, 0, 0,
  127396. NULL,
  127397. NULL,
  127398. NULL,
  127399. NULL,
  127400. 0
  127401. };
  127402. static long _vq_quantlist__44c6_s_p1_0[] = {
  127403. 1,
  127404. 0,
  127405. 2,
  127406. };
  127407. static long _vq_lengthlist__44c6_s_p1_0[] = {
  127408. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  127409. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127411. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127412. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  127413. 8,
  127414. };
  127415. static float _vq_quantthresh__44c6_s_p1_0[] = {
  127416. -0.5, 0.5,
  127417. };
  127418. static long _vq_quantmap__44c6_s_p1_0[] = {
  127419. 1, 0, 2,
  127420. };
  127421. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  127422. _vq_quantthresh__44c6_s_p1_0,
  127423. _vq_quantmap__44c6_s_p1_0,
  127424. 3,
  127425. 3
  127426. };
  127427. static static_codebook _44c6_s_p1_0 = {
  127428. 4, 81,
  127429. _vq_lengthlist__44c6_s_p1_0,
  127430. 1, -535822336, 1611661312, 2, 0,
  127431. _vq_quantlist__44c6_s_p1_0,
  127432. NULL,
  127433. &_vq_auxt__44c6_s_p1_0,
  127434. NULL,
  127435. 0
  127436. };
  127437. static long _vq_quantlist__44c6_s_p2_0[] = {
  127438. 2,
  127439. 1,
  127440. 3,
  127441. 0,
  127442. 4,
  127443. };
  127444. static long _vq_lengthlist__44c6_s_p2_0[] = {
  127445. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127446. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127447. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127448. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  127449. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  127450. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  127451. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  127452. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127455. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  127456. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127457. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  127458. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  127459. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  127460. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  127463. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  127464. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  127465. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  127466. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  127467. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  127468. 13,13, 0, 0, 0,13,13, 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. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  127471. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  127472. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127473. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  127474. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  127475. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  127476. 0, 0,13,13, 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, 9,
  127481. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  127482. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  127483. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  127484. 13,
  127485. };
  127486. static float _vq_quantthresh__44c6_s_p2_0[] = {
  127487. -1.5, -0.5, 0.5, 1.5,
  127488. };
  127489. static long _vq_quantmap__44c6_s_p2_0[] = {
  127490. 3, 1, 0, 2, 4,
  127491. };
  127492. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  127493. _vq_quantthresh__44c6_s_p2_0,
  127494. _vq_quantmap__44c6_s_p2_0,
  127495. 5,
  127496. 5
  127497. };
  127498. static static_codebook _44c6_s_p2_0 = {
  127499. 4, 625,
  127500. _vq_lengthlist__44c6_s_p2_0,
  127501. 1, -533725184, 1611661312, 3, 0,
  127502. _vq_quantlist__44c6_s_p2_0,
  127503. NULL,
  127504. &_vq_auxt__44c6_s_p2_0,
  127505. NULL,
  127506. 0
  127507. };
  127508. static long _vq_quantlist__44c6_s_p3_0[] = {
  127509. 4,
  127510. 3,
  127511. 5,
  127512. 2,
  127513. 6,
  127514. 1,
  127515. 7,
  127516. 0,
  127517. 8,
  127518. };
  127519. static long _vq_lengthlist__44c6_s_p3_0[] = {
  127520. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127521. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  127522. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  127523. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0,
  127526. };
  127527. static float _vq_quantthresh__44c6_s_p3_0[] = {
  127528. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127529. };
  127530. static long _vq_quantmap__44c6_s_p3_0[] = {
  127531. 7, 5, 3, 1, 0, 2, 4, 6,
  127532. 8,
  127533. };
  127534. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  127535. _vq_quantthresh__44c6_s_p3_0,
  127536. _vq_quantmap__44c6_s_p3_0,
  127537. 9,
  127538. 9
  127539. };
  127540. static static_codebook _44c6_s_p3_0 = {
  127541. 2, 81,
  127542. _vq_lengthlist__44c6_s_p3_0,
  127543. 1, -531628032, 1611661312, 4, 0,
  127544. _vq_quantlist__44c6_s_p3_0,
  127545. NULL,
  127546. &_vq_auxt__44c6_s_p3_0,
  127547. NULL,
  127548. 0
  127549. };
  127550. static long _vq_quantlist__44c6_s_p4_0[] = {
  127551. 8,
  127552. 7,
  127553. 9,
  127554. 6,
  127555. 10,
  127556. 5,
  127557. 11,
  127558. 4,
  127559. 12,
  127560. 3,
  127561. 13,
  127562. 2,
  127563. 14,
  127564. 1,
  127565. 15,
  127566. 0,
  127567. 16,
  127568. };
  127569. static long _vq_lengthlist__44c6_s_p4_0[] = {
  127570. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  127571. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127572. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  127573. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127574. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127575. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  127576. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  127577. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  127578. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  127579. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0,
  127589. };
  127590. static float _vq_quantthresh__44c6_s_p4_0[] = {
  127591. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127592. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127593. };
  127594. static long _vq_quantmap__44c6_s_p4_0[] = {
  127595. 15, 13, 11, 9, 7, 5, 3, 1,
  127596. 0, 2, 4, 6, 8, 10, 12, 14,
  127597. 16,
  127598. };
  127599. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  127600. _vq_quantthresh__44c6_s_p4_0,
  127601. _vq_quantmap__44c6_s_p4_0,
  127602. 17,
  127603. 17
  127604. };
  127605. static static_codebook _44c6_s_p4_0 = {
  127606. 2, 289,
  127607. _vq_lengthlist__44c6_s_p4_0,
  127608. 1, -529530880, 1611661312, 5, 0,
  127609. _vq_quantlist__44c6_s_p4_0,
  127610. NULL,
  127611. &_vq_auxt__44c6_s_p4_0,
  127612. NULL,
  127613. 0
  127614. };
  127615. static long _vq_quantlist__44c6_s_p5_0[] = {
  127616. 1,
  127617. 0,
  127618. 2,
  127619. };
  127620. static long _vq_lengthlist__44c6_s_p5_0[] = {
  127621. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  127622. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  127623. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  127624. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  127625. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  127626. 12,
  127627. };
  127628. static float _vq_quantthresh__44c6_s_p5_0[] = {
  127629. -5.5, 5.5,
  127630. };
  127631. static long _vq_quantmap__44c6_s_p5_0[] = {
  127632. 1, 0, 2,
  127633. };
  127634. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  127635. _vq_quantthresh__44c6_s_p5_0,
  127636. _vq_quantmap__44c6_s_p5_0,
  127637. 3,
  127638. 3
  127639. };
  127640. static static_codebook _44c6_s_p5_0 = {
  127641. 4, 81,
  127642. _vq_lengthlist__44c6_s_p5_0,
  127643. 1, -529137664, 1618345984, 2, 0,
  127644. _vq_quantlist__44c6_s_p5_0,
  127645. NULL,
  127646. &_vq_auxt__44c6_s_p5_0,
  127647. NULL,
  127648. 0
  127649. };
  127650. static long _vq_quantlist__44c6_s_p5_1[] = {
  127651. 5,
  127652. 4,
  127653. 6,
  127654. 3,
  127655. 7,
  127656. 2,
  127657. 8,
  127658. 1,
  127659. 9,
  127660. 0,
  127661. 10,
  127662. };
  127663. static long _vq_lengthlist__44c6_s_p5_1[] = {
  127664. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  127665. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  127666. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  127667. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  127668. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  127669. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  127670. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  127671. 11,10,10, 7, 7, 8, 8, 8, 8,
  127672. };
  127673. static float _vq_quantthresh__44c6_s_p5_1[] = {
  127674. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127675. 3.5, 4.5,
  127676. };
  127677. static long _vq_quantmap__44c6_s_p5_1[] = {
  127678. 9, 7, 5, 3, 1, 0, 2, 4,
  127679. 6, 8, 10,
  127680. };
  127681. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  127682. _vq_quantthresh__44c6_s_p5_1,
  127683. _vq_quantmap__44c6_s_p5_1,
  127684. 11,
  127685. 11
  127686. };
  127687. static static_codebook _44c6_s_p5_1 = {
  127688. 2, 121,
  127689. _vq_lengthlist__44c6_s_p5_1,
  127690. 1, -531365888, 1611661312, 4, 0,
  127691. _vq_quantlist__44c6_s_p5_1,
  127692. NULL,
  127693. &_vq_auxt__44c6_s_p5_1,
  127694. NULL,
  127695. 0
  127696. };
  127697. static long _vq_quantlist__44c6_s_p6_0[] = {
  127698. 6,
  127699. 5,
  127700. 7,
  127701. 4,
  127702. 8,
  127703. 3,
  127704. 9,
  127705. 2,
  127706. 10,
  127707. 1,
  127708. 11,
  127709. 0,
  127710. 12,
  127711. };
  127712. static long _vq_lengthlist__44c6_s_p6_0[] = {
  127713. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  127714. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  127715. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  127716. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  127717. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  127718. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127724. };
  127725. static float _vq_quantthresh__44c6_s_p6_0[] = {
  127726. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127727. 12.5, 17.5, 22.5, 27.5,
  127728. };
  127729. static long _vq_quantmap__44c6_s_p6_0[] = {
  127730. 11, 9, 7, 5, 3, 1, 0, 2,
  127731. 4, 6, 8, 10, 12,
  127732. };
  127733. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  127734. _vq_quantthresh__44c6_s_p6_0,
  127735. _vq_quantmap__44c6_s_p6_0,
  127736. 13,
  127737. 13
  127738. };
  127739. static static_codebook _44c6_s_p6_0 = {
  127740. 2, 169,
  127741. _vq_lengthlist__44c6_s_p6_0,
  127742. 1, -526516224, 1616117760, 4, 0,
  127743. _vq_quantlist__44c6_s_p6_0,
  127744. NULL,
  127745. &_vq_auxt__44c6_s_p6_0,
  127746. NULL,
  127747. 0
  127748. };
  127749. static long _vq_quantlist__44c6_s_p6_1[] = {
  127750. 2,
  127751. 1,
  127752. 3,
  127753. 0,
  127754. 4,
  127755. };
  127756. static long _vq_lengthlist__44c6_s_p6_1[] = {
  127757. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  127758. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127759. };
  127760. static float _vq_quantthresh__44c6_s_p6_1[] = {
  127761. -1.5, -0.5, 0.5, 1.5,
  127762. };
  127763. static long _vq_quantmap__44c6_s_p6_1[] = {
  127764. 3, 1, 0, 2, 4,
  127765. };
  127766. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  127767. _vq_quantthresh__44c6_s_p6_1,
  127768. _vq_quantmap__44c6_s_p6_1,
  127769. 5,
  127770. 5
  127771. };
  127772. static static_codebook _44c6_s_p6_1 = {
  127773. 2, 25,
  127774. _vq_lengthlist__44c6_s_p6_1,
  127775. 1, -533725184, 1611661312, 3, 0,
  127776. _vq_quantlist__44c6_s_p6_1,
  127777. NULL,
  127778. &_vq_auxt__44c6_s_p6_1,
  127779. NULL,
  127780. 0
  127781. };
  127782. static long _vq_quantlist__44c6_s_p7_0[] = {
  127783. 6,
  127784. 5,
  127785. 7,
  127786. 4,
  127787. 8,
  127788. 3,
  127789. 9,
  127790. 2,
  127791. 10,
  127792. 1,
  127793. 11,
  127794. 0,
  127795. 12,
  127796. };
  127797. static long _vq_lengthlist__44c6_s_p7_0[] = {
  127798. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  127799. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  127800. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  127801. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  127802. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  127803. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  127804. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  127805. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  127806. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  127807. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  127808. 20,13,13,13,13,13,13,14,14,
  127809. };
  127810. static float _vq_quantthresh__44c6_s_p7_0[] = {
  127811. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  127812. 27.5, 38.5, 49.5, 60.5,
  127813. };
  127814. static long _vq_quantmap__44c6_s_p7_0[] = {
  127815. 11, 9, 7, 5, 3, 1, 0, 2,
  127816. 4, 6, 8, 10, 12,
  127817. };
  127818. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  127819. _vq_quantthresh__44c6_s_p7_0,
  127820. _vq_quantmap__44c6_s_p7_0,
  127821. 13,
  127822. 13
  127823. };
  127824. static static_codebook _44c6_s_p7_0 = {
  127825. 2, 169,
  127826. _vq_lengthlist__44c6_s_p7_0,
  127827. 1, -523206656, 1618345984, 4, 0,
  127828. _vq_quantlist__44c6_s_p7_0,
  127829. NULL,
  127830. &_vq_auxt__44c6_s_p7_0,
  127831. NULL,
  127832. 0
  127833. };
  127834. static long _vq_quantlist__44c6_s_p7_1[] = {
  127835. 5,
  127836. 4,
  127837. 6,
  127838. 3,
  127839. 7,
  127840. 2,
  127841. 8,
  127842. 1,
  127843. 9,
  127844. 0,
  127845. 10,
  127846. };
  127847. static long _vq_lengthlist__44c6_s_p7_1[] = {
  127848. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  127849. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  127850. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  127851. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  127852. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  127853. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  127854. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  127855. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  127856. };
  127857. static float _vq_quantthresh__44c6_s_p7_1[] = {
  127858. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127859. 3.5, 4.5,
  127860. };
  127861. static long _vq_quantmap__44c6_s_p7_1[] = {
  127862. 9, 7, 5, 3, 1, 0, 2, 4,
  127863. 6, 8, 10,
  127864. };
  127865. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  127866. _vq_quantthresh__44c6_s_p7_1,
  127867. _vq_quantmap__44c6_s_p7_1,
  127868. 11,
  127869. 11
  127870. };
  127871. static static_codebook _44c6_s_p7_1 = {
  127872. 2, 121,
  127873. _vq_lengthlist__44c6_s_p7_1,
  127874. 1, -531365888, 1611661312, 4, 0,
  127875. _vq_quantlist__44c6_s_p7_1,
  127876. NULL,
  127877. &_vq_auxt__44c6_s_p7_1,
  127878. NULL,
  127879. 0
  127880. };
  127881. static long _vq_quantlist__44c6_s_p8_0[] = {
  127882. 7,
  127883. 6,
  127884. 8,
  127885. 5,
  127886. 9,
  127887. 4,
  127888. 10,
  127889. 3,
  127890. 11,
  127891. 2,
  127892. 12,
  127893. 1,
  127894. 13,
  127895. 0,
  127896. 14,
  127897. };
  127898. static long _vq_lengthlist__44c6_s_p8_0[] = {
  127899. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  127900. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  127901. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  127902. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  127903. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  127904. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  127905. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  127906. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  127907. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  127908. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  127909. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  127910. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  127911. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  127912. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  127913. 14,
  127914. };
  127915. static float _vq_quantthresh__44c6_s_p8_0[] = {
  127916. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127917. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127918. };
  127919. static long _vq_quantmap__44c6_s_p8_0[] = {
  127920. 13, 11, 9, 7, 5, 3, 1, 0,
  127921. 2, 4, 6, 8, 10, 12, 14,
  127922. };
  127923. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  127924. _vq_quantthresh__44c6_s_p8_0,
  127925. _vq_quantmap__44c6_s_p8_0,
  127926. 15,
  127927. 15
  127928. };
  127929. static static_codebook _44c6_s_p8_0 = {
  127930. 2, 225,
  127931. _vq_lengthlist__44c6_s_p8_0,
  127932. 1, -520986624, 1620377600, 4, 0,
  127933. _vq_quantlist__44c6_s_p8_0,
  127934. NULL,
  127935. &_vq_auxt__44c6_s_p8_0,
  127936. NULL,
  127937. 0
  127938. };
  127939. static long _vq_quantlist__44c6_s_p8_1[] = {
  127940. 10,
  127941. 9,
  127942. 11,
  127943. 8,
  127944. 12,
  127945. 7,
  127946. 13,
  127947. 6,
  127948. 14,
  127949. 5,
  127950. 15,
  127951. 4,
  127952. 16,
  127953. 3,
  127954. 17,
  127955. 2,
  127956. 18,
  127957. 1,
  127958. 19,
  127959. 0,
  127960. 20,
  127961. };
  127962. static long _vq_lengthlist__44c6_s_p8_1[] = {
  127963. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  127964. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  127965. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127966. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127967. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127968. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  127969. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  127970. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  127971. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127972. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127973. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  127974. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  127975. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  127976. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  127977. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  127978. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  127979. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  127980. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  127981. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  127982. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  127983. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  127984. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127985. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  127986. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127987. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  127988. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  127989. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  127990. 10,10,10,10,10,10,10,10,10,
  127991. };
  127992. static float _vq_quantthresh__44c6_s_p8_1[] = {
  127993. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127994. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127995. 6.5, 7.5, 8.5, 9.5,
  127996. };
  127997. static long _vq_quantmap__44c6_s_p8_1[] = {
  127998. 19, 17, 15, 13, 11, 9, 7, 5,
  127999. 3, 1, 0, 2, 4, 6, 8, 10,
  128000. 12, 14, 16, 18, 20,
  128001. };
  128002. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  128003. _vq_quantthresh__44c6_s_p8_1,
  128004. _vq_quantmap__44c6_s_p8_1,
  128005. 21,
  128006. 21
  128007. };
  128008. static static_codebook _44c6_s_p8_1 = {
  128009. 2, 441,
  128010. _vq_lengthlist__44c6_s_p8_1,
  128011. 1, -529268736, 1611661312, 5, 0,
  128012. _vq_quantlist__44c6_s_p8_1,
  128013. NULL,
  128014. &_vq_auxt__44c6_s_p8_1,
  128015. NULL,
  128016. 0
  128017. };
  128018. static long _vq_quantlist__44c6_s_p9_0[] = {
  128019. 6,
  128020. 5,
  128021. 7,
  128022. 4,
  128023. 8,
  128024. 3,
  128025. 9,
  128026. 2,
  128027. 10,
  128028. 1,
  128029. 11,
  128030. 0,
  128031. 12,
  128032. };
  128033. static long _vq_lengthlist__44c6_s_p9_0[] = {
  128034. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  128035. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  128036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128037. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  128038. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128039. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128040. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128041. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128042. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128043. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128044. 10,10,10,10,10,10,10,10,10,
  128045. };
  128046. static float _vq_quantthresh__44c6_s_p9_0[] = {
  128047. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  128048. 1592.5, 2229.5, 2866.5, 3503.5,
  128049. };
  128050. static long _vq_quantmap__44c6_s_p9_0[] = {
  128051. 11, 9, 7, 5, 3, 1, 0, 2,
  128052. 4, 6, 8, 10, 12,
  128053. };
  128054. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  128055. _vq_quantthresh__44c6_s_p9_0,
  128056. _vq_quantmap__44c6_s_p9_0,
  128057. 13,
  128058. 13
  128059. };
  128060. static static_codebook _44c6_s_p9_0 = {
  128061. 2, 169,
  128062. _vq_lengthlist__44c6_s_p9_0,
  128063. 1, -511845376, 1630791680, 4, 0,
  128064. _vq_quantlist__44c6_s_p9_0,
  128065. NULL,
  128066. &_vq_auxt__44c6_s_p9_0,
  128067. NULL,
  128068. 0
  128069. };
  128070. static long _vq_quantlist__44c6_s_p9_1[] = {
  128071. 6,
  128072. 5,
  128073. 7,
  128074. 4,
  128075. 8,
  128076. 3,
  128077. 9,
  128078. 2,
  128079. 10,
  128080. 1,
  128081. 11,
  128082. 0,
  128083. 12,
  128084. };
  128085. static long _vq_lengthlist__44c6_s_p9_1[] = {
  128086. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  128087. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  128088. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  128089. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  128090. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  128091. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  128092. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  128093. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  128094. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  128095. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  128096. 15,12,10,11,11,13,11,12,13,
  128097. };
  128098. static float _vq_quantthresh__44c6_s_p9_1[] = {
  128099. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  128100. 122.5, 171.5, 220.5, 269.5,
  128101. };
  128102. static long _vq_quantmap__44c6_s_p9_1[] = {
  128103. 11, 9, 7, 5, 3, 1, 0, 2,
  128104. 4, 6, 8, 10, 12,
  128105. };
  128106. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  128107. _vq_quantthresh__44c6_s_p9_1,
  128108. _vq_quantmap__44c6_s_p9_1,
  128109. 13,
  128110. 13
  128111. };
  128112. static static_codebook _44c6_s_p9_1 = {
  128113. 2, 169,
  128114. _vq_lengthlist__44c6_s_p9_1,
  128115. 1, -518889472, 1622704128, 4, 0,
  128116. _vq_quantlist__44c6_s_p9_1,
  128117. NULL,
  128118. &_vq_auxt__44c6_s_p9_1,
  128119. NULL,
  128120. 0
  128121. };
  128122. static long _vq_quantlist__44c6_s_p9_2[] = {
  128123. 24,
  128124. 23,
  128125. 25,
  128126. 22,
  128127. 26,
  128128. 21,
  128129. 27,
  128130. 20,
  128131. 28,
  128132. 19,
  128133. 29,
  128134. 18,
  128135. 30,
  128136. 17,
  128137. 31,
  128138. 16,
  128139. 32,
  128140. 15,
  128141. 33,
  128142. 14,
  128143. 34,
  128144. 13,
  128145. 35,
  128146. 12,
  128147. 36,
  128148. 11,
  128149. 37,
  128150. 10,
  128151. 38,
  128152. 9,
  128153. 39,
  128154. 8,
  128155. 40,
  128156. 7,
  128157. 41,
  128158. 6,
  128159. 42,
  128160. 5,
  128161. 43,
  128162. 4,
  128163. 44,
  128164. 3,
  128165. 45,
  128166. 2,
  128167. 46,
  128168. 1,
  128169. 47,
  128170. 0,
  128171. 48,
  128172. };
  128173. static long _vq_lengthlist__44c6_s_p9_2[] = {
  128174. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128175. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128176. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128177. 7,
  128178. };
  128179. static float _vq_quantthresh__44c6_s_p9_2[] = {
  128180. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128181. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128182. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128183. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128184. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128185. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128186. };
  128187. static long _vq_quantmap__44c6_s_p9_2[] = {
  128188. 47, 45, 43, 41, 39, 37, 35, 33,
  128189. 31, 29, 27, 25, 23, 21, 19, 17,
  128190. 15, 13, 11, 9, 7, 5, 3, 1,
  128191. 0, 2, 4, 6, 8, 10, 12, 14,
  128192. 16, 18, 20, 22, 24, 26, 28, 30,
  128193. 32, 34, 36, 38, 40, 42, 44, 46,
  128194. 48,
  128195. };
  128196. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  128197. _vq_quantthresh__44c6_s_p9_2,
  128198. _vq_quantmap__44c6_s_p9_2,
  128199. 49,
  128200. 49
  128201. };
  128202. static static_codebook _44c6_s_p9_2 = {
  128203. 1, 49,
  128204. _vq_lengthlist__44c6_s_p9_2,
  128205. 1, -526909440, 1611661312, 6, 0,
  128206. _vq_quantlist__44c6_s_p9_2,
  128207. NULL,
  128208. &_vq_auxt__44c6_s_p9_2,
  128209. NULL,
  128210. 0
  128211. };
  128212. static long _huff_lengthlist__44c6_s_short[] = {
  128213. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  128214. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  128215. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  128216. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  128217. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  128218. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  128219. 9,10,17,18,
  128220. };
  128221. static static_codebook _huff_book__44c6_s_short = {
  128222. 2, 100,
  128223. _huff_lengthlist__44c6_s_short,
  128224. 0, 0, 0, 0, 0,
  128225. NULL,
  128226. NULL,
  128227. NULL,
  128228. NULL,
  128229. 0
  128230. };
  128231. static long _huff_lengthlist__44c7_s_long[] = {
  128232. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  128233. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  128234. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  128235. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  128236. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  128237. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  128238. 11,10,10,12,
  128239. };
  128240. static static_codebook _huff_book__44c7_s_long = {
  128241. 2, 100,
  128242. _huff_lengthlist__44c7_s_long,
  128243. 0, 0, 0, 0, 0,
  128244. NULL,
  128245. NULL,
  128246. NULL,
  128247. NULL,
  128248. 0
  128249. };
  128250. static long _vq_quantlist__44c7_s_p1_0[] = {
  128251. 1,
  128252. 0,
  128253. 2,
  128254. };
  128255. static long _vq_lengthlist__44c7_s_p1_0[] = {
  128256. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128257. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128259. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128260. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128261. 8,
  128262. };
  128263. static float _vq_quantthresh__44c7_s_p1_0[] = {
  128264. -0.5, 0.5,
  128265. };
  128266. static long _vq_quantmap__44c7_s_p1_0[] = {
  128267. 1, 0, 2,
  128268. };
  128269. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  128270. _vq_quantthresh__44c7_s_p1_0,
  128271. _vq_quantmap__44c7_s_p1_0,
  128272. 3,
  128273. 3
  128274. };
  128275. static static_codebook _44c7_s_p1_0 = {
  128276. 4, 81,
  128277. _vq_lengthlist__44c7_s_p1_0,
  128278. 1, -535822336, 1611661312, 2, 0,
  128279. _vq_quantlist__44c7_s_p1_0,
  128280. NULL,
  128281. &_vq_auxt__44c7_s_p1_0,
  128282. NULL,
  128283. 0
  128284. };
  128285. static long _vq_quantlist__44c7_s_p2_0[] = {
  128286. 2,
  128287. 1,
  128288. 3,
  128289. 0,
  128290. 4,
  128291. };
  128292. static long _vq_lengthlist__44c7_s_p2_0[] = {
  128293. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128294. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128295. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128296. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128297. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128298. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128299. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  128300. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128303. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128304. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128305. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128306. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128307. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  128308. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128311. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  128312. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  128313. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  128314. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  128315. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128316. 13,13, 0, 0, 0,12,13, 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. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128319. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128320. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128321. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  128322. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128323. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  128324. 0, 0,13,13, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128329. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  128330. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  128331. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128332. 13,
  128333. };
  128334. static float _vq_quantthresh__44c7_s_p2_0[] = {
  128335. -1.5, -0.5, 0.5, 1.5,
  128336. };
  128337. static long _vq_quantmap__44c7_s_p2_0[] = {
  128338. 3, 1, 0, 2, 4,
  128339. };
  128340. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  128341. _vq_quantthresh__44c7_s_p2_0,
  128342. _vq_quantmap__44c7_s_p2_0,
  128343. 5,
  128344. 5
  128345. };
  128346. static static_codebook _44c7_s_p2_0 = {
  128347. 4, 625,
  128348. _vq_lengthlist__44c7_s_p2_0,
  128349. 1, -533725184, 1611661312, 3, 0,
  128350. _vq_quantlist__44c7_s_p2_0,
  128351. NULL,
  128352. &_vq_auxt__44c7_s_p2_0,
  128353. NULL,
  128354. 0
  128355. };
  128356. static long _vq_quantlist__44c7_s_p3_0[] = {
  128357. 4,
  128358. 3,
  128359. 5,
  128360. 2,
  128361. 6,
  128362. 1,
  128363. 7,
  128364. 0,
  128365. 8,
  128366. };
  128367. static long _vq_lengthlist__44c7_s_p3_0[] = {
  128368. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128369. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  128370. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  128371. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0,
  128374. };
  128375. static float _vq_quantthresh__44c7_s_p3_0[] = {
  128376. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128377. };
  128378. static long _vq_quantmap__44c7_s_p3_0[] = {
  128379. 7, 5, 3, 1, 0, 2, 4, 6,
  128380. 8,
  128381. };
  128382. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  128383. _vq_quantthresh__44c7_s_p3_0,
  128384. _vq_quantmap__44c7_s_p3_0,
  128385. 9,
  128386. 9
  128387. };
  128388. static static_codebook _44c7_s_p3_0 = {
  128389. 2, 81,
  128390. _vq_lengthlist__44c7_s_p3_0,
  128391. 1, -531628032, 1611661312, 4, 0,
  128392. _vq_quantlist__44c7_s_p3_0,
  128393. NULL,
  128394. &_vq_auxt__44c7_s_p3_0,
  128395. NULL,
  128396. 0
  128397. };
  128398. static long _vq_quantlist__44c7_s_p4_0[] = {
  128399. 8,
  128400. 7,
  128401. 9,
  128402. 6,
  128403. 10,
  128404. 5,
  128405. 11,
  128406. 4,
  128407. 12,
  128408. 3,
  128409. 13,
  128410. 2,
  128411. 14,
  128412. 1,
  128413. 15,
  128414. 0,
  128415. 16,
  128416. };
  128417. static long _vq_lengthlist__44c7_s_p4_0[] = {
  128418. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128419. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  128420. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128421. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  128422. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  128423. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  128424. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  128425. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128426. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128427. 9,10,10,11,11,12,12,13,13, 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,
  128437. };
  128438. static float _vq_quantthresh__44c7_s_p4_0[] = {
  128439. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128440. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128441. };
  128442. static long _vq_quantmap__44c7_s_p4_0[] = {
  128443. 15, 13, 11, 9, 7, 5, 3, 1,
  128444. 0, 2, 4, 6, 8, 10, 12, 14,
  128445. 16,
  128446. };
  128447. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  128448. _vq_quantthresh__44c7_s_p4_0,
  128449. _vq_quantmap__44c7_s_p4_0,
  128450. 17,
  128451. 17
  128452. };
  128453. static static_codebook _44c7_s_p4_0 = {
  128454. 2, 289,
  128455. _vq_lengthlist__44c7_s_p4_0,
  128456. 1, -529530880, 1611661312, 5, 0,
  128457. _vq_quantlist__44c7_s_p4_0,
  128458. NULL,
  128459. &_vq_auxt__44c7_s_p4_0,
  128460. NULL,
  128461. 0
  128462. };
  128463. static long _vq_quantlist__44c7_s_p5_0[] = {
  128464. 1,
  128465. 0,
  128466. 2,
  128467. };
  128468. static long _vq_lengthlist__44c7_s_p5_0[] = {
  128469. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  128470. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  128471. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  128472. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  128473. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  128474. 12,
  128475. };
  128476. static float _vq_quantthresh__44c7_s_p5_0[] = {
  128477. -5.5, 5.5,
  128478. };
  128479. static long _vq_quantmap__44c7_s_p5_0[] = {
  128480. 1, 0, 2,
  128481. };
  128482. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  128483. _vq_quantthresh__44c7_s_p5_0,
  128484. _vq_quantmap__44c7_s_p5_0,
  128485. 3,
  128486. 3
  128487. };
  128488. static static_codebook _44c7_s_p5_0 = {
  128489. 4, 81,
  128490. _vq_lengthlist__44c7_s_p5_0,
  128491. 1, -529137664, 1618345984, 2, 0,
  128492. _vq_quantlist__44c7_s_p5_0,
  128493. NULL,
  128494. &_vq_auxt__44c7_s_p5_0,
  128495. NULL,
  128496. 0
  128497. };
  128498. static long _vq_quantlist__44c7_s_p5_1[] = {
  128499. 5,
  128500. 4,
  128501. 6,
  128502. 3,
  128503. 7,
  128504. 2,
  128505. 8,
  128506. 1,
  128507. 9,
  128508. 0,
  128509. 10,
  128510. };
  128511. static long _vq_lengthlist__44c7_s_p5_1[] = {
  128512. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  128513. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  128514. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  128515. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  128516. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  128517. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  128518. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  128519. 11,11,11, 7, 7, 8, 8, 8, 8,
  128520. };
  128521. static float _vq_quantthresh__44c7_s_p5_1[] = {
  128522. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128523. 3.5, 4.5,
  128524. };
  128525. static long _vq_quantmap__44c7_s_p5_1[] = {
  128526. 9, 7, 5, 3, 1, 0, 2, 4,
  128527. 6, 8, 10,
  128528. };
  128529. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  128530. _vq_quantthresh__44c7_s_p5_1,
  128531. _vq_quantmap__44c7_s_p5_1,
  128532. 11,
  128533. 11
  128534. };
  128535. static static_codebook _44c7_s_p5_1 = {
  128536. 2, 121,
  128537. _vq_lengthlist__44c7_s_p5_1,
  128538. 1, -531365888, 1611661312, 4, 0,
  128539. _vq_quantlist__44c7_s_p5_1,
  128540. NULL,
  128541. &_vq_auxt__44c7_s_p5_1,
  128542. NULL,
  128543. 0
  128544. };
  128545. static long _vq_quantlist__44c7_s_p6_0[] = {
  128546. 6,
  128547. 5,
  128548. 7,
  128549. 4,
  128550. 8,
  128551. 3,
  128552. 9,
  128553. 2,
  128554. 10,
  128555. 1,
  128556. 11,
  128557. 0,
  128558. 12,
  128559. };
  128560. static long _vq_lengthlist__44c7_s_p6_0[] = {
  128561. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  128562. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  128563. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  128564. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  128565. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  128566. 12, 9, 9,10,10,11,11,11,11,12,12, 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,
  128572. };
  128573. static float _vq_quantthresh__44c7_s_p6_0[] = {
  128574. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128575. 12.5, 17.5, 22.5, 27.5,
  128576. };
  128577. static long _vq_quantmap__44c7_s_p6_0[] = {
  128578. 11, 9, 7, 5, 3, 1, 0, 2,
  128579. 4, 6, 8, 10, 12,
  128580. };
  128581. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  128582. _vq_quantthresh__44c7_s_p6_0,
  128583. _vq_quantmap__44c7_s_p6_0,
  128584. 13,
  128585. 13
  128586. };
  128587. static static_codebook _44c7_s_p6_0 = {
  128588. 2, 169,
  128589. _vq_lengthlist__44c7_s_p6_0,
  128590. 1, -526516224, 1616117760, 4, 0,
  128591. _vq_quantlist__44c7_s_p6_0,
  128592. NULL,
  128593. &_vq_auxt__44c7_s_p6_0,
  128594. NULL,
  128595. 0
  128596. };
  128597. static long _vq_quantlist__44c7_s_p6_1[] = {
  128598. 2,
  128599. 1,
  128600. 3,
  128601. 0,
  128602. 4,
  128603. };
  128604. static long _vq_lengthlist__44c7_s_p6_1[] = {
  128605. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128606. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128607. };
  128608. static float _vq_quantthresh__44c7_s_p6_1[] = {
  128609. -1.5, -0.5, 0.5, 1.5,
  128610. };
  128611. static long _vq_quantmap__44c7_s_p6_1[] = {
  128612. 3, 1, 0, 2, 4,
  128613. };
  128614. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  128615. _vq_quantthresh__44c7_s_p6_1,
  128616. _vq_quantmap__44c7_s_p6_1,
  128617. 5,
  128618. 5
  128619. };
  128620. static static_codebook _44c7_s_p6_1 = {
  128621. 2, 25,
  128622. _vq_lengthlist__44c7_s_p6_1,
  128623. 1, -533725184, 1611661312, 3, 0,
  128624. _vq_quantlist__44c7_s_p6_1,
  128625. NULL,
  128626. &_vq_auxt__44c7_s_p6_1,
  128627. NULL,
  128628. 0
  128629. };
  128630. static long _vq_quantlist__44c7_s_p7_0[] = {
  128631. 6,
  128632. 5,
  128633. 7,
  128634. 4,
  128635. 8,
  128636. 3,
  128637. 9,
  128638. 2,
  128639. 10,
  128640. 1,
  128641. 11,
  128642. 0,
  128643. 12,
  128644. };
  128645. static long _vq_lengthlist__44c7_s_p7_0[] = {
  128646. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  128647. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  128648. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  128649. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  128650. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  128651. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  128652. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  128653. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  128654. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  128655. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  128656. 19,13,13,13,13,14,14,15,15,
  128657. };
  128658. static float _vq_quantthresh__44c7_s_p7_0[] = {
  128659. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128660. 27.5, 38.5, 49.5, 60.5,
  128661. };
  128662. static long _vq_quantmap__44c7_s_p7_0[] = {
  128663. 11, 9, 7, 5, 3, 1, 0, 2,
  128664. 4, 6, 8, 10, 12,
  128665. };
  128666. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  128667. _vq_quantthresh__44c7_s_p7_0,
  128668. _vq_quantmap__44c7_s_p7_0,
  128669. 13,
  128670. 13
  128671. };
  128672. static static_codebook _44c7_s_p7_0 = {
  128673. 2, 169,
  128674. _vq_lengthlist__44c7_s_p7_0,
  128675. 1, -523206656, 1618345984, 4, 0,
  128676. _vq_quantlist__44c7_s_p7_0,
  128677. NULL,
  128678. &_vq_auxt__44c7_s_p7_0,
  128679. NULL,
  128680. 0
  128681. };
  128682. static long _vq_quantlist__44c7_s_p7_1[] = {
  128683. 5,
  128684. 4,
  128685. 6,
  128686. 3,
  128687. 7,
  128688. 2,
  128689. 8,
  128690. 1,
  128691. 9,
  128692. 0,
  128693. 10,
  128694. };
  128695. static long _vq_lengthlist__44c7_s_p7_1[] = {
  128696. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  128697. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  128698. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  128699. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128700. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  128701. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  128702. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  128703. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128704. };
  128705. static float _vq_quantthresh__44c7_s_p7_1[] = {
  128706. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128707. 3.5, 4.5,
  128708. };
  128709. static long _vq_quantmap__44c7_s_p7_1[] = {
  128710. 9, 7, 5, 3, 1, 0, 2, 4,
  128711. 6, 8, 10,
  128712. };
  128713. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  128714. _vq_quantthresh__44c7_s_p7_1,
  128715. _vq_quantmap__44c7_s_p7_1,
  128716. 11,
  128717. 11
  128718. };
  128719. static static_codebook _44c7_s_p7_1 = {
  128720. 2, 121,
  128721. _vq_lengthlist__44c7_s_p7_1,
  128722. 1, -531365888, 1611661312, 4, 0,
  128723. _vq_quantlist__44c7_s_p7_1,
  128724. NULL,
  128725. &_vq_auxt__44c7_s_p7_1,
  128726. NULL,
  128727. 0
  128728. };
  128729. static long _vq_quantlist__44c7_s_p8_0[] = {
  128730. 7,
  128731. 6,
  128732. 8,
  128733. 5,
  128734. 9,
  128735. 4,
  128736. 10,
  128737. 3,
  128738. 11,
  128739. 2,
  128740. 12,
  128741. 1,
  128742. 13,
  128743. 0,
  128744. 14,
  128745. };
  128746. static long _vq_lengthlist__44c7_s_p8_0[] = {
  128747. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  128748. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  128749. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  128750. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  128751. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  128752. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  128753. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  128754. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  128755. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  128756. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  128757. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  128758. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  128759. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  128760. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  128761. 14,
  128762. };
  128763. static float _vq_quantthresh__44c7_s_p8_0[] = {
  128764. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128765. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128766. };
  128767. static long _vq_quantmap__44c7_s_p8_0[] = {
  128768. 13, 11, 9, 7, 5, 3, 1, 0,
  128769. 2, 4, 6, 8, 10, 12, 14,
  128770. };
  128771. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  128772. _vq_quantthresh__44c7_s_p8_0,
  128773. _vq_quantmap__44c7_s_p8_0,
  128774. 15,
  128775. 15
  128776. };
  128777. static static_codebook _44c7_s_p8_0 = {
  128778. 2, 225,
  128779. _vq_lengthlist__44c7_s_p8_0,
  128780. 1, -520986624, 1620377600, 4, 0,
  128781. _vq_quantlist__44c7_s_p8_0,
  128782. NULL,
  128783. &_vq_auxt__44c7_s_p8_0,
  128784. NULL,
  128785. 0
  128786. };
  128787. static long _vq_quantlist__44c7_s_p8_1[] = {
  128788. 10,
  128789. 9,
  128790. 11,
  128791. 8,
  128792. 12,
  128793. 7,
  128794. 13,
  128795. 6,
  128796. 14,
  128797. 5,
  128798. 15,
  128799. 4,
  128800. 16,
  128801. 3,
  128802. 17,
  128803. 2,
  128804. 18,
  128805. 1,
  128806. 19,
  128807. 0,
  128808. 20,
  128809. };
  128810. static long _vq_lengthlist__44c7_s_p8_1[] = {
  128811. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  128812. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128813. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128814. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128815. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128816. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  128817. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  128818. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  128819. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128820. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128821. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  128822. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  128823. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  128824. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  128825. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  128826. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  128827. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  128828. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  128829. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  128830. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  128831. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  128832. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  128833. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  128834. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  128835. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  128836. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  128837. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  128838. 10,10,10,10,10,10,10,10,10,
  128839. };
  128840. static float _vq_quantthresh__44c7_s_p8_1[] = {
  128841. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128842. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128843. 6.5, 7.5, 8.5, 9.5,
  128844. };
  128845. static long _vq_quantmap__44c7_s_p8_1[] = {
  128846. 19, 17, 15, 13, 11, 9, 7, 5,
  128847. 3, 1, 0, 2, 4, 6, 8, 10,
  128848. 12, 14, 16, 18, 20,
  128849. };
  128850. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  128851. _vq_quantthresh__44c7_s_p8_1,
  128852. _vq_quantmap__44c7_s_p8_1,
  128853. 21,
  128854. 21
  128855. };
  128856. static static_codebook _44c7_s_p8_1 = {
  128857. 2, 441,
  128858. _vq_lengthlist__44c7_s_p8_1,
  128859. 1, -529268736, 1611661312, 5, 0,
  128860. _vq_quantlist__44c7_s_p8_1,
  128861. NULL,
  128862. &_vq_auxt__44c7_s_p8_1,
  128863. NULL,
  128864. 0
  128865. };
  128866. static long _vq_quantlist__44c7_s_p9_0[] = {
  128867. 6,
  128868. 5,
  128869. 7,
  128870. 4,
  128871. 8,
  128872. 3,
  128873. 9,
  128874. 2,
  128875. 10,
  128876. 1,
  128877. 11,
  128878. 0,
  128879. 12,
  128880. };
  128881. static long _vq_lengthlist__44c7_s_p9_0[] = {
  128882. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  128883. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  128884. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128890. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128892. 11,11,11,11,11,11,11,11,11,
  128893. };
  128894. static float _vq_quantthresh__44c7_s_p9_0[] = {
  128895. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  128896. 1592.5, 2229.5, 2866.5, 3503.5,
  128897. };
  128898. static long _vq_quantmap__44c7_s_p9_0[] = {
  128899. 11, 9, 7, 5, 3, 1, 0, 2,
  128900. 4, 6, 8, 10, 12,
  128901. };
  128902. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  128903. _vq_quantthresh__44c7_s_p9_0,
  128904. _vq_quantmap__44c7_s_p9_0,
  128905. 13,
  128906. 13
  128907. };
  128908. static static_codebook _44c7_s_p9_0 = {
  128909. 2, 169,
  128910. _vq_lengthlist__44c7_s_p9_0,
  128911. 1, -511845376, 1630791680, 4, 0,
  128912. _vq_quantlist__44c7_s_p9_0,
  128913. NULL,
  128914. &_vq_auxt__44c7_s_p9_0,
  128915. NULL,
  128916. 0
  128917. };
  128918. static long _vq_quantlist__44c7_s_p9_1[] = {
  128919. 6,
  128920. 5,
  128921. 7,
  128922. 4,
  128923. 8,
  128924. 3,
  128925. 9,
  128926. 2,
  128927. 10,
  128928. 1,
  128929. 11,
  128930. 0,
  128931. 12,
  128932. };
  128933. static long _vq_lengthlist__44c7_s_p9_1[] = {
  128934. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  128935. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  128936. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  128937. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  128938. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  128939. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  128940. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  128941. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  128942. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  128943. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  128944. 15,11,11,10,10,12,12,12,12,
  128945. };
  128946. static float _vq_quantthresh__44c7_s_p9_1[] = {
  128947. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  128948. 122.5, 171.5, 220.5, 269.5,
  128949. };
  128950. static long _vq_quantmap__44c7_s_p9_1[] = {
  128951. 11, 9, 7, 5, 3, 1, 0, 2,
  128952. 4, 6, 8, 10, 12,
  128953. };
  128954. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  128955. _vq_quantthresh__44c7_s_p9_1,
  128956. _vq_quantmap__44c7_s_p9_1,
  128957. 13,
  128958. 13
  128959. };
  128960. static static_codebook _44c7_s_p9_1 = {
  128961. 2, 169,
  128962. _vq_lengthlist__44c7_s_p9_1,
  128963. 1, -518889472, 1622704128, 4, 0,
  128964. _vq_quantlist__44c7_s_p9_1,
  128965. NULL,
  128966. &_vq_auxt__44c7_s_p9_1,
  128967. NULL,
  128968. 0
  128969. };
  128970. static long _vq_quantlist__44c7_s_p9_2[] = {
  128971. 24,
  128972. 23,
  128973. 25,
  128974. 22,
  128975. 26,
  128976. 21,
  128977. 27,
  128978. 20,
  128979. 28,
  128980. 19,
  128981. 29,
  128982. 18,
  128983. 30,
  128984. 17,
  128985. 31,
  128986. 16,
  128987. 32,
  128988. 15,
  128989. 33,
  128990. 14,
  128991. 34,
  128992. 13,
  128993. 35,
  128994. 12,
  128995. 36,
  128996. 11,
  128997. 37,
  128998. 10,
  128999. 38,
  129000. 9,
  129001. 39,
  129002. 8,
  129003. 40,
  129004. 7,
  129005. 41,
  129006. 6,
  129007. 42,
  129008. 5,
  129009. 43,
  129010. 4,
  129011. 44,
  129012. 3,
  129013. 45,
  129014. 2,
  129015. 46,
  129016. 1,
  129017. 47,
  129018. 0,
  129019. 48,
  129020. };
  129021. static long _vq_lengthlist__44c7_s_p9_2[] = {
  129022. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  129023. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129024. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129025. 7,
  129026. };
  129027. static float _vq_quantthresh__44c7_s_p9_2[] = {
  129028. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129029. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129030. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129031. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129032. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129033. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129034. };
  129035. static long _vq_quantmap__44c7_s_p9_2[] = {
  129036. 47, 45, 43, 41, 39, 37, 35, 33,
  129037. 31, 29, 27, 25, 23, 21, 19, 17,
  129038. 15, 13, 11, 9, 7, 5, 3, 1,
  129039. 0, 2, 4, 6, 8, 10, 12, 14,
  129040. 16, 18, 20, 22, 24, 26, 28, 30,
  129041. 32, 34, 36, 38, 40, 42, 44, 46,
  129042. 48,
  129043. };
  129044. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  129045. _vq_quantthresh__44c7_s_p9_2,
  129046. _vq_quantmap__44c7_s_p9_2,
  129047. 49,
  129048. 49
  129049. };
  129050. static static_codebook _44c7_s_p9_2 = {
  129051. 1, 49,
  129052. _vq_lengthlist__44c7_s_p9_2,
  129053. 1, -526909440, 1611661312, 6, 0,
  129054. _vq_quantlist__44c7_s_p9_2,
  129055. NULL,
  129056. &_vq_auxt__44c7_s_p9_2,
  129057. NULL,
  129058. 0
  129059. };
  129060. static long _huff_lengthlist__44c7_s_short[] = {
  129061. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  129062. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  129063. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  129064. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  129065. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  129066. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  129067. 10, 9,11,14,
  129068. };
  129069. static static_codebook _huff_book__44c7_s_short = {
  129070. 2, 100,
  129071. _huff_lengthlist__44c7_s_short,
  129072. 0, 0, 0, 0, 0,
  129073. NULL,
  129074. NULL,
  129075. NULL,
  129076. NULL,
  129077. 0
  129078. };
  129079. static long _huff_lengthlist__44c8_s_long[] = {
  129080. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  129081. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  129082. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  129083. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  129084. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  129085. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  129086. 11, 9, 9,10,
  129087. };
  129088. static static_codebook _huff_book__44c8_s_long = {
  129089. 2, 100,
  129090. _huff_lengthlist__44c8_s_long,
  129091. 0, 0, 0, 0, 0,
  129092. NULL,
  129093. NULL,
  129094. NULL,
  129095. NULL,
  129096. 0
  129097. };
  129098. static long _vq_quantlist__44c8_s_p1_0[] = {
  129099. 1,
  129100. 0,
  129101. 2,
  129102. };
  129103. static long _vq_lengthlist__44c8_s_p1_0[] = {
  129104. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  129105. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129107. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129108. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  129109. 8,
  129110. };
  129111. static float _vq_quantthresh__44c8_s_p1_0[] = {
  129112. -0.5, 0.5,
  129113. };
  129114. static long _vq_quantmap__44c8_s_p1_0[] = {
  129115. 1, 0, 2,
  129116. };
  129117. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  129118. _vq_quantthresh__44c8_s_p1_0,
  129119. _vq_quantmap__44c8_s_p1_0,
  129120. 3,
  129121. 3
  129122. };
  129123. static static_codebook _44c8_s_p1_0 = {
  129124. 4, 81,
  129125. _vq_lengthlist__44c8_s_p1_0,
  129126. 1, -535822336, 1611661312, 2, 0,
  129127. _vq_quantlist__44c8_s_p1_0,
  129128. NULL,
  129129. &_vq_auxt__44c8_s_p1_0,
  129130. NULL,
  129131. 0
  129132. };
  129133. static long _vq_quantlist__44c8_s_p2_0[] = {
  129134. 2,
  129135. 1,
  129136. 3,
  129137. 0,
  129138. 4,
  129139. };
  129140. static long _vq_lengthlist__44c8_s_p2_0[] = {
  129141. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129142. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129143. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129144. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  129145. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  129146. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  129147. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  129148. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129151. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  129152. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129153. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  129154. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  129155. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  129156. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  129159. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  129160. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  129161. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  129162. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  129163. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  129164. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  129167. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  129168. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129169. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  129170. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  129171. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  129172. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129177. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  129178. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129179. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  129180. 13,
  129181. };
  129182. static float _vq_quantthresh__44c8_s_p2_0[] = {
  129183. -1.5, -0.5, 0.5, 1.5,
  129184. };
  129185. static long _vq_quantmap__44c8_s_p2_0[] = {
  129186. 3, 1, 0, 2, 4,
  129187. };
  129188. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  129189. _vq_quantthresh__44c8_s_p2_0,
  129190. _vq_quantmap__44c8_s_p2_0,
  129191. 5,
  129192. 5
  129193. };
  129194. static static_codebook _44c8_s_p2_0 = {
  129195. 4, 625,
  129196. _vq_lengthlist__44c8_s_p2_0,
  129197. 1, -533725184, 1611661312, 3, 0,
  129198. _vq_quantlist__44c8_s_p2_0,
  129199. NULL,
  129200. &_vq_auxt__44c8_s_p2_0,
  129201. NULL,
  129202. 0
  129203. };
  129204. static long _vq_quantlist__44c8_s_p3_0[] = {
  129205. 4,
  129206. 3,
  129207. 5,
  129208. 2,
  129209. 6,
  129210. 1,
  129211. 7,
  129212. 0,
  129213. 8,
  129214. };
  129215. static long _vq_lengthlist__44c8_s_p3_0[] = {
  129216. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129217. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129218. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129219. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0,
  129222. };
  129223. static float _vq_quantthresh__44c8_s_p3_0[] = {
  129224. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129225. };
  129226. static long _vq_quantmap__44c8_s_p3_0[] = {
  129227. 7, 5, 3, 1, 0, 2, 4, 6,
  129228. 8,
  129229. };
  129230. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  129231. _vq_quantthresh__44c8_s_p3_0,
  129232. _vq_quantmap__44c8_s_p3_0,
  129233. 9,
  129234. 9
  129235. };
  129236. static static_codebook _44c8_s_p3_0 = {
  129237. 2, 81,
  129238. _vq_lengthlist__44c8_s_p3_0,
  129239. 1, -531628032, 1611661312, 4, 0,
  129240. _vq_quantlist__44c8_s_p3_0,
  129241. NULL,
  129242. &_vq_auxt__44c8_s_p3_0,
  129243. NULL,
  129244. 0
  129245. };
  129246. static long _vq_quantlist__44c8_s_p4_0[] = {
  129247. 8,
  129248. 7,
  129249. 9,
  129250. 6,
  129251. 10,
  129252. 5,
  129253. 11,
  129254. 4,
  129255. 12,
  129256. 3,
  129257. 13,
  129258. 2,
  129259. 14,
  129260. 1,
  129261. 15,
  129262. 0,
  129263. 16,
  129264. };
  129265. static long _vq_lengthlist__44c8_s_p4_0[] = {
  129266. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129267. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  129268. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129269. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  129270. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  129271. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129272. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129273. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129274. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129275. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0,
  129285. };
  129286. static float _vq_quantthresh__44c8_s_p4_0[] = {
  129287. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129288. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129289. };
  129290. static long _vq_quantmap__44c8_s_p4_0[] = {
  129291. 15, 13, 11, 9, 7, 5, 3, 1,
  129292. 0, 2, 4, 6, 8, 10, 12, 14,
  129293. 16,
  129294. };
  129295. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  129296. _vq_quantthresh__44c8_s_p4_0,
  129297. _vq_quantmap__44c8_s_p4_0,
  129298. 17,
  129299. 17
  129300. };
  129301. static static_codebook _44c8_s_p4_0 = {
  129302. 2, 289,
  129303. _vq_lengthlist__44c8_s_p4_0,
  129304. 1, -529530880, 1611661312, 5, 0,
  129305. _vq_quantlist__44c8_s_p4_0,
  129306. NULL,
  129307. &_vq_auxt__44c8_s_p4_0,
  129308. NULL,
  129309. 0
  129310. };
  129311. static long _vq_quantlist__44c8_s_p5_0[] = {
  129312. 1,
  129313. 0,
  129314. 2,
  129315. };
  129316. static long _vq_lengthlist__44c8_s_p5_0[] = {
  129317. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  129318. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129319. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129320. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  129321. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  129322. 12,
  129323. };
  129324. static float _vq_quantthresh__44c8_s_p5_0[] = {
  129325. -5.5, 5.5,
  129326. };
  129327. static long _vq_quantmap__44c8_s_p5_0[] = {
  129328. 1, 0, 2,
  129329. };
  129330. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  129331. _vq_quantthresh__44c8_s_p5_0,
  129332. _vq_quantmap__44c8_s_p5_0,
  129333. 3,
  129334. 3
  129335. };
  129336. static static_codebook _44c8_s_p5_0 = {
  129337. 4, 81,
  129338. _vq_lengthlist__44c8_s_p5_0,
  129339. 1, -529137664, 1618345984, 2, 0,
  129340. _vq_quantlist__44c8_s_p5_0,
  129341. NULL,
  129342. &_vq_auxt__44c8_s_p5_0,
  129343. NULL,
  129344. 0
  129345. };
  129346. static long _vq_quantlist__44c8_s_p5_1[] = {
  129347. 5,
  129348. 4,
  129349. 6,
  129350. 3,
  129351. 7,
  129352. 2,
  129353. 8,
  129354. 1,
  129355. 9,
  129356. 0,
  129357. 10,
  129358. };
  129359. static long _vq_lengthlist__44c8_s_p5_1[] = {
  129360. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  129361. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129362. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  129363. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  129364. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  129365. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  129366. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  129367. 11,11,11, 7, 7, 7, 7, 8, 8,
  129368. };
  129369. static float _vq_quantthresh__44c8_s_p5_1[] = {
  129370. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129371. 3.5, 4.5,
  129372. };
  129373. static long _vq_quantmap__44c8_s_p5_1[] = {
  129374. 9, 7, 5, 3, 1, 0, 2, 4,
  129375. 6, 8, 10,
  129376. };
  129377. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  129378. _vq_quantthresh__44c8_s_p5_1,
  129379. _vq_quantmap__44c8_s_p5_1,
  129380. 11,
  129381. 11
  129382. };
  129383. static static_codebook _44c8_s_p5_1 = {
  129384. 2, 121,
  129385. _vq_lengthlist__44c8_s_p5_1,
  129386. 1, -531365888, 1611661312, 4, 0,
  129387. _vq_quantlist__44c8_s_p5_1,
  129388. NULL,
  129389. &_vq_auxt__44c8_s_p5_1,
  129390. NULL,
  129391. 0
  129392. };
  129393. static long _vq_quantlist__44c8_s_p6_0[] = {
  129394. 6,
  129395. 5,
  129396. 7,
  129397. 4,
  129398. 8,
  129399. 3,
  129400. 9,
  129401. 2,
  129402. 10,
  129403. 1,
  129404. 11,
  129405. 0,
  129406. 12,
  129407. };
  129408. static long _vq_lengthlist__44c8_s_p6_0[] = {
  129409. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129410. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  129411. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  129412. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  129413. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  129414. 12, 9, 9,10,10,11,11,12,12,12,12, 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,
  129420. };
  129421. static float _vq_quantthresh__44c8_s_p6_0[] = {
  129422. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129423. 12.5, 17.5, 22.5, 27.5,
  129424. };
  129425. static long _vq_quantmap__44c8_s_p6_0[] = {
  129426. 11, 9, 7, 5, 3, 1, 0, 2,
  129427. 4, 6, 8, 10, 12,
  129428. };
  129429. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  129430. _vq_quantthresh__44c8_s_p6_0,
  129431. _vq_quantmap__44c8_s_p6_0,
  129432. 13,
  129433. 13
  129434. };
  129435. static static_codebook _44c8_s_p6_0 = {
  129436. 2, 169,
  129437. _vq_lengthlist__44c8_s_p6_0,
  129438. 1, -526516224, 1616117760, 4, 0,
  129439. _vq_quantlist__44c8_s_p6_0,
  129440. NULL,
  129441. &_vq_auxt__44c8_s_p6_0,
  129442. NULL,
  129443. 0
  129444. };
  129445. static long _vq_quantlist__44c8_s_p6_1[] = {
  129446. 2,
  129447. 1,
  129448. 3,
  129449. 0,
  129450. 4,
  129451. };
  129452. static long _vq_lengthlist__44c8_s_p6_1[] = {
  129453. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129454. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129455. };
  129456. static float _vq_quantthresh__44c8_s_p6_1[] = {
  129457. -1.5, -0.5, 0.5, 1.5,
  129458. };
  129459. static long _vq_quantmap__44c8_s_p6_1[] = {
  129460. 3, 1, 0, 2, 4,
  129461. };
  129462. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  129463. _vq_quantthresh__44c8_s_p6_1,
  129464. _vq_quantmap__44c8_s_p6_1,
  129465. 5,
  129466. 5
  129467. };
  129468. static static_codebook _44c8_s_p6_1 = {
  129469. 2, 25,
  129470. _vq_lengthlist__44c8_s_p6_1,
  129471. 1, -533725184, 1611661312, 3, 0,
  129472. _vq_quantlist__44c8_s_p6_1,
  129473. NULL,
  129474. &_vq_auxt__44c8_s_p6_1,
  129475. NULL,
  129476. 0
  129477. };
  129478. static long _vq_quantlist__44c8_s_p7_0[] = {
  129479. 6,
  129480. 5,
  129481. 7,
  129482. 4,
  129483. 8,
  129484. 3,
  129485. 9,
  129486. 2,
  129487. 10,
  129488. 1,
  129489. 11,
  129490. 0,
  129491. 12,
  129492. };
  129493. static long _vq_lengthlist__44c8_s_p7_0[] = {
  129494. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  129495. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  129496. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  129497. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  129498. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  129499. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  129500. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  129501. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  129502. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  129503. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  129504. 20,13,13,13,13,14,13,15,15,
  129505. };
  129506. static float _vq_quantthresh__44c8_s_p7_0[] = {
  129507. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129508. 27.5, 38.5, 49.5, 60.5,
  129509. };
  129510. static long _vq_quantmap__44c8_s_p7_0[] = {
  129511. 11, 9, 7, 5, 3, 1, 0, 2,
  129512. 4, 6, 8, 10, 12,
  129513. };
  129514. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  129515. _vq_quantthresh__44c8_s_p7_0,
  129516. _vq_quantmap__44c8_s_p7_0,
  129517. 13,
  129518. 13
  129519. };
  129520. static static_codebook _44c8_s_p7_0 = {
  129521. 2, 169,
  129522. _vq_lengthlist__44c8_s_p7_0,
  129523. 1, -523206656, 1618345984, 4, 0,
  129524. _vq_quantlist__44c8_s_p7_0,
  129525. NULL,
  129526. &_vq_auxt__44c8_s_p7_0,
  129527. NULL,
  129528. 0
  129529. };
  129530. static long _vq_quantlist__44c8_s_p7_1[] = {
  129531. 5,
  129532. 4,
  129533. 6,
  129534. 3,
  129535. 7,
  129536. 2,
  129537. 8,
  129538. 1,
  129539. 9,
  129540. 0,
  129541. 10,
  129542. };
  129543. static long _vq_lengthlist__44c8_s_p7_1[] = {
  129544. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  129545. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129546. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  129547. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129548. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129549. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129550. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129551. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129552. };
  129553. static float _vq_quantthresh__44c8_s_p7_1[] = {
  129554. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129555. 3.5, 4.5,
  129556. };
  129557. static long _vq_quantmap__44c8_s_p7_1[] = {
  129558. 9, 7, 5, 3, 1, 0, 2, 4,
  129559. 6, 8, 10,
  129560. };
  129561. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  129562. _vq_quantthresh__44c8_s_p7_1,
  129563. _vq_quantmap__44c8_s_p7_1,
  129564. 11,
  129565. 11
  129566. };
  129567. static static_codebook _44c8_s_p7_1 = {
  129568. 2, 121,
  129569. _vq_lengthlist__44c8_s_p7_1,
  129570. 1, -531365888, 1611661312, 4, 0,
  129571. _vq_quantlist__44c8_s_p7_1,
  129572. NULL,
  129573. &_vq_auxt__44c8_s_p7_1,
  129574. NULL,
  129575. 0
  129576. };
  129577. static long _vq_quantlist__44c8_s_p8_0[] = {
  129578. 7,
  129579. 6,
  129580. 8,
  129581. 5,
  129582. 9,
  129583. 4,
  129584. 10,
  129585. 3,
  129586. 11,
  129587. 2,
  129588. 12,
  129589. 1,
  129590. 13,
  129591. 0,
  129592. 14,
  129593. };
  129594. static long _vq_lengthlist__44c8_s_p8_0[] = {
  129595. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  129596. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  129597. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  129598. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  129599. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  129600. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  129601. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  129602. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  129603. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  129604. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  129605. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  129606. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  129607. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  129608. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  129609. 15,
  129610. };
  129611. static float _vq_quantthresh__44c8_s_p8_0[] = {
  129612. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129613. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129614. };
  129615. static long _vq_quantmap__44c8_s_p8_0[] = {
  129616. 13, 11, 9, 7, 5, 3, 1, 0,
  129617. 2, 4, 6, 8, 10, 12, 14,
  129618. };
  129619. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  129620. _vq_quantthresh__44c8_s_p8_0,
  129621. _vq_quantmap__44c8_s_p8_0,
  129622. 15,
  129623. 15
  129624. };
  129625. static static_codebook _44c8_s_p8_0 = {
  129626. 2, 225,
  129627. _vq_lengthlist__44c8_s_p8_0,
  129628. 1, -520986624, 1620377600, 4, 0,
  129629. _vq_quantlist__44c8_s_p8_0,
  129630. NULL,
  129631. &_vq_auxt__44c8_s_p8_0,
  129632. NULL,
  129633. 0
  129634. };
  129635. static long _vq_quantlist__44c8_s_p8_1[] = {
  129636. 10,
  129637. 9,
  129638. 11,
  129639. 8,
  129640. 12,
  129641. 7,
  129642. 13,
  129643. 6,
  129644. 14,
  129645. 5,
  129646. 15,
  129647. 4,
  129648. 16,
  129649. 3,
  129650. 17,
  129651. 2,
  129652. 18,
  129653. 1,
  129654. 19,
  129655. 0,
  129656. 20,
  129657. };
  129658. static long _vq_lengthlist__44c8_s_p8_1[] = {
  129659. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129660. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129661. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129662. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129663. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129664. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129665. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  129666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129667. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129668. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129669. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  129670. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  129671. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  129672. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129673. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  129674. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  129675. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  129676. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  129677. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  129678. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  129679. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  129680. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  129681. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  129682. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  129683. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  129684. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  129685. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  129686. 10, 9, 9,10,10, 9,10, 9, 9,
  129687. };
  129688. static float _vq_quantthresh__44c8_s_p8_1[] = {
  129689. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129690. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129691. 6.5, 7.5, 8.5, 9.5,
  129692. };
  129693. static long _vq_quantmap__44c8_s_p8_1[] = {
  129694. 19, 17, 15, 13, 11, 9, 7, 5,
  129695. 3, 1, 0, 2, 4, 6, 8, 10,
  129696. 12, 14, 16, 18, 20,
  129697. };
  129698. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  129699. _vq_quantthresh__44c8_s_p8_1,
  129700. _vq_quantmap__44c8_s_p8_1,
  129701. 21,
  129702. 21
  129703. };
  129704. static static_codebook _44c8_s_p8_1 = {
  129705. 2, 441,
  129706. _vq_lengthlist__44c8_s_p8_1,
  129707. 1, -529268736, 1611661312, 5, 0,
  129708. _vq_quantlist__44c8_s_p8_1,
  129709. NULL,
  129710. &_vq_auxt__44c8_s_p8_1,
  129711. NULL,
  129712. 0
  129713. };
  129714. static long _vq_quantlist__44c8_s_p9_0[] = {
  129715. 8,
  129716. 7,
  129717. 9,
  129718. 6,
  129719. 10,
  129720. 5,
  129721. 11,
  129722. 4,
  129723. 12,
  129724. 3,
  129725. 13,
  129726. 2,
  129727. 14,
  129728. 1,
  129729. 15,
  129730. 0,
  129731. 16,
  129732. };
  129733. static long _vq_lengthlist__44c8_s_p9_0[] = {
  129734. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129735. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  129736. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  129737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129748. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129752. 10,
  129753. };
  129754. static float _vq_quantthresh__44c8_s_p9_0[] = {
  129755. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  129756. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  129757. };
  129758. static long _vq_quantmap__44c8_s_p9_0[] = {
  129759. 15, 13, 11, 9, 7, 5, 3, 1,
  129760. 0, 2, 4, 6, 8, 10, 12, 14,
  129761. 16,
  129762. };
  129763. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  129764. _vq_quantthresh__44c8_s_p9_0,
  129765. _vq_quantmap__44c8_s_p9_0,
  129766. 17,
  129767. 17
  129768. };
  129769. static static_codebook _44c8_s_p9_0 = {
  129770. 2, 289,
  129771. _vq_lengthlist__44c8_s_p9_0,
  129772. 1, -509798400, 1631393792, 5, 0,
  129773. _vq_quantlist__44c8_s_p9_0,
  129774. NULL,
  129775. &_vq_auxt__44c8_s_p9_0,
  129776. NULL,
  129777. 0
  129778. };
  129779. static long _vq_quantlist__44c8_s_p9_1[] = {
  129780. 9,
  129781. 8,
  129782. 10,
  129783. 7,
  129784. 11,
  129785. 6,
  129786. 12,
  129787. 5,
  129788. 13,
  129789. 4,
  129790. 14,
  129791. 3,
  129792. 15,
  129793. 2,
  129794. 16,
  129795. 1,
  129796. 17,
  129797. 0,
  129798. 18,
  129799. };
  129800. static long _vq_lengthlist__44c8_s_p9_1[] = {
  129801. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  129802. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  129803. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  129804. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  129805. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  129806. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  129807. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  129808. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  129809. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  129810. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  129811. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  129812. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  129813. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  129814. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  129815. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  129816. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  129817. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  129818. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  129819. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  129820. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  129821. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  129822. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  129823. 14,13,13,14,14,15,14,15,14,
  129824. };
  129825. static float _vq_quantthresh__44c8_s_p9_1[] = {
  129826. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  129827. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  129828. 367.5, 416.5,
  129829. };
  129830. static long _vq_quantmap__44c8_s_p9_1[] = {
  129831. 17, 15, 13, 11, 9, 7, 5, 3,
  129832. 1, 0, 2, 4, 6, 8, 10, 12,
  129833. 14, 16, 18,
  129834. };
  129835. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  129836. _vq_quantthresh__44c8_s_p9_1,
  129837. _vq_quantmap__44c8_s_p9_1,
  129838. 19,
  129839. 19
  129840. };
  129841. static static_codebook _44c8_s_p9_1 = {
  129842. 2, 361,
  129843. _vq_lengthlist__44c8_s_p9_1,
  129844. 1, -518287360, 1622704128, 5, 0,
  129845. _vq_quantlist__44c8_s_p9_1,
  129846. NULL,
  129847. &_vq_auxt__44c8_s_p9_1,
  129848. NULL,
  129849. 0
  129850. };
  129851. static long _vq_quantlist__44c8_s_p9_2[] = {
  129852. 24,
  129853. 23,
  129854. 25,
  129855. 22,
  129856. 26,
  129857. 21,
  129858. 27,
  129859. 20,
  129860. 28,
  129861. 19,
  129862. 29,
  129863. 18,
  129864. 30,
  129865. 17,
  129866. 31,
  129867. 16,
  129868. 32,
  129869. 15,
  129870. 33,
  129871. 14,
  129872. 34,
  129873. 13,
  129874. 35,
  129875. 12,
  129876. 36,
  129877. 11,
  129878. 37,
  129879. 10,
  129880. 38,
  129881. 9,
  129882. 39,
  129883. 8,
  129884. 40,
  129885. 7,
  129886. 41,
  129887. 6,
  129888. 42,
  129889. 5,
  129890. 43,
  129891. 4,
  129892. 44,
  129893. 3,
  129894. 45,
  129895. 2,
  129896. 46,
  129897. 1,
  129898. 47,
  129899. 0,
  129900. 48,
  129901. };
  129902. static long _vq_lengthlist__44c8_s_p9_2[] = {
  129903. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  129904. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129905. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129906. 7,
  129907. };
  129908. static float _vq_quantthresh__44c8_s_p9_2[] = {
  129909. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129910. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129911. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129912. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129913. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129914. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129915. };
  129916. static long _vq_quantmap__44c8_s_p9_2[] = {
  129917. 47, 45, 43, 41, 39, 37, 35, 33,
  129918. 31, 29, 27, 25, 23, 21, 19, 17,
  129919. 15, 13, 11, 9, 7, 5, 3, 1,
  129920. 0, 2, 4, 6, 8, 10, 12, 14,
  129921. 16, 18, 20, 22, 24, 26, 28, 30,
  129922. 32, 34, 36, 38, 40, 42, 44, 46,
  129923. 48,
  129924. };
  129925. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  129926. _vq_quantthresh__44c8_s_p9_2,
  129927. _vq_quantmap__44c8_s_p9_2,
  129928. 49,
  129929. 49
  129930. };
  129931. static static_codebook _44c8_s_p9_2 = {
  129932. 1, 49,
  129933. _vq_lengthlist__44c8_s_p9_2,
  129934. 1, -526909440, 1611661312, 6, 0,
  129935. _vq_quantlist__44c8_s_p9_2,
  129936. NULL,
  129937. &_vq_auxt__44c8_s_p9_2,
  129938. NULL,
  129939. 0
  129940. };
  129941. static long _huff_lengthlist__44c8_s_short[] = {
  129942. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  129943. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  129944. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  129945. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  129946. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  129947. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  129948. 10, 9,11,14,
  129949. };
  129950. static static_codebook _huff_book__44c8_s_short = {
  129951. 2, 100,
  129952. _huff_lengthlist__44c8_s_short,
  129953. 0, 0, 0, 0, 0,
  129954. NULL,
  129955. NULL,
  129956. NULL,
  129957. NULL,
  129958. 0
  129959. };
  129960. static long _huff_lengthlist__44c9_s_long[] = {
  129961. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  129962. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  129963. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  129964. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  129965. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  129966. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  129967. 10, 9, 8, 9,
  129968. };
  129969. static static_codebook _huff_book__44c9_s_long = {
  129970. 2, 100,
  129971. _huff_lengthlist__44c9_s_long,
  129972. 0, 0, 0, 0, 0,
  129973. NULL,
  129974. NULL,
  129975. NULL,
  129976. NULL,
  129977. 0
  129978. };
  129979. static long _vq_quantlist__44c9_s_p1_0[] = {
  129980. 1,
  129981. 0,
  129982. 2,
  129983. };
  129984. static long _vq_lengthlist__44c9_s_p1_0[] = {
  129985. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  129986. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  129988. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129989. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  129990. 7,
  129991. };
  129992. static float _vq_quantthresh__44c9_s_p1_0[] = {
  129993. -0.5, 0.5,
  129994. };
  129995. static long _vq_quantmap__44c9_s_p1_0[] = {
  129996. 1, 0, 2,
  129997. };
  129998. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  129999. _vq_quantthresh__44c9_s_p1_0,
  130000. _vq_quantmap__44c9_s_p1_0,
  130001. 3,
  130002. 3
  130003. };
  130004. static static_codebook _44c9_s_p1_0 = {
  130005. 4, 81,
  130006. _vq_lengthlist__44c9_s_p1_0,
  130007. 1, -535822336, 1611661312, 2, 0,
  130008. _vq_quantlist__44c9_s_p1_0,
  130009. NULL,
  130010. &_vq_auxt__44c9_s_p1_0,
  130011. NULL,
  130012. 0
  130013. };
  130014. static long _vq_quantlist__44c9_s_p2_0[] = {
  130015. 2,
  130016. 1,
  130017. 3,
  130018. 0,
  130019. 4,
  130020. };
  130021. static long _vq_lengthlist__44c9_s_p2_0[] = {
  130022. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130023. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  130024. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  130025. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  130026. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  130027. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  130028. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  130029. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  130032. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  130033. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  130034. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  130035. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  130036. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  130037. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  130040. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  130041. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  130042. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  130043. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  130044. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  130045. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  130048. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  130049. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  130050. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  130051. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  130052. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  130053. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  130058. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  130059. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  130060. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  130061. 12,
  130062. };
  130063. static float _vq_quantthresh__44c9_s_p2_0[] = {
  130064. -1.5, -0.5, 0.5, 1.5,
  130065. };
  130066. static long _vq_quantmap__44c9_s_p2_0[] = {
  130067. 3, 1, 0, 2, 4,
  130068. };
  130069. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  130070. _vq_quantthresh__44c9_s_p2_0,
  130071. _vq_quantmap__44c9_s_p2_0,
  130072. 5,
  130073. 5
  130074. };
  130075. static static_codebook _44c9_s_p2_0 = {
  130076. 4, 625,
  130077. _vq_lengthlist__44c9_s_p2_0,
  130078. 1, -533725184, 1611661312, 3, 0,
  130079. _vq_quantlist__44c9_s_p2_0,
  130080. NULL,
  130081. &_vq_auxt__44c9_s_p2_0,
  130082. NULL,
  130083. 0
  130084. };
  130085. static long _vq_quantlist__44c9_s_p3_0[] = {
  130086. 4,
  130087. 3,
  130088. 5,
  130089. 2,
  130090. 6,
  130091. 1,
  130092. 7,
  130093. 0,
  130094. 8,
  130095. };
  130096. static long _vq_lengthlist__44c9_s_p3_0[] = {
  130097. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  130098. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  130099. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  130100. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0,
  130103. };
  130104. static float _vq_quantthresh__44c9_s_p3_0[] = {
  130105. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130106. };
  130107. static long _vq_quantmap__44c9_s_p3_0[] = {
  130108. 7, 5, 3, 1, 0, 2, 4, 6,
  130109. 8,
  130110. };
  130111. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  130112. _vq_quantthresh__44c9_s_p3_0,
  130113. _vq_quantmap__44c9_s_p3_0,
  130114. 9,
  130115. 9
  130116. };
  130117. static static_codebook _44c9_s_p3_0 = {
  130118. 2, 81,
  130119. _vq_lengthlist__44c9_s_p3_0,
  130120. 1, -531628032, 1611661312, 4, 0,
  130121. _vq_quantlist__44c9_s_p3_0,
  130122. NULL,
  130123. &_vq_auxt__44c9_s_p3_0,
  130124. NULL,
  130125. 0
  130126. };
  130127. static long _vq_quantlist__44c9_s_p4_0[] = {
  130128. 8,
  130129. 7,
  130130. 9,
  130131. 6,
  130132. 10,
  130133. 5,
  130134. 11,
  130135. 4,
  130136. 12,
  130137. 3,
  130138. 13,
  130139. 2,
  130140. 14,
  130141. 1,
  130142. 15,
  130143. 0,
  130144. 16,
  130145. };
  130146. static long _vq_lengthlist__44c9_s_p4_0[] = {
  130147. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  130148. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  130149. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  130150. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  130151. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  130152. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  130153. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  130154. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130155. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130156. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0,
  130166. };
  130167. static float _vq_quantthresh__44c9_s_p4_0[] = {
  130168. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130169. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130170. };
  130171. static long _vq_quantmap__44c9_s_p4_0[] = {
  130172. 15, 13, 11, 9, 7, 5, 3, 1,
  130173. 0, 2, 4, 6, 8, 10, 12, 14,
  130174. 16,
  130175. };
  130176. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  130177. _vq_quantthresh__44c9_s_p4_0,
  130178. _vq_quantmap__44c9_s_p4_0,
  130179. 17,
  130180. 17
  130181. };
  130182. static static_codebook _44c9_s_p4_0 = {
  130183. 2, 289,
  130184. _vq_lengthlist__44c9_s_p4_0,
  130185. 1, -529530880, 1611661312, 5, 0,
  130186. _vq_quantlist__44c9_s_p4_0,
  130187. NULL,
  130188. &_vq_auxt__44c9_s_p4_0,
  130189. NULL,
  130190. 0
  130191. };
  130192. static long _vq_quantlist__44c9_s_p5_0[] = {
  130193. 1,
  130194. 0,
  130195. 2,
  130196. };
  130197. static long _vq_lengthlist__44c9_s_p5_0[] = {
  130198. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  130199. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  130200. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  130201. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  130202. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  130203. 12,
  130204. };
  130205. static float _vq_quantthresh__44c9_s_p5_0[] = {
  130206. -5.5, 5.5,
  130207. };
  130208. static long _vq_quantmap__44c9_s_p5_0[] = {
  130209. 1, 0, 2,
  130210. };
  130211. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  130212. _vq_quantthresh__44c9_s_p5_0,
  130213. _vq_quantmap__44c9_s_p5_0,
  130214. 3,
  130215. 3
  130216. };
  130217. static static_codebook _44c9_s_p5_0 = {
  130218. 4, 81,
  130219. _vq_lengthlist__44c9_s_p5_0,
  130220. 1, -529137664, 1618345984, 2, 0,
  130221. _vq_quantlist__44c9_s_p5_0,
  130222. NULL,
  130223. &_vq_auxt__44c9_s_p5_0,
  130224. NULL,
  130225. 0
  130226. };
  130227. static long _vq_quantlist__44c9_s_p5_1[] = {
  130228. 5,
  130229. 4,
  130230. 6,
  130231. 3,
  130232. 7,
  130233. 2,
  130234. 8,
  130235. 1,
  130236. 9,
  130237. 0,
  130238. 10,
  130239. };
  130240. static long _vq_lengthlist__44c9_s_p5_1[] = {
  130241. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  130242. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  130243. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  130244. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  130245. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  130246. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  130247. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  130248. 11,11,11, 7, 7, 7, 7, 7, 7,
  130249. };
  130250. static float _vq_quantthresh__44c9_s_p5_1[] = {
  130251. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130252. 3.5, 4.5,
  130253. };
  130254. static long _vq_quantmap__44c9_s_p5_1[] = {
  130255. 9, 7, 5, 3, 1, 0, 2, 4,
  130256. 6, 8, 10,
  130257. };
  130258. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  130259. _vq_quantthresh__44c9_s_p5_1,
  130260. _vq_quantmap__44c9_s_p5_1,
  130261. 11,
  130262. 11
  130263. };
  130264. static static_codebook _44c9_s_p5_1 = {
  130265. 2, 121,
  130266. _vq_lengthlist__44c9_s_p5_1,
  130267. 1, -531365888, 1611661312, 4, 0,
  130268. _vq_quantlist__44c9_s_p5_1,
  130269. NULL,
  130270. &_vq_auxt__44c9_s_p5_1,
  130271. NULL,
  130272. 0
  130273. };
  130274. static long _vq_quantlist__44c9_s_p6_0[] = {
  130275. 6,
  130276. 5,
  130277. 7,
  130278. 4,
  130279. 8,
  130280. 3,
  130281. 9,
  130282. 2,
  130283. 10,
  130284. 1,
  130285. 11,
  130286. 0,
  130287. 12,
  130288. };
  130289. static long _vq_lengthlist__44c9_s_p6_0[] = {
  130290. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  130291. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  130292. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  130293. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130294. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  130295. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. };
  130302. static float _vq_quantthresh__44c9_s_p6_0[] = {
  130303. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130304. 12.5, 17.5, 22.5, 27.5,
  130305. };
  130306. static long _vq_quantmap__44c9_s_p6_0[] = {
  130307. 11, 9, 7, 5, 3, 1, 0, 2,
  130308. 4, 6, 8, 10, 12,
  130309. };
  130310. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  130311. _vq_quantthresh__44c9_s_p6_0,
  130312. _vq_quantmap__44c9_s_p6_0,
  130313. 13,
  130314. 13
  130315. };
  130316. static static_codebook _44c9_s_p6_0 = {
  130317. 2, 169,
  130318. _vq_lengthlist__44c9_s_p6_0,
  130319. 1, -526516224, 1616117760, 4, 0,
  130320. _vq_quantlist__44c9_s_p6_0,
  130321. NULL,
  130322. &_vq_auxt__44c9_s_p6_0,
  130323. NULL,
  130324. 0
  130325. };
  130326. static long _vq_quantlist__44c9_s_p6_1[] = {
  130327. 2,
  130328. 1,
  130329. 3,
  130330. 0,
  130331. 4,
  130332. };
  130333. static long _vq_lengthlist__44c9_s_p6_1[] = {
  130334. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  130335. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  130336. };
  130337. static float _vq_quantthresh__44c9_s_p6_1[] = {
  130338. -1.5, -0.5, 0.5, 1.5,
  130339. };
  130340. static long _vq_quantmap__44c9_s_p6_1[] = {
  130341. 3, 1, 0, 2, 4,
  130342. };
  130343. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  130344. _vq_quantthresh__44c9_s_p6_1,
  130345. _vq_quantmap__44c9_s_p6_1,
  130346. 5,
  130347. 5
  130348. };
  130349. static static_codebook _44c9_s_p6_1 = {
  130350. 2, 25,
  130351. _vq_lengthlist__44c9_s_p6_1,
  130352. 1, -533725184, 1611661312, 3, 0,
  130353. _vq_quantlist__44c9_s_p6_1,
  130354. NULL,
  130355. &_vq_auxt__44c9_s_p6_1,
  130356. NULL,
  130357. 0
  130358. };
  130359. static long _vq_quantlist__44c9_s_p7_0[] = {
  130360. 6,
  130361. 5,
  130362. 7,
  130363. 4,
  130364. 8,
  130365. 3,
  130366. 9,
  130367. 2,
  130368. 10,
  130369. 1,
  130370. 11,
  130371. 0,
  130372. 12,
  130373. };
  130374. static long _vq_lengthlist__44c9_s_p7_0[] = {
  130375. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  130376. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  130377. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  130378. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  130379. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  130380. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  130381. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  130382. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  130383. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  130384. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  130385. 19,12,12,12,12,13,13,14,14,
  130386. };
  130387. static float _vq_quantthresh__44c9_s_p7_0[] = {
  130388. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130389. 27.5, 38.5, 49.5, 60.5,
  130390. };
  130391. static long _vq_quantmap__44c9_s_p7_0[] = {
  130392. 11, 9, 7, 5, 3, 1, 0, 2,
  130393. 4, 6, 8, 10, 12,
  130394. };
  130395. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  130396. _vq_quantthresh__44c9_s_p7_0,
  130397. _vq_quantmap__44c9_s_p7_0,
  130398. 13,
  130399. 13
  130400. };
  130401. static static_codebook _44c9_s_p7_0 = {
  130402. 2, 169,
  130403. _vq_lengthlist__44c9_s_p7_0,
  130404. 1, -523206656, 1618345984, 4, 0,
  130405. _vq_quantlist__44c9_s_p7_0,
  130406. NULL,
  130407. &_vq_auxt__44c9_s_p7_0,
  130408. NULL,
  130409. 0
  130410. };
  130411. static long _vq_quantlist__44c9_s_p7_1[] = {
  130412. 5,
  130413. 4,
  130414. 6,
  130415. 3,
  130416. 7,
  130417. 2,
  130418. 8,
  130419. 1,
  130420. 9,
  130421. 0,
  130422. 10,
  130423. };
  130424. static long _vq_lengthlist__44c9_s_p7_1[] = {
  130425. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  130426. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130427. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  130428. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130429. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130430. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130431. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130432. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130433. };
  130434. static float _vq_quantthresh__44c9_s_p7_1[] = {
  130435. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130436. 3.5, 4.5,
  130437. };
  130438. static long _vq_quantmap__44c9_s_p7_1[] = {
  130439. 9, 7, 5, 3, 1, 0, 2, 4,
  130440. 6, 8, 10,
  130441. };
  130442. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  130443. _vq_quantthresh__44c9_s_p7_1,
  130444. _vq_quantmap__44c9_s_p7_1,
  130445. 11,
  130446. 11
  130447. };
  130448. static static_codebook _44c9_s_p7_1 = {
  130449. 2, 121,
  130450. _vq_lengthlist__44c9_s_p7_1,
  130451. 1, -531365888, 1611661312, 4, 0,
  130452. _vq_quantlist__44c9_s_p7_1,
  130453. NULL,
  130454. &_vq_auxt__44c9_s_p7_1,
  130455. NULL,
  130456. 0
  130457. };
  130458. static long _vq_quantlist__44c9_s_p8_0[] = {
  130459. 7,
  130460. 6,
  130461. 8,
  130462. 5,
  130463. 9,
  130464. 4,
  130465. 10,
  130466. 3,
  130467. 11,
  130468. 2,
  130469. 12,
  130470. 1,
  130471. 13,
  130472. 0,
  130473. 14,
  130474. };
  130475. static long _vq_lengthlist__44c9_s_p8_0[] = {
  130476. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  130477. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  130478. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  130479. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  130480. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  130481. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  130482. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  130483. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  130484. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  130485. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  130486. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  130487. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  130488. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  130489. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  130490. 14,
  130491. };
  130492. static float _vq_quantthresh__44c9_s_p8_0[] = {
  130493. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130494. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130495. };
  130496. static long _vq_quantmap__44c9_s_p8_0[] = {
  130497. 13, 11, 9, 7, 5, 3, 1, 0,
  130498. 2, 4, 6, 8, 10, 12, 14,
  130499. };
  130500. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  130501. _vq_quantthresh__44c9_s_p8_0,
  130502. _vq_quantmap__44c9_s_p8_0,
  130503. 15,
  130504. 15
  130505. };
  130506. static static_codebook _44c9_s_p8_0 = {
  130507. 2, 225,
  130508. _vq_lengthlist__44c9_s_p8_0,
  130509. 1, -520986624, 1620377600, 4, 0,
  130510. _vq_quantlist__44c9_s_p8_0,
  130511. NULL,
  130512. &_vq_auxt__44c9_s_p8_0,
  130513. NULL,
  130514. 0
  130515. };
  130516. static long _vq_quantlist__44c9_s_p8_1[] = {
  130517. 10,
  130518. 9,
  130519. 11,
  130520. 8,
  130521. 12,
  130522. 7,
  130523. 13,
  130524. 6,
  130525. 14,
  130526. 5,
  130527. 15,
  130528. 4,
  130529. 16,
  130530. 3,
  130531. 17,
  130532. 2,
  130533. 18,
  130534. 1,
  130535. 19,
  130536. 0,
  130537. 20,
  130538. };
  130539. static long _vq_lengthlist__44c9_s_p8_1[] = {
  130540. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130541. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130542. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130543. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130544. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130545. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130546. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  130547. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130548. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130549. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130550. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  130551. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130552. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130553. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130554. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  130555. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  130556. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  130557. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  130558. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  130559. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  130560. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  130561. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  130562. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130563. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  130564. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  130565. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  130566. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  130567. 9, 9, 9,10, 9, 9, 9, 9, 9,
  130568. };
  130569. static float _vq_quantthresh__44c9_s_p8_1[] = {
  130570. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130571. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130572. 6.5, 7.5, 8.5, 9.5,
  130573. };
  130574. static long _vq_quantmap__44c9_s_p8_1[] = {
  130575. 19, 17, 15, 13, 11, 9, 7, 5,
  130576. 3, 1, 0, 2, 4, 6, 8, 10,
  130577. 12, 14, 16, 18, 20,
  130578. };
  130579. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  130580. _vq_quantthresh__44c9_s_p8_1,
  130581. _vq_quantmap__44c9_s_p8_1,
  130582. 21,
  130583. 21
  130584. };
  130585. static static_codebook _44c9_s_p8_1 = {
  130586. 2, 441,
  130587. _vq_lengthlist__44c9_s_p8_1,
  130588. 1, -529268736, 1611661312, 5, 0,
  130589. _vq_quantlist__44c9_s_p8_1,
  130590. NULL,
  130591. &_vq_auxt__44c9_s_p8_1,
  130592. NULL,
  130593. 0
  130594. };
  130595. static long _vq_quantlist__44c9_s_p9_0[] = {
  130596. 9,
  130597. 8,
  130598. 10,
  130599. 7,
  130600. 11,
  130601. 6,
  130602. 12,
  130603. 5,
  130604. 13,
  130605. 4,
  130606. 14,
  130607. 3,
  130608. 15,
  130609. 2,
  130610. 16,
  130611. 1,
  130612. 17,
  130613. 0,
  130614. 18,
  130615. };
  130616. static long _vq_lengthlist__44c9_s_p9_0[] = {
  130617. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130618. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  130619. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  130620. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  130621. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130622. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130623. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130624. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130625. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130626. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130627. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130628. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130629. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130630. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130631. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130632. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130633. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130639. 11,11,11,11,11,11,11,11,11,
  130640. };
  130641. static float _vq_quantthresh__44c9_s_p9_0[] = {
  130642. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  130643. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  130644. 6982.5, 7913.5,
  130645. };
  130646. static long _vq_quantmap__44c9_s_p9_0[] = {
  130647. 17, 15, 13, 11, 9, 7, 5, 3,
  130648. 1, 0, 2, 4, 6, 8, 10, 12,
  130649. 14, 16, 18,
  130650. };
  130651. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  130652. _vq_quantthresh__44c9_s_p9_0,
  130653. _vq_quantmap__44c9_s_p9_0,
  130654. 19,
  130655. 19
  130656. };
  130657. static static_codebook _44c9_s_p9_0 = {
  130658. 2, 361,
  130659. _vq_lengthlist__44c9_s_p9_0,
  130660. 1, -508535424, 1631393792, 5, 0,
  130661. _vq_quantlist__44c9_s_p9_0,
  130662. NULL,
  130663. &_vq_auxt__44c9_s_p9_0,
  130664. NULL,
  130665. 0
  130666. };
  130667. static long _vq_quantlist__44c9_s_p9_1[] = {
  130668. 9,
  130669. 8,
  130670. 10,
  130671. 7,
  130672. 11,
  130673. 6,
  130674. 12,
  130675. 5,
  130676. 13,
  130677. 4,
  130678. 14,
  130679. 3,
  130680. 15,
  130681. 2,
  130682. 16,
  130683. 1,
  130684. 17,
  130685. 0,
  130686. 18,
  130687. };
  130688. static long _vq_lengthlist__44c9_s_p9_1[] = {
  130689. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  130690. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  130691. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  130692. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  130693. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  130694. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  130695. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  130696. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  130697. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  130698. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  130699. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  130700. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  130701. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  130702. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  130703. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  130704. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  130705. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  130706. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  130707. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  130708. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  130709. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  130710. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  130711. 13,13,13,14,13,14,15,15,15,
  130712. };
  130713. static float _vq_quantthresh__44c9_s_p9_1[] = {
  130714. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  130715. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  130716. 367.5, 416.5,
  130717. };
  130718. static long _vq_quantmap__44c9_s_p9_1[] = {
  130719. 17, 15, 13, 11, 9, 7, 5, 3,
  130720. 1, 0, 2, 4, 6, 8, 10, 12,
  130721. 14, 16, 18,
  130722. };
  130723. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  130724. _vq_quantthresh__44c9_s_p9_1,
  130725. _vq_quantmap__44c9_s_p9_1,
  130726. 19,
  130727. 19
  130728. };
  130729. static static_codebook _44c9_s_p9_1 = {
  130730. 2, 361,
  130731. _vq_lengthlist__44c9_s_p9_1,
  130732. 1, -518287360, 1622704128, 5, 0,
  130733. _vq_quantlist__44c9_s_p9_1,
  130734. NULL,
  130735. &_vq_auxt__44c9_s_p9_1,
  130736. NULL,
  130737. 0
  130738. };
  130739. static long _vq_quantlist__44c9_s_p9_2[] = {
  130740. 24,
  130741. 23,
  130742. 25,
  130743. 22,
  130744. 26,
  130745. 21,
  130746. 27,
  130747. 20,
  130748. 28,
  130749. 19,
  130750. 29,
  130751. 18,
  130752. 30,
  130753. 17,
  130754. 31,
  130755. 16,
  130756. 32,
  130757. 15,
  130758. 33,
  130759. 14,
  130760. 34,
  130761. 13,
  130762. 35,
  130763. 12,
  130764. 36,
  130765. 11,
  130766. 37,
  130767. 10,
  130768. 38,
  130769. 9,
  130770. 39,
  130771. 8,
  130772. 40,
  130773. 7,
  130774. 41,
  130775. 6,
  130776. 42,
  130777. 5,
  130778. 43,
  130779. 4,
  130780. 44,
  130781. 3,
  130782. 45,
  130783. 2,
  130784. 46,
  130785. 1,
  130786. 47,
  130787. 0,
  130788. 48,
  130789. };
  130790. static long _vq_lengthlist__44c9_s_p9_2[] = {
  130791. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  130792. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130793. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130794. 7,
  130795. };
  130796. static float _vq_quantthresh__44c9_s_p9_2[] = {
  130797. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130798. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130799. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130800. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130801. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130802. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130803. };
  130804. static long _vq_quantmap__44c9_s_p9_2[] = {
  130805. 47, 45, 43, 41, 39, 37, 35, 33,
  130806. 31, 29, 27, 25, 23, 21, 19, 17,
  130807. 15, 13, 11, 9, 7, 5, 3, 1,
  130808. 0, 2, 4, 6, 8, 10, 12, 14,
  130809. 16, 18, 20, 22, 24, 26, 28, 30,
  130810. 32, 34, 36, 38, 40, 42, 44, 46,
  130811. 48,
  130812. };
  130813. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  130814. _vq_quantthresh__44c9_s_p9_2,
  130815. _vq_quantmap__44c9_s_p9_2,
  130816. 49,
  130817. 49
  130818. };
  130819. static static_codebook _44c9_s_p9_2 = {
  130820. 1, 49,
  130821. _vq_lengthlist__44c9_s_p9_2,
  130822. 1, -526909440, 1611661312, 6, 0,
  130823. _vq_quantlist__44c9_s_p9_2,
  130824. NULL,
  130825. &_vq_auxt__44c9_s_p9_2,
  130826. NULL,
  130827. 0
  130828. };
  130829. static long _huff_lengthlist__44c9_s_short[] = {
  130830. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  130831. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  130832. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  130833. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  130834. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  130835. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  130836. 9, 8,10,13,
  130837. };
  130838. static static_codebook _huff_book__44c9_s_short = {
  130839. 2, 100,
  130840. _huff_lengthlist__44c9_s_short,
  130841. 0, 0, 0, 0, 0,
  130842. NULL,
  130843. NULL,
  130844. NULL,
  130845. NULL,
  130846. 0
  130847. };
  130848. static long _huff_lengthlist__44c0_s_long[] = {
  130849. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  130850. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  130851. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  130852. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  130853. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  130854. 12,
  130855. };
  130856. static static_codebook _huff_book__44c0_s_long = {
  130857. 2, 81,
  130858. _huff_lengthlist__44c0_s_long,
  130859. 0, 0, 0, 0, 0,
  130860. NULL,
  130861. NULL,
  130862. NULL,
  130863. NULL,
  130864. 0
  130865. };
  130866. static long _vq_quantlist__44c0_s_p1_0[] = {
  130867. 1,
  130868. 0,
  130869. 2,
  130870. };
  130871. static long _vq_lengthlist__44c0_s_p1_0[] = {
  130872. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130873. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130878. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130882. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130883. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130918. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130923. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130928. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130964. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130969. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  130974. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0,
  131283. };
  131284. static float _vq_quantthresh__44c0_s_p1_0[] = {
  131285. -0.5, 0.5,
  131286. };
  131287. static long _vq_quantmap__44c0_s_p1_0[] = {
  131288. 1, 0, 2,
  131289. };
  131290. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  131291. _vq_quantthresh__44c0_s_p1_0,
  131292. _vq_quantmap__44c0_s_p1_0,
  131293. 3,
  131294. 3
  131295. };
  131296. static static_codebook _44c0_s_p1_0 = {
  131297. 8, 6561,
  131298. _vq_lengthlist__44c0_s_p1_0,
  131299. 1, -535822336, 1611661312, 2, 0,
  131300. _vq_quantlist__44c0_s_p1_0,
  131301. NULL,
  131302. &_vq_auxt__44c0_s_p1_0,
  131303. NULL,
  131304. 0
  131305. };
  131306. static long _vq_quantlist__44c0_s_p2_0[] = {
  131307. 2,
  131308. 1,
  131309. 3,
  131310. 0,
  131311. 4,
  131312. };
  131313. static long _vq_lengthlist__44c0_s_p2_0[] = {
  131314. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0,
  131354. };
  131355. static float _vq_quantthresh__44c0_s_p2_0[] = {
  131356. -1.5, -0.5, 0.5, 1.5,
  131357. };
  131358. static long _vq_quantmap__44c0_s_p2_0[] = {
  131359. 3, 1, 0, 2, 4,
  131360. };
  131361. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  131362. _vq_quantthresh__44c0_s_p2_0,
  131363. _vq_quantmap__44c0_s_p2_0,
  131364. 5,
  131365. 5
  131366. };
  131367. static static_codebook _44c0_s_p2_0 = {
  131368. 4, 625,
  131369. _vq_lengthlist__44c0_s_p2_0,
  131370. 1, -533725184, 1611661312, 3, 0,
  131371. _vq_quantlist__44c0_s_p2_0,
  131372. NULL,
  131373. &_vq_auxt__44c0_s_p2_0,
  131374. NULL,
  131375. 0
  131376. };
  131377. static long _vq_quantlist__44c0_s_p3_0[] = {
  131378. 4,
  131379. 3,
  131380. 5,
  131381. 2,
  131382. 6,
  131383. 1,
  131384. 7,
  131385. 0,
  131386. 8,
  131387. };
  131388. static long _vq_lengthlist__44c0_s_p3_0[] = {
  131389. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  131390. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  131391. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  131392. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  131393. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0,
  131395. };
  131396. static float _vq_quantthresh__44c0_s_p3_0[] = {
  131397. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131398. };
  131399. static long _vq_quantmap__44c0_s_p3_0[] = {
  131400. 7, 5, 3, 1, 0, 2, 4, 6,
  131401. 8,
  131402. };
  131403. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  131404. _vq_quantthresh__44c0_s_p3_0,
  131405. _vq_quantmap__44c0_s_p3_0,
  131406. 9,
  131407. 9
  131408. };
  131409. static static_codebook _44c0_s_p3_0 = {
  131410. 2, 81,
  131411. _vq_lengthlist__44c0_s_p3_0,
  131412. 1, -531628032, 1611661312, 4, 0,
  131413. _vq_quantlist__44c0_s_p3_0,
  131414. NULL,
  131415. &_vq_auxt__44c0_s_p3_0,
  131416. NULL,
  131417. 0
  131418. };
  131419. static long _vq_quantlist__44c0_s_p4_0[] = {
  131420. 4,
  131421. 3,
  131422. 5,
  131423. 2,
  131424. 6,
  131425. 1,
  131426. 7,
  131427. 0,
  131428. 8,
  131429. };
  131430. static long _vq_lengthlist__44c0_s_p4_0[] = {
  131431. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  131432. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  131433. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  131434. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  131435. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131436. 10,
  131437. };
  131438. static float _vq_quantthresh__44c0_s_p4_0[] = {
  131439. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131440. };
  131441. static long _vq_quantmap__44c0_s_p4_0[] = {
  131442. 7, 5, 3, 1, 0, 2, 4, 6,
  131443. 8,
  131444. };
  131445. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  131446. _vq_quantthresh__44c0_s_p4_0,
  131447. _vq_quantmap__44c0_s_p4_0,
  131448. 9,
  131449. 9
  131450. };
  131451. static static_codebook _44c0_s_p4_0 = {
  131452. 2, 81,
  131453. _vq_lengthlist__44c0_s_p4_0,
  131454. 1, -531628032, 1611661312, 4, 0,
  131455. _vq_quantlist__44c0_s_p4_0,
  131456. NULL,
  131457. &_vq_auxt__44c0_s_p4_0,
  131458. NULL,
  131459. 0
  131460. };
  131461. static long _vq_quantlist__44c0_s_p5_0[] = {
  131462. 8,
  131463. 7,
  131464. 9,
  131465. 6,
  131466. 10,
  131467. 5,
  131468. 11,
  131469. 4,
  131470. 12,
  131471. 3,
  131472. 13,
  131473. 2,
  131474. 14,
  131475. 1,
  131476. 15,
  131477. 0,
  131478. 16,
  131479. };
  131480. static long _vq_lengthlist__44c0_s_p5_0[] = {
  131481. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  131482. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  131483. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  131484. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131485. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131486. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  131487. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  131488. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131489. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131490. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  131491. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  131492. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131493. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131494. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131495. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  131496. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  131497. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  131499. 14,
  131500. };
  131501. static float _vq_quantthresh__44c0_s_p5_0[] = {
  131502. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131503. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131504. };
  131505. static long _vq_quantmap__44c0_s_p5_0[] = {
  131506. 15, 13, 11, 9, 7, 5, 3, 1,
  131507. 0, 2, 4, 6, 8, 10, 12, 14,
  131508. 16,
  131509. };
  131510. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  131511. _vq_quantthresh__44c0_s_p5_0,
  131512. _vq_quantmap__44c0_s_p5_0,
  131513. 17,
  131514. 17
  131515. };
  131516. static static_codebook _44c0_s_p5_0 = {
  131517. 2, 289,
  131518. _vq_lengthlist__44c0_s_p5_0,
  131519. 1, -529530880, 1611661312, 5, 0,
  131520. _vq_quantlist__44c0_s_p5_0,
  131521. NULL,
  131522. &_vq_auxt__44c0_s_p5_0,
  131523. NULL,
  131524. 0
  131525. };
  131526. static long _vq_quantlist__44c0_s_p6_0[] = {
  131527. 1,
  131528. 0,
  131529. 2,
  131530. };
  131531. static long _vq_lengthlist__44c0_s_p6_0[] = {
  131532. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  131533. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131534. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  131535. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  131536. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  131537. 10,
  131538. };
  131539. static float _vq_quantthresh__44c0_s_p6_0[] = {
  131540. -5.5, 5.5,
  131541. };
  131542. static long _vq_quantmap__44c0_s_p6_0[] = {
  131543. 1, 0, 2,
  131544. };
  131545. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  131546. _vq_quantthresh__44c0_s_p6_0,
  131547. _vq_quantmap__44c0_s_p6_0,
  131548. 3,
  131549. 3
  131550. };
  131551. static static_codebook _44c0_s_p6_0 = {
  131552. 4, 81,
  131553. _vq_lengthlist__44c0_s_p6_0,
  131554. 1, -529137664, 1618345984, 2, 0,
  131555. _vq_quantlist__44c0_s_p6_0,
  131556. NULL,
  131557. &_vq_auxt__44c0_s_p6_0,
  131558. NULL,
  131559. 0
  131560. };
  131561. static long _vq_quantlist__44c0_s_p6_1[] = {
  131562. 5,
  131563. 4,
  131564. 6,
  131565. 3,
  131566. 7,
  131567. 2,
  131568. 8,
  131569. 1,
  131570. 9,
  131571. 0,
  131572. 10,
  131573. };
  131574. static long _vq_lengthlist__44c0_s_p6_1[] = {
  131575. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  131576. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  131577. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  131578. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131579. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131580. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131581. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131582. 10,10,10, 8, 8, 8, 8, 8, 8,
  131583. };
  131584. static float _vq_quantthresh__44c0_s_p6_1[] = {
  131585. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131586. 3.5, 4.5,
  131587. };
  131588. static long _vq_quantmap__44c0_s_p6_1[] = {
  131589. 9, 7, 5, 3, 1, 0, 2, 4,
  131590. 6, 8, 10,
  131591. };
  131592. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  131593. _vq_quantthresh__44c0_s_p6_1,
  131594. _vq_quantmap__44c0_s_p6_1,
  131595. 11,
  131596. 11
  131597. };
  131598. static static_codebook _44c0_s_p6_1 = {
  131599. 2, 121,
  131600. _vq_lengthlist__44c0_s_p6_1,
  131601. 1, -531365888, 1611661312, 4, 0,
  131602. _vq_quantlist__44c0_s_p6_1,
  131603. NULL,
  131604. &_vq_auxt__44c0_s_p6_1,
  131605. NULL,
  131606. 0
  131607. };
  131608. static long _vq_quantlist__44c0_s_p7_0[] = {
  131609. 6,
  131610. 5,
  131611. 7,
  131612. 4,
  131613. 8,
  131614. 3,
  131615. 9,
  131616. 2,
  131617. 10,
  131618. 1,
  131619. 11,
  131620. 0,
  131621. 12,
  131622. };
  131623. static long _vq_lengthlist__44c0_s_p7_0[] = {
  131624. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  131625. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  131626. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131627. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131628. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  131629. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131630. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  131631. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  131632. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  131633. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  131634. 0,12,12,11,11,12,12,13,13,
  131635. };
  131636. static float _vq_quantthresh__44c0_s_p7_0[] = {
  131637. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131638. 12.5, 17.5, 22.5, 27.5,
  131639. };
  131640. static long _vq_quantmap__44c0_s_p7_0[] = {
  131641. 11, 9, 7, 5, 3, 1, 0, 2,
  131642. 4, 6, 8, 10, 12,
  131643. };
  131644. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  131645. _vq_quantthresh__44c0_s_p7_0,
  131646. _vq_quantmap__44c0_s_p7_0,
  131647. 13,
  131648. 13
  131649. };
  131650. static static_codebook _44c0_s_p7_0 = {
  131651. 2, 169,
  131652. _vq_lengthlist__44c0_s_p7_0,
  131653. 1, -526516224, 1616117760, 4, 0,
  131654. _vq_quantlist__44c0_s_p7_0,
  131655. NULL,
  131656. &_vq_auxt__44c0_s_p7_0,
  131657. NULL,
  131658. 0
  131659. };
  131660. static long _vq_quantlist__44c0_s_p7_1[] = {
  131661. 2,
  131662. 1,
  131663. 3,
  131664. 0,
  131665. 4,
  131666. };
  131667. static long _vq_lengthlist__44c0_s_p7_1[] = {
  131668. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  131669. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  131670. };
  131671. static float _vq_quantthresh__44c0_s_p7_1[] = {
  131672. -1.5, -0.5, 0.5, 1.5,
  131673. };
  131674. static long _vq_quantmap__44c0_s_p7_1[] = {
  131675. 3, 1, 0, 2, 4,
  131676. };
  131677. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  131678. _vq_quantthresh__44c0_s_p7_1,
  131679. _vq_quantmap__44c0_s_p7_1,
  131680. 5,
  131681. 5
  131682. };
  131683. static static_codebook _44c0_s_p7_1 = {
  131684. 2, 25,
  131685. _vq_lengthlist__44c0_s_p7_1,
  131686. 1, -533725184, 1611661312, 3, 0,
  131687. _vq_quantlist__44c0_s_p7_1,
  131688. NULL,
  131689. &_vq_auxt__44c0_s_p7_1,
  131690. NULL,
  131691. 0
  131692. };
  131693. static long _vq_quantlist__44c0_s_p8_0[] = {
  131694. 2,
  131695. 1,
  131696. 3,
  131697. 0,
  131698. 4,
  131699. };
  131700. static long _vq_lengthlist__44c0_s_p8_0[] = {
  131701. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  131702. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131703. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131704. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131705. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131706. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131707. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131708. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  131709. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131710. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131711. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131713. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  131714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131716. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  131717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131740. 11,
  131741. };
  131742. static float _vq_quantthresh__44c0_s_p8_0[] = {
  131743. -331.5, -110.5, 110.5, 331.5,
  131744. };
  131745. static long _vq_quantmap__44c0_s_p8_0[] = {
  131746. 3, 1, 0, 2, 4,
  131747. };
  131748. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  131749. _vq_quantthresh__44c0_s_p8_0,
  131750. _vq_quantmap__44c0_s_p8_0,
  131751. 5,
  131752. 5
  131753. };
  131754. static static_codebook _44c0_s_p8_0 = {
  131755. 4, 625,
  131756. _vq_lengthlist__44c0_s_p8_0,
  131757. 1, -518283264, 1627103232, 3, 0,
  131758. _vq_quantlist__44c0_s_p8_0,
  131759. NULL,
  131760. &_vq_auxt__44c0_s_p8_0,
  131761. NULL,
  131762. 0
  131763. };
  131764. static long _vq_quantlist__44c0_s_p8_1[] = {
  131765. 6,
  131766. 5,
  131767. 7,
  131768. 4,
  131769. 8,
  131770. 3,
  131771. 9,
  131772. 2,
  131773. 10,
  131774. 1,
  131775. 11,
  131776. 0,
  131777. 12,
  131778. };
  131779. static long _vq_lengthlist__44c0_s_p8_1[] = {
  131780. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  131781. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  131782. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  131783. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  131784. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  131785. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  131786. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  131787. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  131788. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  131789. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  131790. 16,13,13,12,12,14,14,15,13,
  131791. };
  131792. static float _vq_quantthresh__44c0_s_p8_1[] = {
  131793. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  131794. 42.5, 59.5, 76.5, 93.5,
  131795. };
  131796. static long _vq_quantmap__44c0_s_p8_1[] = {
  131797. 11, 9, 7, 5, 3, 1, 0, 2,
  131798. 4, 6, 8, 10, 12,
  131799. };
  131800. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  131801. _vq_quantthresh__44c0_s_p8_1,
  131802. _vq_quantmap__44c0_s_p8_1,
  131803. 13,
  131804. 13
  131805. };
  131806. static static_codebook _44c0_s_p8_1 = {
  131807. 2, 169,
  131808. _vq_lengthlist__44c0_s_p8_1,
  131809. 1, -522616832, 1620115456, 4, 0,
  131810. _vq_quantlist__44c0_s_p8_1,
  131811. NULL,
  131812. &_vq_auxt__44c0_s_p8_1,
  131813. NULL,
  131814. 0
  131815. };
  131816. static long _vq_quantlist__44c0_s_p8_2[] = {
  131817. 8,
  131818. 7,
  131819. 9,
  131820. 6,
  131821. 10,
  131822. 5,
  131823. 11,
  131824. 4,
  131825. 12,
  131826. 3,
  131827. 13,
  131828. 2,
  131829. 14,
  131830. 1,
  131831. 15,
  131832. 0,
  131833. 16,
  131834. };
  131835. static long _vq_lengthlist__44c0_s_p8_2[] = {
  131836. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131837. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  131838. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131839. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  131840. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  131841. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  131842. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  131843. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  131844. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  131845. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  131846. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  131847. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  131848. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  131849. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131850. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  131851. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  131852. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  131853. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  131854. 10,
  131855. };
  131856. static float _vq_quantthresh__44c0_s_p8_2[] = {
  131857. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131858. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131859. };
  131860. static long _vq_quantmap__44c0_s_p8_2[] = {
  131861. 15, 13, 11, 9, 7, 5, 3, 1,
  131862. 0, 2, 4, 6, 8, 10, 12, 14,
  131863. 16,
  131864. };
  131865. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  131866. _vq_quantthresh__44c0_s_p8_2,
  131867. _vq_quantmap__44c0_s_p8_2,
  131868. 17,
  131869. 17
  131870. };
  131871. static static_codebook _44c0_s_p8_2 = {
  131872. 2, 289,
  131873. _vq_lengthlist__44c0_s_p8_2,
  131874. 1, -529530880, 1611661312, 5, 0,
  131875. _vq_quantlist__44c0_s_p8_2,
  131876. NULL,
  131877. &_vq_auxt__44c0_s_p8_2,
  131878. NULL,
  131879. 0
  131880. };
  131881. static long _huff_lengthlist__44c0_s_short[] = {
  131882. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  131883. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  131884. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  131885. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  131886. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  131887. 12,
  131888. };
  131889. static static_codebook _huff_book__44c0_s_short = {
  131890. 2, 81,
  131891. _huff_lengthlist__44c0_s_short,
  131892. 0, 0, 0, 0, 0,
  131893. NULL,
  131894. NULL,
  131895. NULL,
  131896. NULL,
  131897. 0
  131898. };
  131899. static long _huff_lengthlist__44c0_sm_long[] = {
  131900. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  131901. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  131902. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  131903. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  131904. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  131905. 13,
  131906. };
  131907. static static_codebook _huff_book__44c0_sm_long = {
  131908. 2, 81,
  131909. _huff_lengthlist__44c0_sm_long,
  131910. 0, 0, 0, 0, 0,
  131911. NULL,
  131912. NULL,
  131913. NULL,
  131914. NULL,
  131915. 0
  131916. };
  131917. static long _vq_quantlist__44c0_sm_p1_0[] = {
  131918. 1,
  131919. 0,
  131920. 2,
  131921. };
  131922. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  131923. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  131924. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131928. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131929. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131933. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131934. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  131969. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131974. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131979. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132014. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132015. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132019. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132020. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  132021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132024. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132025. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  132026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132333. 0,
  132334. };
  132335. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  132336. -0.5, 0.5,
  132337. };
  132338. static long _vq_quantmap__44c0_sm_p1_0[] = {
  132339. 1, 0, 2,
  132340. };
  132341. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  132342. _vq_quantthresh__44c0_sm_p1_0,
  132343. _vq_quantmap__44c0_sm_p1_0,
  132344. 3,
  132345. 3
  132346. };
  132347. static static_codebook _44c0_sm_p1_0 = {
  132348. 8, 6561,
  132349. _vq_lengthlist__44c0_sm_p1_0,
  132350. 1, -535822336, 1611661312, 2, 0,
  132351. _vq_quantlist__44c0_sm_p1_0,
  132352. NULL,
  132353. &_vq_auxt__44c0_sm_p1_0,
  132354. NULL,
  132355. 0
  132356. };
  132357. static long _vq_quantlist__44c0_sm_p2_0[] = {
  132358. 2,
  132359. 1,
  132360. 3,
  132361. 0,
  132362. 4,
  132363. };
  132364. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  132365. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  132367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132368. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  132370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132371. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132404. 0,
  132405. };
  132406. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  132407. -1.5, -0.5, 0.5, 1.5,
  132408. };
  132409. static long _vq_quantmap__44c0_sm_p2_0[] = {
  132410. 3, 1, 0, 2, 4,
  132411. };
  132412. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  132413. _vq_quantthresh__44c0_sm_p2_0,
  132414. _vq_quantmap__44c0_sm_p2_0,
  132415. 5,
  132416. 5
  132417. };
  132418. static static_codebook _44c0_sm_p2_0 = {
  132419. 4, 625,
  132420. _vq_lengthlist__44c0_sm_p2_0,
  132421. 1, -533725184, 1611661312, 3, 0,
  132422. _vq_quantlist__44c0_sm_p2_0,
  132423. NULL,
  132424. &_vq_auxt__44c0_sm_p2_0,
  132425. NULL,
  132426. 0
  132427. };
  132428. static long _vq_quantlist__44c0_sm_p3_0[] = {
  132429. 4,
  132430. 3,
  132431. 5,
  132432. 2,
  132433. 6,
  132434. 1,
  132435. 7,
  132436. 0,
  132437. 8,
  132438. };
  132439. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  132440. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  132441. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  132442. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  132443. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  132444. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132445. 0,
  132446. };
  132447. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  132448. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132449. };
  132450. static long _vq_quantmap__44c0_sm_p3_0[] = {
  132451. 7, 5, 3, 1, 0, 2, 4, 6,
  132452. 8,
  132453. };
  132454. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  132455. _vq_quantthresh__44c0_sm_p3_0,
  132456. _vq_quantmap__44c0_sm_p3_0,
  132457. 9,
  132458. 9
  132459. };
  132460. static static_codebook _44c0_sm_p3_0 = {
  132461. 2, 81,
  132462. _vq_lengthlist__44c0_sm_p3_0,
  132463. 1, -531628032, 1611661312, 4, 0,
  132464. _vq_quantlist__44c0_sm_p3_0,
  132465. NULL,
  132466. &_vq_auxt__44c0_sm_p3_0,
  132467. NULL,
  132468. 0
  132469. };
  132470. static long _vq_quantlist__44c0_sm_p4_0[] = {
  132471. 4,
  132472. 3,
  132473. 5,
  132474. 2,
  132475. 6,
  132476. 1,
  132477. 7,
  132478. 0,
  132479. 8,
  132480. };
  132481. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  132482. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  132483. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  132484. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  132485. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  132486. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  132487. 11,
  132488. };
  132489. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  132490. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132491. };
  132492. static long _vq_quantmap__44c0_sm_p4_0[] = {
  132493. 7, 5, 3, 1, 0, 2, 4, 6,
  132494. 8,
  132495. };
  132496. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  132497. _vq_quantthresh__44c0_sm_p4_0,
  132498. _vq_quantmap__44c0_sm_p4_0,
  132499. 9,
  132500. 9
  132501. };
  132502. static static_codebook _44c0_sm_p4_0 = {
  132503. 2, 81,
  132504. _vq_lengthlist__44c0_sm_p4_0,
  132505. 1, -531628032, 1611661312, 4, 0,
  132506. _vq_quantlist__44c0_sm_p4_0,
  132507. NULL,
  132508. &_vq_auxt__44c0_sm_p4_0,
  132509. NULL,
  132510. 0
  132511. };
  132512. static long _vq_quantlist__44c0_sm_p5_0[] = {
  132513. 8,
  132514. 7,
  132515. 9,
  132516. 6,
  132517. 10,
  132518. 5,
  132519. 11,
  132520. 4,
  132521. 12,
  132522. 3,
  132523. 13,
  132524. 2,
  132525. 14,
  132526. 1,
  132527. 15,
  132528. 0,
  132529. 16,
  132530. };
  132531. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  132532. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  132533. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  132534. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132535. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  132536. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  132537. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  132538. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  132539. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132540. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  132541. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  132542. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132543. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132544. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  132545. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  132546. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  132547. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  132548. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  132549. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132550. 14,
  132551. };
  132552. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  132553. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132554. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132555. };
  132556. static long _vq_quantmap__44c0_sm_p5_0[] = {
  132557. 15, 13, 11, 9, 7, 5, 3, 1,
  132558. 0, 2, 4, 6, 8, 10, 12, 14,
  132559. 16,
  132560. };
  132561. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  132562. _vq_quantthresh__44c0_sm_p5_0,
  132563. _vq_quantmap__44c0_sm_p5_0,
  132564. 17,
  132565. 17
  132566. };
  132567. static static_codebook _44c0_sm_p5_0 = {
  132568. 2, 289,
  132569. _vq_lengthlist__44c0_sm_p5_0,
  132570. 1, -529530880, 1611661312, 5, 0,
  132571. _vq_quantlist__44c0_sm_p5_0,
  132572. NULL,
  132573. &_vq_auxt__44c0_sm_p5_0,
  132574. NULL,
  132575. 0
  132576. };
  132577. static long _vq_quantlist__44c0_sm_p6_0[] = {
  132578. 1,
  132579. 0,
  132580. 2,
  132581. };
  132582. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  132583. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132584. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  132585. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  132586. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  132587. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  132588. 11,
  132589. };
  132590. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  132591. -5.5, 5.5,
  132592. };
  132593. static long _vq_quantmap__44c0_sm_p6_0[] = {
  132594. 1, 0, 2,
  132595. };
  132596. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  132597. _vq_quantthresh__44c0_sm_p6_0,
  132598. _vq_quantmap__44c0_sm_p6_0,
  132599. 3,
  132600. 3
  132601. };
  132602. static static_codebook _44c0_sm_p6_0 = {
  132603. 4, 81,
  132604. _vq_lengthlist__44c0_sm_p6_0,
  132605. 1, -529137664, 1618345984, 2, 0,
  132606. _vq_quantlist__44c0_sm_p6_0,
  132607. NULL,
  132608. &_vq_auxt__44c0_sm_p6_0,
  132609. NULL,
  132610. 0
  132611. };
  132612. static long _vq_quantlist__44c0_sm_p6_1[] = {
  132613. 5,
  132614. 4,
  132615. 6,
  132616. 3,
  132617. 7,
  132618. 2,
  132619. 8,
  132620. 1,
  132621. 9,
  132622. 0,
  132623. 10,
  132624. };
  132625. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  132626. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  132627. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132628. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132629. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  132630. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  132631. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132632. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132633. 10,10,10, 8, 8, 8, 8, 8, 8,
  132634. };
  132635. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  132636. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132637. 3.5, 4.5,
  132638. };
  132639. static long _vq_quantmap__44c0_sm_p6_1[] = {
  132640. 9, 7, 5, 3, 1, 0, 2, 4,
  132641. 6, 8, 10,
  132642. };
  132643. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  132644. _vq_quantthresh__44c0_sm_p6_1,
  132645. _vq_quantmap__44c0_sm_p6_1,
  132646. 11,
  132647. 11
  132648. };
  132649. static static_codebook _44c0_sm_p6_1 = {
  132650. 2, 121,
  132651. _vq_lengthlist__44c0_sm_p6_1,
  132652. 1, -531365888, 1611661312, 4, 0,
  132653. _vq_quantlist__44c0_sm_p6_1,
  132654. NULL,
  132655. &_vq_auxt__44c0_sm_p6_1,
  132656. NULL,
  132657. 0
  132658. };
  132659. static long _vq_quantlist__44c0_sm_p7_0[] = {
  132660. 6,
  132661. 5,
  132662. 7,
  132663. 4,
  132664. 8,
  132665. 3,
  132666. 9,
  132667. 2,
  132668. 10,
  132669. 1,
  132670. 11,
  132671. 0,
  132672. 12,
  132673. };
  132674. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  132675. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  132676. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  132677. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132678. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132679. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  132680. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  132681. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  132682. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132683. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132684. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  132685. 0,12,12,11,11,13,12,14,14,
  132686. };
  132687. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  132688. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132689. 12.5, 17.5, 22.5, 27.5,
  132690. };
  132691. static long _vq_quantmap__44c0_sm_p7_0[] = {
  132692. 11, 9, 7, 5, 3, 1, 0, 2,
  132693. 4, 6, 8, 10, 12,
  132694. };
  132695. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  132696. _vq_quantthresh__44c0_sm_p7_0,
  132697. _vq_quantmap__44c0_sm_p7_0,
  132698. 13,
  132699. 13
  132700. };
  132701. static static_codebook _44c0_sm_p7_0 = {
  132702. 2, 169,
  132703. _vq_lengthlist__44c0_sm_p7_0,
  132704. 1, -526516224, 1616117760, 4, 0,
  132705. _vq_quantlist__44c0_sm_p7_0,
  132706. NULL,
  132707. &_vq_auxt__44c0_sm_p7_0,
  132708. NULL,
  132709. 0
  132710. };
  132711. static long _vq_quantlist__44c0_sm_p7_1[] = {
  132712. 2,
  132713. 1,
  132714. 3,
  132715. 0,
  132716. 4,
  132717. };
  132718. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  132719. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  132720. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132721. };
  132722. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  132723. -1.5, -0.5, 0.5, 1.5,
  132724. };
  132725. static long _vq_quantmap__44c0_sm_p7_1[] = {
  132726. 3, 1, 0, 2, 4,
  132727. };
  132728. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  132729. _vq_quantthresh__44c0_sm_p7_1,
  132730. _vq_quantmap__44c0_sm_p7_1,
  132731. 5,
  132732. 5
  132733. };
  132734. static static_codebook _44c0_sm_p7_1 = {
  132735. 2, 25,
  132736. _vq_lengthlist__44c0_sm_p7_1,
  132737. 1, -533725184, 1611661312, 3, 0,
  132738. _vq_quantlist__44c0_sm_p7_1,
  132739. NULL,
  132740. &_vq_auxt__44c0_sm_p7_1,
  132741. NULL,
  132742. 0
  132743. };
  132744. static long _vq_quantlist__44c0_sm_p8_0[] = {
  132745. 4,
  132746. 3,
  132747. 5,
  132748. 2,
  132749. 6,
  132750. 1,
  132751. 7,
  132752. 0,
  132753. 8,
  132754. };
  132755. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  132756. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  132757. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  132758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132759. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132760. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132761. 12,
  132762. };
  132763. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  132764. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  132765. };
  132766. static long _vq_quantmap__44c0_sm_p8_0[] = {
  132767. 7, 5, 3, 1, 0, 2, 4, 6,
  132768. 8,
  132769. };
  132770. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  132771. _vq_quantthresh__44c0_sm_p8_0,
  132772. _vq_quantmap__44c0_sm_p8_0,
  132773. 9,
  132774. 9
  132775. };
  132776. static static_codebook _44c0_sm_p8_0 = {
  132777. 2, 81,
  132778. _vq_lengthlist__44c0_sm_p8_0,
  132779. 1, -516186112, 1627103232, 4, 0,
  132780. _vq_quantlist__44c0_sm_p8_0,
  132781. NULL,
  132782. &_vq_auxt__44c0_sm_p8_0,
  132783. NULL,
  132784. 0
  132785. };
  132786. static long _vq_quantlist__44c0_sm_p8_1[] = {
  132787. 6,
  132788. 5,
  132789. 7,
  132790. 4,
  132791. 8,
  132792. 3,
  132793. 9,
  132794. 2,
  132795. 10,
  132796. 1,
  132797. 11,
  132798. 0,
  132799. 12,
  132800. };
  132801. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  132802. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  132803. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  132804. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  132805. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  132806. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  132807. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  132808. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  132809. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  132810. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  132811. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  132812. 20,13,13,12,12,16,13,15,13,
  132813. };
  132814. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  132815. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132816. 42.5, 59.5, 76.5, 93.5,
  132817. };
  132818. static long _vq_quantmap__44c0_sm_p8_1[] = {
  132819. 11, 9, 7, 5, 3, 1, 0, 2,
  132820. 4, 6, 8, 10, 12,
  132821. };
  132822. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  132823. _vq_quantthresh__44c0_sm_p8_1,
  132824. _vq_quantmap__44c0_sm_p8_1,
  132825. 13,
  132826. 13
  132827. };
  132828. static static_codebook _44c0_sm_p8_1 = {
  132829. 2, 169,
  132830. _vq_lengthlist__44c0_sm_p8_1,
  132831. 1, -522616832, 1620115456, 4, 0,
  132832. _vq_quantlist__44c0_sm_p8_1,
  132833. NULL,
  132834. &_vq_auxt__44c0_sm_p8_1,
  132835. NULL,
  132836. 0
  132837. };
  132838. static long _vq_quantlist__44c0_sm_p8_2[] = {
  132839. 8,
  132840. 7,
  132841. 9,
  132842. 6,
  132843. 10,
  132844. 5,
  132845. 11,
  132846. 4,
  132847. 12,
  132848. 3,
  132849. 13,
  132850. 2,
  132851. 14,
  132852. 1,
  132853. 15,
  132854. 0,
  132855. 16,
  132856. };
  132857. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  132858. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132859. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  132860. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  132861. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  132862. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132863. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  132864. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  132865. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  132866. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  132867. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  132868. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  132869. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  132870. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  132871. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  132872. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  132873. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132874. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  132875. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  132876. 9,
  132877. };
  132878. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  132879. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132880. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132881. };
  132882. static long _vq_quantmap__44c0_sm_p8_2[] = {
  132883. 15, 13, 11, 9, 7, 5, 3, 1,
  132884. 0, 2, 4, 6, 8, 10, 12, 14,
  132885. 16,
  132886. };
  132887. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  132888. _vq_quantthresh__44c0_sm_p8_2,
  132889. _vq_quantmap__44c0_sm_p8_2,
  132890. 17,
  132891. 17
  132892. };
  132893. static static_codebook _44c0_sm_p8_2 = {
  132894. 2, 289,
  132895. _vq_lengthlist__44c0_sm_p8_2,
  132896. 1, -529530880, 1611661312, 5, 0,
  132897. _vq_quantlist__44c0_sm_p8_2,
  132898. NULL,
  132899. &_vq_auxt__44c0_sm_p8_2,
  132900. NULL,
  132901. 0
  132902. };
  132903. static long _huff_lengthlist__44c0_sm_short[] = {
  132904. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  132905. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  132906. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  132907. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  132908. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  132909. 12,
  132910. };
  132911. static static_codebook _huff_book__44c0_sm_short = {
  132912. 2, 81,
  132913. _huff_lengthlist__44c0_sm_short,
  132914. 0, 0, 0, 0, 0,
  132915. NULL,
  132916. NULL,
  132917. NULL,
  132918. NULL,
  132919. 0
  132920. };
  132921. static long _huff_lengthlist__44c1_s_long[] = {
  132922. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  132923. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  132924. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  132925. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  132926. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  132927. 11,
  132928. };
  132929. static static_codebook _huff_book__44c1_s_long = {
  132930. 2, 81,
  132931. _huff_lengthlist__44c1_s_long,
  132932. 0, 0, 0, 0, 0,
  132933. NULL,
  132934. NULL,
  132935. NULL,
  132936. NULL,
  132937. 0
  132938. };
  132939. static long _vq_quantlist__44c1_s_p1_0[] = {
  132940. 1,
  132941. 0,
  132942. 2,
  132943. };
  132944. static long _vq_lengthlist__44c1_s_p1_0[] = {
  132945. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  132946. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132950. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  132951. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132955. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132956. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  132991. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  132996. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  132997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  133001. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  133002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133036. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133037. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133041. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  133042. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  133043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133046. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  133047. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133355. 0,
  133356. };
  133357. static float _vq_quantthresh__44c1_s_p1_0[] = {
  133358. -0.5, 0.5,
  133359. };
  133360. static long _vq_quantmap__44c1_s_p1_0[] = {
  133361. 1, 0, 2,
  133362. };
  133363. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  133364. _vq_quantthresh__44c1_s_p1_0,
  133365. _vq_quantmap__44c1_s_p1_0,
  133366. 3,
  133367. 3
  133368. };
  133369. static static_codebook _44c1_s_p1_0 = {
  133370. 8, 6561,
  133371. _vq_lengthlist__44c1_s_p1_0,
  133372. 1, -535822336, 1611661312, 2, 0,
  133373. _vq_quantlist__44c1_s_p1_0,
  133374. NULL,
  133375. &_vq_auxt__44c1_s_p1_0,
  133376. NULL,
  133377. 0
  133378. };
  133379. static long _vq_quantlist__44c1_s_p2_0[] = {
  133380. 2,
  133381. 1,
  133382. 3,
  133383. 0,
  133384. 4,
  133385. };
  133386. static long _vq_lengthlist__44c1_s_p2_0[] = {
  133387. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  133389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133390. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  133392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133393. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  133394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133426. 0,
  133427. };
  133428. static float _vq_quantthresh__44c1_s_p2_0[] = {
  133429. -1.5, -0.5, 0.5, 1.5,
  133430. };
  133431. static long _vq_quantmap__44c1_s_p2_0[] = {
  133432. 3, 1, 0, 2, 4,
  133433. };
  133434. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  133435. _vq_quantthresh__44c1_s_p2_0,
  133436. _vq_quantmap__44c1_s_p2_0,
  133437. 5,
  133438. 5
  133439. };
  133440. static static_codebook _44c1_s_p2_0 = {
  133441. 4, 625,
  133442. _vq_lengthlist__44c1_s_p2_0,
  133443. 1, -533725184, 1611661312, 3, 0,
  133444. _vq_quantlist__44c1_s_p2_0,
  133445. NULL,
  133446. &_vq_auxt__44c1_s_p2_0,
  133447. NULL,
  133448. 0
  133449. };
  133450. static long _vq_quantlist__44c1_s_p3_0[] = {
  133451. 4,
  133452. 3,
  133453. 5,
  133454. 2,
  133455. 6,
  133456. 1,
  133457. 7,
  133458. 0,
  133459. 8,
  133460. };
  133461. static long _vq_lengthlist__44c1_s_p3_0[] = {
  133462. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  133463. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  133464. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133465. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133466. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133467. 0,
  133468. };
  133469. static float _vq_quantthresh__44c1_s_p3_0[] = {
  133470. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133471. };
  133472. static long _vq_quantmap__44c1_s_p3_0[] = {
  133473. 7, 5, 3, 1, 0, 2, 4, 6,
  133474. 8,
  133475. };
  133476. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  133477. _vq_quantthresh__44c1_s_p3_0,
  133478. _vq_quantmap__44c1_s_p3_0,
  133479. 9,
  133480. 9
  133481. };
  133482. static static_codebook _44c1_s_p3_0 = {
  133483. 2, 81,
  133484. _vq_lengthlist__44c1_s_p3_0,
  133485. 1, -531628032, 1611661312, 4, 0,
  133486. _vq_quantlist__44c1_s_p3_0,
  133487. NULL,
  133488. &_vq_auxt__44c1_s_p3_0,
  133489. NULL,
  133490. 0
  133491. };
  133492. static long _vq_quantlist__44c1_s_p4_0[] = {
  133493. 4,
  133494. 3,
  133495. 5,
  133496. 2,
  133497. 6,
  133498. 1,
  133499. 7,
  133500. 0,
  133501. 8,
  133502. };
  133503. static long _vq_lengthlist__44c1_s_p4_0[] = {
  133504. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  133505. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  133506. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  133507. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  133508. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133509. 11,
  133510. };
  133511. static float _vq_quantthresh__44c1_s_p4_0[] = {
  133512. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133513. };
  133514. static long _vq_quantmap__44c1_s_p4_0[] = {
  133515. 7, 5, 3, 1, 0, 2, 4, 6,
  133516. 8,
  133517. };
  133518. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  133519. _vq_quantthresh__44c1_s_p4_0,
  133520. _vq_quantmap__44c1_s_p4_0,
  133521. 9,
  133522. 9
  133523. };
  133524. static static_codebook _44c1_s_p4_0 = {
  133525. 2, 81,
  133526. _vq_lengthlist__44c1_s_p4_0,
  133527. 1, -531628032, 1611661312, 4, 0,
  133528. _vq_quantlist__44c1_s_p4_0,
  133529. NULL,
  133530. &_vq_auxt__44c1_s_p4_0,
  133531. NULL,
  133532. 0
  133533. };
  133534. static long _vq_quantlist__44c1_s_p5_0[] = {
  133535. 8,
  133536. 7,
  133537. 9,
  133538. 6,
  133539. 10,
  133540. 5,
  133541. 11,
  133542. 4,
  133543. 12,
  133544. 3,
  133545. 13,
  133546. 2,
  133547. 14,
  133548. 1,
  133549. 15,
  133550. 0,
  133551. 16,
  133552. };
  133553. static long _vq_lengthlist__44c1_s_p5_0[] = {
  133554. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133555. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  133556. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133557. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133558. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133559. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  133560. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  133561. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133562. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133563. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  133564. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133565. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133566. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  133567. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  133568. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  133569. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  133570. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  133571. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133572. 14,
  133573. };
  133574. static float _vq_quantthresh__44c1_s_p5_0[] = {
  133575. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133576. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133577. };
  133578. static long _vq_quantmap__44c1_s_p5_0[] = {
  133579. 15, 13, 11, 9, 7, 5, 3, 1,
  133580. 0, 2, 4, 6, 8, 10, 12, 14,
  133581. 16,
  133582. };
  133583. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  133584. _vq_quantthresh__44c1_s_p5_0,
  133585. _vq_quantmap__44c1_s_p5_0,
  133586. 17,
  133587. 17
  133588. };
  133589. static static_codebook _44c1_s_p5_0 = {
  133590. 2, 289,
  133591. _vq_lengthlist__44c1_s_p5_0,
  133592. 1, -529530880, 1611661312, 5, 0,
  133593. _vq_quantlist__44c1_s_p5_0,
  133594. NULL,
  133595. &_vq_auxt__44c1_s_p5_0,
  133596. NULL,
  133597. 0
  133598. };
  133599. static long _vq_quantlist__44c1_s_p6_0[] = {
  133600. 1,
  133601. 0,
  133602. 2,
  133603. };
  133604. static long _vq_lengthlist__44c1_s_p6_0[] = {
  133605. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133606. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  133607. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  133608. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  133609. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  133610. 11,
  133611. };
  133612. static float _vq_quantthresh__44c1_s_p6_0[] = {
  133613. -5.5, 5.5,
  133614. };
  133615. static long _vq_quantmap__44c1_s_p6_0[] = {
  133616. 1, 0, 2,
  133617. };
  133618. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  133619. _vq_quantthresh__44c1_s_p6_0,
  133620. _vq_quantmap__44c1_s_p6_0,
  133621. 3,
  133622. 3
  133623. };
  133624. static static_codebook _44c1_s_p6_0 = {
  133625. 4, 81,
  133626. _vq_lengthlist__44c1_s_p6_0,
  133627. 1, -529137664, 1618345984, 2, 0,
  133628. _vq_quantlist__44c1_s_p6_0,
  133629. NULL,
  133630. &_vq_auxt__44c1_s_p6_0,
  133631. NULL,
  133632. 0
  133633. };
  133634. static long _vq_quantlist__44c1_s_p6_1[] = {
  133635. 5,
  133636. 4,
  133637. 6,
  133638. 3,
  133639. 7,
  133640. 2,
  133641. 8,
  133642. 1,
  133643. 9,
  133644. 0,
  133645. 10,
  133646. };
  133647. static long _vq_lengthlist__44c1_s_p6_1[] = {
  133648. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  133649. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  133650. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133651. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  133652. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  133653. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133654. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133655. 10,10,10, 8, 8, 8, 8, 8, 8,
  133656. };
  133657. static float _vq_quantthresh__44c1_s_p6_1[] = {
  133658. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133659. 3.5, 4.5,
  133660. };
  133661. static long _vq_quantmap__44c1_s_p6_1[] = {
  133662. 9, 7, 5, 3, 1, 0, 2, 4,
  133663. 6, 8, 10,
  133664. };
  133665. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  133666. _vq_quantthresh__44c1_s_p6_1,
  133667. _vq_quantmap__44c1_s_p6_1,
  133668. 11,
  133669. 11
  133670. };
  133671. static static_codebook _44c1_s_p6_1 = {
  133672. 2, 121,
  133673. _vq_lengthlist__44c1_s_p6_1,
  133674. 1, -531365888, 1611661312, 4, 0,
  133675. _vq_quantlist__44c1_s_p6_1,
  133676. NULL,
  133677. &_vq_auxt__44c1_s_p6_1,
  133678. NULL,
  133679. 0
  133680. };
  133681. static long _vq_quantlist__44c1_s_p7_0[] = {
  133682. 6,
  133683. 5,
  133684. 7,
  133685. 4,
  133686. 8,
  133687. 3,
  133688. 9,
  133689. 2,
  133690. 10,
  133691. 1,
  133692. 11,
  133693. 0,
  133694. 12,
  133695. };
  133696. static long _vq_lengthlist__44c1_s_p7_0[] = {
  133697. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  133698. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  133699. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133700. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133701. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  133702. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  133703. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  133704. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133705. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133706. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  133707. 0,12,11,11,11,13,10,14,13,
  133708. };
  133709. static float _vq_quantthresh__44c1_s_p7_0[] = {
  133710. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133711. 12.5, 17.5, 22.5, 27.5,
  133712. };
  133713. static long _vq_quantmap__44c1_s_p7_0[] = {
  133714. 11, 9, 7, 5, 3, 1, 0, 2,
  133715. 4, 6, 8, 10, 12,
  133716. };
  133717. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  133718. _vq_quantthresh__44c1_s_p7_0,
  133719. _vq_quantmap__44c1_s_p7_0,
  133720. 13,
  133721. 13
  133722. };
  133723. static static_codebook _44c1_s_p7_0 = {
  133724. 2, 169,
  133725. _vq_lengthlist__44c1_s_p7_0,
  133726. 1, -526516224, 1616117760, 4, 0,
  133727. _vq_quantlist__44c1_s_p7_0,
  133728. NULL,
  133729. &_vq_auxt__44c1_s_p7_0,
  133730. NULL,
  133731. 0
  133732. };
  133733. static long _vq_quantlist__44c1_s_p7_1[] = {
  133734. 2,
  133735. 1,
  133736. 3,
  133737. 0,
  133738. 4,
  133739. };
  133740. static long _vq_lengthlist__44c1_s_p7_1[] = {
  133741. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  133742. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133743. };
  133744. static float _vq_quantthresh__44c1_s_p7_1[] = {
  133745. -1.5, -0.5, 0.5, 1.5,
  133746. };
  133747. static long _vq_quantmap__44c1_s_p7_1[] = {
  133748. 3, 1, 0, 2, 4,
  133749. };
  133750. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  133751. _vq_quantthresh__44c1_s_p7_1,
  133752. _vq_quantmap__44c1_s_p7_1,
  133753. 5,
  133754. 5
  133755. };
  133756. static static_codebook _44c1_s_p7_1 = {
  133757. 2, 25,
  133758. _vq_lengthlist__44c1_s_p7_1,
  133759. 1, -533725184, 1611661312, 3, 0,
  133760. _vq_quantlist__44c1_s_p7_1,
  133761. NULL,
  133762. &_vq_auxt__44c1_s_p7_1,
  133763. NULL,
  133764. 0
  133765. };
  133766. static long _vq_quantlist__44c1_s_p8_0[] = {
  133767. 6,
  133768. 5,
  133769. 7,
  133770. 4,
  133771. 8,
  133772. 3,
  133773. 9,
  133774. 2,
  133775. 10,
  133776. 1,
  133777. 11,
  133778. 0,
  133779. 12,
  133780. };
  133781. static long _vq_lengthlist__44c1_s_p8_0[] = {
  133782. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  133783. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  133784. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133785. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133786. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133790. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133792. 10,10,10,10,10,10,10,10,10,
  133793. };
  133794. static float _vq_quantthresh__44c1_s_p8_0[] = {
  133795. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  133796. 552.5, 773.5, 994.5, 1215.5,
  133797. };
  133798. static long _vq_quantmap__44c1_s_p8_0[] = {
  133799. 11, 9, 7, 5, 3, 1, 0, 2,
  133800. 4, 6, 8, 10, 12,
  133801. };
  133802. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  133803. _vq_quantthresh__44c1_s_p8_0,
  133804. _vq_quantmap__44c1_s_p8_0,
  133805. 13,
  133806. 13
  133807. };
  133808. static static_codebook _44c1_s_p8_0 = {
  133809. 2, 169,
  133810. _vq_lengthlist__44c1_s_p8_0,
  133811. 1, -514541568, 1627103232, 4, 0,
  133812. _vq_quantlist__44c1_s_p8_0,
  133813. NULL,
  133814. &_vq_auxt__44c1_s_p8_0,
  133815. NULL,
  133816. 0
  133817. };
  133818. static long _vq_quantlist__44c1_s_p8_1[] = {
  133819. 6,
  133820. 5,
  133821. 7,
  133822. 4,
  133823. 8,
  133824. 3,
  133825. 9,
  133826. 2,
  133827. 10,
  133828. 1,
  133829. 11,
  133830. 0,
  133831. 12,
  133832. };
  133833. static long _vq_lengthlist__44c1_s_p8_1[] = {
  133834. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133835. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  133836. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  133837. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  133838. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  133839. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  133840. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  133841. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  133842. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  133843. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  133844. 16,13,12,12,11,14,12,15,13,
  133845. };
  133846. static float _vq_quantthresh__44c1_s_p8_1[] = {
  133847. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133848. 42.5, 59.5, 76.5, 93.5,
  133849. };
  133850. static long _vq_quantmap__44c1_s_p8_1[] = {
  133851. 11, 9, 7, 5, 3, 1, 0, 2,
  133852. 4, 6, 8, 10, 12,
  133853. };
  133854. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  133855. _vq_quantthresh__44c1_s_p8_1,
  133856. _vq_quantmap__44c1_s_p8_1,
  133857. 13,
  133858. 13
  133859. };
  133860. static static_codebook _44c1_s_p8_1 = {
  133861. 2, 169,
  133862. _vq_lengthlist__44c1_s_p8_1,
  133863. 1, -522616832, 1620115456, 4, 0,
  133864. _vq_quantlist__44c1_s_p8_1,
  133865. NULL,
  133866. &_vq_auxt__44c1_s_p8_1,
  133867. NULL,
  133868. 0
  133869. };
  133870. static long _vq_quantlist__44c1_s_p8_2[] = {
  133871. 8,
  133872. 7,
  133873. 9,
  133874. 6,
  133875. 10,
  133876. 5,
  133877. 11,
  133878. 4,
  133879. 12,
  133880. 3,
  133881. 13,
  133882. 2,
  133883. 14,
  133884. 1,
  133885. 15,
  133886. 0,
  133887. 16,
  133888. };
  133889. static long _vq_lengthlist__44c1_s_p8_2[] = {
  133890. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133891. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133892. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  133893. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133894. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133895. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133896. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133897. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  133898. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  133899. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  133900. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  133901. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  133902. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  133903. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  133904. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133905. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  133906. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  133907. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  133908. 9,
  133909. };
  133910. static float _vq_quantthresh__44c1_s_p8_2[] = {
  133911. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133912. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133913. };
  133914. static long _vq_quantmap__44c1_s_p8_2[] = {
  133915. 15, 13, 11, 9, 7, 5, 3, 1,
  133916. 0, 2, 4, 6, 8, 10, 12, 14,
  133917. 16,
  133918. };
  133919. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  133920. _vq_quantthresh__44c1_s_p8_2,
  133921. _vq_quantmap__44c1_s_p8_2,
  133922. 17,
  133923. 17
  133924. };
  133925. static static_codebook _44c1_s_p8_2 = {
  133926. 2, 289,
  133927. _vq_lengthlist__44c1_s_p8_2,
  133928. 1, -529530880, 1611661312, 5, 0,
  133929. _vq_quantlist__44c1_s_p8_2,
  133930. NULL,
  133931. &_vq_auxt__44c1_s_p8_2,
  133932. NULL,
  133933. 0
  133934. };
  133935. static long _huff_lengthlist__44c1_s_short[] = {
  133936. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  133937. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  133938. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  133939. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  133940. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  133941. 11,
  133942. };
  133943. static static_codebook _huff_book__44c1_s_short = {
  133944. 2, 81,
  133945. _huff_lengthlist__44c1_s_short,
  133946. 0, 0, 0, 0, 0,
  133947. NULL,
  133948. NULL,
  133949. NULL,
  133950. NULL,
  133951. 0
  133952. };
  133953. static long _huff_lengthlist__44c1_sm_long[] = {
  133954. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  133955. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  133956. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  133957. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  133958. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  133959. 11,
  133960. };
  133961. static static_codebook _huff_book__44c1_sm_long = {
  133962. 2, 81,
  133963. _huff_lengthlist__44c1_sm_long,
  133964. 0, 0, 0, 0, 0,
  133965. NULL,
  133966. NULL,
  133967. NULL,
  133968. NULL,
  133969. 0
  133970. };
  133971. static long _vq_quantlist__44c1_sm_p1_0[] = {
  133972. 1,
  133973. 0,
  133974. 2,
  133975. };
  133976. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  133977. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133978. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133982. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133983. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133987. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  133988. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  134023. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134028. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134033. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134068. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134069. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134073. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134074. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  134075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134078. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134079. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  134080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134387. 0,
  134388. };
  134389. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  134390. -0.5, 0.5,
  134391. };
  134392. static long _vq_quantmap__44c1_sm_p1_0[] = {
  134393. 1, 0, 2,
  134394. };
  134395. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  134396. _vq_quantthresh__44c1_sm_p1_0,
  134397. _vq_quantmap__44c1_sm_p1_0,
  134398. 3,
  134399. 3
  134400. };
  134401. static static_codebook _44c1_sm_p1_0 = {
  134402. 8, 6561,
  134403. _vq_lengthlist__44c1_sm_p1_0,
  134404. 1, -535822336, 1611661312, 2, 0,
  134405. _vq_quantlist__44c1_sm_p1_0,
  134406. NULL,
  134407. &_vq_auxt__44c1_sm_p1_0,
  134408. NULL,
  134409. 0
  134410. };
  134411. static long _vq_quantlist__44c1_sm_p2_0[] = {
  134412. 2,
  134413. 1,
  134414. 3,
  134415. 0,
  134416. 4,
  134417. };
  134418. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  134419. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  134421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134422. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  134424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134425. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134458. 0,
  134459. };
  134460. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  134461. -1.5, -0.5, 0.5, 1.5,
  134462. };
  134463. static long _vq_quantmap__44c1_sm_p2_0[] = {
  134464. 3, 1, 0, 2, 4,
  134465. };
  134466. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  134467. _vq_quantthresh__44c1_sm_p2_0,
  134468. _vq_quantmap__44c1_sm_p2_0,
  134469. 5,
  134470. 5
  134471. };
  134472. static static_codebook _44c1_sm_p2_0 = {
  134473. 4, 625,
  134474. _vq_lengthlist__44c1_sm_p2_0,
  134475. 1, -533725184, 1611661312, 3, 0,
  134476. _vq_quantlist__44c1_sm_p2_0,
  134477. NULL,
  134478. &_vq_auxt__44c1_sm_p2_0,
  134479. NULL,
  134480. 0
  134481. };
  134482. static long _vq_quantlist__44c1_sm_p3_0[] = {
  134483. 4,
  134484. 3,
  134485. 5,
  134486. 2,
  134487. 6,
  134488. 1,
  134489. 7,
  134490. 0,
  134491. 8,
  134492. };
  134493. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  134494. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  134495. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  134496. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134497. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134498. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134499. 0,
  134500. };
  134501. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  134502. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134503. };
  134504. static long _vq_quantmap__44c1_sm_p3_0[] = {
  134505. 7, 5, 3, 1, 0, 2, 4, 6,
  134506. 8,
  134507. };
  134508. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  134509. _vq_quantthresh__44c1_sm_p3_0,
  134510. _vq_quantmap__44c1_sm_p3_0,
  134511. 9,
  134512. 9
  134513. };
  134514. static static_codebook _44c1_sm_p3_0 = {
  134515. 2, 81,
  134516. _vq_lengthlist__44c1_sm_p3_0,
  134517. 1, -531628032, 1611661312, 4, 0,
  134518. _vq_quantlist__44c1_sm_p3_0,
  134519. NULL,
  134520. &_vq_auxt__44c1_sm_p3_0,
  134521. NULL,
  134522. 0
  134523. };
  134524. static long _vq_quantlist__44c1_sm_p4_0[] = {
  134525. 4,
  134526. 3,
  134527. 5,
  134528. 2,
  134529. 6,
  134530. 1,
  134531. 7,
  134532. 0,
  134533. 8,
  134534. };
  134535. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  134536. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  134537. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  134538. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  134539. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  134540. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134541. 11,
  134542. };
  134543. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  134544. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134545. };
  134546. static long _vq_quantmap__44c1_sm_p4_0[] = {
  134547. 7, 5, 3, 1, 0, 2, 4, 6,
  134548. 8,
  134549. };
  134550. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  134551. _vq_quantthresh__44c1_sm_p4_0,
  134552. _vq_quantmap__44c1_sm_p4_0,
  134553. 9,
  134554. 9
  134555. };
  134556. static static_codebook _44c1_sm_p4_0 = {
  134557. 2, 81,
  134558. _vq_lengthlist__44c1_sm_p4_0,
  134559. 1, -531628032, 1611661312, 4, 0,
  134560. _vq_quantlist__44c1_sm_p4_0,
  134561. NULL,
  134562. &_vq_auxt__44c1_sm_p4_0,
  134563. NULL,
  134564. 0
  134565. };
  134566. static long _vq_quantlist__44c1_sm_p5_0[] = {
  134567. 8,
  134568. 7,
  134569. 9,
  134570. 6,
  134571. 10,
  134572. 5,
  134573. 11,
  134574. 4,
  134575. 12,
  134576. 3,
  134577. 13,
  134578. 2,
  134579. 14,
  134580. 1,
  134581. 15,
  134582. 0,
  134583. 16,
  134584. };
  134585. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  134586. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134587. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134588. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  134589. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134590. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134591. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  134592. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  134593. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134594. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134595. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  134596. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134597. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134598. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  134599. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134600. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  134601. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  134602. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  134603. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134604. 14,
  134605. };
  134606. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  134607. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134608. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134609. };
  134610. static long _vq_quantmap__44c1_sm_p5_0[] = {
  134611. 15, 13, 11, 9, 7, 5, 3, 1,
  134612. 0, 2, 4, 6, 8, 10, 12, 14,
  134613. 16,
  134614. };
  134615. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  134616. _vq_quantthresh__44c1_sm_p5_0,
  134617. _vq_quantmap__44c1_sm_p5_0,
  134618. 17,
  134619. 17
  134620. };
  134621. static static_codebook _44c1_sm_p5_0 = {
  134622. 2, 289,
  134623. _vq_lengthlist__44c1_sm_p5_0,
  134624. 1, -529530880, 1611661312, 5, 0,
  134625. _vq_quantlist__44c1_sm_p5_0,
  134626. NULL,
  134627. &_vq_auxt__44c1_sm_p5_0,
  134628. NULL,
  134629. 0
  134630. };
  134631. static long _vq_quantlist__44c1_sm_p6_0[] = {
  134632. 1,
  134633. 0,
  134634. 2,
  134635. };
  134636. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  134637. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134638. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  134639. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  134640. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  134641. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  134642. 11,
  134643. };
  134644. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  134645. -5.5, 5.5,
  134646. };
  134647. static long _vq_quantmap__44c1_sm_p6_0[] = {
  134648. 1, 0, 2,
  134649. };
  134650. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  134651. _vq_quantthresh__44c1_sm_p6_0,
  134652. _vq_quantmap__44c1_sm_p6_0,
  134653. 3,
  134654. 3
  134655. };
  134656. static static_codebook _44c1_sm_p6_0 = {
  134657. 4, 81,
  134658. _vq_lengthlist__44c1_sm_p6_0,
  134659. 1, -529137664, 1618345984, 2, 0,
  134660. _vq_quantlist__44c1_sm_p6_0,
  134661. NULL,
  134662. &_vq_auxt__44c1_sm_p6_0,
  134663. NULL,
  134664. 0
  134665. };
  134666. static long _vq_quantlist__44c1_sm_p6_1[] = {
  134667. 5,
  134668. 4,
  134669. 6,
  134670. 3,
  134671. 7,
  134672. 2,
  134673. 8,
  134674. 1,
  134675. 9,
  134676. 0,
  134677. 10,
  134678. };
  134679. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  134680. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  134681. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134682. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  134683. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  134684. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  134685. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  134686. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134687. 10,10,10, 8, 8, 8, 8, 8, 8,
  134688. };
  134689. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  134690. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134691. 3.5, 4.5,
  134692. };
  134693. static long _vq_quantmap__44c1_sm_p6_1[] = {
  134694. 9, 7, 5, 3, 1, 0, 2, 4,
  134695. 6, 8, 10,
  134696. };
  134697. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  134698. _vq_quantthresh__44c1_sm_p6_1,
  134699. _vq_quantmap__44c1_sm_p6_1,
  134700. 11,
  134701. 11
  134702. };
  134703. static static_codebook _44c1_sm_p6_1 = {
  134704. 2, 121,
  134705. _vq_lengthlist__44c1_sm_p6_1,
  134706. 1, -531365888, 1611661312, 4, 0,
  134707. _vq_quantlist__44c1_sm_p6_1,
  134708. NULL,
  134709. &_vq_auxt__44c1_sm_p6_1,
  134710. NULL,
  134711. 0
  134712. };
  134713. static long _vq_quantlist__44c1_sm_p7_0[] = {
  134714. 6,
  134715. 5,
  134716. 7,
  134717. 4,
  134718. 8,
  134719. 3,
  134720. 9,
  134721. 2,
  134722. 10,
  134723. 1,
  134724. 11,
  134725. 0,
  134726. 12,
  134727. };
  134728. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  134729. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  134730. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  134731. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134732. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134733. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  134734. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  134735. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  134736. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134737. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134738. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  134739. 0,12,12,11,11,13,12,14,13,
  134740. };
  134741. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  134742. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134743. 12.5, 17.5, 22.5, 27.5,
  134744. };
  134745. static long _vq_quantmap__44c1_sm_p7_0[] = {
  134746. 11, 9, 7, 5, 3, 1, 0, 2,
  134747. 4, 6, 8, 10, 12,
  134748. };
  134749. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  134750. _vq_quantthresh__44c1_sm_p7_0,
  134751. _vq_quantmap__44c1_sm_p7_0,
  134752. 13,
  134753. 13
  134754. };
  134755. static static_codebook _44c1_sm_p7_0 = {
  134756. 2, 169,
  134757. _vq_lengthlist__44c1_sm_p7_0,
  134758. 1, -526516224, 1616117760, 4, 0,
  134759. _vq_quantlist__44c1_sm_p7_0,
  134760. NULL,
  134761. &_vq_auxt__44c1_sm_p7_0,
  134762. NULL,
  134763. 0
  134764. };
  134765. static long _vq_quantlist__44c1_sm_p7_1[] = {
  134766. 2,
  134767. 1,
  134768. 3,
  134769. 0,
  134770. 4,
  134771. };
  134772. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  134773. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  134774. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134775. };
  134776. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  134777. -1.5, -0.5, 0.5, 1.5,
  134778. };
  134779. static long _vq_quantmap__44c1_sm_p7_1[] = {
  134780. 3, 1, 0, 2, 4,
  134781. };
  134782. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  134783. _vq_quantthresh__44c1_sm_p7_1,
  134784. _vq_quantmap__44c1_sm_p7_1,
  134785. 5,
  134786. 5
  134787. };
  134788. static static_codebook _44c1_sm_p7_1 = {
  134789. 2, 25,
  134790. _vq_lengthlist__44c1_sm_p7_1,
  134791. 1, -533725184, 1611661312, 3, 0,
  134792. _vq_quantlist__44c1_sm_p7_1,
  134793. NULL,
  134794. &_vq_auxt__44c1_sm_p7_1,
  134795. NULL,
  134796. 0
  134797. };
  134798. static long _vq_quantlist__44c1_sm_p8_0[] = {
  134799. 6,
  134800. 5,
  134801. 7,
  134802. 4,
  134803. 8,
  134804. 3,
  134805. 9,
  134806. 2,
  134807. 10,
  134808. 1,
  134809. 11,
  134810. 0,
  134811. 12,
  134812. };
  134813. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  134814. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  134815. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  134816. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134817. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134818. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134819. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134820. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134821. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134822. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134823. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134824. 13,13,13,13,13,13,13,13,13,
  134825. };
  134826. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  134827. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  134828. 552.5, 773.5, 994.5, 1215.5,
  134829. };
  134830. static long _vq_quantmap__44c1_sm_p8_0[] = {
  134831. 11, 9, 7, 5, 3, 1, 0, 2,
  134832. 4, 6, 8, 10, 12,
  134833. };
  134834. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  134835. _vq_quantthresh__44c1_sm_p8_0,
  134836. _vq_quantmap__44c1_sm_p8_0,
  134837. 13,
  134838. 13
  134839. };
  134840. static static_codebook _44c1_sm_p8_0 = {
  134841. 2, 169,
  134842. _vq_lengthlist__44c1_sm_p8_0,
  134843. 1, -514541568, 1627103232, 4, 0,
  134844. _vq_quantlist__44c1_sm_p8_0,
  134845. NULL,
  134846. &_vq_auxt__44c1_sm_p8_0,
  134847. NULL,
  134848. 0
  134849. };
  134850. static long _vq_quantlist__44c1_sm_p8_1[] = {
  134851. 6,
  134852. 5,
  134853. 7,
  134854. 4,
  134855. 8,
  134856. 3,
  134857. 9,
  134858. 2,
  134859. 10,
  134860. 1,
  134861. 11,
  134862. 0,
  134863. 12,
  134864. };
  134865. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  134866. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  134867. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  134868. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  134869. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  134870. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  134871. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  134872. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  134873. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  134874. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  134875. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  134876. 20,13,12,12,12,14,12,14,13,
  134877. };
  134878. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  134879. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134880. 42.5, 59.5, 76.5, 93.5,
  134881. };
  134882. static long _vq_quantmap__44c1_sm_p8_1[] = {
  134883. 11, 9, 7, 5, 3, 1, 0, 2,
  134884. 4, 6, 8, 10, 12,
  134885. };
  134886. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  134887. _vq_quantthresh__44c1_sm_p8_1,
  134888. _vq_quantmap__44c1_sm_p8_1,
  134889. 13,
  134890. 13
  134891. };
  134892. static static_codebook _44c1_sm_p8_1 = {
  134893. 2, 169,
  134894. _vq_lengthlist__44c1_sm_p8_1,
  134895. 1, -522616832, 1620115456, 4, 0,
  134896. _vq_quantlist__44c1_sm_p8_1,
  134897. NULL,
  134898. &_vq_auxt__44c1_sm_p8_1,
  134899. NULL,
  134900. 0
  134901. };
  134902. static long _vq_quantlist__44c1_sm_p8_2[] = {
  134903. 8,
  134904. 7,
  134905. 9,
  134906. 6,
  134907. 10,
  134908. 5,
  134909. 11,
  134910. 4,
  134911. 12,
  134912. 3,
  134913. 13,
  134914. 2,
  134915. 14,
  134916. 1,
  134917. 15,
  134918. 0,
  134919. 16,
  134920. };
  134921. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  134922. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134923. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134924. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134925. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134926. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  134927. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134928. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134929. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  134930. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  134931. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  134932. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  134933. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  134934. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  134935. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  134936. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134937. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  134938. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  134939. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  134940. 9,
  134941. };
  134942. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  134943. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134944. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134945. };
  134946. static long _vq_quantmap__44c1_sm_p8_2[] = {
  134947. 15, 13, 11, 9, 7, 5, 3, 1,
  134948. 0, 2, 4, 6, 8, 10, 12, 14,
  134949. 16,
  134950. };
  134951. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  134952. _vq_quantthresh__44c1_sm_p8_2,
  134953. _vq_quantmap__44c1_sm_p8_2,
  134954. 17,
  134955. 17
  134956. };
  134957. static static_codebook _44c1_sm_p8_2 = {
  134958. 2, 289,
  134959. _vq_lengthlist__44c1_sm_p8_2,
  134960. 1, -529530880, 1611661312, 5, 0,
  134961. _vq_quantlist__44c1_sm_p8_2,
  134962. NULL,
  134963. &_vq_auxt__44c1_sm_p8_2,
  134964. NULL,
  134965. 0
  134966. };
  134967. static long _huff_lengthlist__44c1_sm_short[] = {
  134968. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  134969. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  134970. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  134971. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  134972. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  134973. 11,
  134974. };
  134975. static static_codebook _huff_book__44c1_sm_short = {
  134976. 2, 81,
  134977. _huff_lengthlist__44c1_sm_short,
  134978. 0, 0, 0, 0, 0,
  134979. NULL,
  134980. NULL,
  134981. NULL,
  134982. NULL,
  134983. 0
  134984. };
  134985. static long _huff_lengthlist__44cn1_s_long[] = {
  134986. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  134987. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  134988. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  134989. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  134990. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  134991. 20,
  134992. };
  134993. static static_codebook _huff_book__44cn1_s_long = {
  134994. 2, 81,
  134995. _huff_lengthlist__44cn1_s_long,
  134996. 0, 0, 0, 0, 0,
  134997. NULL,
  134998. NULL,
  134999. NULL,
  135000. NULL,
  135001. 0
  135002. };
  135003. static long _vq_quantlist__44cn1_s_p1_0[] = {
  135004. 1,
  135005. 0,
  135006. 2,
  135007. };
  135008. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  135009. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135010. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135015. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  135020. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  135055. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  135056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  135060. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  135061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  135065. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  135066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  135101. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  135106. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  135111. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0,
  135420. };
  135421. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  135422. -0.5, 0.5,
  135423. };
  135424. static long _vq_quantmap__44cn1_s_p1_0[] = {
  135425. 1, 0, 2,
  135426. };
  135427. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  135428. _vq_quantthresh__44cn1_s_p1_0,
  135429. _vq_quantmap__44cn1_s_p1_0,
  135430. 3,
  135431. 3
  135432. };
  135433. static static_codebook _44cn1_s_p1_0 = {
  135434. 8, 6561,
  135435. _vq_lengthlist__44cn1_s_p1_0,
  135436. 1, -535822336, 1611661312, 2, 0,
  135437. _vq_quantlist__44cn1_s_p1_0,
  135438. NULL,
  135439. &_vq_auxt__44cn1_s_p1_0,
  135440. NULL,
  135441. 0
  135442. };
  135443. static long _vq_quantlist__44cn1_s_p2_0[] = {
  135444. 2,
  135445. 1,
  135446. 3,
  135447. 0,
  135448. 4,
  135449. };
  135450. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  135451. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0,
  135491. };
  135492. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  135493. -1.5, -0.5, 0.5, 1.5,
  135494. };
  135495. static long _vq_quantmap__44cn1_s_p2_0[] = {
  135496. 3, 1, 0, 2, 4,
  135497. };
  135498. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  135499. _vq_quantthresh__44cn1_s_p2_0,
  135500. _vq_quantmap__44cn1_s_p2_0,
  135501. 5,
  135502. 5
  135503. };
  135504. static static_codebook _44cn1_s_p2_0 = {
  135505. 4, 625,
  135506. _vq_lengthlist__44cn1_s_p2_0,
  135507. 1, -533725184, 1611661312, 3, 0,
  135508. _vq_quantlist__44cn1_s_p2_0,
  135509. NULL,
  135510. &_vq_auxt__44cn1_s_p2_0,
  135511. NULL,
  135512. 0
  135513. };
  135514. static long _vq_quantlist__44cn1_s_p3_0[] = {
  135515. 4,
  135516. 3,
  135517. 5,
  135518. 2,
  135519. 6,
  135520. 1,
  135521. 7,
  135522. 0,
  135523. 8,
  135524. };
  135525. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  135526. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135527. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135528. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135529. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135530. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0,
  135532. };
  135533. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  135534. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135535. };
  135536. static long _vq_quantmap__44cn1_s_p3_0[] = {
  135537. 7, 5, 3, 1, 0, 2, 4, 6,
  135538. 8,
  135539. };
  135540. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  135541. _vq_quantthresh__44cn1_s_p3_0,
  135542. _vq_quantmap__44cn1_s_p3_0,
  135543. 9,
  135544. 9
  135545. };
  135546. static static_codebook _44cn1_s_p3_0 = {
  135547. 2, 81,
  135548. _vq_lengthlist__44cn1_s_p3_0,
  135549. 1, -531628032, 1611661312, 4, 0,
  135550. _vq_quantlist__44cn1_s_p3_0,
  135551. NULL,
  135552. &_vq_auxt__44cn1_s_p3_0,
  135553. NULL,
  135554. 0
  135555. };
  135556. static long _vq_quantlist__44cn1_s_p4_0[] = {
  135557. 4,
  135558. 3,
  135559. 5,
  135560. 2,
  135561. 6,
  135562. 1,
  135563. 7,
  135564. 0,
  135565. 8,
  135566. };
  135567. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  135568. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  135569. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135570. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  135571. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  135572. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  135573. 11,
  135574. };
  135575. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  135576. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135577. };
  135578. static long _vq_quantmap__44cn1_s_p4_0[] = {
  135579. 7, 5, 3, 1, 0, 2, 4, 6,
  135580. 8,
  135581. };
  135582. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  135583. _vq_quantthresh__44cn1_s_p4_0,
  135584. _vq_quantmap__44cn1_s_p4_0,
  135585. 9,
  135586. 9
  135587. };
  135588. static static_codebook _44cn1_s_p4_0 = {
  135589. 2, 81,
  135590. _vq_lengthlist__44cn1_s_p4_0,
  135591. 1, -531628032, 1611661312, 4, 0,
  135592. _vq_quantlist__44cn1_s_p4_0,
  135593. NULL,
  135594. &_vq_auxt__44cn1_s_p4_0,
  135595. NULL,
  135596. 0
  135597. };
  135598. static long _vq_quantlist__44cn1_s_p5_0[] = {
  135599. 8,
  135600. 7,
  135601. 9,
  135602. 6,
  135603. 10,
  135604. 5,
  135605. 11,
  135606. 4,
  135607. 12,
  135608. 3,
  135609. 13,
  135610. 2,
  135611. 14,
  135612. 1,
  135613. 15,
  135614. 0,
  135615. 16,
  135616. };
  135617. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  135618. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  135619. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135620. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135621. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135622. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135623. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135624. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135625. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  135626. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135627. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  135628. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135629. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135630. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  135631. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  135632. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  135633. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  135634. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  135636. 14,
  135637. };
  135638. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  135639. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135640. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135641. };
  135642. static long _vq_quantmap__44cn1_s_p5_0[] = {
  135643. 15, 13, 11, 9, 7, 5, 3, 1,
  135644. 0, 2, 4, 6, 8, 10, 12, 14,
  135645. 16,
  135646. };
  135647. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  135648. _vq_quantthresh__44cn1_s_p5_0,
  135649. _vq_quantmap__44cn1_s_p5_0,
  135650. 17,
  135651. 17
  135652. };
  135653. static static_codebook _44cn1_s_p5_0 = {
  135654. 2, 289,
  135655. _vq_lengthlist__44cn1_s_p5_0,
  135656. 1, -529530880, 1611661312, 5, 0,
  135657. _vq_quantlist__44cn1_s_p5_0,
  135658. NULL,
  135659. &_vq_auxt__44cn1_s_p5_0,
  135660. NULL,
  135661. 0
  135662. };
  135663. static long _vq_quantlist__44cn1_s_p6_0[] = {
  135664. 1,
  135665. 0,
  135666. 2,
  135667. };
  135668. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  135669. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  135670. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  135671. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  135672. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  135673. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  135674. 10,
  135675. };
  135676. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  135677. -5.5, 5.5,
  135678. };
  135679. static long _vq_quantmap__44cn1_s_p6_0[] = {
  135680. 1, 0, 2,
  135681. };
  135682. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  135683. _vq_quantthresh__44cn1_s_p6_0,
  135684. _vq_quantmap__44cn1_s_p6_0,
  135685. 3,
  135686. 3
  135687. };
  135688. static static_codebook _44cn1_s_p6_0 = {
  135689. 4, 81,
  135690. _vq_lengthlist__44cn1_s_p6_0,
  135691. 1, -529137664, 1618345984, 2, 0,
  135692. _vq_quantlist__44cn1_s_p6_0,
  135693. NULL,
  135694. &_vq_auxt__44cn1_s_p6_0,
  135695. NULL,
  135696. 0
  135697. };
  135698. static long _vq_quantlist__44cn1_s_p6_1[] = {
  135699. 5,
  135700. 4,
  135701. 6,
  135702. 3,
  135703. 7,
  135704. 2,
  135705. 8,
  135706. 1,
  135707. 9,
  135708. 0,
  135709. 10,
  135710. };
  135711. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  135712. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  135713. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  135714. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135715. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  135716. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  135717. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135718. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  135719. 10,10,10, 9, 9, 9, 9, 9, 9,
  135720. };
  135721. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  135722. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135723. 3.5, 4.5,
  135724. };
  135725. static long _vq_quantmap__44cn1_s_p6_1[] = {
  135726. 9, 7, 5, 3, 1, 0, 2, 4,
  135727. 6, 8, 10,
  135728. };
  135729. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  135730. _vq_quantthresh__44cn1_s_p6_1,
  135731. _vq_quantmap__44cn1_s_p6_1,
  135732. 11,
  135733. 11
  135734. };
  135735. static static_codebook _44cn1_s_p6_1 = {
  135736. 2, 121,
  135737. _vq_lengthlist__44cn1_s_p6_1,
  135738. 1, -531365888, 1611661312, 4, 0,
  135739. _vq_quantlist__44cn1_s_p6_1,
  135740. NULL,
  135741. &_vq_auxt__44cn1_s_p6_1,
  135742. NULL,
  135743. 0
  135744. };
  135745. static long _vq_quantlist__44cn1_s_p7_0[] = {
  135746. 6,
  135747. 5,
  135748. 7,
  135749. 4,
  135750. 8,
  135751. 3,
  135752. 9,
  135753. 2,
  135754. 10,
  135755. 1,
  135756. 11,
  135757. 0,
  135758. 12,
  135759. };
  135760. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  135761. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  135762. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  135763. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135764. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135765. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  135766. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  135767. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  135768. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  135769. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  135770. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  135771. 0,13,13,12,12,13,13,13,14,
  135772. };
  135773. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  135774. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135775. 12.5, 17.5, 22.5, 27.5,
  135776. };
  135777. static long _vq_quantmap__44cn1_s_p7_0[] = {
  135778. 11, 9, 7, 5, 3, 1, 0, 2,
  135779. 4, 6, 8, 10, 12,
  135780. };
  135781. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  135782. _vq_quantthresh__44cn1_s_p7_0,
  135783. _vq_quantmap__44cn1_s_p7_0,
  135784. 13,
  135785. 13
  135786. };
  135787. static static_codebook _44cn1_s_p7_0 = {
  135788. 2, 169,
  135789. _vq_lengthlist__44cn1_s_p7_0,
  135790. 1, -526516224, 1616117760, 4, 0,
  135791. _vq_quantlist__44cn1_s_p7_0,
  135792. NULL,
  135793. &_vq_auxt__44cn1_s_p7_0,
  135794. NULL,
  135795. 0
  135796. };
  135797. static long _vq_quantlist__44cn1_s_p7_1[] = {
  135798. 2,
  135799. 1,
  135800. 3,
  135801. 0,
  135802. 4,
  135803. };
  135804. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  135805. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135806. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135807. };
  135808. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  135809. -1.5, -0.5, 0.5, 1.5,
  135810. };
  135811. static long _vq_quantmap__44cn1_s_p7_1[] = {
  135812. 3, 1, 0, 2, 4,
  135813. };
  135814. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  135815. _vq_quantthresh__44cn1_s_p7_1,
  135816. _vq_quantmap__44cn1_s_p7_1,
  135817. 5,
  135818. 5
  135819. };
  135820. static static_codebook _44cn1_s_p7_1 = {
  135821. 2, 25,
  135822. _vq_lengthlist__44cn1_s_p7_1,
  135823. 1, -533725184, 1611661312, 3, 0,
  135824. _vq_quantlist__44cn1_s_p7_1,
  135825. NULL,
  135826. &_vq_auxt__44cn1_s_p7_1,
  135827. NULL,
  135828. 0
  135829. };
  135830. static long _vq_quantlist__44cn1_s_p8_0[] = {
  135831. 2,
  135832. 1,
  135833. 3,
  135834. 0,
  135835. 4,
  135836. };
  135837. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  135838. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  135839. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  135840. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135841. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  135842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135845. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  135846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135847. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  135848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  135849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135853. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  135854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135855. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135858. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135861. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135871. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  135872. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135873. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135874. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135875. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135876. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135877. 12,
  135878. };
  135879. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  135880. -331.5, -110.5, 110.5, 331.5,
  135881. };
  135882. static long _vq_quantmap__44cn1_s_p8_0[] = {
  135883. 3, 1, 0, 2, 4,
  135884. };
  135885. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  135886. _vq_quantthresh__44cn1_s_p8_0,
  135887. _vq_quantmap__44cn1_s_p8_0,
  135888. 5,
  135889. 5
  135890. };
  135891. static static_codebook _44cn1_s_p8_0 = {
  135892. 4, 625,
  135893. _vq_lengthlist__44cn1_s_p8_0,
  135894. 1, -518283264, 1627103232, 3, 0,
  135895. _vq_quantlist__44cn1_s_p8_0,
  135896. NULL,
  135897. &_vq_auxt__44cn1_s_p8_0,
  135898. NULL,
  135899. 0
  135900. };
  135901. static long _vq_quantlist__44cn1_s_p8_1[] = {
  135902. 6,
  135903. 5,
  135904. 7,
  135905. 4,
  135906. 8,
  135907. 3,
  135908. 9,
  135909. 2,
  135910. 10,
  135911. 1,
  135912. 11,
  135913. 0,
  135914. 12,
  135915. };
  135916. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  135917. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  135918. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  135919. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  135920. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  135921. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  135922. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  135923. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  135924. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  135925. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  135926. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  135927. 15,12,12,11,11,14,12,13,14,
  135928. };
  135929. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  135930. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135931. 42.5, 59.5, 76.5, 93.5,
  135932. };
  135933. static long _vq_quantmap__44cn1_s_p8_1[] = {
  135934. 11, 9, 7, 5, 3, 1, 0, 2,
  135935. 4, 6, 8, 10, 12,
  135936. };
  135937. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  135938. _vq_quantthresh__44cn1_s_p8_1,
  135939. _vq_quantmap__44cn1_s_p8_1,
  135940. 13,
  135941. 13
  135942. };
  135943. static static_codebook _44cn1_s_p8_1 = {
  135944. 2, 169,
  135945. _vq_lengthlist__44cn1_s_p8_1,
  135946. 1, -522616832, 1620115456, 4, 0,
  135947. _vq_quantlist__44cn1_s_p8_1,
  135948. NULL,
  135949. &_vq_auxt__44cn1_s_p8_1,
  135950. NULL,
  135951. 0
  135952. };
  135953. static long _vq_quantlist__44cn1_s_p8_2[] = {
  135954. 8,
  135955. 7,
  135956. 9,
  135957. 6,
  135958. 10,
  135959. 5,
  135960. 11,
  135961. 4,
  135962. 12,
  135963. 3,
  135964. 13,
  135965. 2,
  135966. 14,
  135967. 1,
  135968. 15,
  135969. 0,
  135970. 16,
  135971. };
  135972. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  135973. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  135974. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135975. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135976. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  135977. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  135978. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  135979. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  135980. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  135981. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  135982. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  135983. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  135984. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  135985. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  135986. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  135987. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  135988. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  135989. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135990. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  135991. 9,
  135992. };
  135993. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  135994. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135995. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135996. };
  135997. static long _vq_quantmap__44cn1_s_p8_2[] = {
  135998. 15, 13, 11, 9, 7, 5, 3, 1,
  135999. 0, 2, 4, 6, 8, 10, 12, 14,
  136000. 16,
  136001. };
  136002. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  136003. _vq_quantthresh__44cn1_s_p8_2,
  136004. _vq_quantmap__44cn1_s_p8_2,
  136005. 17,
  136006. 17
  136007. };
  136008. static static_codebook _44cn1_s_p8_2 = {
  136009. 2, 289,
  136010. _vq_lengthlist__44cn1_s_p8_2,
  136011. 1, -529530880, 1611661312, 5, 0,
  136012. _vq_quantlist__44cn1_s_p8_2,
  136013. NULL,
  136014. &_vq_auxt__44cn1_s_p8_2,
  136015. NULL,
  136016. 0
  136017. };
  136018. static long _huff_lengthlist__44cn1_s_short[] = {
  136019. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  136020. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  136021. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  136022. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  136023. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  136024. 10,
  136025. };
  136026. static static_codebook _huff_book__44cn1_s_short = {
  136027. 2, 81,
  136028. _huff_lengthlist__44cn1_s_short,
  136029. 0, 0, 0, 0, 0,
  136030. NULL,
  136031. NULL,
  136032. NULL,
  136033. NULL,
  136034. 0
  136035. };
  136036. static long _huff_lengthlist__44cn1_sm_long[] = {
  136037. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  136038. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  136039. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  136040. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  136041. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  136042. 17,
  136043. };
  136044. static static_codebook _huff_book__44cn1_sm_long = {
  136045. 2, 81,
  136046. _huff_lengthlist__44cn1_sm_long,
  136047. 0, 0, 0, 0, 0,
  136048. NULL,
  136049. NULL,
  136050. NULL,
  136051. NULL,
  136052. 0
  136053. };
  136054. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  136055. 1,
  136056. 0,
  136057. 2,
  136058. };
  136059. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  136060. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136061. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  136066. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136071. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  136106. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  136111. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136116. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136152. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136157. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  136162. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 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,
  136471. };
  136472. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  136473. -0.5, 0.5,
  136474. };
  136475. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  136476. 1, 0, 2,
  136477. };
  136478. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  136479. _vq_quantthresh__44cn1_sm_p1_0,
  136480. _vq_quantmap__44cn1_sm_p1_0,
  136481. 3,
  136482. 3
  136483. };
  136484. static static_codebook _44cn1_sm_p1_0 = {
  136485. 8, 6561,
  136486. _vq_lengthlist__44cn1_sm_p1_0,
  136487. 1, -535822336, 1611661312, 2, 0,
  136488. _vq_quantlist__44cn1_sm_p1_0,
  136489. NULL,
  136490. &_vq_auxt__44cn1_sm_p1_0,
  136491. NULL,
  136492. 0
  136493. };
  136494. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  136495. 2,
  136496. 1,
  136497. 3,
  136498. 0,
  136499. 4,
  136500. };
  136501. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  136502. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136541. 0,
  136542. };
  136543. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  136544. -1.5, -0.5, 0.5, 1.5,
  136545. };
  136546. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  136547. 3, 1, 0, 2, 4,
  136548. };
  136549. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  136550. _vq_quantthresh__44cn1_sm_p2_0,
  136551. _vq_quantmap__44cn1_sm_p2_0,
  136552. 5,
  136553. 5
  136554. };
  136555. static static_codebook _44cn1_sm_p2_0 = {
  136556. 4, 625,
  136557. _vq_lengthlist__44cn1_sm_p2_0,
  136558. 1, -533725184, 1611661312, 3, 0,
  136559. _vq_quantlist__44cn1_sm_p2_0,
  136560. NULL,
  136561. &_vq_auxt__44cn1_sm_p2_0,
  136562. NULL,
  136563. 0
  136564. };
  136565. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  136566. 4,
  136567. 3,
  136568. 5,
  136569. 2,
  136570. 6,
  136571. 1,
  136572. 7,
  136573. 0,
  136574. 8,
  136575. };
  136576. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  136577. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  136578. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136579. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136580. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  136581. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0,
  136583. };
  136584. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  136585. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136586. };
  136587. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  136588. 7, 5, 3, 1, 0, 2, 4, 6,
  136589. 8,
  136590. };
  136591. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  136592. _vq_quantthresh__44cn1_sm_p3_0,
  136593. _vq_quantmap__44cn1_sm_p3_0,
  136594. 9,
  136595. 9
  136596. };
  136597. static static_codebook _44cn1_sm_p3_0 = {
  136598. 2, 81,
  136599. _vq_lengthlist__44cn1_sm_p3_0,
  136600. 1, -531628032, 1611661312, 4, 0,
  136601. _vq_quantlist__44cn1_sm_p3_0,
  136602. NULL,
  136603. &_vq_auxt__44cn1_sm_p3_0,
  136604. NULL,
  136605. 0
  136606. };
  136607. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  136608. 4,
  136609. 3,
  136610. 5,
  136611. 2,
  136612. 6,
  136613. 1,
  136614. 7,
  136615. 0,
  136616. 8,
  136617. };
  136618. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  136619. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136620. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136621. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136622. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  136623. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  136624. 11,
  136625. };
  136626. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  136627. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136628. };
  136629. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  136630. 7, 5, 3, 1, 0, 2, 4, 6,
  136631. 8,
  136632. };
  136633. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  136634. _vq_quantthresh__44cn1_sm_p4_0,
  136635. _vq_quantmap__44cn1_sm_p4_0,
  136636. 9,
  136637. 9
  136638. };
  136639. static static_codebook _44cn1_sm_p4_0 = {
  136640. 2, 81,
  136641. _vq_lengthlist__44cn1_sm_p4_0,
  136642. 1, -531628032, 1611661312, 4, 0,
  136643. _vq_quantlist__44cn1_sm_p4_0,
  136644. NULL,
  136645. &_vq_auxt__44cn1_sm_p4_0,
  136646. NULL,
  136647. 0
  136648. };
  136649. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  136650. 8,
  136651. 7,
  136652. 9,
  136653. 6,
  136654. 10,
  136655. 5,
  136656. 11,
  136657. 4,
  136658. 12,
  136659. 3,
  136660. 13,
  136661. 2,
  136662. 14,
  136663. 1,
  136664. 15,
  136665. 0,
  136666. 16,
  136667. };
  136668. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  136669. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  136670. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  136671. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  136672. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136673. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  136674. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136675. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136676. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136677. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  136678. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136679. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  136680. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  136681. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  136682. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  136683. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  136684. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  136685. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  136687. 14,
  136688. };
  136689. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  136690. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136691. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136692. };
  136693. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  136694. 15, 13, 11, 9, 7, 5, 3, 1,
  136695. 0, 2, 4, 6, 8, 10, 12, 14,
  136696. 16,
  136697. };
  136698. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  136699. _vq_quantthresh__44cn1_sm_p5_0,
  136700. _vq_quantmap__44cn1_sm_p5_0,
  136701. 17,
  136702. 17
  136703. };
  136704. static static_codebook _44cn1_sm_p5_0 = {
  136705. 2, 289,
  136706. _vq_lengthlist__44cn1_sm_p5_0,
  136707. 1, -529530880, 1611661312, 5, 0,
  136708. _vq_quantlist__44cn1_sm_p5_0,
  136709. NULL,
  136710. &_vq_auxt__44cn1_sm_p5_0,
  136711. NULL,
  136712. 0
  136713. };
  136714. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  136715. 1,
  136716. 0,
  136717. 2,
  136718. };
  136719. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  136720. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  136721. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136722. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  136723. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  136724. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  136725. 10,
  136726. };
  136727. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  136728. -5.5, 5.5,
  136729. };
  136730. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  136731. 1, 0, 2,
  136732. };
  136733. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  136734. _vq_quantthresh__44cn1_sm_p6_0,
  136735. _vq_quantmap__44cn1_sm_p6_0,
  136736. 3,
  136737. 3
  136738. };
  136739. static static_codebook _44cn1_sm_p6_0 = {
  136740. 4, 81,
  136741. _vq_lengthlist__44cn1_sm_p6_0,
  136742. 1, -529137664, 1618345984, 2, 0,
  136743. _vq_quantlist__44cn1_sm_p6_0,
  136744. NULL,
  136745. &_vq_auxt__44cn1_sm_p6_0,
  136746. NULL,
  136747. 0
  136748. };
  136749. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  136750. 5,
  136751. 4,
  136752. 6,
  136753. 3,
  136754. 7,
  136755. 2,
  136756. 8,
  136757. 1,
  136758. 9,
  136759. 0,
  136760. 10,
  136761. };
  136762. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  136763. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  136764. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136765. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136766. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  136767. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  136768. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  136769. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  136770. 10,10,10, 8, 9, 8, 8, 9, 8,
  136771. };
  136772. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  136773. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136774. 3.5, 4.5,
  136775. };
  136776. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  136777. 9, 7, 5, 3, 1, 0, 2, 4,
  136778. 6, 8, 10,
  136779. };
  136780. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  136781. _vq_quantthresh__44cn1_sm_p6_1,
  136782. _vq_quantmap__44cn1_sm_p6_1,
  136783. 11,
  136784. 11
  136785. };
  136786. static static_codebook _44cn1_sm_p6_1 = {
  136787. 2, 121,
  136788. _vq_lengthlist__44cn1_sm_p6_1,
  136789. 1, -531365888, 1611661312, 4, 0,
  136790. _vq_quantlist__44cn1_sm_p6_1,
  136791. NULL,
  136792. &_vq_auxt__44cn1_sm_p6_1,
  136793. NULL,
  136794. 0
  136795. };
  136796. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  136797. 6,
  136798. 5,
  136799. 7,
  136800. 4,
  136801. 8,
  136802. 3,
  136803. 9,
  136804. 2,
  136805. 10,
  136806. 1,
  136807. 11,
  136808. 0,
  136809. 12,
  136810. };
  136811. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  136812. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  136813. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  136814. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136815. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136816. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  136817. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  136818. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  136819. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  136820. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  136821. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  136822. 0,13,12,12,12,13,13,13,14,
  136823. };
  136824. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  136825. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136826. 12.5, 17.5, 22.5, 27.5,
  136827. };
  136828. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  136829. 11, 9, 7, 5, 3, 1, 0, 2,
  136830. 4, 6, 8, 10, 12,
  136831. };
  136832. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  136833. _vq_quantthresh__44cn1_sm_p7_0,
  136834. _vq_quantmap__44cn1_sm_p7_0,
  136835. 13,
  136836. 13
  136837. };
  136838. static static_codebook _44cn1_sm_p7_0 = {
  136839. 2, 169,
  136840. _vq_lengthlist__44cn1_sm_p7_0,
  136841. 1, -526516224, 1616117760, 4, 0,
  136842. _vq_quantlist__44cn1_sm_p7_0,
  136843. NULL,
  136844. &_vq_auxt__44cn1_sm_p7_0,
  136845. NULL,
  136846. 0
  136847. };
  136848. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  136849. 2,
  136850. 1,
  136851. 3,
  136852. 0,
  136853. 4,
  136854. };
  136855. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  136856. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136857. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  136858. };
  136859. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  136860. -1.5, -0.5, 0.5, 1.5,
  136861. };
  136862. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  136863. 3, 1, 0, 2, 4,
  136864. };
  136865. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  136866. _vq_quantthresh__44cn1_sm_p7_1,
  136867. _vq_quantmap__44cn1_sm_p7_1,
  136868. 5,
  136869. 5
  136870. };
  136871. static static_codebook _44cn1_sm_p7_1 = {
  136872. 2, 25,
  136873. _vq_lengthlist__44cn1_sm_p7_1,
  136874. 1, -533725184, 1611661312, 3, 0,
  136875. _vq_quantlist__44cn1_sm_p7_1,
  136876. NULL,
  136877. &_vq_auxt__44cn1_sm_p7_1,
  136878. NULL,
  136879. 0
  136880. };
  136881. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  136882. 4,
  136883. 3,
  136884. 5,
  136885. 2,
  136886. 6,
  136887. 1,
  136888. 7,
  136889. 0,
  136890. 8,
  136891. };
  136892. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  136893. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  136894. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  136895. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  136896. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  136897. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  136898. 14,
  136899. };
  136900. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  136901. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  136902. };
  136903. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  136904. 7, 5, 3, 1, 0, 2, 4, 6,
  136905. 8,
  136906. };
  136907. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  136908. _vq_quantthresh__44cn1_sm_p8_0,
  136909. _vq_quantmap__44cn1_sm_p8_0,
  136910. 9,
  136911. 9
  136912. };
  136913. static static_codebook _44cn1_sm_p8_0 = {
  136914. 2, 81,
  136915. _vq_lengthlist__44cn1_sm_p8_0,
  136916. 1, -516186112, 1627103232, 4, 0,
  136917. _vq_quantlist__44cn1_sm_p8_0,
  136918. NULL,
  136919. &_vq_auxt__44cn1_sm_p8_0,
  136920. NULL,
  136921. 0
  136922. };
  136923. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  136924. 6,
  136925. 5,
  136926. 7,
  136927. 4,
  136928. 8,
  136929. 3,
  136930. 9,
  136931. 2,
  136932. 10,
  136933. 1,
  136934. 11,
  136935. 0,
  136936. 12,
  136937. };
  136938. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  136939. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  136940. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  136941. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  136942. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  136943. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  136944. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  136945. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  136946. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  136947. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  136948. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  136949. 17,12,12,11,10,13,11,13,13,
  136950. };
  136951. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  136952. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136953. 42.5, 59.5, 76.5, 93.5,
  136954. };
  136955. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  136956. 11, 9, 7, 5, 3, 1, 0, 2,
  136957. 4, 6, 8, 10, 12,
  136958. };
  136959. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  136960. _vq_quantthresh__44cn1_sm_p8_1,
  136961. _vq_quantmap__44cn1_sm_p8_1,
  136962. 13,
  136963. 13
  136964. };
  136965. static static_codebook _44cn1_sm_p8_1 = {
  136966. 2, 169,
  136967. _vq_lengthlist__44cn1_sm_p8_1,
  136968. 1, -522616832, 1620115456, 4, 0,
  136969. _vq_quantlist__44cn1_sm_p8_1,
  136970. NULL,
  136971. &_vq_auxt__44cn1_sm_p8_1,
  136972. NULL,
  136973. 0
  136974. };
  136975. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  136976. 8,
  136977. 7,
  136978. 9,
  136979. 6,
  136980. 10,
  136981. 5,
  136982. 11,
  136983. 4,
  136984. 12,
  136985. 3,
  136986. 13,
  136987. 2,
  136988. 14,
  136989. 1,
  136990. 15,
  136991. 0,
  136992. 16,
  136993. };
  136994. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  136995. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  136996. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136997. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  136998. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136999. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  137000. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  137001. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  137002. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  137003. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  137004. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  137005. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  137006. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  137007. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  137008. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  137009. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  137010. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137011. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137012. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137013. 9,
  137014. };
  137015. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  137016. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137017. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137018. };
  137019. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  137020. 15, 13, 11, 9, 7, 5, 3, 1,
  137021. 0, 2, 4, 6, 8, 10, 12, 14,
  137022. 16,
  137023. };
  137024. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  137025. _vq_quantthresh__44cn1_sm_p8_2,
  137026. _vq_quantmap__44cn1_sm_p8_2,
  137027. 17,
  137028. 17
  137029. };
  137030. static static_codebook _44cn1_sm_p8_2 = {
  137031. 2, 289,
  137032. _vq_lengthlist__44cn1_sm_p8_2,
  137033. 1, -529530880, 1611661312, 5, 0,
  137034. _vq_quantlist__44cn1_sm_p8_2,
  137035. NULL,
  137036. &_vq_auxt__44cn1_sm_p8_2,
  137037. NULL,
  137038. 0
  137039. };
  137040. static long _huff_lengthlist__44cn1_sm_short[] = {
  137041. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  137042. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  137043. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  137044. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  137045. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  137046. 9,
  137047. };
  137048. static static_codebook _huff_book__44cn1_sm_short = {
  137049. 2, 81,
  137050. _huff_lengthlist__44cn1_sm_short,
  137051. 0, 0, 0, 0, 0,
  137052. NULL,
  137053. NULL,
  137054. NULL,
  137055. NULL,
  137056. 0
  137057. };
  137058. /********* End of inlined file: res_books_stereo.h *********/
  137059. /***** residue backends *********************************************/
  137060. static vorbis_info_residue0 _residue_44_low={
  137061. 0,-1, -1, 9,-1,
  137062. /* 0 1 2 3 4 5 6 7 */
  137063. {0},
  137064. {-1},
  137065. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137066. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  137067. };
  137068. static vorbis_info_residue0 _residue_44_mid={
  137069. 0,-1, -1, 10,-1,
  137070. /* 0 1 2 3 4 5 6 7 8 */
  137071. {0},
  137072. {-1},
  137073. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137074. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  137075. };
  137076. static vorbis_info_residue0 _residue_44_high={
  137077. 0,-1, -1, 10,-1,
  137078. /* 0 1 2 3 4 5 6 7 8 */
  137079. {0},
  137080. {-1},
  137081. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  137082. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  137083. };
  137084. static static_bookblock _resbook_44s_n1={
  137085. {
  137086. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  137087. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  137088. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  137089. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  137090. }
  137091. };
  137092. static static_bookblock _resbook_44sm_n1={
  137093. {
  137094. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  137095. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  137096. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  137097. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  137098. }
  137099. };
  137100. static static_bookblock _resbook_44s_0={
  137101. {
  137102. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  137103. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  137104. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  137105. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  137106. }
  137107. };
  137108. static static_bookblock _resbook_44sm_0={
  137109. {
  137110. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  137111. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  137112. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  137113. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  137114. }
  137115. };
  137116. static static_bookblock _resbook_44s_1={
  137117. {
  137118. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  137119. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  137120. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  137121. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  137122. }
  137123. };
  137124. static static_bookblock _resbook_44sm_1={
  137125. {
  137126. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  137127. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  137128. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  137129. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  137130. }
  137131. };
  137132. static static_bookblock _resbook_44s_2={
  137133. {
  137134. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  137135. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  137136. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  137137. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  137138. }
  137139. };
  137140. static static_bookblock _resbook_44s_3={
  137141. {
  137142. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  137143. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  137144. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  137145. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  137146. }
  137147. };
  137148. static static_bookblock _resbook_44s_4={
  137149. {
  137150. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  137151. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  137152. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  137153. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  137154. }
  137155. };
  137156. static static_bookblock _resbook_44s_5={
  137157. {
  137158. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  137159. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  137160. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  137161. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  137162. }
  137163. };
  137164. static static_bookblock _resbook_44s_6={
  137165. {
  137166. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  137167. {0,0,&_44c6_s_p4_0},
  137168. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  137169. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  137170. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  137171. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  137172. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  137173. }
  137174. };
  137175. static static_bookblock _resbook_44s_7={
  137176. {
  137177. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  137178. {0,0,&_44c7_s_p4_0},
  137179. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  137180. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  137181. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  137182. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  137183. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  137184. }
  137185. };
  137186. static static_bookblock _resbook_44s_8={
  137187. {
  137188. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  137189. {0,0,&_44c8_s_p4_0},
  137190. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  137191. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  137192. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  137193. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  137194. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  137195. }
  137196. };
  137197. static static_bookblock _resbook_44s_9={
  137198. {
  137199. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  137200. {0,0,&_44c9_s_p4_0},
  137201. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  137202. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  137203. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  137204. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  137205. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  137206. }
  137207. };
  137208. static vorbis_residue_template _res_44s_n1[]={
  137209. {2,0, &_residue_44_low,
  137210. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  137211. &_resbook_44s_n1,&_resbook_44sm_n1},
  137212. {2,0, &_residue_44_low,
  137213. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  137214. &_resbook_44s_n1,&_resbook_44sm_n1}
  137215. };
  137216. static vorbis_residue_template _res_44s_0[]={
  137217. {2,0, &_residue_44_low,
  137218. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  137219. &_resbook_44s_0,&_resbook_44sm_0},
  137220. {2,0, &_residue_44_low,
  137221. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  137222. &_resbook_44s_0,&_resbook_44sm_0}
  137223. };
  137224. static vorbis_residue_template _res_44s_1[]={
  137225. {2,0, &_residue_44_low,
  137226. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  137227. &_resbook_44s_1,&_resbook_44sm_1},
  137228. {2,0, &_residue_44_low,
  137229. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  137230. &_resbook_44s_1,&_resbook_44sm_1}
  137231. };
  137232. static vorbis_residue_template _res_44s_2[]={
  137233. {2,0, &_residue_44_mid,
  137234. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  137235. &_resbook_44s_2,&_resbook_44s_2},
  137236. {2,0, &_residue_44_mid,
  137237. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  137238. &_resbook_44s_2,&_resbook_44s_2}
  137239. };
  137240. static vorbis_residue_template _res_44s_3[]={
  137241. {2,0, &_residue_44_mid,
  137242. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  137243. &_resbook_44s_3,&_resbook_44s_3},
  137244. {2,0, &_residue_44_mid,
  137245. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  137246. &_resbook_44s_3,&_resbook_44s_3}
  137247. };
  137248. static vorbis_residue_template _res_44s_4[]={
  137249. {2,0, &_residue_44_mid,
  137250. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  137251. &_resbook_44s_4,&_resbook_44s_4},
  137252. {2,0, &_residue_44_mid,
  137253. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  137254. &_resbook_44s_4,&_resbook_44s_4}
  137255. };
  137256. static vorbis_residue_template _res_44s_5[]={
  137257. {2,0, &_residue_44_mid,
  137258. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  137259. &_resbook_44s_5,&_resbook_44s_5},
  137260. {2,0, &_residue_44_mid,
  137261. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  137262. &_resbook_44s_5,&_resbook_44s_5}
  137263. };
  137264. static vorbis_residue_template _res_44s_6[]={
  137265. {2,0, &_residue_44_high,
  137266. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  137267. &_resbook_44s_6,&_resbook_44s_6},
  137268. {2,0, &_residue_44_high,
  137269. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  137270. &_resbook_44s_6,&_resbook_44s_6}
  137271. };
  137272. static vorbis_residue_template _res_44s_7[]={
  137273. {2,0, &_residue_44_high,
  137274. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  137275. &_resbook_44s_7,&_resbook_44s_7},
  137276. {2,0, &_residue_44_high,
  137277. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  137278. &_resbook_44s_7,&_resbook_44s_7}
  137279. };
  137280. static vorbis_residue_template _res_44s_8[]={
  137281. {2,0, &_residue_44_high,
  137282. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  137283. &_resbook_44s_8,&_resbook_44s_8},
  137284. {2,0, &_residue_44_high,
  137285. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  137286. &_resbook_44s_8,&_resbook_44s_8}
  137287. };
  137288. static vorbis_residue_template _res_44s_9[]={
  137289. {2,0, &_residue_44_high,
  137290. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  137291. &_resbook_44s_9,&_resbook_44s_9},
  137292. {2,0, &_residue_44_high,
  137293. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  137294. &_resbook_44s_9,&_resbook_44s_9}
  137295. };
  137296. static vorbis_mapping_template _mapres_template_44_stereo[]={
  137297. { _map_nominal, _res_44s_n1 }, /* -1 */
  137298. { _map_nominal, _res_44s_0 }, /* 0 */
  137299. { _map_nominal, _res_44s_1 }, /* 1 */
  137300. { _map_nominal, _res_44s_2 }, /* 2 */
  137301. { _map_nominal, _res_44s_3 }, /* 3 */
  137302. { _map_nominal, _res_44s_4 }, /* 4 */
  137303. { _map_nominal, _res_44s_5 }, /* 5 */
  137304. { _map_nominal, _res_44s_6 }, /* 6 */
  137305. { _map_nominal, _res_44s_7 }, /* 7 */
  137306. { _map_nominal, _res_44s_8 }, /* 8 */
  137307. { _map_nominal, _res_44s_9 }, /* 9 */
  137308. };
  137309. /********* End of inlined file: residue_44.h *********/
  137310. /********* Start of inlined file: psych_44.h *********/
  137311. /* preecho trigger settings *****************************************/
  137312. static vorbis_info_psy_global _psy_global_44[5]={
  137313. {8, /* lines per eighth octave */
  137314. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  137315. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  137316. -6.f,
  137317. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137318. },
  137319. {8, /* lines per eighth octave */
  137320. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137321. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  137322. -6.f,
  137323. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137324. },
  137325. {8, /* lines per eighth octave */
  137326. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137327. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  137328. -6.f,
  137329. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137330. },
  137331. {8, /* lines per eighth octave */
  137332. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  137333. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  137334. -6.f,
  137335. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137336. },
  137337. {8, /* lines per eighth octave */
  137338. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  137339. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  137340. -6.f,
  137341. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137342. },
  137343. };
  137344. /* noise compander lookups * low, mid, high quality ****************/
  137345. static compandblock _psy_compand_44[6]={
  137346. /* sub-mode Z short */
  137347. {{
  137348. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137349. 8, 9,10,11,12,13,14, 15, /* 15dB */
  137350. 16,17,18,19,20,21,22, 23, /* 23dB */
  137351. 24,25,26,27,28,29,30, 31, /* 31dB */
  137352. 32,33,34,35,36,37,38, 39, /* 39dB */
  137353. }},
  137354. /* mode_Z nominal short */
  137355. {{
  137356. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  137357. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  137358. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  137359. 15,16,17,17,17,18,18, 19, /* 31dB */
  137360. 19,19,20,21,22,23,24, 25, /* 39dB */
  137361. }},
  137362. /* mode A short */
  137363. {{
  137364. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  137365. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  137366. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  137367. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  137368. 11,12,13,14,15,16,17, 18, /* 39dB */
  137369. }},
  137370. /* sub-mode Z long */
  137371. {{
  137372. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137373. 8, 9,10,11,12,13,14, 15, /* 15dB */
  137374. 16,17,18,19,20,21,22, 23, /* 23dB */
  137375. 24,25,26,27,28,29,30, 31, /* 31dB */
  137376. 32,33,34,35,36,37,38, 39, /* 39dB */
  137377. }},
  137378. /* mode_Z nominal long */
  137379. {{
  137380. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137381. 8, 9,10,11,12,12,13, 13, /* 15dB */
  137382. 13,14,14,14,15,15,15, 15, /* 23dB */
  137383. 16,16,17,17,17,18,18, 19, /* 31dB */
  137384. 19,19,20,21,22,23,24, 25, /* 39dB */
  137385. }},
  137386. /* mode A long */
  137387. {{
  137388. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137389. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  137390. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  137391. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  137392. 11,12,13,14,15,16,17, 18, /* 39dB */
  137393. }}
  137394. };
  137395. /* tonal masking curve level adjustments *************************/
  137396. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  137397. /* 63 125 250 500 1 2 4 8 16 */
  137398. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  137399. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  137400. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  137401. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  137402. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  137403. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  137404. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  137405. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  137406. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  137407. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  137408. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  137409. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  137410. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  137411. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  137412. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  137413. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  137414. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  137415. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  137416. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  137417. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  137418. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  137419. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  137420. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  137421. };
  137422. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  137423. /* 63 125 250 500 1 2 4 8 16 */
  137424. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  137425. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  137426. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  137427. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  137428. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  137429. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  137430. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  137431. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  137432. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  137433. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  137434. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  137435. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  137436. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  137437. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  137438. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  137439. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  137440. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  137441. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  137442. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  137443. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  137444. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  137445. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  137446. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  137447. };
  137448. /* noise bias (transition block) */
  137449. static noise3 _psy_noisebias_trans[12]={
  137450. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  137451. /* -1 */
  137452. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137453. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  137454. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137455. /* 0
  137456. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137457. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  137458. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  137459. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137460. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  137461. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  137462. /* 1
  137463. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137464. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  137465. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  137466. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137467. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  137468. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  137469. /* 2
  137470. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137471. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  137472. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  137473. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137474. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  137475. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  137476. /* 3
  137477. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137478. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  137479. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137480. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137481. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  137482. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  137483. /* 4
  137484. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137485. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  137486. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137487. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137488. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  137489. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  137490. /* 5
  137491. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137492. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  137493. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  137494. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137495. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  137496. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  137497. /* 6
  137498. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137499. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  137500. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  137501. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137502. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  137503. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  137504. /* 7
  137505. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137506. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  137507. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  137508. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137509. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  137510. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  137511. /* 8
  137512. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  137513. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  137514. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  137515. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  137516. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  137517. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  137518. /* 9
  137519. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137520. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  137521. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  137522. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137523. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  137524. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  137525. /* 10 */
  137526. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  137527. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  137528. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  137529. };
  137530. /* noise bias (long block) */
  137531. static noise3 _psy_noisebias_long[12]={
  137532. /*63 125 250 500 1k 2k 4k 8k 16k*/
  137533. /* -1 */
  137534. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  137535. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  137536. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  137537. /* 0 */
  137538. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  137539. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  137540. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  137541. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  137542. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  137543. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  137544. /* 1 */
  137545. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137546. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  137547. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  137548. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137549. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  137550. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  137551. /* 2 */
  137552. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137553. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  137554. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137555. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137556. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  137557. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  137558. /* 3 */
  137559. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137560. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  137561. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137562. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137563. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  137564. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  137565. /* 4 */
  137566. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137567. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  137568. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137569. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137570. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  137571. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  137572. /* 5 */
  137573. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137574. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  137575. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  137576. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137577. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  137578. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  137579. /* 6 */
  137580. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137581. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  137582. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  137583. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137584. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  137585. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  137586. /* 7 */
  137587. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137588. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  137589. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  137590. /* 8 */
  137591. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  137592. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  137593. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  137594. /* 9 */
  137595. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137596. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  137597. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  137598. /* 10 */
  137599. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  137600. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  137601. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  137602. };
  137603. /* noise bias (impulse block) */
  137604. static noise3 _psy_noisebias_impulse[12]={
  137605. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  137606. /* -1 */
  137607. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137608. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  137609. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137610. /* 0 */
  137611. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  137612. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  137613. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  137614. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  137615. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  137616. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137617. /* 1 */
  137618. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  137619. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  137620. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  137621. /* 2 */
  137622. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  137623. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  137624. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  137625. /* 3 */
  137626. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  137627. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  137628. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  137629. /* 4 */
  137630. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  137631. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  137632. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  137633. /* 5 */
  137634. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  137635. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  137636. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  137637. /* 6
  137638. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  137639. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  137640. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  137641. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  137642. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  137643. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  137644. /* 7 */
  137645. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  137646. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  137647. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  137648. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  137649. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  137650. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  137651. /* 8 */
  137652. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  137653. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  137654. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  137655. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  137656. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  137657. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  137658. /* 9 */
  137659. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137660. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  137661. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  137662. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137663. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  137664. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  137665. /* 10 */
  137666. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  137667. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  137668. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  137669. };
  137670. /* noise bias (padding block) */
  137671. static noise3 _psy_noisebias_padding[12]={
  137672. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  137673. /* -1 */
  137674. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137675. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  137676. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137677. /* 0 */
  137678. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137679. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  137680. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  137681. /* 1 */
  137682. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  137683. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  137684. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  137685. /* 2 */
  137686. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  137687. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  137688. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  137689. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  137690. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  137691. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  137692. /* 3 */
  137693. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  137694. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  137695. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  137696. /* 4 */
  137697. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  137698. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  137699. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  137700. /* 5 */
  137701. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  137702. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  137703. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  137704. /* 6 */
  137705. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  137706. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  137707. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  137708. /* 7 */
  137709. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  137710. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  137711. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  137712. /* 8 */
  137713. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  137714. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  137715. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  137716. /* 9 */
  137717. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  137718. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  137719. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  137720. /* 10 */
  137721. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  137722. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  137723. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  137724. };
  137725. static noiseguard _psy_noiseguards_44[4]={
  137726. {3,3,15},
  137727. {3,3,15},
  137728. {10,10,100},
  137729. {10,10,100},
  137730. };
  137731. static int _psy_tone_suppress[12]={
  137732. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  137733. };
  137734. static int _psy_tone_0dB[12]={
  137735. 90,90,95,95,95,95,105,105,105,105,105,105,
  137736. };
  137737. static int _psy_noise_suppress[12]={
  137738. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  137739. };
  137740. static vorbis_info_psy _psy_info_template={
  137741. /* blockflag */
  137742. -1,
  137743. /* ath_adjatt, ath_maxatt */
  137744. -140.,-140.,
  137745. /* tonemask att boost/decay,suppr,curves */
  137746. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  137747. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  137748. 1, -0.f, .5f, .5f, 0,0,0,
  137749. /* noiseoffset*3, noisecompand, max_curve_dB */
  137750. {{-1},{-1},{-1}},{-1},105.f,
  137751. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  137752. 0,0,-1,-1,0.,
  137753. };
  137754. /* ath ****************/
  137755. static int _psy_ath_floater[12]={
  137756. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  137757. };
  137758. static int _psy_ath_abs[12]={
  137759. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  137760. };
  137761. /* stereo setup. These don't map directly to quality level, there's
  137762. an additional indirection as several of the below may be used in a
  137763. single bitmanaged stream
  137764. ****************/
  137765. /* various stereo possibilities */
  137766. /* stereo mode by base quality level */
  137767. static adj_stereo _psy_stereo_modes_44[12]={
  137768. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  137769. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  137770. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  137771. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  137772. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  137773. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  137774. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  137775. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  137776. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  137777. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  137778. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  137779. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  137780. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  137781. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  137782. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  137783. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  137784. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  137785. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  137786. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137787. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  137788. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  137789. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  137790. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  137791. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  137792. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  137793. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  137794. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  137795. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137796. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  137797. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  137798. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  137799. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  137800. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137801. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  137802. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137803. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  137804. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  137805. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137806. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  137807. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137808. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  137809. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  137810. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  137811. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137812. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  137813. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  137814. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137815. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  137816. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137817. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137818. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  137819. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  137820. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137821. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137822. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  137823. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137824. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  137825. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137826. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137827. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  137828. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  137829. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137830. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137831. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  137832. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137833. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  137834. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137835. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137836. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  137837. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  137838. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137839. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137840. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  137841. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137842. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  137843. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137844. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137845. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  137846. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137847. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  137848. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137849. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137850. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  137851. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137852. };
  137853. /* tone master attenuation by base quality mode and bitrate tweak */
  137854. static att3 _psy_tone_masteratt_44[12]={
  137855. {{ 35, 21, 9}, 0, 0}, /* -1 */
  137856. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  137857. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  137858. {{ 25, 12, 2}, 0, 0}, /* 1 */
  137859. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  137860. {{ 20, 9, -3}, 0, 0}, /* 2 */
  137861. {{ 20, 9, -4}, 0, 0}, /* 3 */
  137862. {{ 20, 9, -4}, 0, 0}, /* 4 */
  137863. {{ 20, 6, -6}, 0, 0}, /* 5 */
  137864. {{ 20, 3, -10}, 0, 0}, /* 6 */
  137865. {{ 18, 1, -14}, 0, 0}, /* 7 */
  137866. {{ 18, 0, -16}, 0, 0}, /* 8 */
  137867. {{ 18, -2, -16}, 0, 0}, /* 9 */
  137868. {{ 12, -2, -20}, 0, 0}, /* 10 */
  137869. };
  137870. /* lowpass by mode **************/
  137871. static double _psy_lowpass_44[12]={
  137872. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  137873. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  137874. };
  137875. /* noise normalization **********/
  137876. static int _noise_start_short_44[11]={
  137877. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  137878. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  137879. };
  137880. static int _noise_start_long_44[11]={
  137881. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  137882. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  137883. };
  137884. static int _noise_part_short_44[11]={
  137885. 8,8,8,8,8,8,8,8,8,8,8
  137886. };
  137887. static int _noise_part_long_44[11]={
  137888. 32,32,32,32,32,32,32,32,32,32,32
  137889. };
  137890. static double _noise_thresh_44[11]={
  137891. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  137892. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  137893. };
  137894. static double _noise_thresh_5only[2]={
  137895. .5,.5,
  137896. };
  137897. /********* End of inlined file: psych_44.h *********/
  137898. static double rate_mapping_44_stereo[12]={
  137899. 22500.,32000.,40000.,48000.,56000.,64000.,
  137900. 80000.,96000.,112000.,128000.,160000.,250001.
  137901. };
  137902. static double quality_mapping_44[12]={
  137903. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  137904. };
  137905. static int blocksize_short_44[11]={
  137906. 512,256,256,256,256,256,256,256,256,256,256
  137907. };
  137908. static int blocksize_long_44[11]={
  137909. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  137910. };
  137911. static double _psy_compand_short_mapping[12]={
  137912. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  137913. };
  137914. static double _psy_compand_long_mapping[12]={
  137915. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  137916. };
  137917. static double _global_mapping_44[12]={
  137918. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  137919. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  137920. };
  137921. static int _floor_short_mapping_44[11]={
  137922. 1,0,0,2,2,4,5,5,5,5,5
  137923. };
  137924. static int _floor_long_mapping_44[11]={
  137925. 8,7,7,7,7,7,7,7,7,7,7
  137926. };
  137927. ve_setup_data_template ve_setup_44_stereo={
  137928. 11,
  137929. rate_mapping_44_stereo,
  137930. quality_mapping_44,
  137931. 2,
  137932. 40000,
  137933. 50000,
  137934. blocksize_short_44,
  137935. blocksize_long_44,
  137936. _psy_tone_masteratt_44,
  137937. _psy_tone_0dB,
  137938. _psy_tone_suppress,
  137939. _vp_tonemask_adj_otherblock,
  137940. _vp_tonemask_adj_longblock,
  137941. _vp_tonemask_adj_otherblock,
  137942. _psy_noiseguards_44,
  137943. _psy_noisebias_impulse,
  137944. _psy_noisebias_padding,
  137945. _psy_noisebias_trans,
  137946. _psy_noisebias_long,
  137947. _psy_noise_suppress,
  137948. _psy_compand_44,
  137949. _psy_compand_short_mapping,
  137950. _psy_compand_long_mapping,
  137951. {_noise_start_short_44,_noise_start_long_44},
  137952. {_noise_part_short_44,_noise_part_long_44},
  137953. _noise_thresh_44,
  137954. _psy_ath_floater,
  137955. _psy_ath_abs,
  137956. _psy_lowpass_44,
  137957. _psy_global_44,
  137958. _global_mapping_44,
  137959. _psy_stereo_modes_44,
  137960. _floor_books,
  137961. _floor,
  137962. _floor_short_mapping_44,
  137963. _floor_long_mapping_44,
  137964. _mapres_template_44_stereo
  137965. };
  137966. /********* End of inlined file: setup_44.h *********/
  137967. /********* Start of inlined file: setup_44u.h *********/
  137968. /********* Start of inlined file: residue_44u.h *********/
  137969. /********* Start of inlined file: res_books_uncoupled.h *********/
  137970. static long _vq_quantlist__16u0__p1_0[] = {
  137971. 1,
  137972. 0,
  137973. 2,
  137974. };
  137975. static long _vq_lengthlist__16u0__p1_0[] = {
  137976. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  137977. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  137978. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  137979. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  137980. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  137981. 12,
  137982. };
  137983. static float _vq_quantthresh__16u0__p1_0[] = {
  137984. -0.5, 0.5,
  137985. };
  137986. static long _vq_quantmap__16u0__p1_0[] = {
  137987. 1, 0, 2,
  137988. };
  137989. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  137990. _vq_quantthresh__16u0__p1_0,
  137991. _vq_quantmap__16u0__p1_0,
  137992. 3,
  137993. 3
  137994. };
  137995. static static_codebook _16u0__p1_0 = {
  137996. 4, 81,
  137997. _vq_lengthlist__16u0__p1_0,
  137998. 1, -535822336, 1611661312, 2, 0,
  137999. _vq_quantlist__16u0__p1_0,
  138000. NULL,
  138001. &_vq_auxt__16u0__p1_0,
  138002. NULL,
  138003. 0
  138004. };
  138005. static long _vq_quantlist__16u0__p2_0[] = {
  138006. 1,
  138007. 0,
  138008. 2,
  138009. };
  138010. static long _vq_lengthlist__16u0__p2_0[] = {
  138011. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  138012. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  138013. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  138014. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  138015. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  138016. 8,
  138017. };
  138018. static float _vq_quantthresh__16u0__p2_0[] = {
  138019. -0.5, 0.5,
  138020. };
  138021. static long _vq_quantmap__16u0__p2_0[] = {
  138022. 1, 0, 2,
  138023. };
  138024. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  138025. _vq_quantthresh__16u0__p2_0,
  138026. _vq_quantmap__16u0__p2_0,
  138027. 3,
  138028. 3
  138029. };
  138030. static static_codebook _16u0__p2_0 = {
  138031. 4, 81,
  138032. _vq_lengthlist__16u0__p2_0,
  138033. 1, -535822336, 1611661312, 2, 0,
  138034. _vq_quantlist__16u0__p2_0,
  138035. NULL,
  138036. &_vq_auxt__16u0__p2_0,
  138037. NULL,
  138038. 0
  138039. };
  138040. static long _vq_quantlist__16u0__p3_0[] = {
  138041. 2,
  138042. 1,
  138043. 3,
  138044. 0,
  138045. 4,
  138046. };
  138047. static long _vq_lengthlist__16u0__p3_0[] = {
  138048. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  138049. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  138050. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  138051. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  138052. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  138053. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  138054. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  138055. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  138056. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  138057. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  138058. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  138059. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  138060. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  138061. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  138062. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  138063. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  138064. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  138065. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  138066. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  138067. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  138068. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  138069. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  138070. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  138071. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  138072. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  138073. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  138074. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  138075. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  138076. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  138077. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  138078. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  138079. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  138080. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  138081. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  138082. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  138083. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  138084. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  138085. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  138086. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  138087. 18,
  138088. };
  138089. static float _vq_quantthresh__16u0__p3_0[] = {
  138090. -1.5, -0.5, 0.5, 1.5,
  138091. };
  138092. static long _vq_quantmap__16u0__p3_0[] = {
  138093. 3, 1, 0, 2, 4,
  138094. };
  138095. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  138096. _vq_quantthresh__16u0__p3_0,
  138097. _vq_quantmap__16u0__p3_0,
  138098. 5,
  138099. 5
  138100. };
  138101. static static_codebook _16u0__p3_0 = {
  138102. 4, 625,
  138103. _vq_lengthlist__16u0__p3_0,
  138104. 1, -533725184, 1611661312, 3, 0,
  138105. _vq_quantlist__16u0__p3_0,
  138106. NULL,
  138107. &_vq_auxt__16u0__p3_0,
  138108. NULL,
  138109. 0
  138110. };
  138111. static long _vq_quantlist__16u0__p4_0[] = {
  138112. 2,
  138113. 1,
  138114. 3,
  138115. 0,
  138116. 4,
  138117. };
  138118. static long _vq_lengthlist__16u0__p4_0[] = {
  138119. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  138120. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  138121. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  138122. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  138123. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  138124. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  138125. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  138126. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  138127. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  138128. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  138129. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  138130. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  138131. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  138132. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  138133. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  138134. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  138135. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  138136. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  138137. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  138138. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  138139. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  138140. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  138141. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  138142. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  138143. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  138144. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  138145. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  138146. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  138147. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  138148. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  138149. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  138150. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  138151. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  138152. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  138153. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  138154. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  138155. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  138156. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  138157. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  138158. 11,
  138159. };
  138160. static float _vq_quantthresh__16u0__p4_0[] = {
  138161. -1.5, -0.5, 0.5, 1.5,
  138162. };
  138163. static long _vq_quantmap__16u0__p4_0[] = {
  138164. 3, 1, 0, 2, 4,
  138165. };
  138166. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  138167. _vq_quantthresh__16u0__p4_0,
  138168. _vq_quantmap__16u0__p4_0,
  138169. 5,
  138170. 5
  138171. };
  138172. static static_codebook _16u0__p4_0 = {
  138173. 4, 625,
  138174. _vq_lengthlist__16u0__p4_0,
  138175. 1, -533725184, 1611661312, 3, 0,
  138176. _vq_quantlist__16u0__p4_0,
  138177. NULL,
  138178. &_vq_auxt__16u0__p4_0,
  138179. NULL,
  138180. 0
  138181. };
  138182. static long _vq_quantlist__16u0__p5_0[] = {
  138183. 4,
  138184. 3,
  138185. 5,
  138186. 2,
  138187. 6,
  138188. 1,
  138189. 7,
  138190. 0,
  138191. 8,
  138192. };
  138193. static long _vq_lengthlist__16u0__p5_0[] = {
  138194. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  138195. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  138196. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  138197. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  138198. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  138199. 12,
  138200. };
  138201. static float _vq_quantthresh__16u0__p5_0[] = {
  138202. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138203. };
  138204. static long _vq_quantmap__16u0__p5_0[] = {
  138205. 7, 5, 3, 1, 0, 2, 4, 6,
  138206. 8,
  138207. };
  138208. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  138209. _vq_quantthresh__16u0__p5_0,
  138210. _vq_quantmap__16u0__p5_0,
  138211. 9,
  138212. 9
  138213. };
  138214. static static_codebook _16u0__p5_0 = {
  138215. 2, 81,
  138216. _vq_lengthlist__16u0__p5_0,
  138217. 1, -531628032, 1611661312, 4, 0,
  138218. _vq_quantlist__16u0__p5_0,
  138219. NULL,
  138220. &_vq_auxt__16u0__p5_0,
  138221. NULL,
  138222. 0
  138223. };
  138224. static long _vq_quantlist__16u0__p6_0[] = {
  138225. 6,
  138226. 5,
  138227. 7,
  138228. 4,
  138229. 8,
  138230. 3,
  138231. 9,
  138232. 2,
  138233. 10,
  138234. 1,
  138235. 11,
  138236. 0,
  138237. 12,
  138238. };
  138239. static long _vq_lengthlist__16u0__p6_0[] = {
  138240. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  138241. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  138242. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  138243. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  138244. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  138245. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  138246. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  138247. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  138248. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  138249. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  138250. 18, 0,19, 0, 0, 0, 0, 0, 0,
  138251. };
  138252. static float _vq_quantthresh__16u0__p6_0[] = {
  138253. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138254. 12.5, 17.5, 22.5, 27.5,
  138255. };
  138256. static long _vq_quantmap__16u0__p6_0[] = {
  138257. 11, 9, 7, 5, 3, 1, 0, 2,
  138258. 4, 6, 8, 10, 12,
  138259. };
  138260. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  138261. _vq_quantthresh__16u0__p6_0,
  138262. _vq_quantmap__16u0__p6_0,
  138263. 13,
  138264. 13
  138265. };
  138266. static static_codebook _16u0__p6_0 = {
  138267. 2, 169,
  138268. _vq_lengthlist__16u0__p6_0,
  138269. 1, -526516224, 1616117760, 4, 0,
  138270. _vq_quantlist__16u0__p6_0,
  138271. NULL,
  138272. &_vq_auxt__16u0__p6_0,
  138273. NULL,
  138274. 0
  138275. };
  138276. static long _vq_quantlist__16u0__p6_1[] = {
  138277. 2,
  138278. 1,
  138279. 3,
  138280. 0,
  138281. 4,
  138282. };
  138283. static long _vq_lengthlist__16u0__p6_1[] = {
  138284. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  138285. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  138286. };
  138287. static float _vq_quantthresh__16u0__p6_1[] = {
  138288. -1.5, -0.5, 0.5, 1.5,
  138289. };
  138290. static long _vq_quantmap__16u0__p6_1[] = {
  138291. 3, 1, 0, 2, 4,
  138292. };
  138293. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  138294. _vq_quantthresh__16u0__p6_1,
  138295. _vq_quantmap__16u0__p6_1,
  138296. 5,
  138297. 5
  138298. };
  138299. static static_codebook _16u0__p6_1 = {
  138300. 2, 25,
  138301. _vq_lengthlist__16u0__p6_1,
  138302. 1, -533725184, 1611661312, 3, 0,
  138303. _vq_quantlist__16u0__p6_1,
  138304. NULL,
  138305. &_vq_auxt__16u0__p6_1,
  138306. NULL,
  138307. 0
  138308. };
  138309. static long _vq_quantlist__16u0__p7_0[] = {
  138310. 1,
  138311. 0,
  138312. 2,
  138313. };
  138314. static long _vq_lengthlist__16u0__p7_0[] = {
  138315. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138316. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138317. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138318. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138319. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138320. 7,
  138321. };
  138322. static float _vq_quantthresh__16u0__p7_0[] = {
  138323. -157.5, 157.5,
  138324. };
  138325. static long _vq_quantmap__16u0__p7_0[] = {
  138326. 1, 0, 2,
  138327. };
  138328. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  138329. _vq_quantthresh__16u0__p7_0,
  138330. _vq_quantmap__16u0__p7_0,
  138331. 3,
  138332. 3
  138333. };
  138334. static static_codebook _16u0__p7_0 = {
  138335. 4, 81,
  138336. _vq_lengthlist__16u0__p7_0,
  138337. 1, -518803456, 1628680192, 2, 0,
  138338. _vq_quantlist__16u0__p7_0,
  138339. NULL,
  138340. &_vq_auxt__16u0__p7_0,
  138341. NULL,
  138342. 0
  138343. };
  138344. static long _vq_quantlist__16u0__p7_1[] = {
  138345. 7,
  138346. 6,
  138347. 8,
  138348. 5,
  138349. 9,
  138350. 4,
  138351. 10,
  138352. 3,
  138353. 11,
  138354. 2,
  138355. 12,
  138356. 1,
  138357. 13,
  138358. 0,
  138359. 14,
  138360. };
  138361. static long _vq_lengthlist__16u0__p7_1[] = {
  138362. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  138363. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  138364. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  138365. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  138366. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  138367. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  138368. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138369. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138370. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138371. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138372. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138373. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138374. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138375. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138376. 10,
  138377. };
  138378. static float _vq_quantthresh__16u0__p7_1[] = {
  138379. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138380. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138381. };
  138382. static long _vq_quantmap__16u0__p7_1[] = {
  138383. 13, 11, 9, 7, 5, 3, 1, 0,
  138384. 2, 4, 6, 8, 10, 12, 14,
  138385. };
  138386. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  138387. _vq_quantthresh__16u0__p7_1,
  138388. _vq_quantmap__16u0__p7_1,
  138389. 15,
  138390. 15
  138391. };
  138392. static static_codebook _16u0__p7_1 = {
  138393. 2, 225,
  138394. _vq_lengthlist__16u0__p7_1,
  138395. 1, -520986624, 1620377600, 4, 0,
  138396. _vq_quantlist__16u0__p7_1,
  138397. NULL,
  138398. &_vq_auxt__16u0__p7_1,
  138399. NULL,
  138400. 0
  138401. };
  138402. static long _vq_quantlist__16u0__p7_2[] = {
  138403. 10,
  138404. 9,
  138405. 11,
  138406. 8,
  138407. 12,
  138408. 7,
  138409. 13,
  138410. 6,
  138411. 14,
  138412. 5,
  138413. 15,
  138414. 4,
  138415. 16,
  138416. 3,
  138417. 17,
  138418. 2,
  138419. 18,
  138420. 1,
  138421. 19,
  138422. 0,
  138423. 20,
  138424. };
  138425. static long _vq_lengthlist__16u0__p7_2[] = {
  138426. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  138427. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  138428. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  138429. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  138430. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  138431. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  138432. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  138433. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  138434. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  138435. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  138436. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  138437. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  138438. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  138439. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  138440. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  138441. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  138442. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  138443. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  138444. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  138445. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  138446. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  138447. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  138448. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  138449. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  138450. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  138451. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  138452. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  138453. 10,10,12,11,10,11,11,11,10,
  138454. };
  138455. static float _vq_quantthresh__16u0__p7_2[] = {
  138456. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138457. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138458. 6.5, 7.5, 8.5, 9.5,
  138459. };
  138460. static long _vq_quantmap__16u0__p7_2[] = {
  138461. 19, 17, 15, 13, 11, 9, 7, 5,
  138462. 3, 1, 0, 2, 4, 6, 8, 10,
  138463. 12, 14, 16, 18, 20,
  138464. };
  138465. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  138466. _vq_quantthresh__16u0__p7_2,
  138467. _vq_quantmap__16u0__p7_2,
  138468. 21,
  138469. 21
  138470. };
  138471. static static_codebook _16u0__p7_2 = {
  138472. 2, 441,
  138473. _vq_lengthlist__16u0__p7_2,
  138474. 1, -529268736, 1611661312, 5, 0,
  138475. _vq_quantlist__16u0__p7_2,
  138476. NULL,
  138477. &_vq_auxt__16u0__p7_2,
  138478. NULL,
  138479. 0
  138480. };
  138481. static long _huff_lengthlist__16u0__single[] = {
  138482. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  138483. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  138484. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  138485. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  138486. };
  138487. static static_codebook _huff_book__16u0__single = {
  138488. 2, 64,
  138489. _huff_lengthlist__16u0__single,
  138490. 0, 0, 0, 0, 0,
  138491. NULL,
  138492. NULL,
  138493. NULL,
  138494. NULL,
  138495. 0
  138496. };
  138497. static long _huff_lengthlist__16u1__long[] = {
  138498. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  138499. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  138500. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  138501. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  138502. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  138503. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  138504. 16,13,16,18,
  138505. };
  138506. static static_codebook _huff_book__16u1__long = {
  138507. 2, 100,
  138508. _huff_lengthlist__16u1__long,
  138509. 0, 0, 0, 0, 0,
  138510. NULL,
  138511. NULL,
  138512. NULL,
  138513. NULL,
  138514. 0
  138515. };
  138516. static long _vq_quantlist__16u1__p1_0[] = {
  138517. 1,
  138518. 0,
  138519. 2,
  138520. };
  138521. static long _vq_lengthlist__16u1__p1_0[] = {
  138522. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  138523. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  138524. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  138525. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  138526. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  138527. 11,
  138528. };
  138529. static float _vq_quantthresh__16u1__p1_0[] = {
  138530. -0.5, 0.5,
  138531. };
  138532. static long _vq_quantmap__16u1__p1_0[] = {
  138533. 1, 0, 2,
  138534. };
  138535. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  138536. _vq_quantthresh__16u1__p1_0,
  138537. _vq_quantmap__16u1__p1_0,
  138538. 3,
  138539. 3
  138540. };
  138541. static static_codebook _16u1__p1_0 = {
  138542. 4, 81,
  138543. _vq_lengthlist__16u1__p1_0,
  138544. 1, -535822336, 1611661312, 2, 0,
  138545. _vq_quantlist__16u1__p1_0,
  138546. NULL,
  138547. &_vq_auxt__16u1__p1_0,
  138548. NULL,
  138549. 0
  138550. };
  138551. static long _vq_quantlist__16u1__p2_0[] = {
  138552. 1,
  138553. 0,
  138554. 2,
  138555. };
  138556. static long _vq_lengthlist__16u1__p2_0[] = {
  138557. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  138558. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  138559. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  138560. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  138561. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  138562. 8,
  138563. };
  138564. static float _vq_quantthresh__16u1__p2_0[] = {
  138565. -0.5, 0.5,
  138566. };
  138567. static long _vq_quantmap__16u1__p2_0[] = {
  138568. 1, 0, 2,
  138569. };
  138570. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  138571. _vq_quantthresh__16u1__p2_0,
  138572. _vq_quantmap__16u1__p2_0,
  138573. 3,
  138574. 3
  138575. };
  138576. static static_codebook _16u1__p2_0 = {
  138577. 4, 81,
  138578. _vq_lengthlist__16u1__p2_0,
  138579. 1, -535822336, 1611661312, 2, 0,
  138580. _vq_quantlist__16u1__p2_0,
  138581. NULL,
  138582. &_vq_auxt__16u1__p2_0,
  138583. NULL,
  138584. 0
  138585. };
  138586. static long _vq_quantlist__16u1__p3_0[] = {
  138587. 2,
  138588. 1,
  138589. 3,
  138590. 0,
  138591. 4,
  138592. };
  138593. static long _vq_lengthlist__16u1__p3_0[] = {
  138594. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  138595. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  138596. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  138597. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  138598. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  138599. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  138600. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  138601. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  138602. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  138603. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  138604. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  138605. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  138606. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  138607. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  138608. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  138609. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  138610. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  138611. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  138612. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  138613. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  138614. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  138615. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  138616. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  138617. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  138618. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  138619. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  138620. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  138621. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  138622. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  138623. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  138624. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  138625. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  138626. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  138627. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  138628. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  138629. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  138630. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  138631. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  138632. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  138633. 16,
  138634. };
  138635. static float _vq_quantthresh__16u1__p3_0[] = {
  138636. -1.5, -0.5, 0.5, 1.5,
  138637. };
  138638. static long _vq_quantmap__16u1__p3_0[] = {
  138639. 3, 1, 0, 2, 4,
  138640. };
  138641. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  138642. _vq_quantthresh__16u1__p3_0,
  138643. _vq_quantmap__16u1__p3_0,
  138644. 5,
  138645. 5
  138646. };
  138647. static static_codebook _16u1__p3_0 = {
  138648. 4, 625,
  138649. _vq_lengthlist__16u1__p3_0,
  138650. 1, -533725184, 1611661312, 3, 0,
  138651. _vq_quantlist__16u1__p3_0,
  138652. NULL,
  138653. &_vq_auxt__16u1__p3_0,
  138654. NULL,
  138655. 0
  138656. };
  138657. static long _vq_quantlist__16u1__p4_0[] = {
  138658. 2,
  138659. 1,
  138660. 3,
  138661. 0,
  138662. 4,
  138663. };
  138664. static long _vq_lengthlist__16u1__p4_0[] = {
  138665. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  138666. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  138667. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  138668. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  138669. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  138670. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  138671. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  138672. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  138673. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  138674. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  138675. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  138676. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  138677. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  138678. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  138679. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  138680. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  138681. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  138682. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  138683. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  138684. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  138685. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  138686. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  138687. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  138688. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  138689. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  138690. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  138691. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  138692. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  138693. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  138694. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  138695. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  138696. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  138697. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  138698. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  138699. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  138700. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  138701. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  138702. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  138703. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  138704. 11,
  138705. };
  138706. static float _vq_quantthresh__16u1__p4_0[] = {
  138707. -1.5, -0.5, 0.5, 1.5,
  138708. };
  138709. static long _vq_quantmap__16u1__p4_0[] = {
  138710. 3, 1, 0, 2, 4,
  138711. };
  138712. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  138713. _vq_quantthresh__16u1__p4_0,
  138714. _vq_quantmap__16u1__p4_0,
  138715. 5,
  138716. 5
  138717. };
  138718. static static_codebook _16u1__p4_0 = {
  138719. 4, 625,
  138720. _vq_lengthlist__16u1__p4_0,
  138721. 1, -533725184, 1611661312, 3, 0,
  138722. _vq_quantlist__16u1__p4_0,
  138723. NULL,
  138724. &_vq_auxt__16u1__p4_0,
  138725. NULL,
  138726. 0
  138727. };
  138728. static long _vq_quantlist__16u1__p5_0[] = {
  138729. 4,
  138730. 3,
  138731. 5,
  138732. 2,
  138733. 6,
  138734. 1,
  138735. 7,
  138736. 0,
  138737. 8,
  138738. };
  138739. static long _vq_lengthlist__16u1__p5_0[] = {
  138740. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  138741. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  138742. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  138743. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  138744. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  138745. 13,
  138746. };
  138747. static float _vq_quantthresh__16u1__p5_0[] = {
  138748. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138749. };
  138750. static long _vq_quantmap__16u1__p5_0[] = {
  138751. 7, 5, 3, 1, 0, 2, 4, 6,
  138752. 8,
  138753. };
  138754. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  138755. _vq_quantthresh__16u1__p5_0,
  138756. _vq_quantmap__16u1__p5_0,
  138757. 9,
  138758. 9
  138759. };
  138760. static static_codebook _16u1__p5_0 = {
  138761. 2, 81,
  138762. _vq_lengthlist__16u1__p5_0,
  138763. 1, -531628032, 1611661312, 4, 0,
  138764. _vq_quantlist__16u1__p5_0,
  138765. NULL,
  138766. &_vq_auxt__16u1__p5_0,
  138767. NULL,
  138768. 0
  138769. };
  138770. static long _vq_quantlist__16u1__p6_0[] = {
  138771. 4,
  138772. 3,
  138773. 5,
  138774. 2,
  138775. 6,
  138776. 1,
  138777. 7,
  138778. 0,
  138779. 8,
  138780. };
  138781. static long _vq_lengthlist__16u1__p6_0[] = {
  138782. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  138783. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  138784. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  138785. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  138786. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  138787. 11,
  138788. };
  138789. static float _vq_quantthresh__16u1__p6_0[] = {
  138790. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138791. };
  138792. static long _vq_quantmap__16u1__p6_0[] = {
  138793. 7, 5, 3, 1, 0, 2, 4, 6,
  138794. 8,
  138795. };
  138796. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  138797. _vq_quantthresh__16u1__p6_0,
  138798. _vq_quantmap__16u1__p6_0,
  138799. 9,
  138800. 9
  138801. };
  138802. static static_codebook _16u1__p6_0 = {
  138803. 2, 81,
  138804. _vq_lengthlist__16u1__p6_0,
  138805. 1, -531628032, 1611661312, 4, 0,
  138806. _vq_quantlist__16u1__p6_0,
  138807. NULL,
  138808. &_vq_auxt__16u1__p6_0,
  138809. NULL,
  138810. 0
  138811. };
  138812. static long _vq_quantlist__16u1__p7_0[] = {
  138813. 1,
  138814. 0,
  138815. 2,
  138816. };
  138817. static long _vq_lengthlist__16u1__p7_0[] = {
  138818. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  138819. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  138820. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  138821. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  138822. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  138823. 13,
  138824. };
  138825. static float _vq_quantthresh__16u1__p7_0[] = {
  138826. -5.5, 5.5,
  138827. };
  138828. static long _vq_quantmap__16u1__p7_0[] = {
  138829. 1, 0, 2,
  138830. };
  138831. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  138832. _vq_quantthresh__16u1__p7_0,
  138833. _vq_quantmap__16u1__p7_0,
  138834. 3,
  138835. 3
  138836. };
  138837. static static_codebook _16u1__p7_0 = {
  138838. 4, 81,
  138839. _vq_lengthlist__16u1__p7_0,
  138840. 1, -529137664, 1618345984, 2, 0,
  138841. _vq_quantlist__16u1__p7_0,
  138842. NULL,
  138843. &_vq_auxt__16u1__p7_0,
  138844. NULL,
  138845. 0
  138846. };
  138847. static long _vq_quantlist__16u1__p7_1[] = {
  138848. 5,
  138849. 4,
  138850. 6,
  138851. 3,
  138852. 7,
  138853. 2,
  138854. 8,
  138855. 1,
  138856. 9,
  138857. 0,
  138858. 10,
  138859. };
  138860. static long _vq_lengthlist__16u1__p7_1[] = {
  138861. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  138862. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  138863. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  138864. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  138865. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  138866. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  138867. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  138868. 8, 9, 9,10,10,10,10,10,10,
  138869. };
  138870. static float _vq_quantthresh__16u1__p7_1[] = {
  138871. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138872. 3.5, 4.5,
  138873. };
  138874. static long _vq_quantmap__16u1__p7_1[] = {
  138875. 9, 7, 5, 3, 1, 0, 2, 4,
  138876. 6, 8, 10,
  138877. };
  138878. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  138879. _vq_quantthresh__16u1__p7_1,
  138880. _vq_quantmap__16u1__p7_1,
  138881. 11,
  138882. 11
  138883. };
  138884. static static_codebook _16u1__p7_1 = {
  138885. 2, 121,
  138886. _vq_lengthlist__16u1__p7_1,
  138887. 1, -531365888, 1611661312, 4, 0,
  138888. _vq_quantlist__16u1__p7_1,
  138889. NULL,
  138890. &_vq_auxt__16u1__p7_1,
  138891. NULL,
  138892. 0
  138893. };
  138894. static long _vq_quantlist__16u1__p8_0[] = {
  138895. 5,
  138896. 4,
  138897. 6,
  138898. 3,
  138899. 7,
  138900. 2,
  138901. 8,
  138902. 1,
  138903. 9,
  138904. 0,
  138905. 10,
  138906. };
  138907. static long _vq_lengthlist__16u1__p8_0[] = {
  138908. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  138909. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  138910. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  138911. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  138912. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  138913. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  138914. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  138915. 13,14,14,15,15,16,16,15,16,
  138916. };
  138917. static float _vq_quantthresh__16u1__p8_0[] = {
  138918. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  138919. 38.5, 49.5,
  138920. };
  138921. static long _vq_quantmap__16u1__p8_0[] = {
  138922. 9, 7, 5, 3, 1, 0, 2, 4,
  138923. 6, 8, 10,
  138924. };
  138925. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  138926. _vq_quantthresh__16u1__p8_0,
  138927. _vq_quantmap__16u1__p8_0,
  138928. 11,
  138929. 11
  138930. };
  138931. static static_codebook _16u1__p8_0 = {
  138932. 2, 121,
  138933. _vq_lengthlist__16u1__p8_0,
  138934. 1, -524582912, 1618345984, 4, 0,
  138935. _vq_quantlist__16u1__p8_0,
  138936. NULL,
  138937. &_vq_auxt__16u1__p8_0,
  138938. NULL,
  138939. 0
  138940. };
  138941. static long _vq_quantlist__16u1__p8_1[] = {
  138942. 5,
  138943. 4,
  138944. 6,
  138945. 3,
  138946. 7,
  138947. 2,
  138948. 8,
  138949. 1,
  138950. 9,
  138951. 0,
  138952. 10,
  138953. };
  138954. static long _vq_lengthlist__16u1__p8_1[] = {
  138955. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  138956. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  138957. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  138958. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  138959. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  138960. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  138961. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  138962. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  138963. };
  138964. static float _vq_quantthresh__16u1__p8_1[] = {
  138965. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138966. 3.5, 4.5,
  138967. };
  138968. static long _vq_quantmap__16u1__p8_1[] = {
  138969. 9, 7, 5, 3, 1, 0, 2, 4,
  138970. 6, 8, 10,
  138971. };
  138972. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  138973. _vq_quantthresh__16u1__p8_1,
  138974. _vq_quantmap__16u1__p8_1,
  138975. 11,
  138976. 11
  138977. };
  138978. static static_codebook _16u1__p8_1 = {
  138979. 2, 121,
  138980. _vq_lengthlist__16u1__p8_1,
  138981. 1, -531365888, 1611661312, 4, 0,
  138982. _vq_quantlist__16u1__p8_1,
  138983. NULL,
  138984. &_vq_auxt__16u1__p8_1,
  138985. NULL,
  138986. 0
  138987. };
  138988. static long _vq_quantlist__16u1__p9_0[] = {
  138989. 7,
  138990. 6,
  138991. 8,
  138992. 5,
  138993. 9,
  138994. 4,
  138995. 10,
  138996. 3,
  138997. 11,
  138998. 2,
  138999. 12,
  139000. 1,
  139001. 13,
  139002. 0,
  139003. 14,
  139004. };
  139005. static long _vq_lengthlist__16u1__p9_0[] = {
  139006. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139007. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139008. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139009. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139010. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139011. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139012. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139013. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139014. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139015. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139016. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139017. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139018. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139019. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139020. 8,
  139021. };
  139022. static float _vq_quantthresh__16u1__p9_0[] = {
  139023. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  139024. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  139025. };
  139026. static long _vq_quantmap__16u1__p9_0[] = {
  139027. 13, 11, 9, 7, 5, 3, 1, 0,
  139028. 2, 4, 6, 8, 10, 12, 14,
  139029. };
  139030. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  139031. _vq_quantthresh__16u1__p9_0,
  139032. _vq_quantmap__16u1__p9_0,
  139033. 15,
  139034. 15
  139035. };
  139036. static static_codebook _16u1__p9_0 = {
  139037. 2, 225,
  139038. _vq_lengthlist__16u1__p9_0,
  139039. 1, -514071552, 1627381760, 4, 0,
  139040. _vq_quantlist__16u1__p9_0,
  139041. NULL,
  139042. &_vq_auxt__16u1__p9_0,
  139043. NULL,
  139044. 0
  139045. };
  139046. static long _vq_quantlist__16u1__p9_1[] = {
  139047. 7,
  139048. 6,
  139049. 8,
  139050. 5,
  139051. 9,
  139052. 4,
  139053. 10,
  139054. 3,
  139055. 11,
  139056. 2,
  139057. 12,
  139058. 1,
  139059. 13,
  139060. 0,
  139061. 14,
  139062. };
  139063. static long _vq_lengthlist__16u1__p9_1[] = {
  139064. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  139065. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  139066. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  139067. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  139068. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  139069. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  139070. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  139071. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  139072. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  139073. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139074. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  139075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139076. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139077. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139078. 9,
  139079. };
  139080. static float _vq_quantthresh__16u1__p9_1[] = {
  139081. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  139082. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  139083. };
  139084. static long _vq_quantmap__16u1__p9_1[] = {
  139085. 13, 11, 9, 7, 5, 3, 1, 0,
  139086. 2, 4, 6, 8, 10, 12, 14,
  139087. };
  139088. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  139089. _vq_quantthresh__16u1__p9_1,
  139090. _vq_quantmap__16u1__p9_1,
  139091. 15,
  139092. 15
  139093. };
  139094. static static_codebook _16u1__p9_1 = {
  139095. 2, 225,
  139096. _vq_lengthlist__16u1__p9_1,
  139097. 1, -522338304, 1620115456, 4, 0,
  139098. _vq_quantlist__16u1__p9_1,
  139099. NULL,
  139100. &_vq_auxt__16u1__p9_1,
  139101. NULL,
  139102. 0
  139103. };
  139104. static long _vq_quantlist__16u1__p9_2[] = {
  139105. 8,
  139106. 7,
  139107. 9,
  139108. 6,
  139109. 10,
  139110. 5,
  139111. 11,
  139112. 4,
  139113. 12,
  139114. 3,
  139115. 13,
  139116. 2,
  139117. 14,
  139118. 1,
  139119. 15,
  139120. 0,
  139121. 16,
  139122. };
  139123. static long _vq_lengthlist__16u1__p9_2[] = {
  139124. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  139125. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  139126. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  139127. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  139128. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  139129. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  139130. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  139131. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  139132. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  139133. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  139134. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  139135. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  139136. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  139137. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  139138. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  139139. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  139140. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  139141. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  139142. 10,
  139143. };
  139144. static float _vq_quantthresh__16u1__p9_2[] = {
  139145. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139146. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139147. };
  139148. static long _vq_quantmap__16u1__p9_2[] = {
  139149. 15, 13, 11, 9, 7, 5, 3, 1,
  139150. 0, 2, 4, 6, 8, 10, 12, 14,
  139151. 16,
  139152. };
  139153. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  139154. _vq_quantthresh__16u1__p9_2,
  139155. _vq_quantmap__16u1__p9_2,
  139156. 17,
  139157. 17
  139158. };
  139159. static static_codebook _16u1__p9_2 = {
  139160. 2, 289,
  139161. _vq_lengthlist__16u1__p9_2,
  139162. 1, -529530880, 1611661312, 5, 0,
  139163. _vq_quantlist__16u1__p9_2,
  139164. NULL,
  139165. &_vq_auxt__16u1__p9_2,
  139166. NULL,
  139167. 0
  139168. };
  139169. static long _huff_lengthlist__16u1__short[] = {
  139170. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  139171. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  139172. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  139173. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  139174. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  139175. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  139176. 16,16,16,16,
  139177. };
  139178. static static_codebook _huff_book__16u1__short = {
  139179. 2, 100,
  139180. _huff_lengthlist__16u1__short,
  139181. 0, 0, 0, 0, 0,
  139182. NULL,
  139183. NULL,
  139184. NULL,
  139185. NULL,
  139186. 0
  139187. };
  139188. static long _huff_lengthlist__16u2__long[] = {
  139189. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  139190. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  139191. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  139192. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  139193. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  139194. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  139195. 13,14,18,18,
  139196. };
  139197. static static_codebook _huff_book__16u2__long = {
  139198. 2, 100,
  139199. _huff_lengthlist__16u2__long,
  139200. 0, 0, 0, 0, 0,
  139201. NULL,
  139202. NULL,
  139203. NULL,
  139204. NULL,
  139205. 0
  139206. };
  139207. static long _huff_lengthlist__16u2__short[] = {
  139208. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  139209. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  139210. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  139211. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  139212. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  139213. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  139214. 16,16,16,16,
  139215. };
  139216. static static_codebook _huff_book__16u2__short = {
  139217. 2, 100,
  139218. _huff_lengthlist__16u2__short,
  139219. 0, 0, 0, 0, 0,
  139220. NULL,
  139221. NULL,
  139222. NULL,
  139223. NULL,
  139224. 0
  139225. };
  139226. static long _vq_quantlist__16u2_p1_0[] = {
  139227. 1,
  139228. 0,
  139229. 2,
  139230. };
  139231. static long _vq_lengthlist__16u2_p1_0[] = {
  139232. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  139233. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  139234. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  139235. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  139236. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  139237. 10,
  139238. };
  139239. static float _vq_quantthresh__16u2_p1_0[] = {
  139240. -0.5, 0.5,
  139241. };
  139242. static long _vq_quantmap__16u2_p1_0[] = {
  139243. 1, 0, 2,
  139244. };
  139245. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  139246. _vq_quantthresh__16u2_p1_0,
  139247. _vq_quantmap__16u2_p1_0,
  139248. 3,
  139249. 3
  139250. };
  139251. static static_codebook _16u2_p1_0 = {
  139252. 4, 81,
  139253. _vq_lengthlist__16u2_p1_0,
  139254. 1, -535822336, 1611661312, 2, 0,
  139255. _vq_quantlist__16u2_p1_0,
  139256. NULL,
  139257. &_vq_auxt__16u2_p1_0,
  139258. NULL,
  139259. 0
  139260. };
  139261. static long _vq_quantlist__16u2_p2_0[] = {
  139262. 2,
  139263. 1,
  139264. 3,
  139265. 0,
  139266. 4,
  139267. };
  139268. static long _vq_lengthlist__16u2_p2_0[] = {
  139269. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139270. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  139271. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  139272. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  139273. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  139274. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  139275. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  139276. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  139277. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  139278. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  139279. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  139280. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  139281. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  139282. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  139283. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  139284. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  139285. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  139286. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  139287. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  139288. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  139289. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  139290. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  139291. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  139292. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  139293. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  139294. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  139295. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  139296. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  139297. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  139298. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  139299. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  139300. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  139301. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  139302. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  139303. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  139304. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  139305. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  139306. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  139307. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  139308. 13,
  139309. };
  139310. static float _vq_quantthresh__16u2_p2_0[] = {
  139311. -1.5, -0.5, 0.5, 1.5,
  139312. };
  139313. static long _vq_quantmap__16u2_p2_0[] = {
  139314. 3, 1, 0, 2, 4,
  139315. };
  139316. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  139317. _vq_quantthresh__16u2_p2_0,
  139318. _vq_quantmap__16u2_p2_0,
  139319. 5,
  139320. 5
  139321. };
  139322. static static_codebook _16u2_p2_0 = {
  139323. 4, 625,
  139324. _vq_lengthlist__16u2_p2_0,
  139325. 1, -533725184, 1611661312, 3, 0,
  139326. _vq_quantlist__16u2_p2_0,
  139327. NULL,
  139328. &_vq_auxt__16u2_p2_0,
  139329. NULL,
  139330. 0
  139331. };
  139332. static long _vq_quantlist__16u2_p3_0[] = {
  139333. 4,
  139334. 3,
  139335. 5,
  139336. 2,
  139337. 6,
  139338. 1,
  139339. 7,
  139340. 0,
  139341. 8,
  139342. };
  139343. static long _vq_lengthlist__16u2_p3_0[] = {
  139344. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  139345. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  139346. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  139347. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  139348. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  139349. 11,
  139350. };
  139351. static float _vq_quantthresh__16u2_p3_0[] = {
  139352. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139353. };
  139354. static long _vq_quantmap__16u2_p3_0[] = {
  139355. 7, 5, 3, 1, 0, 2, 4, 6,
  139356. 8,
  139357. };
  139358. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  139359. _vq_quantthresh__16u2_p3_0,
  139360. _vq_quantmap__16u2_p3_0,
  139361. 9,
  139362. 9
  139363. };
  139364. static static_codebook _16u2_p3_0 = {
  139365. 2, 81,
  139366. _vq_lengthlist__16u2_p3_0,
  139367. 1, -531628032, 1611661312, 4, 0,
  139368. _vq_quantlist__16u2_p3_0,
  139369. NULL,
  139370. &_vq_auxt__16u2_p3_0,
  139371. NULL,
  139372. 0
  139373. };
  139374. static long _vq_quantlist__16u2_p4_0[] = {
  139375. 8,
  139376. 7,
  139377. 9,
  139378. 6,
  139379. 10,
  139380. 5,
  139381. 11,
  139382. 4,
  139383. 12,
  139384. 3,
  139385. 13,
  139386. 2,
  139387. 14,
  139388. 1,
  139389. 15,
  139390. 0,
  139391. 16,
  139392. };
  139393. static long _vq_lengthlist__16u2_p4_0[] = {
  139394. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  139395. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  139396. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  139397. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139398. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139399. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  139400. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  139401. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  139402. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  139403. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  139404. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  139405. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  139406. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  139407. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  139408. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  139409. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  139410. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  139411. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  139412. 14,
  139413. };
  139414. static float _vq_quantthresh__16u2_p4_0[] = {
  139415. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139416. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139417. };
  139418. static long _vq_quantmap__16u2_p4_0[] = {
  139419. 15, 13, 11, 9, 7, 5, 3, 1,
  139420. 0, 2, 4, 6, 8, 10, 12, 14,
  139421. 16,
  139422. };
  139423. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  139424. _vq_quantthresh__16u2_p4_0,
  139425. _vq_quantmap__16u2_p4_0,
  139426. 17,
  139427. 17
  139428. };
  139429. static static_codebook _16u2_p4_0 = {
  139430. 2, 289,
  139431. _vq_lengthlist__16u2_p4_0,
  139432. 1, -529530880, 1611661312, 5, 0,
  139433. _vq_quantlist__16u2_p4_0,
  139434. NULL,
  139435. &_vq_auxt__16u2_p4_0,
  139436. NULL,
  139437. 0
  139438. };
  139439. static long _vq_quantlist__16u2_p5_0[] = {
  139440. 1,
  139441. 0,
  139442. 2,
  139443. };
  139444. static long _vq_lengthlist__16u2_p5_0[] = {
  139445. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  139446. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  139447. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  139448. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  139449. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  139450. 10,
  139451. };
  139452. static float _vq_quantthresh__16u2_p5_0[] = {
  139453. -5.5, 5.5,
  139454. };
  139455. static long _vq_quantmap__16u2_p5_0[] = {
  139456. 1, 0, 2,
  139457. };
  139458. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  139459. _vq_quantthresh__16u2_p5_0,
  139460. _vq_quantmap__16u2_p5_0,
  139461. 3,
  139462. 3
  139463. };
  139464. static static_codebook _16u2_p5_0 = {
  139465. 4, 81,
  139466. _vq_lengthlist__16u2_p5_0,
  139467. 1, -529137664, 1618345984, 2, 0,
  139468. _vq_quantlist__16u2_p5_0,
  139469. NULL,
  139470. &_vq_auxt__16u2_p5_0,
  139471. NULL,
  139472. 0
  139473. };
  139474. static long _vq_quantlist__16u2_p5_1[] = {
  139475. 5,
  139476. 4,
  139477. 6,
  139478. 3,
  139479. 7,
  139480. 2,
  139481. 8,
  139482. 1,
  139483. 9,
  139484. 0,
  139485. 10,
  139486. };
  139487. static long _vq_lengthlist__16u2_p5_1[] = {
  139488. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  139489. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  139490. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  139491. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  139492. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  139493. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  139494. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  139495. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  139496. };
  139497. static float _vq_quantthresh__16u2_p5_1[] = {
  139498. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139499. 3.5, 4.5,
  139500. };
  139501. static long _vq_quantmap__16u2_p5_1[] = {
  139502. 9, 7, 5, 3, 1, 0, 2, 4,
  139503. 6, 8, 10,
  139504. };
  139505. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  139506. _vq_quantthresh__16u2_p5_1,
  139507. _vq_quantmap__16u2_p5_1,
  139508. 11,
  139509. 11
  139510. };
  139511. static static_codebook _16u2_p5_1 = {
  139512. 2, 121,
  139513. _vq_lengthlist__16u2_p5_1,
  139514. 1, -531365888, 1611661312, 4, 0,
  139515. _vq_quantlist__16u2_p5_1,
  139516. NULL,
  139517. &_vq_auxt__16u2_p5_1,
  139518. NULL,
  139519. 0
  139520. };
  139521. static long _vq_quantlist__16u2_p6_0[] = {
  139522. 6,
  139523. 5,
  139524. 7,
  139525. 4,
  139526. 8,
  139527. 3,
  139528. 9,
  139529. 2,
  139530. 10,
  139531. 1,
  139532. 11,
  139533. 0,
  139534. 12,
  139535. };
  139536. static long _vq_lengthlist__16u2_p6_0[] = {
  139537. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  139538. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  139539. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  139540. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  139541. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  139542. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  139543. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  139544. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  139545. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  139546. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  139547. 12,13,13,14,14,14,14,15,15,
  139548. };
  139549. static float _vq_quantthresh__16u2_p6_0[] = {
  139550. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139551. 12.5, 17.5, 22.5, 27.5,
  139552. };
  139553. static long _vq_quantmap__16u2_p6_0[] = {
  139554. 11, 9, 7, 5, 3, 1, 0, 2,
  139555. 4, 6, 8, 10, 12,
  139556. };
  139557. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  139558. _vq_quantthresh__16u2_p6_0,
  139559. _vq_quantmap__16u2_p6_0,
  139560. 13,
  139561. 13
  139562. };
  139563. static static_codebook _16u2_p6_0 = {
  139564. 2, 169,
  139565. _vq_lengthlist__16u2_p6_0,
  139566. 1, -526516224, 1616117760, 4, 0,
  139567. _vq_quantlist__16u2_p6_0,
  139568. NULL,
  139569. &_vq_auxt__16u2_p6_0,
  139570. NULL,
  139571. 0
  139572. };
  139573. static long _vq_quantlist__16u2_p6_1[] = {
  139574. 2,
  139575. 1,
  139576. 3,
  139577. 0,
  139578. 4,
  139579. };
  139580. static long _vq_lengthlist__16u2_p6_1[] = {
  139581. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  139582. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  139583. };
  139584. static float _vq_quantthresh__16u2_p6_1[] = {
  139585. -1.5, -0.5, 0.5, 1.5,
  139586. };
  139587. static long _vq_quantmap__16u2_p6_1[] = {
  139588. 3, 1, 0, 2, 4,
  139589. };
  139590. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  139591. _vq_quantthresh__16u2_p6_1,
  139592. _vq_quantmap__16u2_p6_1,
  139593. 5,
  139594. 5
  139595. };
  139596. static static_codebook _16u2_p6_1 = {
  139597. 2, 25,
  139598. _vq_lengthlist__16u2_p6_1,
  139599. 1, -533725184, 1611661312, 3, 0,
  139600. _vq_quantlist__16u2_p6_1,
  139601. NULL,
  139602. &_vq_auxt__16u2_p6_1,
  139603. NULL,
  139604. 0
  139605. };
  139606. static long _vq_quantlist__16u2_p7_0[] = {
  139607. 6,
  139608. 5,
  139609. 7,
  139610. 4,
  139611. 8,
  139612. 3,
  139613. 9,
  139614. 2,
  139615. 10,
  139616. 1,
  139617. 11,
  139618. 0,
  139619. 12,
  139620. };
  139621. static long _vq_lengthlist__16u2_p7_0[] = {
  139622. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  139623. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  139624. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  139625. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  139626. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  139627. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  139628. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  139629. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  139630. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  139631. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  139632. 12,13,13,13,14,14,14,15,14,
  139633. };
  139634. static float _vq_quantthresh__16u2_p7_0[] = {
  139635. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  139636. 27.5, 38.5, 49.5, 60.5,
  139637. };
  139638. static long _vq_quantmap__16u2_p7_0[] = {
  139639. 11, 9, 7, 5, 3, 1, 0, 2,
  139640. 4, 6, 8, 10, 12,
  139641. };
  139642. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  139643. _vq_quantthresh__16u2_p7_0,
  139644. _vq_quantmap__16u2_p7_0,
  139645. 13,
  139646. 13
  139647. };
  139648. static static_codebook _16u2_p7_0 = {
  139649. 2, 169,
  139650. _vq_lengthlist__16u2_p7_0,
  139651. 1, -523206656, 1618345984, 4, 0,
  139652. _vq_quantlist__16u2_p7_0,
  139653. NULL,
  139654. &_vq_auxt__16u2_p7_0,
  139655. NULL,
  139656. 0
  139657. };
  139658. static long _vq_quantlist__16u2_p7_1[] = {
  139659. 5,
  139660. 4,
  139661. 6,
  139662. 3,
  139663. 7,
  139664. 2,
  139665. 8,
  139666. 1,
  139667. 9,
  139668. 0,
  139669. 10,
  139670. };
  139671. static long _vq_lengthlist__16u2_p7_1[] = {
  139672. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  139673. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  139674. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  139675. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  139676. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  139677. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  139678. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  139679. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139680. };
  139681. static float _vq_quantthresh__16u2_p7_1[] = {
  139682. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139683. 3.5, 4.5,
  139684. };
  139685. static long _vq_quantmap__16u2_p7_1[] = {
  139686. 9, 7, 5, 3, 1, 0, 2, 4,
  139687. 6, 8, 10,
  139688. };
  139689. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  139690. _vq_quantthresh__16u2_p7_1,
  139691. _vq_quantmap__16u2_p7_1,
  139692. 11,
  139693. 11
  139694. };
  139695. static static_codebook _16u2_p7_1 = {
  139696. 2, 121,
  139697. _vq_lengthlist__16u2_p7_1,
  139698. 1, -531365888, 1611661312, 4, 0,
  139699. _vq_quantlist__16u2_p7_1,
  139700. NULL,
  139701. &_vq_auxt__16u2_p7_1,
  139702. NULL,
  139703. 0
  139704. };
  139705. static long _vq_quantlist__16u2_p8_0[] = {
  139706. 7,
  139707. 6,
  139708. 8,
  139709. 5,
  139710. 9,
  139711. 4,
  139712. 10,
  139713. 3,
  139714. 11,
  139715. 2,
  139716. 12,
  139717. 1,
  139718. 13,
  139719. 0,
  139720. 14,
  139721. };
  139722. static long _vq_lengthlist__16u2_p8_0[] = {
  139723. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  139724. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  139725. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  139726. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  139727. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  139728. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  139729. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  139730. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  139731. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  139732. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  139733. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  139734. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  139735. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  139736. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  139737. 14,
  139738. };
  139739. static float _vq_quantthresh__16u2_p8_0[] = {
  139740. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139741. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139742. };
  139743. static long _vq_quantmap__16u2_p8_0[] = {
  139744. 13, 11, 9, 7, 5, 3, 1, 0,
  139745. 2, 4, 6, 8, 10, 12, 14,
  139746. };
  139747. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  139748. _vq_quantthresh__16u2_p8_0,
  139749. _vq_quantmap__16u2_p8_0,
  139750. 15,
  139751. 15
  139752. };
  139753. static static_codebook _16u2_p8_0 = {
  139754. 2, 225,
  139755. _vq_lengthlist__16u2_p8_0,
  139756. 1, -520986624, 1620377600, 4, 0,
  139757. _vq_quantlist__16u2_p8_0,
  139758. NULL,
  139759. &_vq_auxt__16u2_p8_0,
  139760. NULL,
  139761. 0
  139762. };
  139763. static long _vq_quantlist__16u2_p8_1[] = {
  139764. 10,
  139765. 9,
  139766. 11,
  139767. 8,
  139768. 12,
  139769. 7,
  139770. 13,
  139771. 6,
  139772. 14,
  139773. 5,
  139774. 15,
  139775. 4,
  139776. 16,
  139777. 3,
  139778. 17,
  139779. 2,
  139780. 18,
  139781. 1,
  139782. 19,
  139783. 0,
  139784. 20,
  139785. };
  139786. static long _vq_lengthlist__16u2_p8_1[] = {
  139787. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  139788. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  139789. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  139790. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  139791. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  139792. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  139793. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  139794. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  139795. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  139796. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  139797. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  139798. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  139799. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  139800. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  139801. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  139802. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  139803. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  139804. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  139805. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  139806. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  139807. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  139808. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  139809. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  139810. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  139811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  139812. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  139813. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  139814. 11,11,10,11,11,11,10,11,11,
  139815. };
  139816. static float _vq_quantthresh__16u2_p8_1[] = {
  139817. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139818. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139819. 6.5, 7.5, 8.5, 9.5,
  139820. };
  139821. static long _vq_quantmap__16u2_p8_1[] = {
  139822. 19, 17, 15, 13, 11, 9, 7, 5,
  139823. 3, 1, 0, 2, 4, 6, 8, 10,
  139824. 12, 14, 16, 18, 20,
  139825. };
  139826. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  139827. _vq_quantthresh__16u2_p8_1,
  139828. _vq_quantmap__16u2_p8_1,
  139829. 21,
  139830. 21
  139831. };
  139832. static static_codebook _16u2_p8_1 = {
  139833. 2, 441,
  139834. _vq_lengthlist__16u2_p8_1,
  139835. 1, -529268736, 1611661312, 5, 0,
  139836. _vq_quantlist__16u2_p8_1,
  139837. NULL,
  139838. &_vq_auxt__16u2_p8_1,
  139839. NULL,
  139840. 0
  139841. };
  139842. static long _vq_quantlist__16u2_p9_0[] = {
  139843. 5586,
  139844. 4655,
  139845. 6517,
  139846. 3724,
  139847. 7448,
  139848. 2793,
  139849. 8379,
  139850. 1862,
  139851. 9310,
  139852. 931,
  139853. 10241,
  139854. 0,
  139855. 11172,
  139856. 5521,
  139857. 5651,
  139858. };
  139859. static long _vq_lengthlist__16u2_p9_0[] = {
  139860. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  139861. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139862. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139863. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139864. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139865. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139866. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139867. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139868. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139872. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  139873. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  139874. 5,
  139875. };
  139876. static float _vq_quantthresh__16u2_p9_0[] = {
  139877. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  139878. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  139879. };
  139880. static long _vq_quantmap__16u2_p9_0[] = {
  139881. 11, 9, 7, 5, 3, 1, 13, 0,
  139882. 14, 2, 4, 6, 8, 10, 12,
  139883. };
  139884. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  139885. _vq_quantthresh__16u2_p9_0,
  139886. _vq_quantmap__16u2_p9_0,
  139887. 15,
  139888. 15
  139889. };
  139890. static static_codebook _16u2_p9_0 = {
  139891. 2, 225,
  139892. _vq_lengthlist__16u2_p9_0,
  139893. 1, -510275072, 1611661312, 14, 0,
  139894. _vq_quantlist__16u2_p9_0,
  139895. NULL,
  139896. &_vq_auxt__16u2_p9_0,
  139897. NULL,
  139898. 0
  139899. };
  139900. static long _vq_quantlist__16u2_p9_1[] = {
  139901. 392,
  139902. 343,
  139903. 441,
  139904. 294,
  139905. 490,
  139906. 245,
  139907. 539,
  139908. 196,
  139909. 588,
  139910. 147,
  139911. 637,
  139912. 98,
  139913. 686,
  139914. 49,
  139915. 735,
  139916. 0,
  139917. 784,
  139918. 388,
  139919. 396,
  139920. };
  139921. static long _vq_lengthlist__16u2_p9_1[] = {
  139922. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  139923. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  139924. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  139925. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  139926. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  139927. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  139928. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139929. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  139930. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  139931. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139932. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139933. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139934. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139935. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139936. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  139937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139942. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  139943. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  139944. 11,11,11,11,11,11,11, 5, 4,
  139945. };
  139946. static float _vq_quantthresh__16u2_p9_1[] = {
  139947. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  139948. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  139949. 318.5, 367.5,
  139950. };
  139951. static long _vq_quantmap__16u2_p9_1[] = {
  139952. 15, 13, 11, 9, 7, 5, 3, 1,
  139953. 17, 0, 18, 2, 4, 6, 8, 10,
  139954. 12, 14, 16,
  139955. };
  139956. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  139957. _vq_quantthresh__16u2_p9_1,
  139958. _vq_quantmap__16u2_p9_1,
  139959. 19,
  139960. 19
  139961. };
  139962. static static_codebook _16u2_p9_1 = {
  139963. 2, 361,
  139964. _vq_lengthlist__16u2_p9_1,
  139965. 1, -518488064, 1611661312, 10, 0,
  139966. _vq_quantlist__16u2_p9_1,
  139967. NULL,
  139968. &_vq_auxt__16u2_p9_1,
  139969. NULL,
  139970. 0
  139971. };
  139972. static long _vq_quantlist__16u2_p9_2[] = {
  139973. 24,
  139974. 23,
  139975. 25,
  139976. 22,
  139977. 26,
  139978. 21,
  139979. 27,
  139980. 20,
  139981. 28,
  139982. 19,
  139983. 29,
  139984. 18,
  139985. 30,
  139986. 17,
  139987. 31,
  139988. 16,
  139989. 32,
  139990. 15,
  139991. 33,
  139992. 14,
  139993. 34,
  139994. 13,
  139995. 35,
  139996. 12,
  139997. 36,
  139998. 11,
  139999. 37,
  140000. 10,
  140001. 38,
  140002. 9,
  140003. 39,
  140004. 8,
  140005. 40,
  140006. 7,
  140007. 41,
  140008. 6,
  140009. 42,
  140010. 5,
  140011. 43,
  140012. 4,
  140013. 44,
  140014. 3,
  140015. 45,
  140016. 2,
  140017. 46,
  140018. 1,
  140019. 47,
  140020. 0,
  140021. 48,
  140022. };
  140023. static long _vq_lengthlist__16u2_p9_2[] = {
  140024. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  140025. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  140026. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  140027. 11,
  140028. };
  140029. static float _vq_quantthresh__16u2_p9_2[] = {
  140030. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  140031. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  140032. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140033. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140034. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  140035. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  140036. };
  140037. static long _vq_quantmap__16u2_p9_2[] = {
  140038. 47, 45, 43, 41, 39, 37, 35, 33,
  140039. 31, 29, 27, 25, 23, 21, 19, 17,
  140040. 15, 13, 11, 9, 7, 5, 3, 1,
  140041. 0, 2, 4, 6, 8, 10, 12, 14,
  140042. 16, 18, 20, 22, 24, 26, 28, 30,
  140043. 32, 34, 36, 38, 40, 42, 44, 46,
  140044. 48,
  140045. };
  140046. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  140047. _vq_quantthresh__16u2_p9_2,
  140048. _vq_quantmap__16u2_p9_2,
  140049. 49,
  140050. 49
  140051. };
  140052. static static_codebook _16u2_p9_2 = {
  140053. 1, 49,
  140054. _vq_lengthlist__16u2_p9_2,
  140055. 1, -526909440, 1611661312, 6, 0,
  140056. _vq_quantlist__16u2_p9_2,
  140057. NULL,
  140058. &_vq_auxt__16u2_p9_2,
  140059. NULL,
  140060. 0
  140061. };
  140062. static long _vq_quantlist__8u0__p1_0[] = {
  140063. 1,
  140064. 0,
  140065. 2,
  140066. };
  140067. static long _vq_lengthlist__8u0__p1_0[] = {
  140068. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  140069. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  140070. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  140071. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  140072. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  140073. 11,
  140074. };
  140075. static float _vq_quantthresh__8u0__p1_0[] = {
  140076. -0.5, 0.5,
  140077. };
  140078. static long _vq_quantmap__8u0__p1_0[] = {
  140079. 1, 0, 2,
  140080. };
  140081. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  140082. _vq_quantthresh__8u0__p1_0,
  140083. _vq_quantmap__8u0__p1_0,
  140084. 3,
  140085. 3
  140086. };
  140087. static static_codebook _8u0__p1_0 = {
  140088. 4, 81,
  140089. _vq_lengthlist__8u0__p1_0,
  140090. 1, -535822336, 1611661312, 2, 0,
  140091. _vq_quantlist__8u0__p1_0,
  140092. NULL,
  140093. &_vq_auxt__8u0__p1_0,
  140094. NULL,
  140095. 0
  140096. };
  140097. static long _vq_quantlist__8u0__p2_0[] = {
  140098. 1,
  140099. 0,
  140100. 2,
  140101. };
  140102. static long _vq_lengthlist__8u0__p2_0[] = {
  140103. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  140104. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  140105. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  140106. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  140107. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  140108. 8,
  140109. };
  140110. static float _vq_quantthresh__8u0__p2_0[] = {
  140111. -0.5, 0.5,
  140112. };
  140113. static long _vq_quantmap__8u0__p2_0[] = {
  140114. 1, 0, 2,
  140115. };
  140116. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  140117. _vq_quantthresh__8u0__p2_0,
  140118. _vq_quantmap__8u0__p2_0,
  140119. 3,
  140120. 3
  140121. };
  140122. static static_codebook _8u0__p2_0 = {
  140123. 4, 81,
  140124. _vq_lengthlist__8u0__p2_0,
  140125. 1, -535822336, 1611661312, 2, 0,
  140126. _vq_quantlist__8u0__p2_0,
  140127. NULL,
  140128. &_vq_auxt__8u0__p2_0,
  140129. NULL,
  140130. 0
  140131. };
  140132. static long _vq_quantlist__8u0__p3_0[] = {
  140133. 2,
  140134. 1,
  140135. 3,
  140136. 0,
  140137. 4,
  140138. };
  140139. static long _vq_lengthlist__8u0__p3_0[] = {
  140140. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  140141. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  140142. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  140143. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140144. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  140145. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  140146. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  140147. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  140148. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  140149. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  140150. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  140151. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  140152. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  140153. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  140154. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  140155. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  140156. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  140157. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  140158. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  140159. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  140160. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  140161. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  140162. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  140163. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  140164. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  140165. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  140166. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  140167. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  140168. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  140169. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  140170. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  140171. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  140172. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  140173. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  140174. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  140175. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  140176. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  140177. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  140178. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  140179. 16,
  140180. };
  140181. static float _vq_quantthresh__8u0__p3_0[] = {
  140182. -1.5, -0.5, 0.5, 1.5,
  140183. };
  140184. static long _vq_quantmap__8u0__p3_0[] = {
  140185. 3, 1, 0, 2, 4,
  140186. };
  140187. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  140188. _vq_quantthresh__8u0__p3_0,
  140189. _vq_quantmap__8u0__p3_0,
  140190. 5,
  140191. 5
  140192. };
  140193. static static_codebook _8u0__p3_0 = {
  140194. 4, 625,
  140195. _vq_lengthlist__8u0__p3_0,
  140196. 1, -533725184, 1611661312, 3, 0,
  140197. _vq_quantlist__8u0__p3_0,
  140198. NULL,
  140199. &_vq_auxt__8u0__p3_0,
  140200. NULL,
  140201. 0
  140202. };
  140203. static long _vq_quantlist__8u0__p4_0[] = {
  140204. 2,
  140205. 1,
  140206. 3,
  140207. 0,
  140208. 4,
  140209. };
  140210. static long _vq_lengthlist__8u0__p4_0[] = {
  140211. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  140212. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  140213. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  140214. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  140215. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  140216. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  140217. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  140218. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  140219. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  140220. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  140221. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  140222. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  140223. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  140224. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  140225. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  140226. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  140227. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  140228. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  140229. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  140230. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  140231. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  140232. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  140233. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  140234. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  140235. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  140236. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  140237. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  140238. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  140239. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  140240. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  140241. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  140242. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  140243. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  140244. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  140245. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  140246. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  140247. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  140248. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  140249. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  140250. 12,
  140251. };
  140252. static float _vq_quantthresh__8u0__p4_0[] = {
  140253. -1.5, -0.5, 0.5, 1.5,
  140254. };
  140255. static long _vq_quantmap__8u0__p4_0[] = {
  140256. 3, 1, 0, 2, 4,
  140257. };
  140258. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  140259. _vq_quantthresh__8u0__p4_0,
  140260. _vq_quantmap__8u0__p4_0,
  140261. 5,
  140262. 5
  140263. };
  140264. static static_codebook _8u0__p4_0 = {
  140265. 4, 625,
  140266. _vq_lengthlist__8u0__p4_0,
  140267. 1, -533725184, 1611661312, 3, 0,
  140268. _vq_quantlist__8u0__p4_0,
  140269. NULL,
  140270. &_vq_auxt__8u0__p4_0,
  140271. NULL,
  140272. 0
  140273. };
  140274. static long _vq_quantlist__8u0__p5_0[] = {
  140275. 4,
  140276. 3,
  140277. 5,
  140278. 2,
  140279. 6,
  140280. 1,
  140281. 7,
  140282. 0,
  140283. 8,
  140284. };
  140285. static long _vq_lengthlist__8u0__p5_0[] = {
  140286. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  140287. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  140288. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140289. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140290. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  140291. 12,
  140292. };
  140293. static float _vq_quantthresh__8u0__p5_0[] = {
  140294. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140295. };
  140296. static long _vq_quantmap__8u0__p5_0[] = {
  140297. 7, 5, 3, 1, 0, 2, 4, 6,
  140298. 8,
  140299. };
  140300. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  140301. _vq_quantthresh__8u0__p5_0,
  140302. _vq_quantmap__8u0__p5_0,
  140303. 9,
  140304. 9
  140305. };
  140306. static static_codebook _8u0__p5_0 = {
  140307. 2, 81,
  140308. _vq_lengthlist__8u0__p5_0,
  140309. 1, -531628032, 1611661312, 4, 0,
  140310. _vq_quantlist__8u0__p5_0,
  140311. NULL,
  140312. &_vq_auxt__8u0__p5_0,
  140313. NULL,
  140314. 0
  140315. };
  140316. static long _vq_quantlist__8u0__p6_0[] = {
  140317. 6,
  140318. 5,
  140319. 7,
  140320. 4,
  140321. 8,
  140322. 3,
  140323. 9,
  140324. 2,
  140325. 10,
  140326. 1,
  140327. 11,
  140328. 0,
  140329. 12,
  140330. };
  140331. static long _vq_lengthlist__8u0__p6_0[] = {
  140332. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  140333. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  140334. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  140335. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  140336. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  140337. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  140338. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  140339. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  140340. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  140341. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  140342. 16, 0,15, 0,17, 0, 0, 0, 0,
  140343. };
  140344. static float _vq_quantthresh__8u0__p6_0[] = {
  140345. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140346. 12.5, 17.5, 22.5, 27.5,
  140347. };
  140348. static long _vq_quantmap__8u0__p6_0[] = {
  140349. 11, 9, 7, 5, 3, 1, 0, 2,
  140350. 4, 6, 8, 10, 12,
  140351. };
  140352. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  140353. _vq_quantthresh__8u0__p6_0,
  140354. _vq_quantmap__8u0__p6_0,
  140355. 13,
  140356. 13
  140357. };
  140358. static static_codebook _8u0__p6_0 = {
  140359. 2, 169,
  140360. _vq_lengthlist__8u0__p6_0,
  140361. 1, -526516224, 1616117760, 4, 0,
  140362. _vq_quantlist__8u0__p6_0,
  140363. NULL,
  140364. &_vq_auxt__8u0__p6_0,
  140365. NULL,
  140366. 0
  140367. };
  140368. static long _vq_quantlist__8u0__p6_1[] = {
  140369. 2,
  140370. 1,
  140371. 3,
  140372. 0,
  140373. 4,
  140374. };
  140375. static long _vq_lengthlist__8u0__p6_1[] = {
  140376. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  140377. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  140378. };
  140379. static float _vq_quantthresh__8u0__p6_1[] = {
  140380. -1.5, -0.5, 0.5, 1.5,
  140381. };
  140382. static long _vq_quantmap__8u0__p6_1[] = {
  140383. 3, 1, 0, 2, 4,
  140384. };
  140385. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  140386. _vq_quantthresh__8u0__p6_1,
  140387. _vq_quantmap__8u0__p6_1,
  140388. 5,
  140389. 5
  140390. };
  140391. static static_codebook _8u0__p6_1 = {
  140392. 2, 25,
  140393. _vq_lengthlist__8u0__p6_1,
  140394. 1, -533725184, 1611661312, 3, 0,
  140395. _vq_quantlist__8u0__p6_1,
  140396. NULL,
  140397. &_vq_auxt__8u0__p6_1,
  140398. NULL,
  140399. 0
  140400. };
  140401. static long _vq_quantlist__8u0__p7_0[] = {
  140402. 1,
  140403. 0,
  140404. 2,
  140405. };
  140406. static long _vq_lengthlist__8u0__p7_0[] = {
  140407. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140408. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140409. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140410. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140411. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140412. 7,
  140413. };
  140414. static float _vq_quantthresh__8u0__p7_0[] = {
  140415. -157.5, 157.5,
  140416. };
  140417. static long _vq_quantmap__8u0__p7_0[] = {
  140418. 1, 0, 2,
  140419. };
  140420. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  140421. _vq_quantthresh__8u0__p7_0,
  140422. _vq_quantmap__8u0__p7_0,
  140423. 3,
  140424. 3
  140425. };
  140426. static static_codebook _8u0__p7_0 = {
  140427. 4, 81,
  140428. _vq_lengthlist__8u0__p7_0,
  140429. 1, -518803456, 1628680192, 2, 0,
  140430. _vq_quantlist__8u0__p7_0,
  140431. NULL,
  140432. &_vq_auxt__8u0__p7_0,
  140433. NULL,
  140434. 0
  140435. };
  140436. static long _vq_quantlist__8u0__p7_1[] = {
  140437. 7,
  140438. 6,
  140439. 8,
  140440. 5,
  140441. 9,
  140442. 4,
  140443. 10,
  140444. 3,
  140445. 11,
  140446. 2,
  140447. 12,
  140448. 1,
  140449. 13,
  140450. 0,
  140451. 14,
  140452. };
  140453. static long _vq_lengthlist__8u0__p7_1[] = {
  140454. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  140455. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  140456. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  140457. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  140458. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  140459. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  140460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140461. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140462. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140466. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  140467. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140468. 10,
  140469. };
  140470. static float _vq_quantthresh__8u0__p7_1[] = {
  140471. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140472. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140473. };
  140474. static long _vq_quantmap__8u0__p7_1[] = {
  140475. 13, 11, 9, 7, 5, 3, 1, 0,
  140476. 2, 4, 6, 8, 10, 12, 14,
  140477. };
  140478. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  140479. _vq_quantthresh__8u0__p7_1,
  140480. _vq_quantmap__8u0__p7_1,
  140481. 15,
  140482. 15
  140483. };
  140484. static static_codebook _8u0__p7_1 = {
  140485. 2, 225,
  140486. _vq_lengthlist__8u0__p7_1,
  140487. 1, -520986624, 1620377600, 4, 0,
  140488. _vq_quantlist__8u0__p7_1,
  140489. NULL,
  140490. &_vq_auxt__8u0__p7_1,
  140491. NULL,
  140492. 0
  140493. };
  140494. static long _vq_quantlist__8u0__p7_2[] = {
  140495. 10,
  140496. 9,
  140497. 11,
  140498. 8,
  140499. 12,
  140500. 7,
  140501. 13,
  140502. 6,
  140503. 14,
  140504. 5,
  140505. 15,
  140506. 4,
  140507. 16,
  140508. 3,
  140509. 17,
  140510. 2,
  140511. 18,
  140512. 1,
  140513. 19,
  140514. 0,
  140515. 20,
  140516. };
  140517. static long _vq_lengthlist__8u0__p7_2[] = {
  140518. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  140519. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  140520. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  140521. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  140522. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  140523. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  140524. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  140525. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  140526. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  140527. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  140528. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  140529. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  140530. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  140531. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  140532. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  140533. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  140534. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  140535. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  140536. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  140537. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  140538. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  140539. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  140540. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  140541. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  140542. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  140543. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  140544. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  140545. 11,12,11,11,11,10,10,11,11,
  140546. };
  140547. static float _vq_quantthresh__8u0__p7_2[] = {
  140548. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  140549. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  140550. 6.5, 7.5, 8.5, 9.5,
  140551. };
  140552. static long _vq_quantmap__8u0__p7_2[] = {
  140553. 19, 17, 15, 13, 11, 9, 7, 5,
  140554. 3, 1, 0, 2, 4, 6, 8, 10,
  140555. 12, 14, 16, 18, 20,
  140556. };
  140557. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  140558. _vq_quantthresh__8u0__p7_2,
  140559. _vq_quantmap__8u0__p7_2,
  140560. 21,
  140561. 21
  140562. };
  140563. static static_codebook _8u0__p7_2 = {
  140564. 2, 441,
  140565. _vq_lengthlist__8u0__p7_2,
  140566. 1, -529268736, 1611661312, 5, 0,
  140567. _vq_quantlist__8u0__p7_2,
  140568. NULL,
  140569. &_vq_auxt__8u0__p7_2,
  140570. NULL,
  140571. 0
  140572. };
  140573. static long _huff_lengthlist__8u0__single[] = {
  140574. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  140575. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  140576. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  140577. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  140578. };
  140579. static static_codebook _huff_book__8u0__single = {
  140580. 2, 64,
  140581. _huff_lengthlist__8u0__single,
  140582. 0, 0, 0, 0, 0,
  140583. NULL,
  140584. NULL,
  140585. NULL,
  140586. NULL,
  140587. 0
  140588. };
  140589. static long _vq_quantlist__8u1__p1_0[] = {
  140590. 1,
  140591. 0,
  140592. 2,
  140593. };
  140594. static long _vq_lengthlist__8u1__p1_0[] = {
  140595. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  140596. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  140597. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  140598. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  140599. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  140600. 10,
  140601. };
  140602. static float _vq_quantthresh__8u1__p1_0[] = {
  140603. -0.5, 0.5,
  140604. };
  140605. static long _vq_quantmap__8u1__p1_0[] = {
  140606. 1, 0, 2,
  140607. };
  140608. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  140609. _vq_quantthresh__8u1__p1_0,
  140610. _vq_quantmap__8u1__p1_0,
  140611. 3,
  140612. 3
  140613. };
  140614. static static_codebook _8u1__p1_0 = {
  140615. 4, 81,
  140616. _vq_lengthlist__8u1__p1_0,
  140617. 1, -535822336, 1611661312, 2, 0,
  140618. _vq_quantlist__8u1__p1_0,
  140619. NULL,
  140620. &_vq_auxt__8u1__p1_0,
  140621. NULL,
  140622. 0
  140623. };
  140624. static long _vq_quantlist__8u1__p2_0[] = {
  140625. 1,
  140626. 0,
  140627. 2,
  140628. };
  140629. static long _vq_lengthlist__8u1__p2_0[] = {
  140630. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  140631. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  140632. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  140633. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  140634. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  140635. 7,
  140636. };
  140637. static float _vq_quantthresh__8u1__p2_0[] = {
  140638. -0.5, 0.5,
  140639. };
  140640. static long _vq_quantmap__8u1__p2_0[] = {
  140641. 1, 0, 2,
  140642. };
  140643. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  140644. _vq_quantthresh__8u1__p2_0,
  140645. _vq_quantmap__8u1__p2_0,
  140646. 3,
  140647. 3
  140648. };
  140649. static static_codebook _8u1__p2_0 = {
  140650. 4, 81,
  140651. _vq_lengthlist__8u1__p2_0,
  140652. 1, -535822336, 1611661312, 2, 0,
  140653. _vq_quantlist__8u1__p2_0,
  140654. NULL,
  140655. &_vq_auxt__8u1__p2_0,
  140656. NULL,
  140657. 0
  140658. };
  140659. static long _vq_quantlist__8u1__p3_0[] = {
  140660. 2,
  140661. 1,
  140662. 3,
  140663. 0,
  140664. 4,
  140665. };
  140666. static long _vq_lengthlist__8u1__p3_0[] = {
  140667. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  140668. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  140669. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  140670. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  140671. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  140672. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  140673. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  140674. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  140675. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  140676. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  140677. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  140678. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  140679. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  140680. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  140681. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  140682. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  140683. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  140684. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  140685. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  140686. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  140687. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  140688. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  140689. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  140690. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  140691. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  140692. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  140693. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  140694. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  140695. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  140696. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  140697. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  140698. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  140699. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  140700. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  140701. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  140702. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  140703. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  140704. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  140705. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  140706. 16,
  140707. };
  140708. static float _vq_quantthresh__8u1__p3_0[] = {
  140709. -1.5, -0.5, 0.5, 1.5,
  140710. };
  140711. static long _vq_quantmap__8u1__p3_0[] = {
  140712. 3, 1, 0, 2, 4,
  140713. };
  140714. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  140715. _vq_quantthresh__8u1__p3_0,
  140716. _vq_quantmap__8u1__p3_0,
  140717. 5,
  140718. 5
  140719. };
  140720. static static_codebook _8u1__p3_0 = {
  140721. 4, 625,
  140722. _vq_lengthlist__8u1__p3_0,
  140723. 1, -533725184, 1611661312, 3, 0,
  140724. _vq_quantlist__8u1__p3_0,
  140725. NULL,
  140726. &_vq_auxt__8u1__p3_0,
  140727. NULL,
  140728. 0
  140729. };
  140730. static long _vq_quantlist__8u1__p4_0[] = {
  140731. 2,
  140732. 1,
  140733. 3,
  140734. 0,
  140735. 4,
  140736. };
  140737. static long _vq_lengthlist__8u1__p4_0[] = {
  140738. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  140739. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  140740. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  140741. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  140742. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  140743. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  140744. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  140745. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  140746. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  140747. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  140748. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  140749. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  140750. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  140751. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  140752. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  140753. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  140754. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  140755. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  140756. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  140757. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  140758. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  140759. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  140760. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  140761. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  140762. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  140763. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  140764. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  140765. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  140766. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  140767. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  140768. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  140769. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  140770. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  140771. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  140772. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  140773. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  140774. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  140775. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  140776. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  140777. 10,
  140778. };
  140779. static float _vq_quantthresh__8u1__p4_0[] = {
  140780. -1.5, -0.5, 0.5, 1.5,
  140781. };
  140782. static long _vq_quantmap__8u1__p4_0[] = {
  140783. 3, 1, 0, 2, 4,
  140784. };
  140785. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  140786. _vq_quantthresh__8u1__p4_0,
  140787. _vq_quantmap__8u1__p4_0,
  140788. 5,
  140789. 5
  140790. };
  140791. static static_codebook _8u1__p4_0 = {
  140792. 4, 625,
  140793. _vq_lengthlist__8u1__p4_0,
  140794. 1, -533725184, 1611661312, 3, 0,
  140795. _vq_quantlist__8u1__p4_0,
  140796. NULL,
  140797. &_vq_auxt__8u1__p4_0,
  140798. NULL,
  140799. 0
  140800. };
  140801. static long _vq_quantlist__8u1__p5_0[] = {
  140802. 4,
  140803. 3,
  140804. 5,
  140805. 2,
  140806. 6,
  140807. 1,
  140808. 7,
  140809. 0,
  140810. 8,
  140811. };
  140812. static long _vq_lengthlist__8u1__p5_0[] = {
  140813. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  140814. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  140815. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  140816. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  140817. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  140818. 13,
  140819. };
  140820. static float _vq_quantthresh__8u1__p5_0[] = {
  140821. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140822. };
  140823. static long _vq_quantmap__8u1__p5_0[] = {
  140824. 7, 5, 3, 1, 0, 2, 4, 6,
  140825. 8,
  140826. };
  140827. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  140828. _vq_quantthresh__8u1__p5_0,
  140829. _vq_quantmap__8u1__p5_0,
  140830. 9,
  140831. 9
  140832. };
  140833. static static_codebook _8u1__p5_0 = {
  140834. 2, 81,
  140835. _vq_lengthlist__8u1__p5_0,
  140836. 1, -531628032, 1611661312, 4, 0,
  140837. _vq_quantlist__8u1__p5_0,
  140838. NULL,
  140839. &_vq_auxt__8u1__p5_0,
  140840. NULL,
  140841. 0
  140842. };
  140843. static long _vq_quantlist__8u1__p6_0[] = {
  140844. 4,
  140845. 3,
  140846. 5,
  140847. 2,
  140848. 6,
  140849. 1,
  140850. 7,
  140851. 0,
  140852. 8,
  140853. };
  140854. static long _vq_lengthlist__8u1__p6_0[] = {
  140855. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  140856. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  140857. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  140858. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  140859. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  140860. 10,
  140861. };
  140862. static float _vq_quantthresh__8u1__p6_0[] = {
  140863. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140864. };
  140865. static long _vq_quantmap__8u1__p6_0[] = {
  140866. 7, 5, 3, 1, 0, 2, 4, 6,
  140867. 8,
  140868. };
  140869. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  140870. _vq_quantthresh__8u1__p6_0,
  140871. _vq_quantmap__8u1__p6_0,
  140872. 9,
  140873. 9
  140874. };
  140875. static static_codebook _8u1__p6_0 = {
  140876. 2, 81,
  140877. _vq_lengthlist__8u1__p6_0,
  140878. 1, -531628032, 1611661312, 4, 0,
  140879. _vq_quantlist__8u1__p6_0,
  140880. NULL,
  140881. &_vq_auxt__8u1__p6_0,
  140882. NULL,
  140883. 0
  140884. };
  140885. static long _vq_quantlist__8u1__p7_0[] = {
  140886. 1,
  140887. 0,
  140888. 2,
  140889. };
  140890. static long _vq_lengthlist__8u1__p7_0[] = {
  140891. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  140892. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  140893. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  140894. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  140895. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  140896. 11,
  140897. };
  140898. static float _vq_quantthresh__8u1__p7_0[] = {
  140899. -5.5, 5.5,
  140900. };
  140901. static long _vq_quantmap__8u1__p7_0[] = {
  140902. 1, 0, 2,
  140903. };
  140904. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  140905. _vq_quantthresh__8u1__p7_0,
  140906. _vq_quantmap__8u1__p7_0,
  140907. 3,
  140908. 3
  140909. };
  140910. static static_codebook _8u1__p7_0 = {
  140911. 4, 81,
  140912. _vq_lengthlist__8u1__p7_0,
  140913. 1, -529137664, 1618345984, 2, 0,
  140914. _vq_quantlist__8u1__p7_0,
  140915. NULL,
  140916. &_vq_auxt__8u1__p7_0,
  140917. NULL,
  140918. 0
  140919. };
  140920. static long _vq_quantlist__8u1__p7_1[] = {
  140921. 5,
  140922. 4,
  140923. 6,
  140924. 3,
  140925. 7,
  140926. 2,
  140927. 8,
  140928. 1,
  140929. 9,
  140930. 0,
  140931. 10,
  140932. };
  140933. static long _vq_lengthlist__8u1__p7_1[] = {
  140934. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  140935. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  140936. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  140937. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  140938. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  140939. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  140940. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  140941. 9, 9, 9, 9, 9,10,10,10,10,
  140942. };
  140943. static float _vq_quantthresh__8u1__p7_1[] = {
  140944. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140945. 3.5, 4.5,
  140946. };
  140947. static long _vq_quantmap__8u1__p7_1[] = {
  140948. 9, 7, 5, 3, 1, 0, 2, 4,
  140949. 6, 8, 10,
  140950. };
  140951. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  140952. _vq_quantthresh__8u1__p7_1,
  140953. _vq_quantmap__8u1__p7_1,
  140954. 11,
  140955. 11
  140956. };
  140957. static static_codebook _8u1__p7_1 = {
  140958. 2, 121,
  140959. _vq_lengthlist__8u1__p7_1,
  140960. 1, -531365888, 1611661312, 4, 0,
  140961. _vq_quantlist__8u1__p7_1,
  140962. NULL,
  140963. &_vq_auxt__8u1__p7_1,
  140964. NULL,
  140965. 0
  140966. };
  140967. static long _vq_quantlist__8u1__p8_0[] = {
  140968. 5,
  140969. 4,
  140970. 6,
  140971. 3,
  140972. 7,
  140973. 2,
  140974. 8,
  140975. 1,
  140976. 9,
  140977. 0,
  140978. 10,
  140979. };
  140980. static long _vq_lengthlist__8u1__p8_0[] = {
  140981. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  140982. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  140983. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  140984. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  140985. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  140986. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  140987. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  140988. 12,13,13,14,14,15,15,15,15,
  140989. };
  140990. static float _vq_quantthresh__8u1__p8_0[] = {
  140991. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  140992. 38.5, 49.5,
  140993. };
  140994. static long _vq_quantmap__8u1__p8_0[] = {
  140995. 9, 7, 5, 3, 1, 0, 2, 4,
  140996. 6, 8, 10,
  140997. };
  140998. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  140999. _vq_quantthresh__8u1__p8_0,
  141000. _vq_quantmap__8u1__p8_0,
  141001. 11,
  141002. 11
  141003. };
  141004. static static_codebook _8u1__p8_0 = {
  141005. 2, 121,
  141006. _vq_lengthlist__8u1__p8_0,
  141007. 1, -524582912, 1618345984, 4, 0,
  141008. _vq_quantlist__8u1__p8_0,
  141009. NULL,
  141010. &_vq_auxt__8u1__p8_0,
  141011. NULL,
  141012. 0
  141013. };
  141014. static long _vq_quantlist__8u1__p8_1[] = {
  141015. 5,
  141016. 4,
  141017. 6,
  141018. 3,
  141019. 7,
  141020. 2,
  141021. 8,
  141022. 1,
  141023. 9,
  141024. 0,
  141025. 10,
  141026. };
  141027. static long _vq_lengthlist__8u1__p8_1[] = {
  141028. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  141029. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  141030. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  141031. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  141032. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141033. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  141034. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  141035. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141036. };
  141037. static float _vq_quantthresh__8u1__p8_1[] = {
  141038. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141039. 3.5, 4.5,
  141040. };
  141041. static long _vq_quantmap__8u1__p8_1[] = {
  141042. 9, 7, 5, 3, 1, 0, 2, 4,
  141043. 6, 8, 10,
  141044. };
  141045. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  141046. _vq_quantthresh__8u1__p8_1,
  141047. _vq_quantmap__8u1__p8_1,
  141048. 11,
  141049. 11
  141050. };
  141051. static static_codebook _8u1__p8_1 = {
  141052. 2, 121,
  141053. _vq_lengthlist__8u1__p8_1,
  141054. 1, -531365888, 1611661312, 4, 0,
  141055. _vq_quantlist__8u1__p8_1,
  141056. NULL,
  141057. &_vq_auxt__8u1__p8_1,
  141058. NULL,
  141059. 0
  141060. };
  141061. static long _vq_quantlist__8u1__p9_0[] = {
  141062. 7,
  141063. 6,
  141064. 8,
  141065. 5,
  141066. 9,
  141067. 4,
  141068. 10,
  141069. 3,
  141070. 11,
  141071. 2,
  141072. 12,
  141073. 1,
  141074. 13,
  141075. 0,
  141076. 14,
  141077. };
  141078. static long _vq_lengthlist__8u1__p9_0[] = {
  141079. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  141080. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  141081. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141082. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141083. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141084. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141091. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  141092. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141093. 10,
  141094. };
  141095. static float _vq_quantthresh__8u1__p9_0[] = {
  141096. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  141097. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  141098. };
  141099. static long _vq_quantmap__8u1__p9_0[] = {
  141100. 13, 11, 9, 7, 5, 3, 1, 0,
  141101. 2, 4, 6, 8, 10, 12, 14,
  141102. };
  141103. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  141104. _vq_quantthresh__8u1__p9_0,
  141105. _vq_quantmap__8u1__p9_0,
  141106. 15,
  141107. 15
  141108. };
  141109. static static_codebook _8u1__p9_0 = {
  141110. 2, 225,
  141111. _vq_lengthlist__8u1__p9_0,
  141112. 1, -514071552, 1627381760, 4, 0,
  141113. _vq_quantlist__8u1__p9_0,
  141114. NULL,
  141115. &_vq_auxt__8u1__p9_0,
  141116. NULL,
  141117. 0
  141118. };
  141119. static long _vq_quantlist__8u1__p9_1[] = {
  141120. 7,
  141121. 6,
  141122. 8,
  141123. 5,
  141124. 9,
  141125. 4,
  141126. 10,
  141127. 3,
  141128. 11,
  141129. 2,
  141130. 12,
  141131. 1,
  141132. 13,
  141133. 0,
  141134. 14,
  141135. };
  141136. static long _vq_lengthlist__8u1__p9_1[] = {
  141137. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  141138. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  141139. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  141140. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  141141. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  141142. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  141143. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  141144. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  141145. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  141146. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  141147. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  141148. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  141149. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  141150. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  141151. 13,
  141152. };
  141153. static float _vq_quantthresh__8u1__p9_1[] = {
  141154. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141155. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141156. };
  141157. static long _vq_quantmap__8u1__p9_1[] = {
  141158. 13, 11, 9, 7, 5, 3, 1, 0,
  141159. 2, 4, 6, 8, 10, 12, 14,
  141160. };
  141161. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  141162. _vq_quantthresh__8u1__p9_1,
  141163. _vq_quantmap__8u1__p9_1,
  141164. 15,
  141165. 15
  141166. };
  141167. static static_codebook _8u1__p9_1 = {
  141168. 2, 225,
  141169. _vq_lengthlist__8u1__p9_1,
  141170. 1, -522338304, 1620115456, 4, 0,
  141171. _vq_quantlist__8u1__p9_1,
  141172. NULL,
  141173. &_vq_auxt__8u1__p9_1,
  141174. NULL,
  141175. 0
  141176. };
  141177. static long _vq_quantlist__8u1__p9_2[] = {
  141178. 8,
  141179. 7,
  141180. 9,
  141181. 6,
  141182. 10,
  141183. 5,
  141184. 11,
  141185. 4,
  141186. 12,
  141187. 3,
  141188. 13,
  141189. 2,
  141190. 14,
  141191. 1,
  141192. 15,
  141193. 0,
  141194. 16,
  141195. };
  141196. static long _vq_lengthlist__8u1__p9_2[] = {
  141197. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141198. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  141199. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141200. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  141201. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141202. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  141203. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141204. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  141205. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141206. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  141207. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  141208. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  141209. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  141210. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141211. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  141212. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  141213. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141214. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141215. 10,
  141216. };
  141217. static float _vq_quantthresh__8u1__p9_2[] = {
  141218. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141219. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141220. };
  141221. static long _vq_quantmap__8u1__p9_2[] = {
  141222. 15, 13, 11, 9, 7, 5, 3, 1,
  141223. 0, 2, 4, 6, 8, 10, 12, 14,
  141224. 16,
  141225. };
  141226. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  141227. _vq_quantthresh__8u1__p9_2,
  141228. _vq_quantmap__8u1__p9_2,
  141229. 17,
  141230. 17
  141231. };
  141232. static static_codebook _8u1__p9_2 = {
  141233. 2, 289,
  141234. _vq_lengthlist__8u1__p9_2,
  141235. 1, -529530880, 1611661312, 5, 0,
  141236. _vq_quantlist__8u1__p9_2,
  141237. NULL,
  141238. &_vq_auxt__8u1__p9_2,
  141239. NULL,
  141240. 0
  141241. };
  141242. static long _huff_lengthlist__8u1__single[] = {
  141243. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  141244. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  141245. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  141246. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  141247. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  141248. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  141249. 13, 8, 8,15,
  141250. };
  141251. static static_codebook _huff_book__8u1__single = {
  141252. 2, 100,
  141253. _huff_lengthlist__8u1__single,
  141254. 0, 0, 0, 0, 0,
  141255. NULL,
  141256. NULL,
  141257. NULL,
  141258. NULL,
  141259. 0
  141260. };
  141261. static long _huff_lengthlist__44u0__long[] = {
  141262. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  141263. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  141264. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  141265. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  141266. };
  141267. static static_codebook _huff_book__44u0__long = {
  141268. 2, 64,
  141269. _huff_lengthlist__44u0__long,
  141270. 0, 0, 0, 0, 0,
  141271. NULL,
  141272. NULL,
  141273. NULL,
  141274. NULL,
  141275. 0
  141276. };
  141277. static long _vq_quantlist__44u0__p1_0[] = {
  141278. 1,
  141279. 0,
  141280. 2,
  141281. };
  141282. static long _vq_lengthlist__44u0__p1_0[] = {
  141283. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141284. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141285. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  141286. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  141287. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  141288. 13,
  141289. };
  141290. static float _vq_quantthresh__44u0__p1_0[] = {
  141291. -0.5, 0.5,
  141292. };
  141293. static long _vq_quantmap__44u0__p1_0[] = {
  141294. 1, 0, 2,
  141295. };
  141296. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  141297. _vq_quantthresh__44u0__p1_0,
  141298. _vq_quantmap__44u0__p1_0,
  141299. 3,
  141300. 3
  141301. };
  141302. static static_codebook _44u0__p1_0 = {
  141303. 4, 81,
  141304. _vq_lengthlist__44u0__p1_0,
  141305. 1, -535822336, 1611661312, 2, 0,
  141306. _vq_quantlist__44u0__p1_0,
  141307. NULL,
  141308. &_vq_auxt__44u0__p1_0,
  141309. NULL,
  141310. 0
  141311. };
  141312. static long _vq_quantlist__44u0__p2_0[] = {
  141313. 1,
  141314. 0,
  141315. 2,
  141316. };
  141317. static long _vq_lengthlist__44u0__p2_0[] = {
  141318. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  141319. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  141320. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141321. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  141322. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141323. 9,
  141324. };
  141325. static float _vq_quantthresh__44u0__p2_0[] = {
  141326. -0.5, 0.5,
  141327. };
  141328. static long _vq_quantmap__44u0__p2_0[] = {
  141329. 1, 0, 2,
  141330. };
  141331. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  141332. _vq_quantthresh__44u0__p2_0,
  141333. _vq_quantmap__44u0__p2_0,
  141334. 3,
  141335. 3
  141336. };
  141337. static static_codebook _44u0__p2_0 = {
  141338. 4, 81,
  141339. _vq_lengthlist__44u0__p2_0,
  141340. 1, -535822336, 1611661312, 2, 0,
  141341. _vq_quantlist__44u0__p2_0,
  141342. NULL,
  141343. &_vq_auxt__44u0__p2_0,
  141344. NULL,
  141345. 0
  141346. };
  141347. static long _vq_quantlist__44u0__p3_0[] = {
  141348. 2,
  141349. 1,
  141350. 3,
  141351. 0,
  141352. 4,
  141353. };
  141354. static long _vq_lengthlist__44u0__p3_0[] = {
  141355. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  141356. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  141357. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  141358. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  141359. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  141360. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  141361. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  141362. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  141363. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  141364. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  141365. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  141366. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  141367. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  141368. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  141369. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  141370. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  141371. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  141372. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  141373. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  141374. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  141375. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  141376. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  141377. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  141378. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  141379. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  141380. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  141381. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  141382. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  141383. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  141384. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  141385. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  141386. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  141387. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  141388. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  141389. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  141390. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  141391. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  141392. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  141393. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  141394. 19,
  141395. };
  141396. static float _vq_quantthresh__44u0__p3_0[] = {
  141397. -1.5, -0.5, 0.5, 1.5,
  141398. };
  141399. static long _vq_quantmap__44u0__p3_0[] = {
  141400. 3, 1, 0, 2, 4,
  141401. };
  141402. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  141403. _vq_quantthresh__44u0__p3_0,
  141404. _vq_quantmap__44u0__p3_0,
  141405. 5,
  141406. 5
  141407. };
  141408. static static_codebook _44u0__p3_0 = {
  141409. 4, 625,
  141410. _vq_lengthlist__44u0__p3_0,
  141411. 1, -533725184, 1611661312, 3, 0,
  141412. _vq_quantlist__44u0__p3_0,
  141413. NULL,
  141414. &_vq_auxt__44u0__p3_0,
  141415. NULL,
  141416. 0
  141417. };
  141418. static long _vq_quantlist__44u0__p4_0[] = {
  141419. 2,
  141420. 1,
  141421. 3,
  141422. 0,
  141423. 4,
  141424. };
  141425. static long _vq_lengthlist__44u0__p4_0[] = {
  141426. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  141427. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  141428. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  141429. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  141430. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  141431. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  141432. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  141433. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  141434. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  141435. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  141436. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  141437. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141438. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  141439. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  141440. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  141441. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  141442. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  141443. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  141444. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  141445. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  141446. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  141447. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  141448. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  141449. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  141450. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  141451. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  141452. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  141453. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  141454. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  141455. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  141456. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  141457. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  141458. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  141459. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  141460. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  141461. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  141462. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  141463. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  141464. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  141465. 12,
  141466. };
  141467. static float _vq_quantthresh__44u0__p4_0[] = {
  141468. -1.5, -0.5, 0.5, 1.5,
  141469. };
  141470. static long _vq_quantmap__44u0__p4_0[] = {
  141471. 3, 1, 0, 2, 4,
  141472. };
  141473. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  141474. _vq_quantthresh__44u0__p4_0,
  141475. _vq_quantmap__44u0__p4_0,
  141476. 5,
  141477. 5
  141478. };
  141479. static static_codebook _44u0__p4_0 = {
  141480. 4, 625,
  141481. _vq_lengthlist__44u0__p4_0,
  141482. 1, -533725184, 1611661312, 3, 0,
  141483. _vq_quantlist__44u0__p4_0,
  141484. NULL,
  141485. &_vq_auxt__44u0__p4_0,
  141486. NULL,
  141487. 0
  141488. };
  141489. static long _vq_quantlist__44u0__p5_0[] = {
  141490. 4,
  141491. 3,
  141492. 5,
  141493. 2,
  141494. 6,
  141495. 1,
  141496. 7,
  141497. 0,
  141498. 8,
  141499. };
  141500. static long _vq_lengthlist__44u0__p5_0[] = {
  141501. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  141502. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  141503. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  141504. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141505. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  141506. 12,
  141507. };
  141508. static float _vq_quantthresh__44u0__p5_0[] = {
  141509. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141510. };
  141511. static long _vq_quantmap__44u0__p5_0[] = {
  141512. 7, 5, 3, 1, 0, 2, 4, 6,
  141513. 8,
  141514. };
  141515. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  141516. _vq_quantthresh__44u0__p5_0,
  141517. _vq_quantmap__44u0__p5_0,
  141518. 9,
  141519. 9
  141520. };
  141521. static static_codebook _44u0__p5_0 = {
  141522. 2, 81,
  141523. _vq_lengthlist__44u0__p5_0,
  141524. 1, -531628032, 1611661312, 4, 0,
  141525. _vq_quantlist__44u0__p5_0,
  141526. NULL,
  141527. &_vq_auxt__44u0__p5_0,
  141528. NULL,
  141529. 0
  141530. };
  141531. static long _vq_quantlist__44u0__p6_0[] = {
  141532. 6,
  141533. 5,
  141534. 7,
  141535. 4,
  141536. 8,
  141537. 3,
  141538. 9,
  141539. 2,
  141540. 10,
  141541. 1,
  141542. 11,
  141543. 0,
  141544. 12,
  141545. };
  141546. static long _vq_lengthlist__44u0__p6_0[] = {
  141547. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  141548. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  141549. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141550. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  141551. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  141552. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  141553. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  141554. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  141555. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  141556. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  141557. 15,17,16,17,18,17,17,18, 0,
  141558. };
  141559. static float _vq_quantthresh__44u0__p6_0[] = {
  141560. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141561. 12.5, 17.5, 22.5, 27.5,
  141562. };
  141563. static long _vq_quantmap__44u0__p6_0[] = {
  141564. 11, 9, 7, 5, 3, 1, 0, 2,
  141565. 4, 6, 8, 10, 12,
  141566. };
  141567. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  141568. _vq_quantthresh__44u0__p6_0,
  141569. _vq_quantmap__44u0__p6_0,
  141570. 13,
  141571. 13
  141572. };
  141573. static static_codebook _44u0__p6_0 = {
  141574. 2, 169,
  141575. _vq_lengthlist__44u0__p6_0,
  141576. 1, -526516224, 1616117760, 4, 0,
  141577. _vq_quantlist__44u0__p6_0,
  141578. NULL,
  141579. &_vq_auxt__44u0__p6_0,
  141580. NULL,
  141581. 0
  141582. };
  141583. static long _vq_quantlist__44u0__p6_1[] = {
  141584. 2,
  141585. 1,
  141586. 3,
  141587. 0,
  141588. 4,
  141589. };
  141590. static long _vq_lengthlist__44u0__p6_1[] = {
  141591. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  141592. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  141593. };
  141594. static float _vq_quantthresh__44u0__p6_1[] = {
  141595. -1.5, -0.5, 0.5, 1.5,
  141596. };
  141597. static long _vq_quantmap__44u0__p6_1[] = {
  141598. 3, 1, 0, 2, 4,
  141599. };
  141600. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  141601. _vq_quantthresh__44u0__p6_1,
  141602. _vq_quantmap__44u0__p6_1,
  141603. 5,
  141604. 5
  141605. };
  141606. static static_codebook _44u0__p6_1 = {
  141607. 2, 25,
  141608. _vq_lengthlist__44u0__p6_1,
  141609. 1, -533725184, 1611661312, 3, 0,
  141610. _vq_quantlist__44u0__p6_1,
  141611. NULL,
  141612. &_vq_auxt__44u0__p6_1,
  141613. NULL,
  141614. 0
  141615. };
  141616. static long _vq_quantlist__44u0__p7_0[] = {
  141617. 2,
  141618. 1,
  141619. 3,
  141620. 0,
  141621. 4,
  141622. };
  141623. static long _vq_lengthlist__44u0__p7_0[] = {
  141624. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  141625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141627. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141631. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  141632. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141654. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  141655. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141656. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141657. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141658. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141659. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141660. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141663. 10,
  141664. };
  141665. static float _vq_quantthresh__44u0__p7_0[] = {
  141666. -253.5, -84.5, 84.5, 253.5,
  141667. };
  141668. static long _vq_quantmap__44u0__p7_0[] = {
  141669. 3, 1, 0, 2, 4,
  141670. };
  141671. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  141672. _vq_quantthresh__44u0__p7_0,
  141673. _vq_quantmap__44u0__p7_0,
  141674. 5,
  141675. 5
  141676. };
  141677. static static_codebook _44u0__p7_0 = {
  141678. 4, 625,
  141679. _vq_lengthlist__44u0__p7_0,
  141680. 1, -518709248, 1626677248, 3, 0,
  141681. _vq_quantlist__44u0__p7_0,
  141682. NULL,
  141683. &_vq_auxt__44u0__p7_0,
  141684. NULL,
  141685. 0
  141686. };
  141687. static long _vq_quantlist__44u0__p7_1[] = {
  141688. 6,
  141689. 5,
  141690. 7,
  141691. 4,
  141692. 8,
  141693. 3,
  141694. 9,
  141695. 2,
  141696. 10,
  141697. 1,
  141698. 11,
  141699. 0,
  141700. 12,
  141701. };
  141702. static long _vq_lengthlist__44u0__p7_1[] = {
  141703. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  141704. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  141705. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  141706. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  141707. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  141708. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  141709. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  141710. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  141711. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  141712. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  141713. 15,15,15,15,15,15,15,15,15,
  141714. };
  141715. static float _vq_quantthresh__44u0__p7_1[] = {
  141716. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141717. 32.5, 45.5, 58.5, 71.5,
  141718. };
  141719. static long _vq_quantmap__44u0__p7_1[] = {
  141720. 11, 9, 7, 5, 3, 1, 0, 2,
  141721. 4, 6, 8, 10, 12,
  141722. };
  141723. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  141724. _vq_quantthresh__44u0__p7_1,
  141725. _vq_quantmap__44u0__p7_1,
  141726. 13,
  141727. 13
  141728. };
  141729. static static_codebook _44u0__p7_1 = {
  141730. 2, 169,
  141731. _vq_lengthlist__44u0__p7_1,
  141732. 1, -523010048, 1618608128, 4, 0,
  141733. _vq_quantlist__44u0__p7_1,
  141734. NULL,
  141735. &_vq_auxt__44u0__p7_1,
  141736. NULL,
  141737. 0
  141738. };
  141739. static long _vq_quantlist__44u0__p7_2[] = {
  141740. 6,
  141741. 5,
  141742. 7,
  141743. 4,
  141744. 8,
  141745. 3,
  141746. 9,
  141747. 2,
  141748. 10,
  141749. 1,
  141750. 11,
  141751. 0,
  141752. 12,
  141753. };
  141754. static long _vq_lengthlist__44u0__p7_2[] = {
  141755. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  141756. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  141757. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  141758. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141759. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  141760. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  141761. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  141762. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141763. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141764. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  141765. 9, 9, 9,10, 9, 9,10,10, 9,
  141766. };
  141767. static float _vq_quantthresh__44u0__p7_2[] = {
  141768. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141769. 2.5, 3.5, 4.5, 5.5,
  141770. };
  141771. static long _vq_quantmap__44u0__p7_2[] = {
  141772. 11, 9, 7, 5, 3, 1, 0, 2,
  141773. 4, 6, 8, 10, 12,
  141774. };
  141775. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  141776. _vq_quantthresh__44u0__p7_2,
  141777. _vq_quantmap__44u0__p7_2,
  141778. 13,
  141779. 13
  141780. };
  141781. static static_codebook _44u0__p7_2 = {
  141782. 2, 169,
  141783. _vq_lengthlist__44u0__p7_2,
  141784. 1, -531103744, 1611661312, 4, 0,
  141785. _vq_quantlist__44u0__p7_2,
  141786. NULL,
  141787. &_vq_auxt__44u0__p7_2,
  141788. NULL,
  141789. 0
  141790. };
  141791. static long _huff_lengthlist__44u0__short[] = {
  141792. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  141793. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  141794. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  141795. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  141796. };
  141797. static static_codebook _huff_book__44u0__short = {
  141798. 2, 64,
  141799. _huff_lengthlist__44u0__short,
  141800. 0, 0, 0, 0, 0,
  141801. NULL,
  141802. NULL,
  141803. NULL,
  141804. NULL,
  141805. 0
  141806. };
  141807. static long _huff_lengthlist__44u1__long[] = {
  141808. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  141809. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  141810. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  141811. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  141812. };
  141813. static static_codebook _huff_book__44u1__long = {
  141814. 2, 64,
  141815. _huff_lengthlist__44u1__long,
  141816. 0, 0, 0, 0, 0,
  141817. NULL,
  141818. NULL,
  141819. NULL,
  141820. NULL,
  141821. 0
  141822. };
  141823. static long _vq_quantlist__44u1__p1_0[] = {
  141824. 1,
  141825. 0,
  141826. 2,
  141827. };
  141828. static long _vq_lengthlist__44u1__p1_0[] = {
  141829. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141830. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141831. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  141832. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  141833. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  141834. 13,
  141835. };
  141836. static float _vq_quantthresh__44u1__p1_0[] = {
  141837. -0.5, 0.5,
  141838. };
  141839. static long _vq_quantmap__44u1__p1_0[] = {
  141840. 1, 0, 2,
  141841. };
  141842. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  141843. _vq_quantthresh__44u1__p1_0,
  141844. _vq_quantmap__44u1__p1_0,
  141845. 3,
  141846. 3
  141847. };
  141848. static static_codebook _44u1__p1_0 = {
  141849. 4, 81,
  141850. _vq_lengthlist__44u1__p1_0,
  141851. 1, -535822336, 1611661312, 2, 0,
  141852. _vq_quantlist__44u1__p1_0,
  141853. NULL,
  141854. &_vq_auxt__44u1__p1_0,
  141855. NULL,
  141856. 0
  141857. };
  141858. static long _vq_quantlist__44u1__p2_0[] = {
  141859. 1,
  141860. 0,
  141861. 2,
  141862. };
  141863. static long _vq_lengthlist__44u1__p2_0[] = {
  141864. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  141865. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  141866. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141867. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  141868. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141869. 9,
  141870. };
  141871. static float _vq_quantthresh__44u1__p2_0[] = {
  141872. -0.5, 0.5,
  141873. };
  141874. static long _vq_quantmap__44u1__p2_0[] = {
  141875. 1, 0, 2,
  141876. };
  141877. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  141878. _vq_quantthresh__44u1__p2_0,
  141879. _vq_quantmap__44u1__p2_0,
  141880. 3,
  141881. 3
  141882. };
  141883. static static_codebook _44u1__p2_0 = {
  141884. 4, 81,
  141885. _vq_lengthlist__44u1__p2_0,
  141886. 1, -535822336, 1611661312, 2, 0,
  141887. _vq_quantlist__44u1__p2_0,
  141888. NULL,
  141889. &_vq_auxt__44u1__p2_0,
  141890. NULL,
  141891. 0
  141892. };
  141893. static long _vq_quantlist__44u1__p3_0[] = {
  141894. 2,
  141895. 1,
  141896. 3,
  141897. 0,
  141898. 4,
  141899. };
  141900. static long _vq_lengthlist__44u1__p3_0[] = {
  141901. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  141902. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  141903. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  141904. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  141905. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  141906. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  141907. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  141908. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  141909. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  141910. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  141911. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  141912. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  141913. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  141914. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  141915. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  141916. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  141917. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  141918. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  141919. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  141920. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  141921. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  141922. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  141923. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  141924. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  141925. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  141926. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  141927. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  141928. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  141929. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  141930. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  141931. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  141932. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  141933. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  141934. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  141935. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  141936. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  141937. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  141938. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  141939. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  141940. 19,
  141941. };
  141942. static float _vq_quantthresh__44u1__p3_0[] = {
  141943. -1.5, -0.5, 0.5, 1.5,
  141944. };
  141945. static long _vq_quantmap__44u1__p3_0[] = {
  141946. 3, 1, 0, 2, 4,
  141947. };
  141948. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  141949. _vq_quantthresh__44u1__p3_0,
  141950. _vq_quantmap__44u1__p3_0,
  141951. 5,
  141952. 5
  141953. };
  141954. static static_codebook _44u1__p3_0 = {
  141955. 4, 625,
  141956. _vq_lengthlist__44u1__p3_0,
  141957. 1, -533725184, 1611661312, 3, 0,
  141958. _vq_quantlist__44u1__p3_0,
  141959. NULL,
  141960. &_vq_auxt__44u1__p3_0,
  141961. NULL,
  141962. 0
  141963. };
  141964. static long _vq_quantlist__44u1__p4_0[] = {
  141965. 2,
  141966. 1,
  141967. 3,
  141968. 0,
  141969. 4,
  141970. };
  141971. static long _vq_lengthlist__44u1__p4_0[] = {
  141972. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  141973. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  141974. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  141975. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  141976. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  141977. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  141978. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  141979. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  141980. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  141981. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  141982. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  141983. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141984. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  141985. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  141986. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  141987. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  141988. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  141989. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  141990. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  141991. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  141992. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  141993. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  141994. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  141995. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  141996. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  141997. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  141998. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  141999. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142000. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142001. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142002. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142003. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142004. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142005. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142006. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142007. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142008. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142009. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142010. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142011. 12,
  142012. };
  142013. static float _vq_quantthresh__44u1__p4_0[] = {
  142014. -1.5, -0.5, 0.5, 1.5,
  142015. };
  142016. static long _vq_quantmap__44u1__p4_0[] = {
  142017. 3, 1, 0, 2, 4,
  142018. };
  142019. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  142020. _vq_quantthresh__44u1__p4_0,
  142021. _vq_quantmap__44u1__p4_0,
  142022. 5,
  142023. 5
  142024. };
  142025. static static_codebook _44u1__p4_0 = {
  142026. 4, 625,
  142027. _vq_lengthlist__44u1__p4_0,
  142028. 1, -533725184, 1611661312, 3, 0,
  142029. _vq_quantlist__44u1__p4_0,
  142030. NULL,
  142031. &_vq_auxt__44u1__p4_0,
  142032. NULL,
  142033. 0
  142034. };
  142035. static long _vq_quantlist__44u1__p5_0[] = {
  142036. 4,
  142037. 3,
  142038. 5,
  142039. 2,
  142040. 6,
  142041. 1,
  142042. 7,
  142043. 0,
  142044. 8,
  142045. };
  142046. static long _vq_lengthlist__44u1__p5_0[] = {
  142047. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142048. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142049. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142050. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142051. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142052. 12,
  142053. };
  142054. static float _vq_quantthresh__44u1__p5_0[] = {
  142055. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142056. };
  142057. static long _vq_quantmap__44u1__p5_0[] = {
  142058. 7, 5, 3, 1, 0, 2, 4, 6,
  142059. 8,
  142060. };
  142061. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  142062. _vq_quantthresh__44u1__p5_0,
  142063. _vq_quantmap__44u1__p5_0,
  142064. 9,
  142065. 9
  142066. };
  142067. static static_codebook _44u1__p5_0 = {
  142068. 2, 81,
  142069. _vq_lengthlist__44u1__p5_0,
  142070. 1, -531628032, 1611661312, 4, 0,
  142071. _vq_quantlist__44u1__p5_0,
  142072. NULL,
  142073. &_vq_auxt__44u1__p5_0,
  142074. NULL,
  142075. 0
  142076. };
  142077. static long _vq_quantlist__44u1__p6_0[] = {
  142078. 6,
  142079. 5,
  142080. 7,
  142081. 4,
  142082. 8,
  142083. 3,
  142084. 9,
  142085. 2,
  142086. 10,
  142087. 1,
  142088. 11,
  142089. 0,
  142090. 12,
  142091. };
  142092. static long _vq_lengthlist__44u1__p6_0[] = {
  142093. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142094. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142095. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142096. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142097. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142098. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142099. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142100. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142101. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142102. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142103. 15,17,16,17,18,17,17,18, 0,
  142104. };
  142105. static float _vq_quantthresh__44u1__p6_0[] = {
  142106. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142107. 12.5, 17.5, 22.5, 27.5,
  142108. };
  142109. static long _vq_quantmap__44u1__p6_0[] = {
  142110. 11, 9, 7, 5, 3, 1, 0, 2,
  142111. 4, 6, 8, 10, 12,
  142112. };
  142113. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  142114. _vq_quantthresh__44u1__p6_0,
  142115. _vq_quantmap__44u1__p6_0,
  142116. 13,
  142117. 13
  142118. };
  142119. static static_codebook _44u1__p6_0 = {
  142120. 2, 169,
  142121. _vq_lengthlist__44u1__p6_0,
  142122. 1, -526516224, 1616117760, 4, 0,
  142123. _vq_quantlist__44u1__p6_0,
  142124. NULL,
  142125. &_vq_auxt__44u1__p6_0,
  142126. NULL,
  142127. 0
  142128. };
  142129. static long _vq_quantlist__44u1__p6_1[] = {
  142130. 2,
  142131. 1,
  142132. 3,
  142133. 0,
  142134. 4,
  142135. };
  142136. static long _vq_lengthlist__44u1__p6_1[] = {
  142137. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142138. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142139. };
  142140. static float _vq_quantthresh__44u1__p6_1[] = {
  142141. -1.5, -0.5, 0.5, 1.5,
  142142. };
  142143. static long _vq_quantmap__44u1__p6_1[] = {
  142144. 3, 1, 0, 2, 4,
  142145. };
  142146. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  142147. _vq_quantthresh__44u1__p6_1,
  142148. _vq_quantmap__44u1__p6_1,
  142149. 5,
  142150. 5
  142151. };
  142152. static static_codebook _44u1__p6_1 = {
  142153. 2, 25,
  142154. _vq_lengthlist__44u1__p6_1,
  142155. 1, -533725184, 1611661312, 3, 0,
  142156. _vq_quantlist__44u1__p6_1,
  142157. NULL,
  142158. &_vq_auxt__44u1__p6_1,
  142159. NULL,
  142160. 0
  142161. };
  142162. static long _vq_quantlist__44u1__p7_0[] = {
  142163. 3,
  142164. 2,
  142165. 4,
  142166. 1,
  142167. 5,
  142168. 0,
  142169. 6,
  142170. };
  142171. static long _vq_lengthlist__44u1__p7_0[] = {
  142172. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142173. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142174. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142175. 8,
  142176. };
  142177. static float _vq_quantthresh__44u1__p7_0[] = {
  142178. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  142179. };
  142180. static long _vq_quantmap__44u1__p7_0[] = {
  142181. 5, 3, 1, 0, 2, 4, 6,
  142182. };
  142183. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  142184. _vq_quantthresh__44u1__p7_0,
  142185. _vq_quantmap__44u1__p7_0,
  142186. 7,
  142187. 7
  142188. };
  142189. static static_codebook _44u1__p7_0 = {
  142190. 2, 49,
  142191. _vq_lengthlist__44u1__p7_0,
  142192. 1, -518017024, 1626677248, 3, 0,
  142193. _vq_quantlist__44u1__p7_0,
  142194. NULL,
  142195. &_vq_auxt__44u1__p7_0,
  142196. NULL,
  142197. 0
  142198. };
  142199. static long _vq_quantlist__44u1__p7_1[] = {
  142200. 6,
  142201. 5,
  142202. 7,
  142203. 4,
  142204. 8,
  142205. 3,
  142206. 9,
  142207. 2,
  142208. 10,
  142209. 1,
  142210. 11,
  142211. 0,
  142212. 12,
  142213. };
  142214. static long _vq_lengthlist__44u1__p7_1[] = {
  142215. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142216. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142217. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142218. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142219. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142220. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142221. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142222. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142223. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142224. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142225. 15,15,15,15,15,15,15,15,15,
  142226. };
  142227. static float _vq_quantthresh__44u1__p7_1[] = {
  142228. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142229. 32.5, 45.5, 58.5, 71.5,
  142230. };
  142231. static long _vq_quantmap__44u1__p7_1[] = {
  142232. 11, 9, 7, 5, 3, 1, 0, 2,
  142233. 4, 6, 8, 10, 12,
  142234. };
  142235. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  142236. _vq_quantthresh__44u1__p7_1,
  142237. _vq_quantmap__44u1__p7_1,
  142238. 13,
  142239. 13
  142240. };
  142241. static static_codebook _44u1__p7_1 = {
  142242. 2, 169,
  142243. _vq_lengthlist__44u1__p7_1,
  142244. 1, -523010048, 1618608128, 4, 0,
  142245. _vq_quantlist__44u1__p7_1,
  142246. NULL,
  142247. &_vq_auxt__44u1__p7_1,
  142248. NULL,
  142249. 0
  142250. };
  142251. static long _vq_quantlist__44u1__p7_2[] = {
  142252. 6,
  142253. 5,
  142254. 7,
  142255. 4,
  142256. 8,
  142257. 3,
  142258. 9,
  142259. 2,
  142260. 10,
  142261. 1,
  142262. 11,
  142263. 0,
  142264. 12,
  142265. };
  142266. static long _vq_lengthlist__44u1__p7_2[] = {
  142267. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142268. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142269. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142270. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142271. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142272. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142273. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142274. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142275. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142276. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142277. 9, 9, 9,10, 9, 9,10,10, 9,
  142278. };
  142279. static float _vq_quantthresh__44u1__p7_2[] = {
  142280. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142281. 2.5, 3.5, 4.5, 5.5,
  142282. };
  142283. static long _vq_quantmap__44u1__p7_2[] = {
  142284. 11, 9, 7, 5, 3, 1, 0, 2,
  142285. 4, 6, 8, 10, 12,
  142286. };
  142287. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  142288. _vq_quantthresh__44u1__p7_2,
  142289. _vq_quantmap__44u1__p7_2,
  142290. 13,
  142291. 13
  142292. };
  142293. static static_codebook _44u1__p7_2 = {
  142294. 2, 169,
  142295. _vq_lengthlist__44u1__p7_2,
  142296. 1, -531103744, 1611661312, 4, 0,
  142297. _vq_quantlist__44u1__p7_2,
  142298. NULL,
  142299. &_vq_auxt__44u1__p7_2,
  142300. NULL,
  142301. 0
  142302. };
  142303. static long _huff_lengthlist__44u1__short[] = {
  142304. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142305. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142306. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142307. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142308. };
  142309. static static_codebook _huff_book__44u1__short = {
  142310. 2, 64,
  142311. _huff_lengthlist__44u1__short,
  142312. 0, 0, 0, 0, 0,
  142313. NULL,
  142314. NULL,
  142315. NULL,
  142316. NULL,
  142317. 0
  142318. };
  142319. static long _huff_lengthlist__44u2__long[] = {
  142320. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  142321. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  142322. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  142323. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  142324. };
  142325. static static_codebook _huff_book__44u2__long = {
  142326. 2, 64,
  142327. _huff_lengthlist__44u2__long,
  142328. 0, 0, 0, 0, 0,
  142329. NULL,
  142330. NULL,
  142331. NULL,
  142332. NULL,
  142333. 0
  142334. };
  142335. static long _vq_quantlist__44u2__p1_0[] = {
  142336. 1,
  142337. 0,
  142338. 2,
  142339. };
  142340. static long _vq_lengthlist__44u2__p1_0[] = {
  142341. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142342. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142343. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  142344. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  142345. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  142346. 13,
  142347. };
  142348. static float _vq_quantthresh__44u2__p1_0[] = {
  142349. -0.5, 0.5,
  142350. };
  142351. static long _vq_quantmap__44u2__p1_0[] = {
  142352. 1, 0, 2,
  142353. };
  142354. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  142355. _vq_quantthresh__44u2__p1_0,
  142356. _vq_quantmap__44u2__p1_0,
  142357. 3,
  142358. 3
  142359. };
  142360. static static_codebook _44u2__p1_0 = {
  142361. 4, 81,
  142362. _vq_lengthlist__44u2__p1_0,
  142363. 1, -535822336, 1611661312, 2, 0,
  142364. _vq_quantlist__44u2__p1_0,
  142365. NULL,
  142366. &_vq_auxt__44u2__p1_0,
  142367. NULL,
  142368. 0
  142369. };
  142370. static long _vq_quantlist__44u2__p2_0[] = {
  142371. 1,
  142372. 0,
  142373. 2,
  142374. };
  142375. static long _vq_lengthlist__44u2__p2_0[] = {
  142376. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142377. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  142378. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142379. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142380. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142381. 9,
  142382. };
  142383. static float _vq_quantthresh__44u2__p2_0[] = {
  142384. -0.5, 0.5,
  142385. };
  142386. static long _vq_quantmap__44u2__p2_0[] = {
  142387. 1, 0, 2,
  142388. };
  142389. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  142390. _vq_quantthresh__44u2__p2_0,
  142391. _vq_quantmap__44u2__p2_0,
  142392. 3,
  142393. 3
  142394. };
  142395. static static_codebook _44u2__p2_0 = {
  142396. 4, 81,
  142397. _vq_lengthlist__44u2__p2_0,
  142398. 1, -535822336, 1611661312, 2, 0,
  142399. _vq_quantlist__44u2__p2_0,
  142400. NULL,
  142401. &_vq_auxt__44u2__p2_0,
  142402. NULL,
  142403. 0
  142404. };
  142405. static long _vq_quantlist__44u2__p3_0[] = {
  142406. 2,
  142407. 1,
  142408. 3,
  142409. 0,
  142410. 4,
  142411. };
  142412. static long _vq_lengthlist__44u2__p3_0[] = {
  142413. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142414. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  142415. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  142416. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  142417. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  142418. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  142419. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  142420. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  142421. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  142422. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  142423. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  142424. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  142425. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  142426. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  142427. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  142428. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  142429. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  142430. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  142431. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  142432. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  142433. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  142434. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  142435. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  142436. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  142437. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  142438. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  142439. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  142440. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  142441. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  142442. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  142443. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  142444. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  142445. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  142446. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  142447. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  142448. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  142449. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  142450. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  142451. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  142452. 0,
  142453. };
  142454. static float _vq_quantthresh__44u2__p3_0[] = {
  142455. -1.5, -0.5, 0.5, 1.5,
  142456. };
  142457. static long _vq_quantmap__44u2__p3_0[] = {
  142458. 3, 1, 0, 2, 4,
  142459. };
  142460. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  142461. _vq_quantthresh__44u2__p3_0,
  142462. _vq_quantmap__44u2__p3_0,
  142463. 5,
  142464. 5
  142465. };
  142466. static static_codebook _44u2__p3_0 = {
  142467. 4, 625,
  142468. _vq_lengthlist__44u2__p3_0,
  142469. 1, -533725184, 1611661312, 3, 0,
  142470. _vq_quantlist__44u2__p3_0,
  142471. NULL,
  142472. &_vq_auxt__44u2__p3_0,
  142473. NULL,
  142474. 0
  142475. };
  142476. static long _vq_quantlist__44u2__p4_0[] = {
  142477. 2,
  142478. 1,
  142479. 3,
  142480. 0,
  142481. 4,
  142482. };
  142483. static long _vq_lengthlist__44u2__p4_0[] = {
  142484. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142485. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142486. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142487. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  142488. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  142489. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  142490. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  142491. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  142492. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142493. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142494. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  142495. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142496. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  142497. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  142498. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  142499. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  142500. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  142501. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142502. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142503. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  142504. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142505. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  142506. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  142507. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142508. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  142509. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  142510. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  142511. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  142512. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  142513. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  142514. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  142515. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  142516. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  142517. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  142518. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  142519. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  142520. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  142521. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  142522. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  142523. 13,
  142524. };
  142525. static float _vq_quantthresh__44u2__p4_0[] = {
  142526. -1.5, -0.5, 0.5, 1.5,
  142527. };
  142528. static long _vq_quantmap__44u2__p4_0[] = {
  142529. 3, 1, 0, 2, 4,
  142530. };
  142531. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  142532. _vq_quantthresh__44u2__p4_0,
  142533. _vq_quantmap__44u2__p4_0,
  142534. 5,
  142535. 5
  142536. };
  142537. static static_codebook _44u2__p4_0 = {
  142538. 4, 625,
  142539. _vq_lengthlist__44u2__p4_0,
  142540. 1, -533725184, 1611661312, 3, 0,
  142541. _vq_quantlist__44u2__p4_0,
  142542. NULL,
  142543. &_vq_auxt__44u2__p4_0,
  142544. NULL,
  142545. 0
  142546. };
  142547. static long _vq_quantlist__44u2__p5_0[] = {
  142548. 4,
  142549. 3,
  142550. 5,
  142551. 2,
  142552. 6,
  142553. 1,
  142554. 7,
  142555. 0,
  142556. 8,
  142557. };
  142558. static long _vq_lengthlist__44u2__p5_0[] = {
  142559. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  142560. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142561. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  142562. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  142563. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  142564. 13,
  142565. };
  142566. static float _vq_quantthresh__44u2__p5_0[] = {
  142567. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142568. };
  142569. static long _vq_quantmap__44u2__p5_0[] = {
  142570. 7, 5, 3, 1, 0, 2, 4, 6,
  142571. 8,
  142572. };
  142573. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  142574. _vq_quantthresh__44u2__p5_0,
  142575. _vq_quantmap__44u2__p5_0,
  142576. 9,
  142577. 9
  142578. };
  142579. static static_codebook _44u2__p5_0 = {
  142580. 2, 81,
  142581. _vq_lengthlist__44u2__p5_0,
  142582. 1, -531628032, 1611661312, 4, 0,
  142583. _vq_quantlist__44u2__p5_0,
  142584. NULL,
  142585. &_vq_auxt__44u2__p5_0,
  142586. NULL,
  142587. 0
  142588. };
  142589. static long _vq_quantlist__44u2__p6_0[] = {
  142590. 6,
  142591. 5,
  142592. 7,
  142593. 4,
  142594. 8,
  142595. 3,
  142596. 9,
  142597. 2,
  142598. 10,
  142599. 1,
  142600. 11,
  142601. 0,
  142602. 12,
  142603. };
  142604. static long _vq_lengthlist__44u2__p6_0[] = {
  142605. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  142606. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  142607. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  142608. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  142609. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  142610. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  142611. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  142612. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  142613. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  142614. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  142615. 15,17,17,16,18,17,18, 0, 0,
  142616. };
  142617. static float _vq_quantthresh__44u2__p6_0[] = {
  142618. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142619. 12.5, 17.5, 22.5, 27.5,
  142620. };
  142621. static long _vq_quantmap__44u2__p6_0[] = {
  142622. 11, 9, 7, 5, 3, 1, 0, 2,
  142623. 4, 6, 8, 10, 12,
  142624. };
  142625. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  142626. _vq_quantthresh__44u2__p6_0,
  142627. _vq_quantmap__44u2__p6_0,
  142628. 13,
  142629. 13
  142630. };
  142631. static static_codebook _44u2__p6_0 = {
  142632. 2, 169,
  142633. _vq_lengthlist__44u2__p6_0,
  142634. 1, -526516224, 1616117760, 4, 0,
  142635. _vq_quantlist__44u2__p6_0,
  142636. NULL,
  142637. &_vq_auxt__44u2__p6_0,
  142638. NULL,
  142639. 0
  142640. };
  142641. static long _vq_quantlist__44u2__p6_1[] = {
  142642. 2,
  142643. 1,
  142644. 3,
  142645. 0,
  142646. 4,
  142647. };
  142648. static long _vq_lengthlist__44u2__p6_1[] = {
  142649. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142650. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142651. };
  142652. static float _vq_quantthresh__44u2__p6_1[] = {
  142653. -1.5, -0.5, 0.5, 1.5,
  142654. };
  142655. static long _vq_quantmap__44u2__p6_1[] = {
  142656. 3, 1, 0, 2, 4,
  142657. };
  142658. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  142659. _vq_quantthresh__44u2__p6_1,
  142660. _vq_quantmap__44u2__p6_1,
  142661. 5,
  142662. 5
  142663. };
  142664. static static_codebook _44u2__p6_1 = {
  142665. 2, 25,
  142666. _vq_lengthlist__44u2__p6_1,
  142667. 1, -533725184, 1611661312, 3, 0,
  142668. _vq_quantlist__44u2__p6_1,
  142669. NULL,
  142670. &_vq_auxt__44u2__p6_1,
  142671. NULL,
  142672. 0
  142673. };
  142674. static long _vq_quantlist__44u2__p7_0[] = {
  142675. 4,
  142676. 3,
  142677. 5,
  142678. 2,
  142679. 6,
  142680. 1,
  142681. 7,
  142682. 0,
  142683. 8,
  142684. };
  142685. static long _vq_lengthlist__44u2__p7_0[] = {
  142686. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  142687. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  142688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142691. 11,
  142692. };
  142693. static float _vq_quantthresh__44u2__p7_0[] = {
  142694. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  142695. };
  142696. static long _vq_quantmap__44u2__p7_0[] = {
  142697. 7, 5, 3, 1, 0, 2, 4, 6,
  142698. 8,
  142699. };
  142700. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  142701. _vq_quantthresh__44u2__p7_0,
  142702. _vq_quantmap__44u2__p7_0,
  142703. 9,
  142704. 9
  142705. };
  142706. static static_codebook _44u2__p7_0 = {
  142707. 2, 81,
  142708. _vq_lengthlist__44u2__p7_0,
  142709. 1, -516612096, 1626677248, 4, 0,
  142710. _vq_quantlist__44u2__p7_0,
  142711. NULL,
  142712. &_vq_auxt__44u2__p7_0,
  142713. NULL,
  142714. 0
  142715. };
  142716. static long _vq_quantlist__44u2__p7_1[] = {
  142717. 6,
  142718. 5,
  142719. 7,
  142720. 4,
  142721. 8,
  142722. 3,
  142723. 9,
  142724. 2,
  142725. 10,
  142726. 1,
  142727. 11,
  142728. 0,
  142729. 12,
  142730. };
  142731. static long _vq_lengthlist__44u2__p7_1[] = {
  142732. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  142733. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  142734. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  142735. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  142736. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  142737. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  142738. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  142739. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  142740. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  142741. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  142742. 14,14,14,17,15,17,17,17,17,
  142743. };
  142744. static float _vq_quantthresh__44u2__p7_1[] = {
  142745. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142746. 32.5, 45.5, 58.5, 71.5,
  142747. };
  142748. static long _vq_quantmap__44u2__p7_1[] = {
  142749. 11, 9, 7, 5, 3, 1, 0, 2,
  142750. 4, 6, 8, 10, 12,
  142751. };
  142752. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  142753. _vq_quantthresh__44u2__p7_1,
  142754. _vq_quantmap__44u2__p7_1,
  142755. 13,
  142756. 13
  142757. };
  142758. static static_codebook _44u2__p7_1 = {
  142759. 2, 169,
  142760. _vq_lengthlist__44u2__p7_1,
  142761. 1, -523010048, 1618608128, 4, 0,
  142762. _vq_quantlist__44u2__p7_1,
  142763. NULL,
  142764. &_vq_auxt__44u2__p7_1,
  142765. NULL,
  142766. 0
  142767. };
  142768. static long _vq_quantlist__44u2__p7_2[] = {
  142769. 6,
  142770. 5,
  142771. 7,
  142772. 4,
  142773. 8,
  142774. 3,
  142775. 9,
  142776. 2,
  142777. 10,
  142778. 1,
  142779. 11,
  142780. 0,
  142781. 12,
  142782. };
  142783. static long _vq_lengthlist__44u2__p7_2[] = {
  142784. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  142785. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  142786. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  142787. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142788. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  142789. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  142790. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  142791. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142792. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  142793. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  142794. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142795. };
  142796. static float _vq_quantthresh__44u2__p7_2[] = {
  142797. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142798. 2.5, 3.5, 4.5, 5.5,
  142799. };
  142800. static long _vq_quantmap__44u2__p7_2[] = {
  142801. 11, 9, 7, 5, 3, 1, 0, 2,
  142802. 4, 6, 8, 10, 12,
  142803. };
  142804. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  142805. _vq_quantthresh__44u2__p7_2,
  142806. _vq_quantmap__44u2__p7_2,
  142807. 13,
  142808. 13
  142809. };
  142810. static static_codebook _44u2__p7_2 = {
  142811. 2, 169,
  142812. _vq_lengthlist__44u2__p7_2,
  142813. 1, -531103744, 1611661312, 4, 0,
  142814. _vq_quantlist__44u2__p7_2,
  142815. NULL,
  142816. &_vq_auxt__44u2__p7_2,
  142817. NULL,
  142818. 0
  142819. };
  142820. static long _huff_lengthlist__44u2__short[] = {
  142821. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  142822. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  142823. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  142824. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  142825. };
  142826. static static_codebook _huff_book__44u2__short = {
  142827. 2, 64,
  142828. _huff_lengthlist__44u2__short,
  142829. 0, 0, 0, 0, 0,
  142830. NULL,
  142831. NULL,
  142832. NULL,
  142833. NULL,
  142834. 0
  142835. };
  142836. static long _huff_lengthlist__44u3__long[] = {
  142837. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  142838. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  142839. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  142840. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  142841. };
  142842. static static_codebook _huff_book__44u3__long = {
  142843. 2, 64,
  142844. _huff_lengthlist__44u3__long,
  142845. 0, 0, 0, 0, 0,
  142846. NULL,
  142847. NULL,
  142848. NULL,
  142849. NULL,
  142850. 0
  142851. };
  142852. static long _vq_quantlist__44u3__p1_0[] = {
  142853. 1,
  142854. 0,
  142855. 2,
  142856. };
  142857. static long _vq_lengthlist__44u3__p1_0[] = {
  142858. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  142859. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142860. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  142861. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  142862. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  142863. 13,
  142864. };
  142865. static float _vq_quantthresh__44u3__p1_0[] = {
  142866. -0.5, 0.5,
  142867. };
  142868. static long _vq_quantmap__44u3__p1_0[] = {
  142869. 1, 0, 2,
  142870. };
  142871. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  142872. _vq_quantthresh__44u3__p1_0,
  142873. _vq_quantmap__44u3__p1_0,
  142874. 3,
  142875. 3
  142876. };
  142877. static static_codebook _44u3__p1_0 = {
  142878. 4, 81,
  142879. _vq_lengthlist__44u3__p1_0,
  142880. 1, -535822336, 1611661312, 2, 0,
  142881. _vq_quantlist__44u3__p1_0,
  142882. NULL,
  142883. &_vq_auxt__44u3__p1_0,
  142884. NULL,
  142885. 0
  142886. };
  142887. static long _vq_quantlist__44u3__p2_0[] = {
  142888. 1,
  142889. 0,
  142890. 2,
  142891. };
  142892. static long _vq_lengthlist__44u3__p2_0[] = {
  142893. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142894. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  142895. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142896. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142897. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  142898. 9,
  142899. };
  142900. static float _vq_quantthresh__44u3__p2_0[] = {
  142901. -0.5, 0.5,
  142902. };
  142903. static long _vq_quantmap__44u3__p2_0[] = {
  142904. 1, 0, 2,
  142905. };
  142906. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  142907. _vq_quantthresh__44u3__p2_0,
  142908. _vq_quantmap__44u3__p2_0,
  142909. 3,
  142910. 3
  142911. };
  142912. static static_codebook _44u3__p2_0 = {
  142913. 4, 81,
  142914. _vq_lengthlist__44u3__p2_0,
  142915. 1, -535822336, 1611661312, 2, 0,
  142916. _vq_quantlist__44u3__p2_0,
  142917. NULL,
  142918. &_vq_auxt__44u3__p2_0,
  142919. NULL,
  142920. 0
  142921. };
  142922. static long _vq_quantlist__44u3__p3_0[] = {
  142923. 2,
  142924. 1,
  142925. 3,
  142926. 0,
  142927. 4,
  142928. };
  142929. static long _vq_lengthlist__44u3__p3_0[] = {
  142930. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142931. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  142932. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  142933. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  142934. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  142935. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  142936. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  142937. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  142938. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  142939. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  142940. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  142941. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  142942. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  142943. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  142944. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  142945. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  142946. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  142947. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  142948. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  142949. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  142950. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  142951. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  142952. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  142953. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  142954. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  142955. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  142956. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  142957. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  142958. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  142959. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  142960. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  142961. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  142962. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  142963. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  142964. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  142965. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  142966. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  142967. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  142968. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  142969. 0,
  142970. };
  142971. static float _vq_quantthresh__44u3__p3_0[] = {
  142972. -1.5, -0.5, 0.5, 1.5,
  142973. };
  142974. static long _vq_quantmap__44u3__p3_0[] = {
  142975. 3, 1, 0, 2, 4,
  142976. };
  142977. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  142978. _vq_quantthresh__44u3__p3_0,
  142979. _vq_quantmap__44u3__p3_0,
  142980. 5,
  142981. 5
  142982. };
  142983. static static_codebook _44u3__p3_0 = {
  142984. 4, 625,
  142985. _vq_lengthlist__44u3__p3_0,
  142986. 1, -533725184, 1611661312, 3, 0,
  142987. _vq_quantlist__44u3__p3_0,
  142988. NULL,
  142989. &_vq_auxt__44u3__p3_0,
  142990. NULL,
  142991. 0
  142992. };
  142993. static long _vq_quantlist__44u3__p4_0[] = {
  142994. 2,
  142995. 1,
  142996. 3,
  142997. 0,
  142998. 4,
  142999. };
  143000. static long _vq_lengthlist__44u3__p4_0[] = {
  143001. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143002. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143003. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  143004. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  143005. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  143006. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143007. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  143008. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  143009. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143010. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143011. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  143012. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143013. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  143014. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  143015. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  143016. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143017. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  143018. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143019. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143020. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  143021. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143022. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  143023. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143024. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143025. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  143026. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  143027. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  143028. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  143029. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143030. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  143031. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  143032. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  143033. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  143034. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143035. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  143036. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  143037. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  143038. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  143039. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  143040. 13,
  143041. };
  143042. static float _vq_quantthresh__44u3__p4_0[] = {
  143043. -1.5, -0.5, 0.5, 1.5,
  143044. };
  143045. static long _vq_quantmap__44u3__p4_0[] = {
  143046. 3, 1, 0, 2, 4,
  143047. };
  143048. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  143049. _vq_quantthresh__44u3__p4_0,
  143050. _vq_quantmap__44u3__p4_0,
  143051. 5,
  143052. 5
  143053. };
  143054. static static_codebook _44u3__p4_0 = {
  143055. 4, 625,
  143056. _vq_lengthlist__44u3__p4_0,
  143057. 1, -533725184, 1611661312, 3, 0,
  143058. _vq_quantlist__44u3__p4_0,
  143059. NULL,
  143060. &_vq_auxt__44u3__p4_0,
  143061. NULL,
  143062. 0
  143063. };
  143064. static long _vq_quantlist__44u3__p5_0[] = {
  143065. 4,
  143066. 3,
  143067. 5,
  143068. 2,
  143069. 6,
  143070. 1,
  143071. 7,
  143072. 0,
  143073. 8,
  143074. };
  143075. static long _vq_lengthlist__44u3__p5_0[] = {
  143076. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  143077. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  143078. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  143079. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143080. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  143081. 12,
  143082. };
  143083. static float _vq_quantthresh__44u3__p5_0[] = {
  143084. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143085. };
  143086. static long _vq_quantmap__44u3__p5_0[] = {
  143087. 7, 5, 3, 1, 0, 2, 4, 6,
  143088. 8,
  143089. };
  143090. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  143091. _vq_quantthresh__44u3__p5_0,
  143092. _vq_quantmap__44u3__p5_0,
  143093. 9,
  143094. 9
  143095. };
  143096. static static_codebook _44u3__p5_0 = {
  143097. 2, 81,
  143098. _vq_lengthlist__44u3__p5_0,
  143099. 1, -531628032, 1611661312, 4, 0,
  143100. _vq_quantlist__44u3__p5_0,
  143101. NULL,
  143102. &_vq_auxt__44u3__p5_0,
  143103. NULL,
  143104. 0
  143105. };
  143106. static long _vq_quantlist__44u3__p6_0[] = {
  143107. 6,
  143108. 5,
  143109. 7,
  143110. 4,
  143111. 8,
  143112. 3,
  143113. 9,
  143114. 2,
  143115. 10,
  143116. 1,
  143117. 11,
  143118. 0,
  143119. 12,
  143120. };
  143121. static long _vq_lengthlist__44u3__p6_0[] = {
  143122. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  143123. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  143124. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143125. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  143126. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  143127. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  143128. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  143129. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  143130. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  143131. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  143132. 15,16,16,16,17,18,16,20,18,
  143133. };
  143134. static float _vq_quantthresh__44u3__p6_0[] = {
  143135. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143136. 12.5, 17.5, 22.5, 27.5,
  143137. };
  143138. static long _vq_quantmap__44u3__p6_0[] = {
  143139. 11, 9, 7, 5, 3, 1, 0, 2,
  143140. 4, 6, 8, 10, 12,
  143141. };
  143142. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  143143. _vq_quantthresh__44u3__p6_0,
  143144. _vq_quantmap__44u3__p6_0,
  143145. 13,
  143146. 13
  143147. };
  143148. static static_codebook _44u3__p6_0 = {
  143149. 2, 169,
  143150. _vq_lengthlist__44u3__p6_0,
  143151. 1, -526516224, 1616117760, 4, 0,
  143152. _vq_quantlist__44u3__p6_0,
  143153. NULL,
  143154. &_vq_auxt__44u3__p6_0,
  143155. NULL,
  143156. 0
  143157. };
  143158. static long _vq_quantlist__44u3__p6_1[] = {
  143159. 2,
  143160. 1,
  143161. 3,
  143162. 0,
  143163. 4,
  143164. };
  143165. static long _vq_lengthlist__44u3__p6_1[] = {
  143166. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143167. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143168. };
  143169. static float _vq_quantthresh__44u3__p6_1[] = {
  143170. -1.5, -0.5, 0.5, 1.5,
  143171. };
  143172. static long _vq_quantmap__44u3__p6_1[] = {
  143173. 3, 1, 0, 2, 4,
  143174. };
  143175. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  143176. _vq_quantthresh__44u3__p6_1,
  143177. _vq_quantmap__44u3__p6_1,
  143178. 5,
  143179. 5
  143180. };
  143181. static static_codebook _44u3__p6_1 = {
  143182. 2, 25,
  143183. _vq_lengthlist__44u3__p6_1,
  143184. 1, -533725184, 1611661312, 3, 0,
  143185. _vq_quantlist__44u3__p6_1,
  143186. NULL,
  143187. &_vq_auxt__44u3__p6_1,
  143188. NULL,
  143189. 0
  143190. };
  143191. static long _vq_quantlist__44u3__p7_0[] = {
  143192. 4,
  143193. 3,
  143194. 5,
  143195. 2,
  143196. 6,
  143197. 1,
  143198. 7,
  143199. 0,
  143200. 8,
  143201. };
  143202. static long _vq_lengthlist__44u3__p7_0[] = {
  143203. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  143204. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 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,
  143209. };
  143210. static float _vq_quantthresh__44u3__p7_0[] = {
  143211. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  143212. };
  143213. static long _vq_quantmap__44u3__p7_0[] = {
  143214. 7, 5, 3, 1, 0, 2, 4, 6,
  143215. 8,
  143216. };
  143217. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  143218. _vq_quantthresh__44u3__p7_0,
  143219. _vq_quantmap__44u3__p7_0,
  143220. 9,
  143221. 9
  143222. };
  143223. static static_codebook _44u3__p7_0 = {
  143224. 2, 81,
  143225. _vq_lengthlist__44u3__p7_0,
  143226. 1, -515907584, 1627381760, 4, 0,
  143227. _vq_quantlist__44u3__p7_0,
  143228. NULL,
  143229. &_vq_auxt__44u3__p7_0,
  143230. NULL,
  143231. 0
  143232. };
  143233. static long _vq_quantlist__44u3__p7_1[] = {
  143234. 7,
  143235. 6,
  143236. 8,
  143237. 5,
  143238. 9,
  143239. 4,
  143240. 10,
  143241. 3,
  143242. 11,
  143243. 2,
  143244. 12,
  143245. 1,
  143246. 13,
  143247. 0,
  143248. 14,
  143249. };
  143250. static long _vq_lengthlist__44u3__p7_1[] = {
  143251. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  143252. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  143253. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  143254. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  143255. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  143256. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  143257. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  143258. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  143259. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  143260. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  143261. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  143262. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  143263. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  143264. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  143265. 17,
  143266. };
  143267. static float _vq_quantthresh__44u3__p7_1[] = {
  143268. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143269. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143270. };
  143271. static long _vq_quantmap__44u3__p7_1[] = {
  143272. 13, 11, 9, 7, 5, 3, 1, 0,
  143273. 2, 4, 6, 8, 10, 12, 14,
  143274. };
  143275. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  143276. _vq_quantthresh__44u3__p7_1,
  143277. _vq_quantmap__44u3__p7_1,
  143278. 15,
  143279. 15
  143280. };
  143281. static static_codebook _44u3__p7_1 = {
  143282. 2, 225,
  143283. _vq_lengthlist__44u3__p7_1,
  143284. 1, -522338304, 1620115456, 4, 0,
  143285. _vq_quantlist__44u3__p7_1,
  143286. NULL,
  143287. &_vq_auxt__44u3__p7_1,
  143288. NULL,
  143289. 0
  143290. };
  143291. static long _vq_quantlist__44u3__p7_2[] = {
  143292. 8,
  143293. 7,
  143294. 9,
  143295. 6,
  143296. 10,
  143297. 5,
  143298. 11,
  143299. 4,
  143300. 12,
  143301. 3,
  143302. 13,
  143303. 2,
  143304. 14,
  143305. 1,
  143306. 15,
  143307. 0,
  143308. 16,
  143309. };
  143310. static long _vq_lengthlist__44u3__p7_2[] = {
  143311. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143312. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143313. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  143314. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143315. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143316. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143317. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  143318. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143319. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  143320. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  143321. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143322. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  143323. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  143324. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143325. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  143326. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  143327. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143328. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  143329. 11,
  143330. };
  143331. static float _vq_quantthresh__44u3__p7_2[] = {
  143332. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143333. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143334. };
  143335. static long _vq_quantmap__44u3__p7_2[] = {
  143336. 15, 13, 11, 9, 7, 5, 3, 1,
  143337. 0, 2, 4, 6, 8, 10, 12, 14,
  143338. 16,
  143339. };
  143340. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  143341. _vq_quantthresh__44u3__p7_2,
  143342. _vq_quantmap__44u3__p7_2,
  143343. 17,
  143344. 17
  143345. };
  143346. static static_codebook _44u3__p7_2 = {
  143347. 2, 289,
  143348. _vq_lengthlist__44u3__p7_2,
  143349. 1, -529530880, 1611661312, 5, 0,
  143350. _vq_quantlist__44u3__p7_2,
  143351. NULL,
  143352. &_vq_auxt__44u3__p7_2,
  143353. NULL,
  143354. 0
  143355. };
  143356. static long _huff_lengthlist__44u3__short[] = {
  143357. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  143358. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  143359. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  143360. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  143361. };
  143362. static static_codebook _huff_book__44u3__short = {
  143363. 2, 64,
  143364. _huff_lengthlist__44u3__short,
  143365. 0, 0, 0, 0, 0,
  143366. NULL,
  143367. NULL,
  143368. NULL,
  143369. NULL,
  143370. 0
  143371. };
  143372. static long _huff_lengthlist__44u4__long[] = {
  143373. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  143374. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  143375. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  143376. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  143377. };
  143378. static static_codebook _huff_book__44u4__long = {
  143379. 2, 64,
  143380. _huff_lengthlist__44u4__long,
  143381. 0, 0, 0, 0, 0,
  143382. NULL,
  143383. NULL,
  143384. NULL,
  143385. NULL,
  143386. 0
  143387. };
  143388. static long _vq_quantlist__44u4__p1_0[] = {
  143389. 1,
  143390. 0,
  143391. 2,
  143392. };
  143393. static long _vq_lengthlist__44u4__p1_0[] = {
  143394. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  143395. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143396. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  143397. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  143398. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  143399. 13,
  143400. };
  143401. static float _vq_quantthresh__44u4__p1_0[] = {
  143402. -0.5, 0.5,
  143403. };
  143404. static long _vq_quantmap__44u4__p1_0[] = {
  143405. 1, 0, 2,
  143406. };
  143407. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  143408. _vq_quantthresh__44u4__p1_0,
  143409. _vq_quantmap__44u4__p1_0,
  143410. 3,
  143411. 3
  143412. };
  143413. static static_codebook _44u4__p1_0 = {
  143414. 4, 81,
  143415. _vq_lengthlist__44u4__p1_0,
  143416. 1, -535822336, 1611661312, 2, 0,
  143417. _vq_quantlist__44u4__p1_0,
  143418. NULL,
  143419. &_vq_auxt__44u4__p1_0,
  143420. NULL,
  143421. 0
  143422. };
  143423. static long _vq_quantlist__44u4__p2_0[] = {
  143424. 1,
  143425. 0,
  143426. 2,
  143427. };
  143428. static long _vq_lengthlist__44u4__p2_0[] = {
  143429. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143430. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  143431. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143432. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  143433. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143434. 9,
  143435. };
  143436. static float _vq_quantthresh__44u4__p2_0[] = {
  143437. -0.5, 0.5,
  143438. };
  143439. static long _vq_quantmap__44u4__p2_0[] = {
  143440. 1, 0, 2,
  143441. };
  143442. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  143443. _vq_quantthresh__44u4__p2_0,
  143444. _vq_quantmap__44u4__p2_0,
  143445. 3,
  143446. 3
  143447. };
  143448. static static_codebook _44u4__p2_0 = {
  143449. 4, 81,
  143450. _vq_lengthlist__44u4__p2_0,
  143451. 1, -535822336, 1611661312, 2, 0,
  143452. _vq_quantlist__44u4__p2_0,
  143453. NULL,
  143454. &_vq_auxt__44u4__p2_0,
  143455. NULL,
  143456. 0
  143457. };
  143458. static long _vq_quantlist__44u4__p3_0[] = {
  143459. 2,
  143460. 1,
  143461. 3,
  143462. 0,
  143463. 4,
  143464. };
  143465. static long _vq_lengthlist__44u4__p3_0[] = {
  143466. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143467. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  143468. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  143469. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  143470. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  143471. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  143472. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  143473. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  143474. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  143475. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  143476. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  143477. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  143478. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  143479. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  143480. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  143481. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  143482. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  143483. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  143484. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  143485. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  143486. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  143487. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  143488. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  143489. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  143490. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  143491. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  143492. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  143493. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  143494. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  143495. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  143496. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  143497. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  143498. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  143499. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  143500. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  143501. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  143502. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  143503. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  143504. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  143505. 0,
  143506. };
  143507. static float _vq_quantthresh__44u4__p3_0[] = {
  143508. -1.5, -0.5, 0.5, 1.5,
  143509. };
  143510. static long _vq_quantmap__44u4__p3_0[] = {
  143511. 3, 1, 0, 2, 4,
  143512. };
  143513. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  143514. _vq_quantthresh__44u4__p3_0,
  143515. _vq_quantmap__44u4__p3_0,
  143516. 5,
  143517. 5
  143518. };
  143519. static static_codebook _44u4__p3_0 = {
  143520. 4, 625,
  143521. _vq_lengthlist__44u4__p3_0,
  143522. 1, -533725184, 1611661312, 3, 0,
  143523. _vq_quantlist__44u4__p3_0,
  143524. NULL,
  143525. &_vq_auxt__44u4__p3_0,
  143526. NULL,
  143527. 0
  143528. };
  143529. static long _vq_quantlist__44u4__p4_0[] = {
  143530. 2,
  143531. 1,
  143532. 3,
  143533. 0,
  143534. 4,
  143535. };
  143536. static long _vq_lengthlist__44u4__p4_0[] = {
  143537. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143538. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143539. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  143540. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  143541. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  143542. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143543. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  143544. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  143545. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143546. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143547. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  143548. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143549. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  143550. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  143551. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  143552. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143553. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  143554. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143555. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143556. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  143557. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143558. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  143559. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  143560. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143561. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  143562. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  143563. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  143564. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  143565. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  143566. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  143567. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  143568. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  143569. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  143570. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  143571. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  143572. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  143573. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  143574. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  143575. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  143576. 13,
  143577. };
  143578. static float _vq_quantthresh__44u4__p4_0[] = {
  143579. -1.5, -0.5, 0.5, 1.5,
  143580. };
  143581. static long _vq_quantmap__44u4__p4_0[] = {
  143582. 3, 1, 0, 2, 4,
  143583. };
  143584. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  143585. _vq_quantthresh__44u4__p4_0,
  143586. _vq_quantmap__44u4__p4_0,
  143587. 5,
  143588. 5
  143589. };
  143590. static static_codebook _44u4__p4_0 = {
  143591. 4, 625,
  143592. _vq_lengthlist__44u4__p4_0,
  143593. 1, -533725184, 1611661312, 3, 0,
  143594. _vq_quantlist__44u4__p4_0,
  143595. NULL,
  143596. &_vq_auxt__44u4__p4_0,
  143597. NULL,
  143598. 0
  143599. };
  143600. static long _vq_quantlist__44u4__p5_0[] = {
  143601. 4,
  143602. 3,
  143603. 5,
  143604. 2,
  143605. 6,
  143606. 1,
  143607. 7,
  143608. 0,
  143609. 8,
  143610. };
  143611. static long _vq_lengthlist__44u4__p5_0[] = {
  143612. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  143613. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  143614. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  143615. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143616. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  143617. 12,
  143618. };
  143619. static float _vq_quantthresh__44u4__p5_0[] = {
  143620. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143621. };
  143622. static long _vq_quantmap__44u4__p5_0[] = {
  143623. 7, 5, 3, 1, 0, 2, 4, 6,
  143624. 8,
  143625. };
  143626. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  143627. _vq_quantthresh__44u4__p5_0,
  143628. _vq_quantmap__44u4__p5_0,
  143629. 9,
  143630. 9
  143631. };
  143632. static static_codebook _44u4__p5_0 = {
  143633. 2, 81,
  143634. _vq_lengthlist__44u4__p5_0,
  143635. 1, -531628032, 1611661312, 4, 0,
  143636. _vq_quantlist__44u4__p5_0,
  143637. NULL,
  143638. &_vq_auxt__44u4__p5_0,
  143639. NULL,
  143640. 0
  143641. };
  143642. static long _vq_quantlist__44u4__p6_0[] = {
  143643. 6,
  143644. 5,
  143645. 7,
  143646. 4,
  143647. 8,
  143648. 3,
  143649. 9,
  143650. 2,
  143651. 10,
  143652. 1,
  143653. 11,
  143654. 0,
  143655. 12,
  143656. };
  143657. static long _vq_lengthlist__44u4__p6_0[] = {
  143658. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  143659. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  143660. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143661. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  143662. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  143663. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  143664. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  143665. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  143666. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  143667. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  143668. 16,16,16,17,17,18,17,20,21,
  143669. };
  143670. static float _vq_quantthresh__44u4__p6_0[] = {
  143671. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143672. 12.5, 17.5, 22.5, 27.5,
  143673. };
  143674. static long _vq_quantmap__44u4__p6_0[] = {
  143675. 11, 9, 7, 5, 3, 1, 0, 2,
  143676. 4, 6, 8, 10, 12,
  143677. };
  143678. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  143679. _vq_quantthresh__44u4__p6_0,
  143680. _vq_quantmap__44u4__p6_0,
  143681. 13,
  143682. 13
  143683. };
  143684. static static_codebook _44u4__p6_0 = {
  143685. 2, 169,
  143686. _vq_lengthlist__44u4__p6_0,
  143687. 1, -526516224, 1616117760, 4, 0,
  143688. _vq_quantlist__44u4__p6_0,
  143689. NULL,
  143690. &_vq_auxt__44u4__p6_0,
  143691. NULL,
  143692. 0
  143693. };
  143694. static long _vq_quantlist__44u4__p6_1[] = {
  143695. 2,
  143696. 1,
  143697. 3,
  143698. 0,
  143699. 4,
  143700. };
  143701. static long _vq_lengthlist__44u4__p6_1[] = {
  143702. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143703. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143704. };
  143705. static float _vq_quantthresh__44u4__p6_1[] = {
  143706. -1.5, -0.5, 0.5, 1.5,
  143707. };
  143708. static long _vq_quantmap__44u4__p6_1[] = {
  143709. 3, 1, 0, 2, 4,
  143710. };
  143711. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  143712. _vq_quantthresh__44u4__p6_1,
  143713. _vq_quantmap__44u4__p6_1,
  143714. 5,
  143715. 5
  143716. };
  143717. static static_codebook _44u4__p6_1 = {
  143718. 2, 25,
  143719. _vq_lengthlist__44u4__p6_1,
  143720. 1, -533725184, 1611661312, 3, 0,
  143721. _vq_quantlist__44u4__p6_1,
  143722. NULL,
  143723. &_vq_auxt__44u4__p6_1,
  143724. NULL,
  143725. 0
  143726. };
  143727. static long _vq_quantlist__44u4__p7_0[] = {
  143728. 6,
  143729. 5,
  143730. 7,
  143731. 4,
  143732. 8,
  143733. 3,
  143734. 9,
  143735. 2,
  143736. 10,
  143737. 1,
  143738. 11,
  143739. 0,
  143740. 12,
  143741. };
  143742. static long _vq_lengthlist__44u4__p7_0[] = {
  143743. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  143744. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  143745. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143746. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143747. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143748. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143753. 11,11,11,11,11,11,11,11,11,
  143754. };
  143755. static float _vq_quantthresh__44u4__p7_0[] = {
  143756. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  143757. 637.5, 892.5, 1147.5, 1402.5,
  143758. };
  143759. static long _vq_quantmap__44u4__p7_0[] = {
  143760. 11, 9, 7, 5, 3, 1, 0, 2,
  143761. 4, 6, 8, 10, 12,
  143762. };
  143763. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  143764. _vq_quantthresh__44u4__p7_0,
  143765. _vq_quantmap__44u4__p7_0,
  143766. 13,
  143767. 13
  143768. };
  143769. static static_codebook _44u4__p7_0 = {
  143770. 2, 169,
  143771. _vq_lengthlist__44u4__p7_0,
  143772. 1, -514332672, 1627381760, 4, 0,
  143773. _vq_quantlist__44u4__p7_0,
  143774. NULL,
  143775. &_vq_auxt__44u4__p7_0,
  143776. NULL,
  143777. 0
  143778. };
  143779. static long _vq_quantlist__44u4__p7_1[] = {
  143780. 7,
  143781. 6,
  143782. 8,
  143783. 5,
  143784. 9,
  143785. 4,
  143786. 10,
  143787. 3,
  143788. 11,
  143789. 2,
  143790. 12,
  143791. 1,
  143792. 13,
  143793. 0,
  143794. 14,
  143795. };
  143796. static long _vq_lengthlist__44u4__p7_1[] = {
  143797. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  143798. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  143799. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  143800. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  143801. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  143802. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  143803. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  143804. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  143805. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  143806. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  143807. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  143808. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  143809. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  143810. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  143811. 16,
  143812. };
  143813. static float _vq_quantthresh__44u4__p7_1[] = {
  143814. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143815. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143816. };
  143817. static long _vq_quantmap__44u4__p7_1[] = {
  143818. 13, 11, 9, 7, 5, 3, 1, 0,
  143819. 2, 4, 6, 8, 10, 12, 14,
  143820. };
  143821. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  143822. _vq_quantthresh__44u4__p7_1,
  143823. _vq_quantmap__44u4__p7_1,
  143824. 15,
  143825. 15
  143826. };
  143827. static static_codebook _44u4__p7_1 = {
  143828. 2, 225,
  143829. _vq_lengthlist__44u4__p7_1,
  143830. 1, -522338304, 1620115456, 4, 0,
  143831. _vq_quantlist__44u4__p7_1,
  143832. NULL,
  143833. &_vq_auxt__44u4__p7_1,
  143834. NULL,
  143835. 0
  143836. };
  143837. static long _vq_quantlist__44u4__p7_2[] = {
  143838. 8,
  143839. 7,
  143840. 9,
  143841. 6,
  143842. 10,
  143843. 5,
  143844. 11,
  143845. 4,
  143846. 12,
  143847. 3,
  143848. 13,
  143849. 2,
  143850. 14,
  143851. 1,
  143852. 15,
  143853. 0,
  143854. 16,
  143855. };
  143856. static long _vq_lengthlist__44u4__p7_2[] = {
  143857. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143858. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143859. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143860. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143861. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143862. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143863. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143864. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143865. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  143866. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  143867. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143868. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  143869. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  143870. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  143871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  143872. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  143873. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143874. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  143875. 10,
  143876. };
  143877. static float _vq_quantthresh__44u4__p7_2[] = {
  143878. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143879. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143880. };
  143881. static long _vq_quantmap__44u4__p7_2[] = {
  143882. 15, 13, 11, 9, 7, 5, 3, 1,
  143883. 0, 2, 4, 6, 8, 10, 12, 14,
  143884. 16,
  143885. };
  143886. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  143887. _vq_quantthresh__44u4__p7_2,
  143888. _vq_quantmap__44u4__p7_2,
  143889. 17,
  143890. 17
  143891. };
  143892. static static_codebook _44u4__p7_2 = {
  143893. 2, 289,
  143894. _vq_lengthlist__44u4__p7_2,
  143895. 1, -529530880, 1611661312, 5, 0,
  143896. _vq_quantlist__44u4__p7_2,
  143897. NULL,
  143898. &_vq_auxt__44u4__p7_2,
  143899. NULL,
  143900. 0
  143901. };
  143902. static long _huff_lengthlist__44u4__short[] = {
  143903. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  143904. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  143905. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  143906. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  143907. };
  143908. static static_codebook _huff_book__44u4__short = {
  143909. 2, 64,
  143910. _huff_lengthlist__44u4__short,
  143911. 0, 0, 0, 0, 0,
  143912. NULL,
  143913. NULL,
  143914. NULL,
  143915. NULL,
  143916. 0
  143917. };
  143918. static long _huff_lengthlist__44u5__long[] = {
  143919. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  143920. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  143921. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  143922. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  143923. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  143924. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  143925. 14, 8, 7, 8,
  143926. };
  143927. static static_codebook _huff_book__44u5__long = {
  143928. 2, 100,
  143929. _huff_lengthlist__44u5__long,
  143930. 0, 0, 0, 0, 0,
  143931. NULL,
  143932. NULL,
  143933. NULL,
  143934. NULL,
  143935. 0
  143936. };
  143937. static long _vq_quantlist__44u5__p1_0[] = {
  143938. 1,
  143939. 0,
  143940. 2,
  143941. };
  143942. static long _vq_lengthlist__44u5__p1_0[] = {
  143943. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143944. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  143945. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  143946. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  143947. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  143948. 12,
  143949. };
  143950. static float _vq_quantthresh__44u5__p1_0[] = {
  143951. -0.5, 0.5,
  143952. };
  143953. static long _vq_quantmap__44u5__p1_0[] = {
  143954. 1, 0, 2,
  143955. };
  143956. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  143957. _vq_quantthresh__44u5__p1_0,
  143958. _vq_quantmap__44u5__p1_0,
  143959. 3,
  143960. 3
  143961. };
  143962. static static_codebook _44u5__p1_0 = {
  143963. 4, 81,
  143964. _vq_lengthlist__44u5__p1_0,
  143965. 1, -535822336, 1611661312, 2, 0,
  143966. _vq_quantlist__44u5__p1_0,
  143967. NULL,
  143968. &_vq_auxt__44u5__p1_0,
  143969. NULL,
  143970. 0
  143971. };
  143972. static long _vq_quantlist__44u5__p2_0[] = {
  143973. 1,
  143974. 0,
  143975. 2,
  143976. };
  143977. static long _vq_lengthlist__44u5__p2_0[] = {
  143978. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  143979. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  143980. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  143981. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  143982. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  143983. 9,
  143984. };
  143985. static float _vq_quantthresh__44u5__p2_0[] = {
  143986. -0.5, 0.5,
  143987. };
  143988. static long _vq_quantmap__44u5__p2_0[] = {
  143989. 1, 0, 2,
  143990. };
  143991. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  143992. _vq_quantthresh__44u5__p2_0,
  143993. _vq_quantmap__44u5__p2_0,
  143994. 3,
  143995. 3
  143996. };
  143997. static static_codebook _44u5__p2_0 = {
  143998. 4, 81,
  143999. _vq_lengthlist__44u5__p2_0,
  144000. 1, -535822336, 1611661312, 2, 0,
  144001. _vq_quantlist__44u5__p2_0,
  144002. NULL,
  144003. &_vq_auxt__44u5__p2_0,
  144004. NULL,
  144005. 0
  144006. };
  144007. static long _vq_quantlist__44u5__p3_0[] = {
  144008. 2,
  144009. 1,
  144010. 3,
  144011. 0,
  144012. 4,
  144013. };
  144014. static long _vq_lengthlist__44u5__p3_0[] = {
  144015. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144016. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144017. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144018. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  144019. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  144020. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  144021. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  144022. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  144023. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  144024. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  144025. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  144026. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  144027. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  144028. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  144029. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  144030. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  144031. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144032. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  144033. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  144034. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  144035. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  144036. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  144037. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  144038. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  144039. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  144040. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  144041. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  144042. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  144043. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  144044. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  144045. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  144046. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  144047. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  144048. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  144049. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  144050. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  144051. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  144052. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  144053. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  144054. 0,
  144055. };
  144056. static float _vq_quantthresh__44u5__p3_0[] = {
  144057. -1.5, -0.5, 0.5, 1.5,
  144058. };
  144059. static long _vq_quantmap__44u5__p3_0[] = {
  144060. 3, 1, 0, 2, 4,
  144061. };
  144062. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  144063. _vq_quantthresh__44u5__p3_0,
  144064. _vq_quantmap__44u5__p3_0,
  144065. 5,
  144066. 5
  144067. };
  144068. static static_codebook _44u5__p3_0 = {
  144069. 4, 625,
  144070. _vq_lengthlist__44u5__p3_0,
  144071. 1, -533725184, 1611661312, 3, 0,
  144072. _vq_quantlist__44u5__p3_0,
  144073. NULL,
  144074. &_vq_auxt__44u5__p3_0,
  144075. NULL,
  144076. 0
  144077. };
  144078. static long _vq_quantlist__44u5__p4_0[] = {
  144079. 2,
  144080. 1,
  144081. 3,
  144082. 0,
  144083. 4,
  144084. };
  144085. static long _vq_lengthlist__44u5__p4_0[] = {
  144086. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144087. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  144088. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  144089. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  144090. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  144091. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  144092. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144093. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  144094. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  144095. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  144096. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  144097. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144098. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144099. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  144100. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  144101. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  144102. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  144103. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144104. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  144105. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  144106. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  144107. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  144108. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  144109. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  144110. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  144111. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  144112. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  144113. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  144114. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  144115. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  144116. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  144117. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144118. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  144119. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  144120. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  144121. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  144122. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  144123. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  144124. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  144125. 12,
  144126. };
  144127. static float _vq_quantthresh__44u5__p4_0[] = {
  144128. -1.5, -0.5, 0.5, 1.5,
  144129. };
  144130. static long _vq_quantmap__44u5__p4_0[] = {
  144131. 3, 1, 0, 2, 4,
  144132. };
  144133. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  144134. _vq_quantthresh__44u5__p4_0,
  144135. _vq_quantmap__44u5__p4_0,
  144136. 5,
  144137. 5
  144138. };
  144139. static static_codebook _44u5__p4_0 = {
  144140. 4, 625,
  144141. _vq_lengthlist__44u5__p4_0,
  144142. 1, -533725184, 1611661312, 3, 0,
  144143. _vq_quantlist__44u5__p4_0,
  144144. NULL,
  144145. &_vq_auxt__44u5__p4_0,
  144146. NULL,
  144147. 0
  144148. };
  144149. static long _vq_quantlist__44u5__p5_0[] = {
  144150. 4,
  144151. 3,
  144152. 5,
  144153. 2,
  144154. 6,
  144155. 1,
  144156. 7,
  144157. 0,
  144158. 8,
  144159. };
  144160. static long _vq_lengthlist__44u5__p5_0[] = {
  144161. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144162. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  144163. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  144164. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  144165. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  144166. 14,
  144167. };
  144168. static float _vq_quantthresh__44u5__p5_0[] = {
  144169. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144170. };
  144171. static long _vq_quantmap__44u5__p5_0[] = {
  144172. 7, 5, 3, 1, 0, 2, 4, 6,
  144173. 8,
  144174. };
  144175. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  144176. _vq_quantthresh__44u5__p5_0,
  144177. _vq_quantmap__44u5__p5_0,
  144178. 9,
  144179. 9
  144180. };
  144181. static static_codebook _44u5__p5_0 = {
  144182. 2, 81,
  144183. _vq_lengthlist__44u5__p5_0,
  144184. 1, -531628032, 1611661312, 4, 0,
  144185. _vq_quantlist__44u5__p5_0,
  144186. NULL,
  144187. &_vq_auxt__44u5__p5_0,
  144188. NULL,
  144189. 0
  144190. };
  144191. static long _vq_quantlist__44u5__p6_0[] = {
  144192. 4,
  144193. 3,
  144194. 5,
  144195. 2,
  144196. 6,
  144197. 1,
  144198. 7,
  144199. 0,
  144200. 8,
  144201. };
  144202. static long _vq_lengthlist__44u5__p6_0[] = {
  144203. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144204. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144205. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  144206. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  144207. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  144208. 11,
  144209. };
  144210. static float _vq_quantthresh__44u5__p6_0[] = {
  144211. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144212. };
  144213. static long _vq_quantmap__44u5__p6_0[] = {
  144214. 7, 5, 3, 1, 0, 2, 4, 6,
  144215. 8,
  144216. };
  144217. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  144218. _vq_quantthresh__44u5__p6_0,
  144219. _vq_quantmap__44u5__p6_0,
  144220. 9,
  144221. 9
  144222. };
  144223. static static_codebook _44u5__p6_0 = {
  144224. 2, 81,
  144225. _vq_lengthlist__44u5__p6_0,
  144226. 1, -531628032, 1611661312, 4, 0,
  144227. _vq_quantlist__44u5__p6_0,
  144228. NULL,
  144229. &_vq_auxt__44u5__p6_0,
  144230. NULL,
  144231. 0
  144232. };
  144233. static long _vq_quantlist__44u5__p7_0[] = {
  144234. 1,
  144235. 0,
  144236. 2,
  144237. };
  144238. static long _vq_lengthlist__44u5__p7_0[] = {
  144239. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  144240. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  144241. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  144242. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  144243. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  144244. 12,
  144245. };
  144246. static float _vq_quantthresh__44u5__p7_0[] = {
  144247. -5.5, 5.5,
  144248. };
  144249. static long _vq_quantmap__44u5__p7_0[] = {
  144250. 1, 0, 2,
  144251. };
  144252. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  144253. _vq_quantthresh__44u5__p7_0,
  144254. _vq_quantmap__44u5__p7_0,
  144255. 3,
  144256. 3
  144257. };
  144258. static static_codebook _44u5__p7_0 = {
  144259. 4, 81,
  144260. _vq_lengthlist__44u5__p7_0,
  144261. 1, -529137664, 1618345984, 2, 0,
  144262. _vq_quantlist__44u5__p7_0,
  144263. NULL,
  144264. &_vq_auxt__44u5__p7_0,
  144265. NULL,
  144266. 0
  144267. };
  144268. static long _vq_quantlist__44u5__p7_1[] = {
  144269. 5,
  144270. 4,
  144271. 6,
  144272. 3,
  144273. 7,
  144274. 2,
  144275. 8,
  144276. 1,
  144277. 9,
  144278. 0,
  144279. 10,
  144280. };
  144281. static long _vq_lengthlist__44u5__p7_1[] = {
  144282. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  144283. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  144284. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144285. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  144286. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  144287. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144288. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  144289. 9, 9, 9, 9, 9,10,10,10,10,
  144290. };
  144291. static float _vq_quantthresh__44u5__p7_1[] = {
  144292. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144293. 3.5, 4.5,
  144294. };
  144295. static long _vq_quantmap__44u5__p7_1[] = {
  144296. 9, 7, 5, 3, 1, 0, 2, 4,
  144297. 6, 8, 10,
  144298. };
  144299. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  144300. _vq_quantthresh__44u5__p7_1,
  144301. _vq_quantmap__44u5__p7_1,
  144302. 11,
  144303. 11
  144304. };
  144305. static static_codebook _44u5__p7_1 = {
  144306. 2, 121,
  144307. _vq_lengthlist__44u5__p7_1,
  144308. 1, -531365888, 1611661312, 4, 0,
  144309. _vq_quantlist__44u5__p7_1,
  144310. NULL,
  144311. &_vq_auxt__44u5__p7_1,
  144312. NULL,
  144313. 0
  144314. };
  144315. static long _vq_quantlist__44u5__p8_0[] = {
  144316. 5,
  144317. 4,
  144318. 6,
  144319. 3,
  144320. 7,
  144321. 2,
  144322. 8,
  144323. 1,
  144324. 9,
  144325. 0,
  144326. 10,
  144327. };
  144328. static long _vq_lengthlist__44u5__p8_0[] = {
  144329. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144330. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144331. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  144332. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  144333. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  144334. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  144335. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  144336. 12,13,13,14,14,14,14,15,15,
  144337. };
  144338. static float _vq_quantthresh__44u5__p8_0[] = {
  144339. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144340. 38.5, 49.5,
  144341. };
  144342. static long _vq_quantmap__44u5__p8_0[] = {
  144343. 9, 7, 5, 3, 1, 0, 2, 4,
  144344. 6, 8, 10,
  144345. };
  144346. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  144347. _vq_quantthresh__44u5__p8_0,
  144348. _vq_quantmap__44u5__p8_0,
  144349. 11,
  144350. 11
  144351. };
  144352. static static_codebook _44u5__p8_0 = {
  144353. 2, 121,
  144354. _vq_lengthlist__44u5__p8_0,
  144355. 1, -524582912, 1618345984, 4, 0,
  144356. _vq_quantlist__44u5__p8_0,
  144357. NULL,
  144358. &_vq_auxt__44u5__p8_0,
  144359. NULL,
  144360. 0
  144361. };
  144362. static long _vq_quantlist__44u5__p8_1[] = {
  144363. 5,
  144364. 4,
  144365. 6,
  144366. 3,
  144367. 7,
  144368. 2,
  144369. 8,
  144370. 1,
  144371. 9,
  144372. 0,
  144373. 10,
  144374. };
  144375. static long _vq_lengthlist__44u5__p8_1[] = {
  144376. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  144377. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  144378. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  144379. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144380. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  144381. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144382. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144383. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144384. };
  144385. static float _vq_quantthresh__44u5__p8_1[] = {
  144386. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144387. 3.5, 4.5,
  144388. };
  144389. static long _vq_quantmap__44u5__p8_1[] = {
  144390. 9, 7, 5, 3, 1, 0, 2, 4,
  144391. 6, 8, 10,
  144392. };
  144393. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  144394. _vq_quantthresh__44u5__p8_1,
  144395. _vq_quantmap__44u5__p8_1,
  144396. 11,
  144397. 11
  144398. };
  144399. static static_codebook _44u5__p8_1 = {
  144400. 2, 121,
  144401. _vq_lengthlist__44u5__p8_1,
  144402. 1, -531365888, 1611661312, 4, 0,
  144403. _vq_quantlist__44u5__p8_1,
  144404. NULL,
  144405. &_vq_auxt__44u5__p8_1,
  144406. NULL,
  144407. 0
  144408. };
  144409. static long _vq_quantlist__44u5__p9_0[] = {
  144410. 6,
  144411. 5,
  144412. 7,
  144413. 4,
  144414. 8,
  144415. 3,
  144416. 9,
  144417. 2,
  144418. 10,
  144419. 1,
  144420. 11,
  144421. 0,
  144422. 12,
  144423. };
  144424. static long _vq_lengthlist__44u5__p9_0[] = {
  144425. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  144426. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  144427. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  144428. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  144429. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144430. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144431. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144432. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144433. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  144434. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144435. 12,12,12,12,12,12,12,12,12,
  144436. };
  144437. static float _vq_quantthresh__44u5__p9_0[] = {
  144438. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  144439. 637.5, 892.5, 1147.5, 1402.5,
  144440. };
  144441. static long _vq_quantmap__44u5__p9_0[] = {
  144442. 11, 9, 7, 5, 3, 1, 0, 2,
  144443. 4, 6, 8, 10, 12,
  144444. };
  144445. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  144446. _vq_quantthresh__44u5__p9_0,
  144447. _vq_quantmap__44u5__p9_0,
  144448. 13,
  144449. 13
  144450. };
  144451. static static_codebook _44u5__p9_0 = {
  144452. 2, 169,
  144453. _vq_lengthlist__44u5__p9_0,
  144454. 1, -514332672, 1627381760, 4, 0,
  144455. _vq_quantlist__44u5__p9_0,
  144456. NULL,
  144457. &_vq_auxt__44u5__p9_0,
  144458. NULL,
  144459. 0
  144460. };
  144461. static long _vq_quantlist__44u5__p9_1[] = {
  144462. 7,
  144463. 6,
  144464. 8,
  144465. 5,
  144466. 9,
  144467. 4,
  144468. 10,
  144469. 3,
  144470. 11,
  144471. 2,
  144472. 12,
  144473. 1,
  144474. 13,
  144475. 0,
  144476. 14,
  144477. };
  144478. static long _vq_lengthlist__44u5__p9_1[] = {
  144479. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  144480. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  144481. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  144482. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  144483. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  144484. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  144485. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  144486. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  144487. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  144488. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  144489. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  144490. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  144491. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  144492. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  144493. 14,
  144494. };
  144495. static float _vq_quantthresh__44u5__p9_1[] = {
  144496. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144497. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144498. };
  144499. static long _vq_quantmap__44u5__p9_1[] = {
  144500. 13, 11, 9, 7, 5, 3, 1, 0,
  144501. 2, 4, 6, 8, 10, 12, 14,
  144502. };
  144503. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  144504. _vq_quantthresh__44u5__p9_1,
  144505. _vq_quantmap__44u5__p9_1,
  144506. 15,
  144507. 15
  144508. };
  144509. static static_codebook _44u5__p9_1 = {
  144510. 2, 225,
  144511. _vq_lengthlist__44u5__p9_1,
  144512. 1, -522338304, 1620115456, 4, 0,
  144513. _vq_quantlist__44u5__p9_1,
  144514. NULL,
  144515. &_vq_auxt__44u5__p9_1,
  144516. NULL,
  144517. 0
  144518. };
  144519. static long _vq_quantlist__44u5__p9_2[] = {
  144520. 8,
  144521. 7,
  144522. 9,
  144523. 6,
  144524. 10,
  144525. 5,
  144526. 11,
  144527. 4,
  144528. 12,
  144529. 3,
  144530. 13,
  144531. 2,
  144532. 14,
  144533. 1,
  144534. 15,
  144535. 0,
  144536. 16,
  144537. };
  144538. static long _vq_lengthlist__44u5__p9_2[] = {
  144539. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144540. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144541. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  144542. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144543. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  144544. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  144545. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  144546. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144547. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144548. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  144549. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  144550. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  144551. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144552. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144553. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  144554. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144555. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144556. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  144557. 10,
  144558. };
  144559. static float _vq_quantthresh__44u5__p9_2[] = {
  144560. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144561. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144562. };
  144563. static long _vq_quantmap__44u5__p9_2[] = {
  144564. 15, 13, 11, 9, 7, 5, 3, 1,
  144565. 0, 2, 4, 6, 8, 10, 12, 14,
  144566. 16,
  144567. };
  144568. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  144569. _vq_quantthresh__44u5__p9_2,
  144570. _vq_quantmap__44u5__p9_2,
  144571. 17,
  144572. 17
  144573. };
  144574. static static_codebook _44u5__p9_2 = {
  144575. 2, 289,
  144576. _vq_lengthlist__44u5__p9_2,
  144577. 1, -529530880, 1611661312, 5, 0,
  144578. _vq_quantlist__44u5__p9_2,
  144579. NULL,
  144580. &_vq_auxt__44u5__p9_2,
  144581. NULL,
  144582. 0
  144583. };
  144584. static long _huff_lengthlist__44u5__short[] = {
  144585. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  144586. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  144587. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  144588. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  144589. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  144590. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  144591. 6, 8,15,17,
  144592. };
  144593. static static_codebook _huff_book__44u5__short = {
  144594. 2, 100,
  144595. _huff_lengthlist__44u5__short,
  144596. 0, 0, 0, 0, 0,
  144597. NULL,
  144598. NULL,
  144599. NULL,
  144600. NULL,
  144601. 0
  144602. };
  144603. static long _huff_lengthlist__44u6__long[] = {
  144604. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  144605. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  144606. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  144607. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  144608. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  144609. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  144610. 13, 8, 7, 7,
  144611. };
  144612. static static_codebook _huff_book__44u6__long = {
  144613. 2, 100,
  144614. _huff_lengthlist__44u6__long,
  144615. 0, 0, 0, 0, 0,
  144616. NULL,
  144617. NULL,
  144618. NULL,
  144619. NULL,
  144620. 0
  144621. };
  144622. static long _vq_quantlist__44u6__p1_0[] = {
  144623. 1,
  144624. 0,
  144625. 2,
  144626. };
  144627. static long _vq_lengthlist__44u6__p1_0[] = {
  144628. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144629. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  144630. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144631. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  144632. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  144633. 12,
  144634. };
  144635. static float _vq_quantthresh__44u6__p1_0[] = {
  144636. -0.5, 0.5,
  144637. };
  144638. static long _vq_quantmap__44u6__p1_0[] = {
  144639. 1, 0, 2,
  144640. };
  144641. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  144642. _vq_quantthresh__44u6__p1_0,
  144643. _vq_quantmap__44u6__p1_0,
  144644. 3,
  144645. 3
  144646. };
  144647. static static_codebook _44u6__p1_0 = {
  144648. 4, 81,
  144649. _vq_lengthlist__44u6__p1_0,
  144650. 1, -535822336, 1611661312, 2, 0,
  144651. _vq_quantlist__44u6__p1_0,
  144652. NULL,
  144653. &_vq_auxt__44u6__p1_0,
  144654. NULL,
  144655. 0
  144656. };
  144657. static long _vq_quantlist__44u6__p2_0[] = {
  144658. 1,
  144659. 0,
  144660. 2,
  144661. };
  144662. static long _vq_lengthlist__44u6__p2_0[] = {
  144663. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144664. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144665. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  144666. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144667. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144668. 9,
  144669. };
  144670. static float _vq_quantthresh__44u6__p2_0[] = {
  144671. -0.5, 0.5,
  144672. };
  144673. static long _vq_quantmap__44u6__p2_0[] = {
  144674. 1, 0, 2,
  144675. };
  144676. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  144677. _vq_quantthresh__44u6__p2_0,
  144678. _vq_quantmap__44u6__p2_0,
  144679. 3,
  144680. 3
  144681. };
  144682. static static_codebook _44u6__p2_0 = {
  144683. 4, 81,
  144684. _vq_lengthlist__44u6__p2_0,
  144685. 1, -535822336, 1611661312, 2, 0,
  144686. _vq_quantlist__44u6__p2_0,
  144687. NULL,
  144688. &_vq_auxt__44u6__p2_0,
  144689. NULL,
  144690. 0
  144691. };
  144692. static long _vq_quantlist__44u6__p3_0[] = {
  144693. 2,
  144694. 1,
  144695. 3,
  144696. 0,
  144697. 4,
  144698. };
  144699. static long _vq_lengthlist__44u6__p3_0[] = {
  144700. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144701. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  144702. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144703. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  144704. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  144705. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  144706. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  144707. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  144708. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  144709. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  144710. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  144711. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  144712. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  144713. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  144714. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  144715. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  144716. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144717. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  144718. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  144719. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  144720. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  144721. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  144722. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  144723. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  144724. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  144725. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  144726. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  144727. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  144728. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  144729. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  144730. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  144731. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  144732. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  144733. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  144734. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  144735. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  144736. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  144737. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  144738. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  144739. 19,
  144740. };
  144741. static float _vq_quantthresh__44u6__p3_0[] = {
  144742. -1.5, -0.5, 0.5, 1.5,
  144743. };
  144744. static long _vq_quantmap__44u6__p3_0[] = {
  144745. 3, 1, 0, 2, 4,
  144746. };
  144747. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  144748. _vq_quantthresh__44u6__p3_0,
  144749. _vq_quantmap__44u6__p3_0,
  144750. 5,
  144751. 5
  144752. };
  144753. static static_codebook _44u6__p3_0 = {
  144754. 4, 625,
  144755. _vq_lengthlist__44u6__p3_0,
  144756. 1, -533725184, 1611661312, 3, 0,
  144757. _vq_quantlist__44u6__p3_0,
  144758. NULL,
  144759. &_vq_auxt__44u6__p3_0,
  144760. NULL,
  144761. 0
  144762. };
  144763. static long _vq_quantlist__44u6__p4_0[] = {
  144764. 2,
  144765. 1,
  144766. 3,
  144767. 0,
  144768. 4,
  144769. };
  144770. static long _vq_lengthlist__44u6__p4_0[] = {
  144771. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144772. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  144773. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  144774. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  144775. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  144776. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  144777. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144778. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  144779. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  144780. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  144781. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  144782. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  144783. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144784. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  144785. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  144786. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  144787. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  144788. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144789. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  144790. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  144791. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  144792. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  144793. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  144794. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  144795. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  144796. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  144797. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  144798. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  144799. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  144800. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  144801. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  144802. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144803. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  144804. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  144805. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  144806. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  144807. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  144808. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  144809. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  144810. 13,
  144811. };
  144812. static float _vq_quantthresh__44u6__p4_0[] = {
  144813. -1.5, -0.5, 0.5, 1.5,
  144814. };
  144815. static long _vq_quantmap__44u6__p4_0[] = {
  144816. 3, 1, 0, 2, 4,
  144817. };
  144818. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  144819. _vq_quantthresh__44u6__p4_0,
  144820. _vq_quantmap__44u6__p4_0,
  144821. 5,
  144822. 5
  144823. };
  144824. static static_codebook _44u6__p4_0 = {
  144825. 4, 625,
  144826. _vq_lengthlist__44u6__p4_0,
  144827. 1, -533725184, 1611661312, 3, 0,
  144828. _vq_quantlist__44u6__p4_0,
  144829. NULL,
  144830. &_vq_auxt__44u6__p4_0,
  144831. NULL,
  144832. 0
  144833. };
  144834. static long _vq_quantlist__44u6__p5_0[] = {
  144835. 4,
  144836. 3,
  144837. 5,
  144838. 2,
  144839. 6,
  144840. 1,
  144841. 7,
  144842. 0,
  144843. 8,
  144844. };
  144845. static long _vq_lengthlist__44u6__p5_0[] = {
  144846. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144847. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  144848. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  144849. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  144850. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  144851. 14,
  144852. };
  144853. static float _vq_quantthresh__44u6__p5_0[] = {
  144854. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144855. };
  144856. static long _vq_quantmap__44u6__p5_0[] = {
  144857. 7, 5, 3, 1, 0, 2, 4, 6,
  144858. 8,
  144859. };
  144860. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  144861. _vq_quantthresh__44u6__p5_0,
  144862. _vq_quantmap__44u6__p5_0,
  144863. 9,
  144864. 9
  144865. };
  144866. static static_codebook _44u6__p5_0 = {
  144867. 2, 81,
  144868. _vq_lengthlist__44u6__p5_0,
  144869. 1, -531628032, 1611661312, 4, 0,
  144870. _vq_quantlist__44u6__p5_0,
  144871. NULL,
  144872. &_vq_auxt__44u6__p5_0,
  144873. NULL,
  144874. 0
  144875. };
  144876. static long _vq_quantlist__44u6__p6_0[] = {
  144877. 4,
  144878. 3,
  144879. 5,
  144880. 2,
  144881. 6,
  144882. 1,
  144883. 7,
  144884. 0,
  144885. 8,
  144886. };
  144887. static long _vq_lengthlist__44u6__p6_0[] = {
  144888. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144889. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  144890. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  144891. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  144892. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  144893. 12,
  144894. };
  144895. static float _vq_quantthresh__44u6__p6_0[] = {
  144896. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144897. };
  144898. static long _vq_quantmap__44u6__p6_0[] = {
  144899. 7, 5, 3, 1, 0, 2, 4, 6,
  144900. 8,
  144901. };
  144902. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  144903. _vq_quantthresh__44u6__p6_0,
  144904. _vq_quantmap__44u6__p6_0,
  144905. 9,
  144906. 9
  144907. };
  144908. static static_codebook _44u6__p6_0 = {
  144909. 2, 81,
  144910. _vq_lengthlist__44u6__p6_0,
  144911. 1, -531628032, 1611661312, 4, 0,
  144912. _vq_quantlist__44u6__p6_0,
  144913. NULL,
  144914. &_vq_auxt__44u6__p6_0,
  144915. NULL,
  144916. 0
  144917. };
  144918. static long _vq_quantlist__44u6__p7_0[] = {
  144919. 1,
  144920. 0,
  144921. 2,
  144922. };
  144923. static long _vq_lengthlist__44u6__p7_0[] = {
  144924. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  144925. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  144926. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  144927. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  144928. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  144929. 10,
  144930. };
  144931. static float _vq_quantthresh__44u6__p7_0[] = {
  144932. -5.5, 5.5,
  144933. };
  144934. static long _vq_quantmap__44u6__p7_0[] = {
  144935. 1, 0, 2,
  144936. };
  144937. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  144938. _vq_quantthresh__44u6__p7_0,
  144939. _vq_quantmap__44u6__p7_0,
  144940. 3,
  144941. 3
  144942. };
  144943. static static_codebook _44u6__p7_0 = {
  144944. 4, 81,
  144945. _vq_lengthlist__44u6__p7_0,
  144946. 1, -529137664, 1618345984, 2, 0,
  144947. _vq_quantlist__44u6__p7_0,
  144948. NULL,
  144949. &_vq_auxt__44u6__p7_0,
  144950. NULL,
  144951. 0
  144952. };
  144953. static long _vq_quantlist__44u6__p7_1[] = {
  144954. 5,
  144955. 4,
  144956. 6,
  144957. 3,
  144958. 7,
  144959. 2,
  144960. 8,
  144961. 1,
  144962. 9,
  144963. 0,
  144964. 10,
  144965. };
  144966. static long _vq_lengthlist__44u6__p7_1[] = {
  144967. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  144968. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  144969. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144970. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  144971. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144972. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144973. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144974. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144975. };
  144976. static float _vq_quantthresh__44u6__p7_1[] = {
  144977. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144978. 3.5, 4.5,
  144979. };
  144980. static long _vq_quantmap__44u6__p7_1[] = {
  144981. 9, 7, 5, 3, 1, 0, 2, 4,
  144982. 6, 8, 10,
  144983. };
  144984. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  144985. _vq_quantthresh__44u6__p7_1,
  144986. _vq_quantmap__44u6__p7_1,
  144987. 11,
  144988. 11
  144989. };
  144990. static static_codebook _44u6__p7_1 = {
  144991. 2, 121,
  144992. _vq_lengthlist__44u6__p7_1,
  144993. 1, -531365888, 1611661312, 4, 0,
  144994. _vq_quantlist__44u6__p7_1,
  144995. NULL,
  144996. &_vq_auxt__44u6__p7_1,
  144997. NULL,
  144998. 0
  144999. };
  145000. static long _vq_quantlist__44u6__p8_0[] = {
  145001. 5,
  145002. 4,
  145003. 6,
  145004. 3,
  145005. 7,
  145006. 2,
  145007. 8,
  145008. 1,
  145009. 9,
  145010. 0,
  145011. 10,
  145012. };
  145013. static long _vq_lengthlist__44u6__p8_0[] = {
  145014. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  145015. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  145016. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  145017. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  145018. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  145019. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  145020. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  145021. 12,13,13,14,14,14,15,15,15,
  145022. };
  145023. static float _vq_quantthresh__44u6__p8_0[] = {
  145024. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145025. 38.5, 49.5,
  145026. };
  145027. static long _vq_quantmap__44u6__p8_0[] = {
  145028. 9, 7, 5, 3, 1, 0, 2, 4,
  145029. 6, 8, 10,
  145030. };
  145031. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  145032. _vq_quantthresh__44u6__p8_0,
  145033. _vq_quantmap__44u6__p8_0,
  145034. 11,
  145035. 11
  145036. };
  145037. static static_codebook _44u6__p8_0 = {
  145038. 2, 121,
  145039. _vq_lengthlist__44u6__p8_0,
  145040. 1, -524582912, 1618345984, 4, 0,
  145041. _vq_quantlist__44u6__p8_0,
  145042. NULL,
  145043. &_vq_auxt__44u6__p8_0,
  145044. NULL,
  145045. 0
  145046. };
  145047. static long _vq_quantlist__44u6__p8_1[] = {
  145048. 5,
  145049. 4,
  145050. 6,
  145051. 3,
  145052. 7,
  145053. 2,
  145054. 8,
  145055. 1,
  145056. 9,
  145057. 0,
  145058. 10,
  145059. };
  145060. static long _vq_lengthlist__44u6__p8_1[] = {
  145061. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  145062. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  145063. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  145064. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145065. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  145066. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145067. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  145068. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145069. };
  145070. static float _vq_quantthresh__44u6__p8_1[] = {
  145071. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145072. 3.5, 4.5,
  145073. };
  145074. static long _vq_quantmap__44u6__p8_1[] = {
  145075. 9, 7, 5, 3, 1, 0, 2, 4,
  145076. 6, 8, 10,
  145077. };
  145078. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  145079. _vq_quantthresh__44u6__p8_1,
  145080. _vq_quantmap__44u6__p8_1,
  145081. 11,
  145082. 11
  145083. };
  145084. static static_codebook _44u6__p8_1 = {
  145085. 2, 121,
  145086. _vq_lengthlist__44u6__p8_1,
  145087. 1, -531365888, 1611661312, 4, 0,
  145088. _vq_quantlist__44u6__p8_1,
  145089. NULL,
  145090. &_vq_auxt__44u6__p8_1,
  145091. NULL,
  145092. 0
  145093. };
  145094. static long _vq_quantlist__44u6__p9_0[] = {
  145095. 7,
  145096. 6,
  145097. 8,
  145098. 5,
  145099. 9,
  145100. 4,
  145101. 10,
  145102. 3,
  145103. 11,
  145104. 2,
  145105. 12,
  145106. 1,
  145107. 13,
  145108. 0,
  145109. 14,
  145110. };
  145111. static long _vq_lengthlist__44u6__p9_0[] = {
  145112. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  145113. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  145114. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  145115. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  145116. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145117. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145118. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145119. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145120. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145121. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145122. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145123. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145124. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145125. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145126. 14,
  145127. };
  145128. static float _vq_quantthresh__44u6__p9_0[] = {
  145129. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145130. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145131. };
  145132. static long _vq_quantmap__44u6__p9_0[] = {
  145133. 13, 11, 9, 7, 5, 3, 1, 0,
  145134. 2, 4, 6, 8, 10, 12, 14,
  145135. };
  145136. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  145137. _vq_quantthresh__44u6__p9_0,
  145138. _vq_quantmap__44u6__p9_0,
  145139. 15,
  145140. 15
  145141. };
  145142. static static_codebook _44u6__p9_0 = {
  145143. 2, 225,
  145144. _vq_lengthlist__44u6__p9_0,
  145145. 1, -514071552, 1627381760, 4, 0,
  145146. _vq_quantlist__44u6__p9_0,
  145147. NULL,
  145148. &_vq_auxt__44u6__p9_0,
  145149. NULL,
  145150. 0
  145151. };
  145152. static long _vq_quantlist__44u6__p9_1[] = {
  145153. 7,
  145154. 6,
  145155. 8,
  145156. 5,
  145157. 9,
  145158. 4,
  145159. 10,
  145160. 3,
  145161. 11,
  145162. 2,
  145163. 12,
  145164. 1,
  145165. 13,
  145166. 0,
  145167. 14,
  145168. };
  145169. static long _vq_lengthlist__44u6__p9_1[] = {
  145170. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  145171. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  145172. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  145173. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  145174. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  145175. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  145176. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  145177. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  145178. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  145179. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  145180. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  145181. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  145182. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  145183. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  145184. 13,
  145185. };
  145186. static float _vq_quantthresh__44u6__p9_1[] = {
  145187. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145188. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145189. };
  145190. static long _vq_quantmap__44u6__p9_1[] = {
  145191. 13, 11, 9, 7, 5, 3, 1, 0,
  145192. 2, 4, 6, 8, 10, 12, 14,
  145193. };
  145194. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  145195. _vq_quantthresh__44u6__p9_1,
  145196. _vq_quantmap__44u6__p9_1,
  145197. 15,
  145198. 15
  145199. };
  145200. static static_codebook _44u6__p9_1 = {
  145201. 2, 225,
  145202. _vq_lengthlist__44u6__p9_1,
  145203. 1, -522338304, 1620115456, 4, 0,
  145204. _vq_quantlist__44u6__p9_1,
  145205. NULL,
  145206. &_vq_auxt__44u6__p9_1,
  145207. NULL,
  145208. 0
  145209. };
  145210. static long _vq_quantlist__44u6__p9_2[] = {
  145211. 8,
  145212. 7,
  145213. 9,
  145214. 6,
  145215. 10,
  145216. 5,
  145217. 11,
  145218. 4,
  145219. 12,
  145220. 3,
  145221. 13,
  145222. 2,
  145223. 14,
  145224. 1,
  145225. 15,
  145226. 0,
  145227. 16,
  145228. };
  145229. static long _vq_lengthlist__44u6__p9_2[] = {
  145230. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  145231. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145232. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  145233. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145234. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145235. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145236. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145237. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145238. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  145239. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  145240. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  145241. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145242. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  145243. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  145244. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  145245. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  145246. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  145247. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  145248. 10,
  145249. };
  145250. static float _vq_quantthresh__44u6__p9_2[] = {
  145251. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145252. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145253. };
  145254. static long _vq_quantmap__44u6__p9_2[] = {
  145255. 15, 13, 11, 9, 7, 5, 3, 1,
  145256. 0, 2, 4, 6, 8, 10, 12, 14,
  145257. 16,
  145258. };
  145259. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  145260. _vq_quantthresh__44u6__p9_2,
  145261. _vq_quantmap__44u6__p9_2,
  145262. 17,
  145263. 17
  145264. };
  145265. static static_codebook _44u6__p9_2 = {
  145266. 2, 289,
  145267. _vq_lengthlist__44u6__p9_2,
  145268. 1, -529530880, 1611661312, 5, 0,
  145269. _vq_quantlist__44u6__p9_2,
  145270. NULL,
  145271. &_vq_auxt__44u6__p9_2,
  145272. NULL,
  145273. 0
  145274. };
  145275. static long _huff_lengthlist__44u6__short[] = {
  145276. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  145277. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  145278. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  145279. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  145280. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  145281. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  145282. 7, 6, 9,16,
  145283. };
  145284. static static_codebook _huff_book__44u6__short = {
  145285. 2, 100,
  145286. _huff_lengthlist__44u6__short,
  145287. 0, 0, 0, 0, 0,
  145288. NULL,
  145289. NULL,
  145290. NULL,
  145291. NULL,
  145292. 0
  145293. };
  145294. static long _huff_lengthlist__44u7__long[] = {
  145295. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  145296. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  145297. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  145298. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  145299. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  145300. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  145301. 12, 8, 6, 7,
  145302. };
  145303. static static_codebook _huff_book__44u7__long = {
  145304. 2, 100,
  145305. _huff_lengthlist__44u7__long,
  145306. 0, 0, 0, 0, 0,
  145307. NULL,
  145308. NULL,
  145309. NULL,
  145310. NULL,
  145311. 0
  145312. };
  145313. static long _vq_quantlist__44u7__p1_0[] = {
  145314. 1,
  145315. 0,
  145316. 2,
  145317. };
  145318. static long _vq_lengthlist__44u7__p1_0[] = {
  145319. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145320. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  145321. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145322. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  145323. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  145324. 12,
  145325. };
  145326. static float _vq_quantthresh__44u7__p1_0[] = {
  145327. -0.5, 0.5,
  145328. };
  145329. static long _vq_quantmap__44u7__p1_0[] = {
  145330. 1, 0, 2,
  145331. };
  145332. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  145333. _vq_quantthresh__44u7__p1_0,
  145334. _vq_quantmap__44u7__p1_0,
  145335. 3,
  145336. 3
  145337. };
  145338. static static_codebook _44u7__p1_0 = {
  145339. 4, 81,
  145340. _vq_lengthlist__44u7__p1_0,
  145341. 1, -535822336, 1611661312, 2, 0,
  145342. _vq_quantlist__44u7__p1_0,
  145343. NULL,
  145344. &_vq_auxt__44u7__p1_0,
  145345. NULL,
  145346. 0
  145347. };
  145348. static long _vq_quantlist__44u7__p2_0[] = {
  145349. 1,
  145350. 0,
  145351. 2,
  145352. };
  145353. static long _vq_lengthlist__44u7__p2_0[] = {
  145354. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145355. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145356. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  145357. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145358. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145359. 9,
  145360. };
  145361. static float _vq_quantthresh__44u7__p2_0[] = {
  145362. -0.5, 0.5,
  145363. };
  145364. static long _vq_quantmap__44u7__p2_0[] = {
  145365. 1, 0, 2,
  145366. };
  145367. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  145368. _vq_quantthresh__44u7__p2_0,
  145369. _vq_quantmap__44u7__p2_0,
  145370. 3,
  145371. 3
  145372. };
  145373. static static_codebook _44u7__p2_0 = {
  145374. 4, 81,
  145375. _vq_lengthlist__44u7__p2_0,
  145376. 1, -535822336, 1611661312, 2, 0,
  145377. _vq_quantlist__44u7__p2_0,
  145378. NULL,
  145379. &_vq_auxt__44u7__p2_0,
  145380. NULL,
  145381. 0
  145382. };
  145383. static long _vq_quantlist__44u7__p3_0[] = {
  145384. 2,
  145385. 1,
  145386. 3,
  145387. 0,
  145388. 4,
  145389. };
  145390. static long _vq_lengthlist__44u7__p3_0[] = {
  145391. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145392. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  145393. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145394. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  145395. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  145396. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  145397. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  145398. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  145399. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  145400. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  145401. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  145402. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  145403. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  145404. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  145405. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  145406. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  145407. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  145408. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  145409. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  145410. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  145411. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  145412. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  145413. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  145414. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  145415. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  145416. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  145417. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  145418. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  145419. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  145420. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  145421. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  145422. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  145423. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  145424. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  145425. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  145426. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  145427. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  145428. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  145429. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  145430. 0,
  145431. };
  145432. static float _vq_quantthresh__44u7__p3_0[] = {
  145433. -1.5, -0.5, 0.5, 1.5,
  145434. };
  145435. static long _vq_quantmap__44u7__p3_0[] = {
  145436. 3, 1, 0, 2, 4,
  145437. };
  145438. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  145439. _vq_quantthresh__44u7__p3_0,
  145440. _vq_quantmap__44u7__p3_0,
  145441. 5,
  145442. 5
  145443. };
  145444. static static_codebook _44u7__p3_0 = {
  145445. 4, 625,
  145446. _vq_lengthlist__44u7__p3_0,
  145447. 1, -533725184, 1611661312, 3, 0,
  145448. _vq_quantlist__44u7__p3_0,
  145449. NULL,
  145450. &_vq_auxt__44u7__p3_0,
  145451. NULL,
  145452. 0
  145453. };
  145454. static long _vq_quantlist__44u7__p4_0[] = {
  145455. 2,
  145456. 1,
  145457. 3,
  145458. 0,
  145459. 4,
  145460. };
  145461. static long _vq_lengthlist__44u7__p4_0[] = {
  145462. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145463. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  145464. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  145465. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  145466. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  145467. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  145468. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  145469. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  145470. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  145471. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  145472. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  145473. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  145474. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145475. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  145476. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  145477. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  145478. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  145479. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145480. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  145481. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  145482. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  145483. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  145484. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  145485. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145486. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  145487. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  145488. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  145489. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  145490. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  145491. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  145492. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  145493. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145494. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  145495. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  145496. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  145497. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  145498. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  145499. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  145500. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  145501. 14,
  145502. };
  145503. static float _vq_quantthresh__44u7__p4_0[] = {
  145504. -1.5, -0.5, 0.5, 1.5,
  145505. };
  145506. static long _vq_quantmap__44u7__p4_0[] = {
  145507. 3, 1, 0, 2, 4,
  145508. };
  145509. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  145510. _vq_quantthresh__44u7__p4_0,
  145511. _vq_quantmap__44u7__p4_0,
  145512. 5,
  145513. 5
  145514. };
  145515. static static_codebook _44u7__p4_0 = {
  145516. 4, 625,
  145517. _vq_lengthlist__44u7__p4_0,
  145518. 1, -533725184, 1611661312, 3, 0,
  145519. _vq_quantlist__44u7__p4_0,
  145520. NULL,
  145521. &_vq_auxt__44u7__p4_0,
  145522. NULL,
  145523. 0
  145524. };
  145525. static long _vq_quantlist__44u7__p5_0[] = {
  145526. 4,
  145527. 3,
  145528. 5,
  145529. 2,
  145530. 6,
  145531. 1,
  145532. 7,
  145533. 0,
  145534. 8,
  145535. };
  145536. static long _vq_lengthlist__44u7__p5_0[] = {
  145537. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  145538. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  145539. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  145540. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  145541. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  145542. 14,
  145543. };
  145544. static float _vq_quantthresh__44u7__p5_0[] = {
  145545. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145546. };
  145547. static long _vq_quantmap__44u7__p5_0[] = {
  145548. 7, 5, 3, 1, 0, 2, 4, 6,
  145549. 8,
  145550. };
  145551. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  145552. _vq_quantthresh__44u7__p5_0,
  145553. _vq_quantmap__44u7__p5_0,
  145554. 9,
  145555. 9
  145556. };
  145557. static static_codebook _44u7__p5_0 = {
  145558. 2, 81,
  145559. _vq_lengthlist__44u7__p5_0,
  145560. 1, -531628032, 1611661312, 4, 0,
  145561. _vq_quantlist__44u7__p5_0,
  145562. NULL,
  145563. &_vq_auxt__44u7__p5_0,
  145564. NULL,
  145565. 0
  145566. };
  145567. static long _vq_quantlist__44u7__p6_0[] = {
  145568. 4,
  145569. 3,
  145570. 5,
  145571. 2,
  145572. 6,
  145573. 1,
  145574. 7,
  145575. 0,
  145576. 8,
  145577. };
  145578. static long _vq_lengthlist__44u7__p6_0[] = {
  145579. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  145580. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145581. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  145582. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  145583. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  145584. 12,
  145585. };
  145586. static float _vq_quantthresh__44u7__p6_0[] = {
  145587. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145588. };
  145589. static long _vq_quantmap__44u7__p6_0[] = {
  145590. 7, 5, 3, 1, 0, 2, 4, 6,
  145591. 8,
  145592. };
  145593. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  145594. _vq_quantthresh__44u7__p6_0,
  145595. _vq_quantmap__44u7__p6_0,
  145596. 9,
  145597. 9
  145598. };
  145599. static static_codebook _44u7__p6_0 = {
  145600. 2, 81,
  145601. _vq_lengthlist__44u7__p6_0,
  145602. 1, -531628032, 1611661312, 4, 0,
  145603. _vq_quantlist__44u7__p6_0,
  145604. NULL,
  145605. &_vq_auxt__44u7__p6_0,
  145606. NULL,
  145607. 0
  145608. };
  145609. static long _vq_quantlist__44u7__p7_0[] = {
  145610. 1,
  145611. 0,
  145612. 2,
  145613. };
  145614. static long _vq_lengthlist__44u7__p7_0[] = {
  145615. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  145616. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  145617. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  145618. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  145619. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  145620. 10,
  145621. };
  145622. static float _vq_quantthresh__44u7__p7_0[] = {
  145623. -5.5, 5.5,
  145624. };
  145625. static long _vq_quantmap__44u7__p7_0[] = {
  145626. 1, 0, 2,
  145627. };
  145628. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  145629. _vq_quantthresh__44u7__p7_0,
  145630. _vq_quantmap__44u7__p7_0,
  145631. 3,
  145632. 3
  145633. };
  145634. static static_codebook _44u7__p7_0 = {
  145635. 4, 81,
  145636. _vq_lengthlist__44u7__p7_0,
  145637. 1, -529137664, 1618345984, 2, 0,
  145638. _vq_quantlist__44u7__p7_0,
  145639. NULL,
  145640. &_vq_auxt__44u7__p7_0,
  145641. NULL,
  145642. 0
  145643. };
  145644. static long _vq_quantlist__44u7__p7_1[] = {
  145645. 5,
  145646. 4,
  145647. 6,
  145648. 3,
  145649. 7,
  145650. 2,
  145651. 8,
  145652. 1,
  145653. 9,
  145654. 0,
  145655. 10,
  145656. };
  145657. static long _vq_lengthlist__44u7__p7_1[] = {
  145658. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  145659. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  145660. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  145661. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  145662. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  145663. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  145664. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  145665. 8, 9, 9, 9, 9, 9,10,10,10,
  145666. };
  145667. static float _vq_quantthresh__44u7__p7_1[] = {
  145668. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145669. 3.5, 4.5,
  145670. };
  145671. static long _vq_quantmap__44u7__p7_1[] = {
  145672. 9, 7, 5, 3, 1, 0, 2, 4,
  145673. 6, 8, 10,
  145674. };
  145675. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  145676. _vq_quantthresh__44u7__p7_1,
  145677. _vq_quantmap__44u7__p7_1,
  145678. 11,
  145679. 11
  145680. };
  145681. static static_codebook _44u7__p7_1 = {
  145682. 2, 121,
  145683. _vq_lengthlist__44u7__p7_1,
  145684. 1, -531365888, 1611661312, 4, 0,
  145685. _vq_quantlist__44u7__p7_1,
  145686. NULL,
  145687. &_vq_auxt__44u7__p7_1,
  145688. NULL,
  145689. 0
  145690. };
  145691. static long _vq_quantlist__44u7__p8_0[] = {
  145692. 5,
  145693. 4,
  145694. 6,
  145695. 3,
  145696. 7,
  145697. 2,
  145698. 8,
  145699. 1,
  145700. 9,
  145701. 0,
  145702. 10,
  145703. };
  145704. static long _vq_lengthlist__44u7__p8_0[] = {
  145705. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145706. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  145707. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  145708. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  145709. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  145710. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  145711. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  145712. 12,13,13,14,14,15,15,15,16,
  145713. };
  145714. static float _vq_quantthresh__44u7__p8_0[] = {
  145715. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145716. 38.5, 49.5,
  145717. };
  145718. static long _vq_quantmap__44u7__p8_0[] = {
  145719. 9, 7, 5, 3, 1, 0, 2, 4,
  145720. 6, 8, 10,
  145721. };
  145722. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  145723. _vq_quantthresh__44u7__p8_0,
  145724. _vq_quantmap__44u7__p8_0,
  145725. 11,
  145726. 11
  145727. };
  145728. static static_codebook _44u7__p8_0 = {
  145729. 2, 121,
  145730. _vq_lengthlist__44u7__p8_0,
  145731. 1, -524582912, 1618345984, 4, 0,
  145732. _vq_quantlist__44u7__p8_0,
  145733. NULL,
  145734. &_vq_auxt__44u7__p8_0,
  145735. NULL,
  145736. 0
  145737. };
  145738. static long _vq_quantlist__44u7__p8_1[] = {
  145739. 5,
  145740. 4,
  145741. 6,
  145742. 3,
  145743. 7,
  145744. 2,
  145745. 8,
  145746. 1,
  145747. 9,
  145748. 0,
  145749. 10,
  145750. };
  145751. static long _vq_lengthlist__44u7__p8_1[] = {
  145752. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  145753. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  145754. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  145755. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  145756. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  145757. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  145758. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  145759. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  145760. };
  145761. static float _vq_quantthresh__44u7__p8_1[] = {
  145762. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145763. 3.5, 4.5,
  145764. };
  145765. static long _vq_quantmap__44u7__p8_1[] = {
  145766. 9, 7, 5, 3, 1, 0, 2, 4,
  145767. 6, 8, 10,
  145768. };
  145769. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  145770. _vq_quantthresh__44u7__p8_1,
  145771. _vq_quantmap__44u7__p8_1,
  145772. 11,
  145773. 11
  145774. };
  145775. static static_codebook _44u7__p8_1 = {
  145776. 2, 121,
  145777. _vq_lengthlist__44u7__p8_1,
  145778. 1, -531365888, 1611661312, 4, 0,
  145779. _vq_quantlist__44u7__p8_1,
  145780. NULL,
  145781. &_vq_auxt__44u7__p8_1,
  145782. NULL,
  145783. 0
  145784. };
  145785. static long _vq_quantlist__44u7__p9_0[] = {
  145786. 5,
  145787. 4,
  145788. 6,
  145789. 3,
  145790. 7,
  145791. 2,
  145792. 8,
  145793. 1,
  145794. 9,
  145795. 0,
  145796. 10,
  145797. };
  145798. static long _vq_lengthlist__44u7__p9_0[] = {
  145799. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  145800. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  145801. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145802. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145803. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145804. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145805. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145806. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145807. };
  145808. static float _vq_quantthresh__44u7__p9_0[] = {
  145809. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  145810. 2229.5, 2866.5,
  145811. };
  145812. static long _vq_quantmap__44u7__p9_0[] = {
  145813. 9, 7, 5, 3, 1, 0, 2, 4,
  145814. 6, 8, 10,
  145815. };
  145816. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  145817. _vq_quantthresh__44u7__p9_0,
  145818. _vq_quantmap__44u7__p9_0,
  145819. 11,
  145820. 11
  145821. };
  145822. static static_codebook _44u7__p9_0 = {
  145823. 2, 121,
  145824. _vq_lengthlist__44u7__p9_0,
  145825. 1, -512171520, 1630791680, 4, 0,
  145826. _vq_quantlist__44u7__p9_0,
  145827. NULL,
  145828. &_vq_auxt__44u7__p9_0,
  145829. NULL,
  145830. 0
  145831. };
  145832. static long _vq_quantlist__44u7__p9_1[] = {
  145833. 6,
  145834. 5,
  145835. 7,
  145836. 4,
  145837. 8,
  145838. 3,
  145839. 9,
  145840. 2,
  145841. 10,
  145842. 1,
  145843. 11,
  145844. 0,
  145845. 12,
  145846. };
  145847. static long _vq_lengthlist__44u7__p9_1[] = {
  145848. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  145849. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  145850. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  145851. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  145852. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  145853. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  145854. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  145855. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  145856. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  145857. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  145858. 15,15,15,15,17,17,16,17,16,
  145859. };
  145860. static float _vq_quantthresh__44u7__p9_1[] = {
  145861. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  145862. 122.5, 171.5, 220.5, 269.5,
  145863. };
  145864. static long _vq_quantmap__44u7__p9_1[] = {
  145865. 11, 9, 7, 5, 3, 1, 0, 2,
  145866. 4, 6, 8, 10, 12,
  145867. };
  145868. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  145869. _vq_quantthresh__44u7__p9_1,
  145870. _vq_quantmap__44u7__p9_1,
  145871. 13,
  145872. 13
  145873. };
  145874. static static_codebook _44u7__p9_1 = {
  145875. 2, 169,
  145876. _vq_lengthlist__44u7__p9_1,
  145877. 1, -518889472, 1622704128, 4, 0,
  145878. _vq_quantlist__44u7__p9_1,
  145879. NULL,
  145880. &_vq_auxt__44u7__p9_1,
  145881. NULL,
  145882. 0
  145883. };
  145884. static long _vq_quantlist__44u7__p9_2[] = {
  145885. 24,
  145886. 23,
  145887. 25,
  145888. 22,
  145889. 26,
  145890. 21,
  145891. 27,
  145892. 20,
  145893. 28,
  145894. 19,
  145895. 29,
  145896. 18,
  145897. 30,
  145898. 17,
  145899. 31,
  145900. 16,
  145901. 32,
  145902. 15,
  145903. 33,
  145904. 14,
  145905. 34,
  145906. 13,
  145907. 35,
  145908. 12,
  145909. 36,
  145910. 11,
  145911. 37,
  145912. 10,
  145913. 38,
  145914. 9,
  145915. 39,
  145916. 8,
  145917. 40,
  145918. 7,
  145919. 41,
  145920. 6,
  145921. 42,
  145922. 5,
  145923. 43,
  145924. 4,
  145925. 44,
  145926. 3,
  145927. 45,
  145928. 2,
  145929. 46,
  145930. 1,
  145931. 47,
  145932. 0,
  145933. 48,
  145934. };
  145935. static long _vq_lengthlist__44u7__p9_2[] = {
  145936. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  145937. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145938. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  145939. 8,
  145940. };
  145941. static float _vq_quantthresh__44u7__p9_2[] = {
  145942. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145943. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145944. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145945. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145946. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145947. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145948. };
  145949. static long _vq_quantmap__44u7__p9_2[] = {
  145950. 47, 45, 43, 41, 39, 37, 35, 33,
  145951. 31, 29, 27, 25, 23, 21, 19, 17,
  145952. 15, 13, 11, 9, 7, 5, 3, 1,
  145953. 0, 2, 4, 6, 8, 10, 12, 14,
  145954. 16, 18, 20, 22, 24, 26, 28, 30,
  145955. 32, 34, 36, 38, 40, 42, 44, 46,
  145956. 48,
  145957. };
  145958. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  145959. _vq_quantthresh__44u7__p9_2,
  145960. _vq_quantmap__44u7__p9_2,
  145961. 49,
  145962. 49
  145963. };
  145964. static static_codebook _44u7__p9_2 = {
  145965. 1, 49,
  145966. _vq_lengthlist__44u7__p9_2,
  145967. 1, -526909440, 1611661312, 6, 0,
  145968. _vq_quantlist__44u7__p9_2,
  145969. NULL,
  145970. &_vq_auxt__44u7__p9_2,
  145971. NULL,
  145972. 0
  145973. };
  145974. static long _huff_lengthlist__44u7__short[] = {
  145975. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  145976. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  145977. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  145978. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  145979. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  145980. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  145981. 6, 8, 5, 9,
  145982. };
  145983. static static_codebook _huff_book__44u7__short = {
  145984. 2, 100,
  145985. _huff_lengthlist__44u7__short,
  145986. 0, 0, 0, 0, 0,
  145987. NULL,
  145988. NULL,
  145989. NULL,
  145990. NULL,
  145991. 0
  145992. };
  145993. static long _huff_lengthlist__44u8__long[] = {
  145994. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  145995. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  145996. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  145997. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  145998. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  145999. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  146000. 10, 8, 8, 9,
  146001. };
  146002. static static_codebook _huff_book__44u8__long = {
  146003. 2, 100,
  146004. _huff_lengthlist__44u8__long,
  146005. 0, 0, 0, 0, 0,
  146006. NULL,
  146007. NULL,
  146008. NULL,
  146009. NULL,
  146010. 0
  146011. };
  146012. static long _huff_lengthlist__44u8__short[] = {
  146013. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  146014. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  146015. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  146016. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  146017. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  146018. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  146019. 10,10,15,17,
  146020. };
  146021. static static_codebook _huff_book__44u8__short = {
  146022. 2, 100,
  146023. _huff_lengthlist__44u8__short,
  146024. 0, 0, 0, 0, 0,
  146025. NULL,
  146026. NULL,
  146027. NULL,
  146028. NULL,
  146029. 0
  146030. };
  146031. static long _vq_quantlist__44u8_p1_0[] = {
  146032. 1,
  146033. 0,
  146034. 2,
  146035. };
  146036. static long _vq_lengthlist__44u8_p1_0[] = {
  146037. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  146038. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  146039. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  146040. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  146041. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  146042. 10,
  146043. };
  146044. static float _vq_quantthresh__44u8_p1_0[] = {
  146045. -0.5, 0.5,
  146046. };
  146047. static long _vq_quantmap__44u8_p1_0[] = {
  146048. 1, 0, 2,
  146049. };
  146050. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  146051. _vq_quantthresh__44u8_p1_0,
  146052. _vq_quantmap__44u8_p1_0,
  146053. 3,
  146054. 3
  146055. };
  146056. static static_codebook _44u8_p1_0 = {
  146057. 4, 81,
  146058. _vq_lengthlist__44u8_p1_0,
  146059. 1, -535822336, 1611661312, 2, 0,
  146060. _vq_quantlist__44u8_p1_0,
  146061. NULL,
  146062. &_vq_auxt__44u8_p1_0,
  146063. NULL,
  146064. 0
  146065. };
  146066. static long _vq_quantlist__44u8_p2_0[] = {
  146067. 2,
  146068. 1,
  146069. 3,
  146070. 0,
  146071. 4,
  146072. };
  146073. static long _vq_lengthlist__44u8_p2_0[] = {
  146074. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146075. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146076. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  146077. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  146078. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  146079. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  146080. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146081. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  146082. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146083. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  146084. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  146085. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146086. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  146087. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  146088. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  146089. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  146090. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  146091. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  146092. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  146093. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  146094. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  146095. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  146096. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  146097. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146098. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  146099. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146100. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  146101. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  146102. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  146103. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  146104. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  146105. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146106. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  146107. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  146108. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146109. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  146110. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  146111. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  146112. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  146113. 14,
  146114. };
  146115. static float _vq_quantthresh__44u8_p2_0[] = {
  146116. -1.5, -0.5, 0.5, 1.5,
  146117. };
  146118. static long _vq_quantmap__44u8_p2_0[] = {
  146119. 3, 1, 0, 2, 4,
  146120. };
  146121. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  146122. _vq_quantthresh__44u8_p2_0,
  146123. _vq_quantmap__44u8_p2_0,
  146124. 5,
  146125. 5
  146126. };
  146127. static static_codebook _44u8_p2_0 = {
  146128. 4, 625,
  146129. _vq_lengthlist__44u8_p2_0,
  146130. 1, -533725184, 1611661312, 3, 0,
  146131. _vq_quantlist__44u8_p2_0,
  146132. NULL,
  146133. &_vq_auxt__44u8_p2_0,
  146134. NULL,
  146135. 0
  146136. };
  146137. static long _vq_quantlist__44u8_p3_0[] = {
  146138. 4,
  146139. 3,
  146140. 5,
  146141. 2,
  146142. 6,
  146143. 1,
  146144. 7,
  146145. 0,
  146146. 8,
  146147. };
  146148. static long _vq_lengthlist__44u8_p3_0[] = {
  146149. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146150. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146151. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  146152. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  146153. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  146154. 12,
  146155. };
  146156. static float _vq_quantthresh__44u8_p3_0[] = {
  146157. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146158. };
  146159. static long _vq_quantmap__44u8_p3_0[] = {
  146160. 7, 5, 3, 1, 0, 2, 4, 6,
  146161. 8,
  146162. };
  146163. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  146164. _vq_quantthresh__44u8_p3_0,
  146165. _vq_quantmap__44u8_p3_0,
  146166. 9,
  146167. 9
  146168. };
  146169. static static_codebook _44u8_p3_0 = {
  146170. 2, 81,
  146171. _vq_lengthlist__44u8_p3_0,
  146172. 1, -531628032, 1611661312, 4, 0,
  146173. _vq_quantlist__44u8_p3_0,
  146174. NULL,
  146175. &_vq_auxt__44u8_p3_0,
  146176. NULL,
  146177. 0
  146178. };
  146179. static long _vq_quantlist__44u8_p4_0[] = {
  146180. 8,
  146181. 7,
  146182. 9,
  146183. 6,
  146184. 10,
  146185. 5,
  146186. 11,
  146187. 4,
  146188. 12,
  146189. 3,
  146190. 13,
  146191. 2,
  146192. 14,
  146193. 1,
  146194. 15,
  146195. 0,
  146196. 16,
  146197. };
  146198. static long _vq_lengthlist__44u8_p4_0[] = {
  146199. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  146200. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  146201. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  146202. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  146203. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  146204. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  146205. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  146206. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  146207. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  146208. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  146209. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  146210. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  146211. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  146212. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  146213. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  146214. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  146215. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  146216. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  146217. 14,
  146218. };
  146219. static float _vq_quantthresh__44u8_p4_0[] = {
  146220. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146221. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146222. };
  146223. static long _vq_quantmap__44u8_p4_0[] = {
  146224. 15, 13, 11, 9, 7, 5, 3, 1,
  146225. 0, 2, 4, 6, 8, 10, 12, 14,
  146226. 16,
  146227. };
  146228. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  146229. _vq_quantthresh__44u8_p4_0,
  146230. _vq_quantmap__44u8_p4_0,
  146231. 17,
  146232. 17
  146233. };
  146234. static static_codebook _44u8_p4_0 = {
  146235. 2, 289,
  146236. _vq_lengthlist__44u8_p4_0,
  146237. 1, -529530880, 1611661312, 5, 0,
  146238. _vq_quantlist__44u8_p4_0,
  146239. NULL,
  146240. &_vq_auxt__44u8_p4_0,
  146241. NULL,
  146242. 0
  146243. };
  146244. static long _vq_quantlist__44u8_p5_0[] = {
  146245. 1,
  146246. 0,
  146247. 2,
  146248. };
  146249. static long _vq_lengthlist__44u8_p5_0[] = {
  146250. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146251. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146252. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  146253. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146254. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146255. 10,
  146256. };
  146257. static float _vq_quantthresh__44u8_p5_0[] = {
  146258. -5.5, 5.5,
  146259. };
  146260. static long _vq_quantmap__44u8_p5_0[] = {
  146261. 1, 0, 2,
  146262. };
  146263. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  146264. _vq_quantthresh__44u8_p5_0,
  146265. _vq_quantmap__44u8_p5_0,
  146266. 3,
  146267. 3
  146268. };
  146269. static static_codebook _44u8_p5_0 = {
  146270. 4, 81,
  146271. _vq_lengthlist__44u8_p5_0,
  146272. 1, -529137664, 1618345984, 2, 0,
  146273. _vq_quantlist__44u8_p5_0,
  146274. NULL,
  146275. &_vq_auxt__44u8_p5_0,
  146276. NULL,
  146277. 0
  146278. };
  146279. static long _vq_quantlist__44u8_p5_1[] = {
  146280. 5,
  146281. 4,
  146282. 6,
  146283. 3,
  146284. 7,
  146285. 2,
  146286. 8,
  146287. 1,
  146288. 9,
  146289. 0,
  146290. 10,
  146291. };
  146292. static long _vq_lengthlist__44u8_p5_1[] = {
  146293. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  146294. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  146295. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  146296. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146297. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  146298. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146299. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  146300. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  146301. };
  146302. static float _vq_quantthresh__44u8_p5_1[] = {
  146303. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146304. 3.5, 4.5,
  146305. };
  146306. static long _vq_quantmap__44u8_p5_1[] = {
  146307. 9, 7, 5, 3, 1, 0, 2, 4,
  146308. 6, 8, 10,
  146309. };
  146310. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  146311. _vq_quantthresh__44u8_p5_1,
  146312. _vq_quantmap__44u8_p5_1,
  146313. 11,
  146314. 11
  146315. };
  146316. static static_codebook _44u8_p5_1 = {
  146317. 2, 121,
  146318. _vq_lengthlist__44u8_p5_1,
  146319. 1, -531365888, 1611661312, 4, 0,
  146320. _vq_quantlist__44u8_p5_1,
  146321. NULL,
  146322. &_vq_auxt__44u8_p5_1,
  146323. NULL,
  146324. 0
  146325. };
  146326. static long _vq_quantlist__44u8_p6_0[] = {
  146327. 6,
  146328. 5,
  146329. 7,
  146330. 4,
  146331. 8,
  146332. 3,
  146333. 9,
  146334. 2,
  146335. 10,
  146336. 1,
  146337. 11,
  146338. 0,
  146339. 12,
  146340. };
  146341. static long _vq_lengthlist__44u8_p6_0[] = {
  146342. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  146343. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  146344. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  146345. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  146346. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  146347. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  146348. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  146349. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  146350. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  146351. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  146352. 11,11,11,11,11,12,11,12,12,
  146353. };
  146354. static float _vq_quantthresh__44u8_p6_0[] = {
  146355. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146356. 12.5, 17.5, 22.5, 27.5,
  146357. };
  146358. static long _vq_quantmap__44u8_p6_0[] = {
  146359. 11, 9, 7, 5, 3, 1, 0, 2,
  146360. 4, 6, 8, 10, 12,
  146361. };
  146362. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  146363. _vq_quantthresh__44u8_p6_0,
  146364. _vq_quantmap__44u8_p6_0,
  146365. 13,
  146366. 13
  146367. };
  146368. static static_codebook _44u8_p6_0 = {
  146369. 2, 169,
  146370. _vq_lengthlist__44u8_p6_0,
  146371. 1, -526516224, 1616117760, 4, 0,
  146372. _vq_quantlist__44u8_p6_0,
  146373. NULL,
  146374. &_vq_auxt__44u8_p6_0,
  146375. NULL,
  146376. 0
  146377. };
  146378. static long _vq_quantlist__44u8_p6_1[] = {
  146379. 2,
  146380. 1,
  146381. 3,
  146382. 0,
  146383. 4,
  146384. };
  146385. static long _vq_lengthlist__44u8_p6_1[] = {
  146386. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146387. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  146388. };
  146389. static float _vq_quantthresh__44u8_p6_1[] = {
  146390. -1.5, -0.5, 0.5, 1.5,
  146391. };
  146392. static long _vq_quantmap__44u8_p6_1[] = {
  146393. 3, 1, 0, 2, 4,
  146394. };
  146395. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  146396. _vq_quantthresh__44u8_p6_1,
  146397. _vq_quantmap__44u8_p6_1,
  146398. 5,
  146399. 5
  146400. };
  146401. static static_codebook _44u8_p6_1 = {
  146402. 2, 25,
  146403. _vq_lengthlist__44u8_p6_1,
  146404. 1, -533725184, 1611661312, 3, 0,
  146405. _vq_quantlist__44u8_p6_1,
  146406. NULL,
  146407. &_vq_auxt__44u8_p6_1,
  146408. NULL,
  146409. 0
  146410. };
  146411. static long _vq_quantlist__44u8_p7_0[] = {
  146412. 6,
  146413. 5,
  146414. 7,
  146415. 4,
  146416. 8,
  146417. 3,
  146418. 9,
  146419. 2,
  146420. 10,
  146421. 1,
  146422. 11,
  146423. 0,
  146424. 12,
  146425. };
  146426. static long _vq_lengthlist__44u8_p7_0[] = {
  146427. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  146428. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  146429. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  146430. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  146431. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  146432. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  146433. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  146434. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  146435. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  146436. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  146437. 13,13,14,14,14,15,15,15,16,
  146438. };
  146439. static float _vq_quantthresh__44u8_p7_0[] = {
  146440. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  146441. 27.5, 38.5, 49.5, 60.5,
  146442. };
  146443. static long _vq_quantmap__44u8_p7_0[] = {
  146444. 11, 9, 7, 5, 3, 1, 0, 2,
  146445. 4, 6, 8, 10, 12,
  146446. };
  146447. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  146448. _vq_quantthresh__44u8_p7_0,
  146449. _vq_quantmap__44u8_p7_0,
  146450. 13,
  146451. 13
  146452. };
  146453. static static_codebook _44u8_p7_0 = {
  146454. 2, 169,
  146455. _vq_lengthlist__44u8_p7_0,
  146456. 1, -523206656, 1618345984, 4, 0,
  146457. _vq_quantlist__44u8_p7_0,
  146458. NULL,
  146459. &_vq_auxt__44u8_p7_0,
  146460. NULL,
  146461. 0
  146462. };
  146463. static long _vq_quantlist__44u8_p7_1[] = {
  146464. 5,
  146465. 4,
  146466. 6,
  146467. 3,
  146468. 7,
  146469. 2,
  146470. 8,
  146471. 1,
  146472. 9,
  146473. 0,
  146474. 10,
  146475. };
  146476. static long _vq_lengthlist__44u8_p7_1[] = {
  146477. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  146478. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  146479. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  146480. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  146481. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  146482. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  146483. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  146484. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  146485. };
  146486. static float _vq_quantthresh__44u8_p7_1[] = {
  146487. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146488. 3.5, 4.5,
  146489. };
  146490. static long _vq_quantmap__44u8_p7_1[] = {
  146491. 9, 7, 5, 3, 1, 0, 2, 4,
  146492. 6, 8, 10,
  146493. };
  146494. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  146495. _vq_quantthresh__44u8_p7_1,
  146496. _vq_quantmap__44u8_p7_1,
  146497. 11,
  146498. 11
  146499. };
  146500. static static_codebook _44u8_p7_1 = {
  146501. 2, 121,
  146502. _vq_lengthlist__44u8_p7_1,
  146503. 1, -531365888, 1611661312, 4, 0,
  146504. _vq_quantlist__44u8_p7_1,
  146505. NULL,
  146506. &_vq_auxt__44u8_p7_1,
  146507. NULL,
  146508. 0
  146509. };
  146510. static long _vq_quantlist__44u8_p8_0[] = {
  146511. 7,
  146512. 6,
  146513. 8,
  146514. 5,
  146515. 9,
  146516. 4,
  146517. 10,
  146518. 3,
  146519. 11,
  146520. 2,
  146521. 12,
  146522. 1,
  146523. 13,
  146524. 0,
  146525. 14,
  146526. };
  146527. static long _vq_lengthlist__44u8_p8_0[] = {
  146528. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  146529. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  146530. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  146531. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  146532. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  146533. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  146534. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  146535. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  146536. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  146537. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  146538. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  146539. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  146540. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  146541. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  146542. 17,
  146543. };
  146544. static float _vq_quantthresh__44u8_p8_0[] = {
  146545. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  146546. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  146547. };
  146548. static long _vq_quantmap__44u8_p8_0[] = {
  146549. 13, 11, 9, 7, 5, 3, 1, 0,
  146550. 2, 4, 6, 8, 10, 12, 14,
  146551. };
  146552. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  146553. _vq_quantthresh__44u8_p8_0,
  146554. _vq_quantmap__44u8_p8_0,
  146555. 15,
  146556. 15
  146557. };
  146558. static static_codebook _44u8_p8_0 = {
  146559. 2, 225,
  146560. _vq_lengthlist__44u8_p8_0,
  146561. 1, -520986624, 1620377600, 4, 0,
  146562. _vq_quantlist__44u8_p8_0,
  146563. NULL,
  146564. &_vq_auxt__44u8_p8_0,
  146565. NULL,
  146566. 0
  146567. };
  146568. static long _vq_quantlist__44u8_p8_1[] = {
  146569. 10,
  146570. 9,
  146571. 11,
  146572. 8,
  146573. 12,
  146574. 7,
  146575. 13,
  146576. 6,
  146577. 14,
  146578. 5,
  146579. 15,
  146580. 4,
  146581. 16,
  146582. 3,
  146583. 17,
  146584. 2,
  146585. 18,
  146586. 1,
  146587. 19,
  146588. 0,
  146589. 20,
  146590. };
  146591. static long _vq_lengthlist__44u8_p8_1[] = {
  146592. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146593. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  146594. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  146595. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  146596. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146597. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146598. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  146599. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  146600. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  146601. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  146602. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  146603. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  146604. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146605. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  146606. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  146607. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146608. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  146609. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  146610. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  146611. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  146612. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146613. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  146614. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146615. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146616. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146617. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  146618. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  146619. 10,10,10,10,10,10,10,10,10,
  146620. };
  146621. static float _vq_quantthresh__44u8_p8_1[] = {
  146622. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  146623. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  146624. 6.5, 7.5, 8.5, 9.5,
  146625. };
  146626. static long _vq_quantmap__44u8_p8_1[] = {
  146627. 19, 17, 15, 13, 11, 9, 7, 5,
  146628. 3, 1, 0, 2, 4, 6, 8, 10,
  146629. 12, 14, 16, 18, 20,
  146630. };
  146631. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  146632. _vq_quantthresh__44u8_p8_1,
  146633. _vq_quantmap__44u8_p8_1,
  146634. 21,
  146635. 21
  146636. };
  146637. static static_codebook _44u8_p8_1 = {
  146638. 2, 441,
  146639. _vq_lengthlist__44u8_p8_1,
  146640. 1, -529268736, 1611661312, 5, 0,
  146641. _vq_quantlist__44u8_p8_1,
  146642. NULL,
  146643. &_vq_auxt__44u8_p8_1,
  146644. NULL,
  146645. 0
  146646. };
  146647. static long _vq_quantlist__44u8_p9_0[] = {
  146648. 4,
  146649. 3,
  146650. 5,
  146651. 2,
  146652. 6,
  146653. 1,
  146654. 7,
  146655. 0,
  146656. 8,
  146657. };
  146658. static long _vq_lengthlist__44u8_p9_0[] = {
  146659. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  146660. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146661. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146662. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146663. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  146664. 8,
  146665. };
  146666. static float _vq_quantthresh__44u8_p9_0[] = {
  146667. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  146668. };
  146669. static long _vq_quantmap__44u8_p9_0[] = {
  146670. 7, 5, 3, 1, 0, 2, 4, 6,
  146671. 8,
  146672. };
  146673. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  146674. _vq_quantthresh__44u8_p9_0,
  146675. _vq_quantmap__44u8_p9_0,
  146676. 9,
  146677. 9
  146678. };
  146679. static static_codebook _44u8_p9_0 = {
  146680. 2, 81,
  146681. _vq_lengthlist__44u8_p9_0,
  146682. 1, -511895552, 1631393792, 4, 0,
  146683. _vq_quantlist__44u8_p9_0,
  146684. NULL,
  146685. &_vq_auxt__44u8_p9_0,
  146686. NULL,
  146687. 0
  146688. };
  146689. static long _vq_quantlist__44u8_p9_1[] = {
  146690. 9,
  146691. 8,
  146692. 10,
  146693. 7,
  146694. 11,
  146695. 6,
  146696. 12,
  146697. 5,
  146698. 13,
  146699. 4,
  146700. 14,
  146701. 3,
  146702. 15,
  146703. 2,
  146704. 16,
  146705. 1,
  146706. 17,
  146707. 0,
  146708. 18,
  146709. };
  146710. static long _vq_lengthlist__44u8_p9_1[] = {
  146711. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  146712. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  146713. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  146714. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  146715. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  146716. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  146717. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  146718. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  146719. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  146720. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  146721. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  146722. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  146723. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  146724. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  146725. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  146726. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  146727. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  146728. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  146729. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  146730. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  146731. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  146732. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  146733. 16,15,16,16,16,16,16,16,16,
  146734. };
  146735. static float _vq_quantthresh__44u8_p9_1[] = {
  146736. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  146737. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  146738. 367.5, 416.5,
  146739. };
  146740. static long _vq_quantmap__44u8_p9_1[] = {
  146741. 17, 15, 13, 11, 9, 7, 5, 3,
  146742. 1, 0, 2, 4, 6, 8, 10, 12,
  146743. 14, 16, 18,
  146744. };
  146745. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  146746. _vq_quantthresh__44u8_p9_1,
  146747. _vq_quantmap__44u8_p9_1,
  146748. 19,
  146749. 19
  146750. };
  146751. static static_codebook _44u8_p9_1 = {
  146752. 2, 361,
  146753. _vq_lengthlist__44u8_p9_1,
  146754. 1, -518287360, 1622704128, 5, 0,
  146755. _vq_quantlist__44u8_p9_1,
  146756. NULL,
  146757. &_vq_auxt__44u8_p9_1,
  146758. NULL,
  146759. 0
  146760. };
  146761. static long _vq_quantlist__44u8_p9_2[] = {
  146762. 24,
  146763. 23,
  146764. 25,
  146765. 22,
  146766. 26,
  146767. 21,
  146768. 27,
  146769. 20,
  146770. 28,
  146771. 19,
  146772. 29,
  146773. 18,
  146774. 30,
  146775. 17,
  146776. 31,
  146777. 16,
  146778. 32,
  146779. 15,
  146780. 33,
  146781. 14,
  146782. 34,
  146783. 13,
  146784. 35,
  146785. 12,
  146786. 36,
  146787. 11,
  146788. 37,
  146789. 10,
  146790. 38,
  146791. 9,
  146792. 39,
  146793. 8,
  146794. 40,
  146795. 7,
  146796. 41,
  146797. 6,
  146798. 42,
  146799. 5,
  146800. 43,
  146801. 4,
  146802. 44,
  146803. 3,
  146804. 45,
  146805. 2,
  146806. 46,
  146807. 1,
  146808. 47,
  146809. 0,
  146810. 48,
  146811. };
  146812. static long _vq_lengthlist__44u8_p9_2[] = {
  146813. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  146814. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146815. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146816. 7,
  146817. };
  146818. static float _vq_quantthresh__44u8_p9_2[] = {
  146819. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146820. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146821. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146822. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146823. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146824. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146825. };
  146826. static long _vq_quantmap__44u8_p9_2[] = {
  146827. 47, 45, 43, 41, 39, 37, 35, 33,
  146828. 31, 29, 27, 25, 23, 21, 19, 17,
  146829. 15, 13, 11, 9, 7, 5, 3, 1,
  146830. 0, 2, 4, 6, 8, 10, 12, 14,
  146831. 16, 18, 20, 22, 24, 26, 28, 30,
  146832. 32, 34, 36, 38, 40, 42, 44, 46,
  146833. 48,
  146834. };
  146835. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  146836. _vq_quantthresh__44u8_p9_2,
  146837. _vq_quantmap__44u8_p9_2,
  146838. 49,
  146839. 49
  146840. };
  146841. static static_codebook _44u8_p9_2 = {
  146842. 1, 49,
  146843. _vq_lengthlist__44u8_p9_2,
  146844. 1, -526909440, 1611661312, 6, 0,
  146845. _vq_quantlist__44u8_p9_2,
  146846. NULL,
  146847. &_vq_auxt__44u8_p9_2,
  146848. NULL,
  146849. 0
  146850. };
  146851. static long _huff_lengthlist__44u9__long[] = {
  146852. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  146853. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  146854. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  146855. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  146856. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  146857. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  146858. 10, 8, 8, 9,
  146859. };
  146860. static static_codebook _huff_book__44u9__long = {
  146861. 2, 100,
  146862. _huff_lengthlist__44u9__long,
  146863. 0, 0, 0, 0, 0,
  146864. NULL,
  146865. NULL,
  146866. NULL,
  146867. NULL,
  146868. 0
  146869. };
  146870. static long _huff_lengthlist__44u9__short[] = {
  146871. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  146872. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  146873. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  146874. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  146875. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  146876. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  146877. 9, 9,12,15,
  146878. };
  146879. static static_codebook _huff_book__44u9__short = {
  146880. 2, 100,
  146881. _huff_lengthlist__44u9__short,
  146882. 0, 0, 0, 0, 0,
  146883. NULL,
  146884. NULL,
  146885. NULL,
  146886. NULL,
  146887. 0
  146888. };
  146889. static long _vq_quantlist__44u9_p1_0[] = {
  146890. 1,
  146891. 0,
  146892. 2,
  146893. };
  146894. static long _vq_lengthlist__44u9_p1_0[] = {
  146895. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  146896. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  146897. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  146898. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  146899. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  146900. 10,
  146901. };
  146902. static float _vq_quantthresh__44u9_p1_0[] = {
  146903. -0.5, 0.5,
  146904. };
  146905. static long _vq_quantmap__44u9_p1_0[] = {
  146906. 1, 0, 2,
  146907. };
  146908. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  146909. _vq_quantthresh__44u9_p1_0,
  146910. _vq_quantmap__44u9_p1_0,
  146911. 3,
  146912. 3
  146913. };
  146914. static static_codebook _44u9_p1_0 = {
  146915. 4, 81,
  146916. _vq_lengthlist__44u9_p1_0,
  146917. 1, -535822336, 1611661312, 2, 0,
  146918. _vq_quantlist__44u9_p1_0,
  146919. NULL,
  146920. &_vq_auxt__44u9_p1_0,
  146921. NULL,
  146922. 0
  146923. };
  146924. static long _vq_quantlist__44u9_p2_0[] = {
  146925. 2,
  146926. 1,
  146927. 3,
  146928. 0,
  146929. 4,
  146930. };
  146931. static long _vq_lengthlist__44u9_p2_0[] = {
  146932. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  146933. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146934. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  146935. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  146936. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  146937. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  146938. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  146939. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  146940. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146941. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  146942. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  146943. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  146944. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  146945. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  146946. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  146947. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  146948. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  146949. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  146950. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  146951. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  146952. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  146953. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  146954. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  146955. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  146956. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  146957. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  146958. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  146959. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  146960. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  146961. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  146962. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  146963. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  146964. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  146965. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  146966. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  146967. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  146968. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  146969. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  146970. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  146971. 14,
  146972. };
  146973. static float _vq_quantthresh__44u9_p2_0[] = {
  146974. -1.5, -0.5, 0.5, 1.5,
  146975. };
  146976. static long _vq_quantmap__44u9_p2_0[] = {
  146977. 3, 1, 0, 2, 4,
  146978. };
  146979. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  146980. _vq_quantthresh__44u9_p2_0,
  146981. _vq_quantmap__44u9_p2_0,
  146982. 5,
  146983. 5
  146984. };
  146985. static static_codebook _44u9_p2_0 = {
  146986. 4, 625,
  146987. _vq_lengthlist__44u9_p2_0,
  146988. 1, -533725184, 1611661312, 3, 0,
  146989. _vq_quantlist__44u9_p2_0,
  146990. NULL,
  146991. &_vq_auxt__44u9_p2_0,
  146992. NULL,
  146993. 0
  146994. };
  146995. static long _vq_quantlist__44u9_p3_0[] = {
  146996. 4,
  146997. 3,
  146998. 5,
  146999. 2,
  147000. 6,
  147001. 1,
  147002. 7,
  147003. 0,
  147004. 8,
  147005. };
  147006. static long _vq_lengthlist__44u9_p3_0[] = {
  147007. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  147008. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147009. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  147010. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  147011. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  147012. 11,
  147013. };
  147014. static float _vq_quantthresh__44u9_p3_0[] = {
  147015. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147016. };
  147017. static long _vq_quantmap__44u9_p3_0[] = {
  147018. 7, 5, 3, 1, 0, 2, 4, 6,
  147019. 8,
  147020. };
  147021. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  147022. _vq_quantthresh__44u9_p3_0,
  147023. _vq_quantmap__44u9_p3_0,
  147024. 9,
  147025. 9
  147026. };
  147027. static static_codebook _44u9_p3_0 = {
  147028. 2, 81,
  147029. _vq_lengthlist__44u9_p3_0,
  147030. 1, -531628032, 1611661312, 4, 0,
  147031. _vq_quantlist__44u9_p3_0,
  147032. NULL,
  147033. &_vq_auxt__44u9_p3_0,
  147034. NULL,
  147035. 0
  147036. };
  147037. static long _vq_quantlist__44u9_p4_0[] = {
  147038. 8,
  147039. 7,
  147040. 9,
  147041. 6,
  147042. 10,
  147043. 5,
  147044. 11,
  147045. 4,
  147046. 12,
  147047. 3,
  147048. 13,
  147049. 2,
  147050. 14,
  147051. 1,
  147052. 15,
  147053. 0,
  147054. 16,
  147055. };
  147056. static long _vq_lengthlist__44u9_p4_0[] = {
  147057. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  147058. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  147059. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  147060. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  147061. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  147062. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  147063. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  147064. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  147065. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  147066. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  147067. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  147068. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  147069. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  147070. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  147071. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  147072. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  147073. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  147074. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  147075. 14,
  147076. };
  147077. static float _vq_quantthresh__44u9_p4_0[] = {
  147078. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147079. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147080. };
  147081. static long _vq_quantmap__44u9_p4_0[] = {
  147082. 15, 13, 11, 9, 7, 5, 3, 1,
  147083. 0, 2, 4, 6, 8, 10, 12, 14,
  147084. 16,
  147085. };
  147086. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  147087. _vq_quantthresh__44u9_p4_0,
  147088. _vq_quantmap__44u9_p4_0,
  147089. 17,
  147090. 17
  147091. };
  147092. static static_codebook _44u9_p4_0 = {
  147093. 2, 289,
  147094. _vq_lengthlist__44u9_p4_0,
  147095. 1, -529530880, 1611661312, 5, 0,
  147096. _vq_quantlist__44u9_p4_0,
  147097. NULL,
  147098. &_vq_auxt__44u9_p4_0,
  147099. NULL,
  147100. 0
  147101. };
  147102. static long _vq_quantlist__44u9_p5_0[] = {
  147103. 1,
  147104. 0,
  147105. 2,
  147106. };
  147107. static long _vq_lengthlist__44u9_p5_0[] = {
  147108. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  147109. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  147110. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  147111. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  147112. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  147113. 10,
  147114. };
  147115. static float _vq_quantthresh__44u9_p5_0[] = {
  147116. -5.5, 5.5,
  147117. };
  147118. static long _vq_quantmap__44u9_p5_0[] = {
  147119. 1, 0, 2,
  147120. };
  147121. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  147122. _vq_quantthresh__44u9_p5_0,
  147123. _vq_quantmap__44u9_p5_0,
  147124. 3,
  147125. 3
  147126. };
  147127. static static_codebook _44u9_p5_0 = {
  147128. 4, 81,
  147129. _vq_lengthlist__44u9_p5_0,
  147130. 1, -529137664, 1618345984, 2, 0,
  147131. _vq_quantlist__44u9_p5_0,
  147132. NULL,
  147133. &_vq_auxt__44u9_p5_0,
  147134. NULL,
  147135. 0
  147136. };
  147137. static long _vq_quantlist__44u9_p5_1[] = {
  147138. 5,
  147139. 4,
  147140. 6,
  147141. 3,
  147142. 7,
  147143. 2,
  147144. 8,
  147145. 1,
  147146. 9,
  147147. 0,
  147148. 10,
  147149. };
  147150. static long _vq_lengthlist__44u9_p5_1[] = {
  147151. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  147152. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  147153. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  147154. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147155. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147156. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  147157. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  147158. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147159. };
  147160. static float _vq_quantthresh__44u9_p5_1[] = {
  147161. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147162. 3.5, 4.5,
  147163. };
  147164. static long _vq_quantmap__44u9_p5_1[] = {
  147165. 9, 7, 5, 3, 1, 0, 2, 4,
  147166. 6, 8, 10,
  147167. };
  147168. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  147169. _vq_quantthresh__44u9_p5_1,
  147170. _vq_quantmap__44u9_p5_1,
  147171. 11,
  147172. 11
  147173. };
  147174. static static_codebook _44u9_p5_1 = {
  147175. 2, 121,
  147176. _vq_lengthlist__44u9_p5_1,
  147177. 1, -531365888, 1611661312, 4, 0,
  147178. _vq_quantlist__44u9_p5_1,
  147179. NULL,
  147180. &_vq_auxt__44u9_p5_1,
  147181. NULL,
  147182. 0
  147183. };
  147184. static long _vq_quantlist__44u9_p6_0[] = {
  147185. 6,
  147186. 5,
  147187. 7,
  147188. 4,
  147189. 8,
  147190. 3,
  147191. 9,
  147192. 2,
  147193. 10,
  147194. 1,
  147195. 11,
  147196. 0,
  147197. 12,
  147198. };
  147199. static long _vq_lengthlist__44u9_p6_0[] = {
  147200. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147201. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  147202. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147203. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  147204. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  147205. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147206. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147207. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  147208. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  147209. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147210. 10,11,11,11,11,12,11,12,12,
  147211. };
  147212. static float _vq_quantthresh__44u9_p6_0[] = {
  147213. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147214. 12.5, 17.5, 22.5, 27.5,
  147215. };
  147216. static long _vq_quantmap__44u9_p6_0[] = {
  147217. 11, 9, 7, 5, 3, 1, 0, 2,
  147218. 4, 6, 8, 10, 12,
  147219. };
  147220. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  147221. _vq_quantthresh__44u9_p6_0,
  147222. _vq_quantmap__44u9_p6_0,
  147223. 13,
  147224. 13
  147225. };
  147226. static static_codebook _44u9_p6_0 = {
  147227. 2, 169,
  147228. _vq_lengthlist__44u9_p6_0,
  147229. 1, -526516224, 1616117760, 4, 0,
  147230. _vq_quantlist__44u9_p6_0,
  147231. NULL,
  147232. &_vq_auxt__44u9_p6_0,
  147233. NULL,
  147234. 0
  147235. };
  147236. static long _vq_quantlist__44u9_p6_1[] = {
  147237. 2,
  147238. 1,
  147239. 3,
  147240. 0,
  147241. 4,
  147242. };
  147243. static long _vq_lengthlist__44u9_p6_1[] = {
  147244. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  147245. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147246. };
  147247. static float _vq_quantthresh__44u9_p6_1[] = {
  147248. -1.5, -0.5, 0.5, 1.5,
  147249. };
  147250. static long _vq_quantmap__44u9_p6_1[] = {
  147251. 3, 1, 0, 2, 4,
  147252. };
  147253. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  147254. _vq_quantthresh__44u9_p6_1,
  147255. _vq_quantmap__44u9_p6_1,
  147256. 5,
  147257. 5
  147258. };
  147259. static static_codebook _44u9_p6_1 = {
  147260. 2, 25,
  147261. _vq_lengthlist__44u9_p6_1,
  147262. 1, -533725184, 1611661312, 3, 0,
  147263. _vq_quantlist__44u9_p6_1,
  147264. NULL,
  147265. &_vq_auxt__44u9_p6_1,
  147266. NULL,
  147267. 0
  147268. };
  147269. static long _vq_quantlist__44u9_p7_0[] = {
  147270. 6,
  147271. 5,
  147272. 7,
  147273. 4,
  147274. 8,
  147275. 3,
  147276. 9,
  147277. 2,
  147278. 10,
  147279. 1,
  147280. 11,
  147281. 0,
  147282. 12,
  147283. };
  147284. static long _vq_lengthlist__44u9_p7_0[] = {
  147285. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  147286. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  147287. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  147288. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  147289. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147290. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147291. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  147292. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  147293. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  147294. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  147295. 12,13,13,14,14,14,15,15,15,
  147296. };
  147297. static float _vq_quantthresh__44u9_p7_0[] = {
  147298. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147299. 27.5, 38.5, 49.5, 60.5,
  147300. };
  147301. static long _vq_quantmap__44u9_p7_0[] = {
  147302. 11, 9, 7, 5, 3, 1, 0, 2,
  147303. 4, 6, 8, 10, 12,
  147304. };
  147305. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  147306. _vq_quantthresh__44u9_p7_0,
  147307. _vq_quantmap__44u9_p7_0,
  147308. 13,
  147309. 13
  147310. };
  147311. static static_codebook _44u9_p7_0 = {
  147312. 2, 169,
  147313. _vq_lengthlist__44u9_p7_0,
  147314. 1, -523206656, 1618345984, 4, 0,
  147315. _vq_quantlist__44u9_p7_0,
  147316. NULL,
  147317. &_vq_auxt__44u9_p7_0,
  147318. NULL,
  147319. 0
  147320. };
  147321. static long _vq_quantlist__44u9_p7_1[] = {
  147322. 5,
  147323. 4,
  147324. 6,
  147325. 3,
  147326. 7,
  147327. 2,
  147328. 8,
  147329. 1,
  147330. 9,
  147331. 0,
  147332. 10,
  147333. };
  147334. static long _vq_lengthlist__44u9_p7_1[] = {
  147335. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  147336. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147337. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  147338. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147339. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147340. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147341. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  147342. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  147343. };
  147344. static float _vq_quantthresh__44u9_p7_1[] = {
  147345. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147346. 3.5, 4.5,
  147347. };
  147348. static long _vq_quantmap__44u9_p7_1[] = {
  147349. 9, 7, 5, 3, 1, 0, 2, 4,
  147350. 6, 8, 10,
  147351. };
  147352. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  147353. _vq_quantthresh__44u9_p7_1,
  147354. _vq_quantmap__44u9_p7_1,
  147355. 11,
  147356. 11
  147357. };
  147358. static static_codebook _44u9_p7_1 = {
  147359. 2, 121,
  147360. _vq_lengthlist__44u9_p7_1,
  147361. 1, -531365888, 1611661312, 4, 0,
  147362. _vq_quantlist__44u9_p7_1,
  147363. NULL,
  147364. &_vq_auxt__44u9_p7_1,
  147365. NULL,
  147366. 0
  147367. };
  147368. static long _vq_quantlist__44u9_p8_0[] = {
  147369. 7,
  147370. 6,
  147371. 8,
  147372. 5,
  147373. 9,
  147374. 4,
  147375. 10,
  147376. 3,
  147377. 11,
  147378. 2,
  147379. 12,
  147380. 1,
  147381. 13,
  147382. 0,
  147383. 14,
  147384. };
  147385. static long _vq_lengthlist__44u9_p8_0[] = {
  147386. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  147387. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147388. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  147389. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  147390. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  147391. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  147392. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  147393. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  147394. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  147395. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  147396. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  147397. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  147398. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  147399. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  147400. 15,
  147401. };
  147402. static float _vq_quantthresh__44u9_p8_0[] = {
  147403. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147404. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147405. };
  147406. static long _vq_quantmap__44u9_p8_0[] = {
  147407. 13, 11, 9, 7, 5, 3, 1, 0,
  147408. 2, 4, 6, 8, 10, 12, 14,
  147409. };
  147410. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  147411. _vq_quantthresh__44u9_p8_0,
  147412. _vq_quantmap__44u9_p8_0,
  147413. 15,
  147414. 15
  147415. };
  147416. static static_codebook _44u9_p8_0 = {
  147417. 2, 225,
  147418. _vq_lengthlist__44u9_p8_0,
  147419. 1, -520986624, 1620377600, 4, 0,
  147420. _vq_quantlist__44u9_p8_0,
  147421. NULL,
  147422. &_vq_auxt__44u9_p8_0,
  147423. NULL,
  147424. 0
  147425. };
  147426. static long _vq_quantlist__44u9_p8_1[] = {
  147427. 10,
  147428. 9,
  147429. 11,
  147430. 8,
  147431. 12,
  147432. 7,
  147433. 13,
  147434. 6,
  147435. 14,
  147436. 5,
  147437. 15,
  147438. 4,
  147439. 16,
  147440. 3,
  147441. 17,
  147442. 2,
  147443. 18,
  147444. 1,
  147445. 19,
  147446. 0,
  147447. 20,
  147448. };
  147449. static long _vq_lengthlist__44u9_p8_1[] = {
  147450. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  147451. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147452. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  147453. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  147454. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  147455. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147456. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  147457. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  147458. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147459. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147460. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  147461. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  147462. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147463. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  147464. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147465. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147466. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147467. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147468. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  147469. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  147470. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147471. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  147472. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  147473. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  147474. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147475. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  147476. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147477. 10,10,10,10,10,10,10,10,10,
  147478. };
  147479. static float _vq_quantthresh__44u9_p8_1[] = {
  147480. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  147481. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  147482. 6.5, 7.5, 8.5, 9.5,
  147483. };
  147484. static long _vq_quantmap__44u9_p8_1[] = {
  147485. 19, 17, 15, 13, 11, 9, 7, 5,
  147486. 3, 1, 0, 2, 4, 6, 8, 10,
  147487. 12, 14, 16, 18, 20,
  147488. };
  147489. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  147490. _vq_quantthresh__44u9_p8_1,
  147491. _vq_quantmap__44u9_p8_1,
  147492. 21,
  147493. 21
  147494. };
  147495. static static_codebook _44u9_p8_1 = {
  147496. 2, 441,
  147497. _vq_lengthlist__44u9_p8_1,
  147498. 1, -529268736, 1611661312, 5, 0,
  147499. _vq_quantlist__44u9_p8_1,
  147500. NULL,
  147501. &_vq_auxt__44u9_p8_1,
  147502. NULL,
  147503. 0
  147504. };
  147505. static long _vq_quantlist__44u9_p9_0[] = {
  147506. 7,
  147507. 6,
  147508. 8,
  147509. 5,
  147510. 9,
  147511. 4,
  147512. 10,
  147513. 3,
  147514. 11,
  147515. 2,
  147516. 12,
  147517. 1,
  147518. 13,
  147519. 0,
  147520. 14,
  147521. };
  147522. static long _vq_lengthlist__44u9_p9_0[] = {
  147523. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  147524. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  147525. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147526. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147527. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147528. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147535. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147536. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147537. 10,
  147538. };
  147539. static float _vq_quantthresh__44u9_p9_0[] = {
  147540. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  147541. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  147542. };
  147543. static long _vq_quantmap__44u9_p9_0[] = {
  147544. 13, 11, 9, 7, 5, 3, 1, 0,
  147545. 2, 4, 6, 8, 10, 12, 14,
  147546. };
  147547. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  147548. _vq_quantthresh__44u9_p9_0,
  147549. _vq_quantmap__44u9_p9_0,
  147550. 15,
  147551. 15
  147552. };
  147553. static static_codebook _44u9_p9_0 = {
  147554. 2, 225,
  147555. _vq_lengthlist__44u9_p9_0,
  147556. 1, -510036736, 1631393792, 4, 0,
  147557. _vq_quantlist__44u9_p9_0,
  147558. NULL,
  147559. &_vq_auxt__44u9_p9_0,
  147560. NULL,
  147561. 0
  147562. };
  147563. static long _vq_quantlist__44u9_p9_1[] = {
  147564. 9,
  147565. 8,
  147566. 10,
  147567. 7,
  147568. 11,
  147569. 6,
  147570. 12,
  147571. 5,
  147572. 13,
  147573. 4,
  147574. 14,
  147575. 3,
  147576. 15,
  147577. 2,
  147578. 16,
  147579. 1,
  147580. 17,
  147581. 0,
  147582. 18,
  147583. };
  147584. static long _vq_lengthlist__44u9_p9_1[] = {
  147585. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  147586. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  147587. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  147588. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  147589. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  147590. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  147591. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  147592. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  147593. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  147594. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  147595. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  147596. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  147597. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  147598. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  147599. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  147600. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  147601. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  147602. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  147603. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  147604. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  147605. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  147606. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  147607. 17,17,15,17,15,17,16,16,17,
  147608. };
  147609. static float _vq_quantthresh__44u9_p9_1[] = {
  147610. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  147611. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  147612. 367.5, 416.5,
  147613. };
  147614. static long _vq_quantmap__44u9_p9_1[] = {
  147615. 17, 15, 13, 11, 9, 7, 5, 3,
  147616. 1, 0, 2, 4, 6, 8, 10, 12,
  147617. 14, 16, 18,
  147618. };
  147619. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  147620. _vq_quantthresh__44u9_p9_1,
  147621. _vq_quantmap__44u9_p9_1,
  147622. 19,
  147623. 19
  147624. };
  147625. static static_codebook _44u9_p9_1 = {
  147626. 2, 361,
  147627. _vq_lengthlist__44u9_p9_1,
  147628. 1, -518287360, 1622704128, 5, 0,
  147629. _vq_quantlist__44u9_p9_1,
  147630. NULL,
  147631. &_vq_auxt__44u9_p9_1,
  147632. NULL,
  147633. 0
  147634. };
  147635. static long _vq_quantlist__44u9_p9_2[] = {
  147636. 24,
  147637. 23,
  147638. 25,
  147639. 22,
  147640. 26,
  147641. 21,
  147642. 27,
  147643. 20,
  147644. 28,
  147645. 19,
  147646. 29,
  147647. 18,
  147648. 30,
  147649. 17,
  147650. 31,
  147651. 16,
  147652. 32,
  147653. 15,
  147654. 33,
  147655. 14,
  147656. 34,
  147657. 13,
  147658. 35,
  147659. 12,
  147660. 36,
  147661. 11,
  147662. 37,
  147663. 10,
  147664. 38,
  147665. 9,
  147666. 39,
  147667. 8,
  147668. 40,
  147669. 7,
  147670. 41,
  147671. 6,
  147672. 42,
  147673. 5,
  147674. 43,
  147675. 4,
  147676. 44,
  147677. 3,
  147678. 45,
  147679. 2,
  147680. 46,
  147681. 1,
  147682. 47,
  147683. 0,
  147684. 48,
  147685. };
  147686. static long _vq_lengthlist__44u9_p9_2[] = {
  147687. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  147688. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147689. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147690. 7,
  147691. };
  147692. static float _vq_quantthresh__44u9_p9_2[] = {
  147693. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147694. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147695. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147696. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147697. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147698. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147699. };
  147700. static long _vq_quantmap__44u9_p9_2[] = {
  147701. 47, 45, 43, 41, 39, 37, 35, 33,
  147702. 31, 29, 27, 25, 23, 21, 19, 17,
  147703. 15, 13, 11, 9, 7, 5, 3, 1,
  147704. 0, 2, 4, 6, 8, 10, 12, 14,
  147705. 16, 18, 20, 22, 24, 26, 28, 30,
  147706. 32, 34, 36, 38, 40, 42, 44, 46,
  147707. 48,
  147708. };
  147709. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  147710. _vq_quantthresh__44u9_p9_2,
  147711. _vq_quantmap__44u9_p9_2,
  147712. 49,
  147713. 49
  147714. };
  147715. static static_codebook _44u9_p9_2 = {
  147716. 1, 49,
  147717. _vq_lengthlist__44u9_p9_2,
  147718. 1, -526909440, 1611661312, 6, 0,
  147719. _vq_quantlist__44u9_p9_2,
  147720. NULL,
  147721. &_vq_auxt__44u9_p9_2,
  147722. NULL,
  147723. 0
  147724. };
  147725. static long _huff_lengthlist__44un1__long[] = {
  147726. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  147727. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  147728. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  147729. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  147730. };
  147731. static static_codebook _huff_book__44un1__long = {
  147732. 2, 64,
  147733. _huff_lengthlist__44un1__long,
  147734. 0, 0, 0, 0, 0,
  147735. NULL,
  147736. NULL,
  147737. NULL,
  147738. NULL,
  147739. 0
  147740. };
  147741. static long _vq_quantlist__44un1__p1_0[] = {
  147742. 1,
  147743. 0,
  147744. 2,
  147745. };
  147746. static long _vq_lengthlist__44un1__p1_0[] = {
  147747. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147748. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  147749. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  147750. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  147751. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  147752. 12,
  147753. };
  147754. static float _vq_quantthresh__44un1__p1_0[] = {
  147755. -0.5, 0.5,
  147756. };
  147757. static long _vq_quantmap__44un1__p1_0[] = {
  147758. 1, 0, 2,
  147759. };
  147760. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  147761. _vq_quantthresh__44un1__p1_0,
  147762. _vq_quantmap__44un1__p1_0,
  147763. 3,
  147764. 3
  147765. };
  147766. static static_codebook _44un1__p1_0 = {
  147767. 4, 81,
  147768. _vq_lengthlist__44un1__p1_0,
  147769. 1, -535822336, 1611661312, 2, 0,
  147770. _vq_quantlist__44un1__p1_0,
  147771. NULL,
  147772. &_vq_auxt__44un1__p1_0,
  147773. NULL,
  147774. 0
  147775. };
  147776. static long _vq_quantlist__44un1__p2_0[] = {
  147777. 1,
  147778. 0,
  147779. 2,
  147780. };
  147781. static long _vq_lengthlist__44un1__p2_0[] = {
  147782. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147783. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  147784. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  147785. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  147786. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  147787. 8,
  147788. };
  147789. static float _vq_quantthresh__44un1__p2_0[] = {
  147790. -0.5, 0.5,
  147791. };
  147792. static long _vq_quantmap__44un1__p2_0[] = {
  147793. 1, 0, 2,
  147794. };
  147795. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  147796. _vq_quantthresh__44un1__p2_0,
  147797. _vq_quantmap__44un1__p2_0,
  147798. 3,
  147799. 3
  147800. };
  147801. static static_codebook _44un1__p2_0 = {
  147802. 4, 81,
  147803. _vq_lengthlist__44un1__p2_0,
  147804. 1, -535822336, 1611661312, 2, 0,
  147805. _vq_quantlist__44un1__p2_0,
  147806. NULL,
  147807. &_vq_auxt__44un1__p2_0,
  147808. NULL,
  147809. 0
  147810. };
  147811. static long _vq_quantlist__44un1__p3_0[] = {
  147812. 2,
  147813. 1,
  147814. 3,
  147815. 0,
  147816. 4,
  147817. };
  147818. static long _vq_lengthlist__44un1__p3_0[] = {
  147819. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147820. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  147821. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  147822. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  147823. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  147824. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  147825. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  147826. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  147827. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  147828. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  147829. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  147830. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  147831. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  147832. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  147833. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  147834. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  147835. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  147836. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  147837. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  147838. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  147839. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  147840. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  147841. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  147842. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  147843. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  147844. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  147845. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  147846. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  147847. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  147848. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  147849. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  147850. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  147851. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  147852. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  147853. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  147854. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  147855. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  147856. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  147857. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  147858. 17,
  147859. };
  147860. static float _vq_quantthresh__44un1__p3_0[] = {
  147861. -1.5, -0.5, 0.5, 1.5,
  147862. };
  147863. static long _vq_quantmap__44un1__p3_0[] = {
  147864. 3, 1, 0, 2, 4,
  147865. };
  147866. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  147867. _vq_quantthresh__44un1__p3_0,
  147868. _vq_quantmap__44un1__p3_0,
  147869. 5,
  147870. 5
  147871. };
  147872. static static_codebook _44un1__p3_0 = {
  147873. 4, 625,
  147874. _vq_lengthlist__44un1__p3_0,
  147875. 1, -533725184, 1611661312, 3, 0,
  147876. _vq_quantlist__44un1__p3_0,
  147877. NULL,
  147878. &_vq_auxt__44un1__p3_0,
  147879. NULL,
  147880. 0
  147881. };
  147882. static long _vq_quantlist__44un1__p4_0[] = {
  147883. 2,
  147884. 1,
  147885. 3,
  147886. 0,
  147887. 4,
  147888. };
  147889. static long _vq_lengthlist__44un1__p4_0[] = {
  147890. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  147891. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  147892. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  147893. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  147894. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  147895. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  147896. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  147897. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  147898. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  147899. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  147900. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  147901. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  147902. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  147903. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  147904. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  147905. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  147906. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  147907. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  147908. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  147909. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  147910. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  147911. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  147912. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  147913. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  147914. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  147915. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  147916. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  147917. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  147918. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  147919. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  147920. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  147921. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  147922. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  147923. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  147924. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  147925. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  147926. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  147927. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  147928. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  147929. 12,
  147930. };
  147931. static float _vq_quantthresh__44un1__p4_0[] = {
  147932. -1.5, -0.5, 0.5, 1.5,
  147933. };
  147934. static long _vq_quantmap__44un1__p4_0[] = {
  147935. 3, 1, 0, 2, 4,
  147936. };
  147937. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  147938. _vq_quantthresh__44un1__p4_0,
  147939. _vq_quantmap__44un1__p4_0,
  147940. 5,
  147941. 5
  147942. };
  147943. static static_codebook _44un1__p4_0 = {
  147944. 4, 625,
  147945. _vq_lengthlist__44un1__p4_0,
  147946. 1, -533725184, 1611661312, 3, 0,
  147947. _vq_quantlist__44un1__p4_0,
  147948. NULL,
  147949. &_vq_auxt__44un1__p4_0,
  147950. NULL,
  147951. 0
  147952. };
  147953. static long _vq_quantlist__44un1__p5_0[] = {
  147954. 4,
  147955. 3,
  147956. 5,
  147957. 2,
  147958. 6,
  147959. 1,
  147960. 7,
  147961. 0,
  147962. 8,
  147963. };
  147964. static long _vq_lengthlist__44un1__p5_0[] = {
  147965. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  147966. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  147967. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  147968. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  147969. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147970. 12,
  147971. };
  147972. static float _vq_quantthresh__44un1__p5_0[] = {
  147973. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147974. };
  147975. static long _vq_quantmap__44un1__p5_0[] = {
  147976. 7, 5, 3, 1, 0, 2, 4, 6,
  147977. 8,
  147978. };
  147979. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  147980. _vq_quantthresh__44un1__p5_0,
  147981. _vq_quantmap__44un1__p5_0,
  147982. 9,
  147983. 9
  147984. };
  147985. static static_codebook _44un1__p5_0 = {
  147986. 2, 81,
  147987. _vq_lengthlist__44un1__p5_0,
  147988. 1, -531628032, 1611661312, 4, 0,
  147989. _vq_quantlist__44un1__p5_0,
  147990. NULL,
  147991. &_vq_auxt__44un1__p5_0,
  147992. NULL,
  147993. 0
  147994. };
  147995. static long _vq_quantlist__44un1__p6_0[] = {
  147996. 6,
  147997. 5,
  147998. 7,
  147999. 4,
  148000. 8,
  148001. 3,
  148002. 9,
  148003. 2,
  148004. 10,
  148005. 1,
  148006. 11,
  148007. 0,
  148008. 12,
  148009. };
  148010. static long _vq_lengthlist__44un1__p6_0[] = {
  148011. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  148012. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  148013. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  148014. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  148015. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  148016. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  148017. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  148018. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  148019. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  148020. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  148021. 16, 0,15,18,18, 0,16, 0, 0,
  148022. };
  148023. static float _vq_quantthresh__44un1__p6_0[] = {
  148024. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148025. 12.5, 17.5, 22.5, 27.5,
  148026. };
  148027. static long _vq_quantmap__44un1__p6_0[] = {
  148028. 11, 9, 7, 5, 3, 1, 0, 2,
  148029. 4, 6, 8, 10, 12,
  148030. };
  148031. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  148032. _vq_quantthresh__44un1__p6_0,
  148033. _vq_quantmap__44un1__p6_0,
  148034. 13,
  148035. 13
  148036. };
  148037. static static_codebook _44un1__p6_0 = {
  148038. 2, 169,
  148039. _vq_lengthlist__44un1__p6_0,
  148040. 1, -526516224, 1616117760, 4, 0,
  148041. _vq_quantlist__44un1__p6_0,
  148042. NULL,
  148043. &_vq_auxt__44un1__p6_0,
  148044. NULL,
  148045. 0
  148046. };
  148047. static long _vq_quantlist__44un1__p6_1[] = {
  148048. 2,
  148049. 1,
  148050. 3,
  148051. 0,
  148052. 4,
  148053. };
  148054. static long _vq_lengthlist__44un1__p6_1[] = {
  148055. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  148056. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  148057. };
  148058. static float _vq_quantthresh__44un1__p6_1[] = {
  148059. -1.5, -0.5, 0.5, 1.5,
  148060. };
  148061. static long _vq_quantmap__44un1__p6_1[] = {
  148062. 3, 1, 0, 2, 4,
  148063. };
  148064. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  148065. _vq_quantthresh__44un1__p6_1,
  148066. _vq_quantmap__44un1__p6_1,
  148067. 5,
  148068. 5
  148069. };
  148070. static static_codebook _44un1__p6_1 = {
  148071. 2, 25,
  148072. _vq_lengthlist__44un1__p6_1,
  148073. 1, -533725184, 1611661312, 3, 0,
  148074. _vq_quantlist__44un1__p6_1,
  148075. NULL,
  148076. &_vq_auxt__44un1__p6_1,
  148077. NULL,
  148078. 0
  148079. };
  148080. static long _vq_quantlist__44un1__p7_0[] = {
  148081. 2,
  148082. 1,
  148083. 3,
  148084. 0,
  148085. 4,
  148086. };
  148087. static long _vq_lengthlist__44un1__p7_0[] = {
  148088. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  148089. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  148090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148091. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148095. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  148096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  148099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148101. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148103. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  148104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148105. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  148106. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148108. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148109. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148110. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148111. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148117. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148118. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148119. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148120. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148121. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148122. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148123. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148124. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148125. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148126. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148127. 10,
  148128. };
  148129. static float _vq_quantthresh__44un1__p7_0[] = {
  148130. -253.5, -84.5, 84.5, 253.5,
  148131. };
  148132. static long _vq_quantmap__44un1__p7_0[] = {
  148133. 3, 1, 0, 2, 4,
  148134. };
  148135. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  148136. _vq_quantthresh__44un1__p7_0,
  148137. _vq_quantmap__44un1__p7_0,
  148138. 5,
  148139. 5
  148140. };
  148141. static static_codebook _44un1__p7_0 = {
  148142. 4, 625,
  148143. _vq_lengthlist__44un1__p7_0,
  148144. 1, -518709248, 1626677248, 3, 0,
  148145. _vq_quantlist__44un1__p7_0,
  148146. NULL,
  148147. &_vq_auxt__44un1__p7_0,
  148148. NULL,
  148149. 0
  148150. };
  148151. static long _vq_quantlist__44un1__p7_1[] = {
  148152. 6,
  148153. 5,
  148154. 7,
  148155. 4,
  148156. 8,
  148157. 3,
  148158. 9,
  148159. 2,
  148160. 10,
  148161. 1,
  148162. 11,
  148163. 0,
  148164. 12,
  148165. };
  148166. static long _vq_lengthlist__44un1__p7_1[] = {
  148167. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  148168. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  148169. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  148170. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  148171. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  148172. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  148173. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  148174. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  148175. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  148176. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  148177. 12,13,13,12,13,13,14,14,14,
  148178. };
  148179. static float _vq_quantthresh__44un1__p7_1[] = {
  148180. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  148181. 32.5, 45.5, 58.5, 71.5,
  148182. };
  148183. static long _vq_quantmap__44un1__p7_1[] = {
  148184. 11, 9, 7, 5, 3, 1, 0, 2,
  148185. 4, 6, 8, 10, 12,
  148186. };
  148187. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  148188. _vq_quantthresh__44un1__p7_1,
  148189. _vq_quantmap__44un1__p7_1,
  148190. 13,
  148191. 13
  148192. };
  148193. static static_codebook _44un1__p7_1 = {
  148194. 2, 169,
  148195. _vq_lengthlist__44un1__p7_1,
  148196. 1, -523010048, 1618608128, 4, 0,
  148197. _vq_quantlist__44un1__p7_1,
  148198. NULL,
  148199. &_vq_auxt__44un1__p7_1,
  148200. NULL,
  148201. 0
  148202. };
  148203. static long _vq_quantlist__44un1__p7_2[] = {
  148204. 6,
  148205. 5,
  148206. 7,
  148207. 4,
  148208. 8,
  148209. 3,
  148210. 9,
  148211. 2,
  148212. 10,
  148213. 1,
  148214. 11,
  148215. 0,
  148216. 12,
  148217. };
  148218. static long _vq_lengthlist__44un1__p7_2[] = {
  148219. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  148220. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  148221. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  148222. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  148223. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  148224. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  148225. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  148226. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  148227. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  148228. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  148229. 9, 9, 9,10,10,10,10,10,10,
  148230. };
  148231. static float _vq_quantthresh__44un1__p7_2[] = {
  148232. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  148233. 2.5, 3.5, 4.5, 5.5,
  148234. };
  148235. static long _vq_quantmap__44un1__p7_2[] = {
  148236. 11, 9, 7, 5, 3, 1, 0, 2,
  148237. 4, 6, 8, 10, 12,
  148238. };
  148239. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  148240. _vq_quantthresh__44un1__p7_2,
  148241. _vq_quantmap__44un1__p7_2,
  148242. 13,
  148243. 13
  148244. };
  148245. static static_codebook _44un1__p7_2 = {
  148246. 2, 169,
  148247. _vq_lengthlist__44un1__p7_2,
  148248. 1, -531103744, 1611661312, 4, 0,
  148249. _vq_quantlist__44un1__p7_2,
  148250. NULL,
  148251. &_vq_auxt__44un1__p7_2,
  148252. NULL,
  148253. 0
  148254. };
  148255. static long _huff_lengthlist__44un1__short[] = {
  148256. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  148257. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  148258. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  148259. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  148260. };
  148261. static static_codebook _huff_book__44un1__short = {
  148262. 2, 64,
  148263. _huff_lengthlist__44un1__short,
  148264. 0, 0, 0, 0, 0,
  148265. NULL,
  148266. NULL,
  148267. NULL,
  148268. NULL,
  148269. 0
  148270. };
  148271. /********* End of inlined file: res_books_uncoupled.h *********/
  148272. /***** residue backends *********************************************/
  148273. static vorbis_info_residue0 _residue_44_low_un={
  148274. 0,-1, -1, 8,-1,
  148275. {0},
  148276. {-1},
  148277. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  148278. { -1, 25, -1, 45, -1, -1, -1}
  148279. };
  148280. static vorbis_info_residue0 _residue_44_mid_un={
  148281. 0,-1, -1, 10,-1,
  148282. /* 0 1 2 3 4 5 6 7 8 9 */
  148283. {0},
  148284. {-1},
  148285. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  148286. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  148287. };
  148288. static vorbis_info_residue0 _residue_44_hi_un={
  148289. 0,-1, -1, 10,-1,
  148290. /* 0 1 2 3 4 5 6 7 8 9 */
  148291. {0},
  148292. {-1},
  148293. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  148294. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  148295. };
  148296. /* mapping conventions:
  148297. only one submap (this would change for efficient 5.1 support for example)*/
  148298. /* Four psychoacoustic profiles are used, one for each blocktype */
  148299. static vorbis_info_mapping0 _map_nominal_u[2]={
  148300. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  148301. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  148302. };
  148303. static static_bookblock _resbook_44u_n1={
  148304. {
  148305. {0},
  148306. {0,0,&_44un1__p1_0},
  148307. {0,0,&_44un1__p2_0},
  148308. {0,0,&_44un1__p3_0},
  148309. {0,0,&_44un1__p4_0},
  148310. {0,0,&_44un1__p5_0},
  148311. {&_44un1__p6_0,&_44un1__p6_1},
  148312. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  148313. }
  148314. };
  148315. static static_bookblock _resbook_44u_0={
  148316. {
  148317. {0},
  148318. {0,0,&_44u0__p1_0},
  148319. {0,0,&_44u0__p2_0},
  148320. {0,0,&_44u0__p3_0},
  148321. {0,0,&_44u0__p4_0},
  148322. {0,0,&_44u0__p5_0},
  148323. {&_44u0__p6_0,&_44u0__p6_1},
  148324. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  148325. }
  148326. };
  148327. static static_bookblock _resbook_44u_1={
  148328. {
  148329. {0},
  148330. {0,0,&_44u1__p1_0},
  148331. {0,0,&_44u1__p2_0},
  148332. {0,0,&_44u1__p3_0},
  148333. {0,0,&_44u1__p4_0},
  148334. {0,0,&_44u1__p5_0},
  148335. {&_44u1__p6_0,&_44u1__p6_1},
  148336. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  148337. }
  148338. };
  148339. static static_bookblock _resbook_44u_2={
  148340. {
  148341. {0},
  148342. {0,0,&_44u2__p1_0},
  148343. {0,0,&_44u2__p2_0},
  148344. {0,0,&_44u2__p3_0},
  148345. {0,0,&_44u2__p4_0},
  148346. {0,0,&_44u2__p5_0},
  148347. {&_44u2__p6_0,&_44u2__p6_1},
  148348. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  148349. }
  148350. };
  148351. static static_bookblock _resbook_44u_3={
  148352. {
  148353. {0},
  148354. {0,0,&_44u3__p1_0},
  148355. {0,0,&_44u3__p2_0},
  148356. {0,0,&_44u3__p3_0},
  148357. {0,0,&_44u3__p4_0},
  148358. {0,0,&_44u3__p5_0},
  148359. {&_44u3__p6_0,&_44u3__p6_1},
  148360. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  148361. }
  148362. };
  148363. static static_bookblock _resbook_44u_4={
  148364. {
  148365. {0},
  148366. {0,0,&_44u4__p1_0},
  148367. {0,0,&_44u4__p2_0},
  148368. {0,0,&_44u4__p3_0},
  148369. {0,0,&_44u4__p4_0},
  148370. {0,0,&_44u4__p5_0},
  148371. {&_44u4__p6_0,&_44u4__p6_1},
  148372. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  148373. }
  148374. };
  148375. static static_bookblock _resbook_44u_5={
  148376. {
  148377. {0},
  148378. {0,0,&_44u5__p1_0},
  148379. {0,0,&_44u5__p2_0},
  148380. {0,0,&_44u5__p3_0},
  148381. {0,0,&_44u5__p4_0},
  148382. {0,0,&_44u5__p5_0},
  148383. {0,0,&_44u5__p6_0},
  148384. {&_44u5__p7_0,&_44u5__p7_1},
  148385. {&_44u5__p8_0,&_44u5__p8_1},
  148386. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  148387. }
  148388. };
  148389. static static_bookblock _resbook_44u_6={
  148390. {
  148391. {0},
  148392. {0,0,&_44u6__p1_0},
  148393. {0,0,&_44u6__p2_0},
  148394. {0,0,&_44u6__p3_0},
  148395. {0,0,&_44u6__p4_0},
  148396. {0,0,&_44u6__p5_0},
  148397. {0,0,&_44u6__p6_0},
  148398. {&_44u6__p7_0,&_44u6__p7_1},
  148399. {&_44u6__p8_0,&_44u6__p8_1},
  148400. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  148401. }
  148402. };
  148403. static static_bookblock _resbook_44u_7={
  148404. {
  148405. {0},
  148406. {0,0,&_44u7__p1_0},
  148407. {0,0,&_44u7__p2_0},
  148408. {0,0,&_44u7__p3_0},
  148409. {0,0,&_44u7__p4_0},
  148410. {0,0,&_44u7__p5_0},
  148411. {0,0,&_44u7__p6_0},
  148412. {&_44u7__p7_0,&_44u7__p7_1},
  148413. {&_44u7__p8_0,&_44u7__p8_1},
  148414. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  148415. }
  148416. };
  148417. static static_bookblock _resbook_44u_8={
  148418. {
  148419. {0},
  148420. {0,0,&_44u8_p1_0},
  148421. {0,0,&_44u8_p2_0},
  148422. {0,0,&_44u8_p3_0},
  148423. {0,0,&_44u8_p4_0},
  148424. {&_44u8_p5_0,&_44u8_p5_1},
  148425. {&_44u8_p6_0,&_44u8_p6_1},
  148426. {&_44u8_p7_0,&_44u8_p7_1},
  148427. {&_44u8_p8_0,&_44u8_p8_1},
  148428. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  148429. }
  148430. };
  148431. static static_bookblock _resbook_44u_9={
  148432. {
  148433. {0},
  148434. {0,0,&_44u9_p1_0},
  148435. {0,0,&_44u9_p2_0},
  148436. {0,0,&_44u9_p3_0},
  148437. {0,0,&_44u9_p4_0},
  148438. {&_44u9_p5_0,&_44u9_p5_1},
  148439. {&_44u9_p6_0,&_44u9_p6_1},
  148440. {&_44u9_p7_0,&_44u9_p7_1},
  148441. {&_44u9_p8_0,&_44u9_p8_1},
  148442. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  148443. }
  148444. };
  148445. static vorbis_residue_template _res_44u_n1[]={
  148446. {1,0, &_residue_44_low_un,
  148447. &_huff_book__44un1__short,&_huff_book__44un1__short,
  148448. &_resbook_44u_n1,&_resbook_44u_n1},
  148449. {1,0, &_residue_44_low_un,
  148450. &_huff_book__44un1__long,&_huff_book__44un1__long,
  148451. &_resbook_44u_n1,&_resbook_44u_n1}
  148452. };
  148453. static vorbis_residue_template _res_44u_0[]={
  148454. {1,0, &_residue_44_low_un,
  148455. &_huff_book__44u0__short,&_huff_book__44u0__short,
  148456. &_resbook_44u_0,&_resbook_44u_0},
  148457. {1,0, &_residue_44_low_un,
  148458. &_huff_book__44u0__long,&_huff_book__44u0__long,
  148459. &_resbook_44u_0,&_resbook_44u_0}
  148460. };
  148461. static vorbis_residue_template _res_44u_1[]={
  148462. {1,0, &_residue_44_low_un,
  148463. &_huff_book__44u1__short,&_huff_book__44u1__short,
  148464. &_resbook_44u_1,&_resbook_44u_1},
  148465. {1,0, &_residue_44_low_un,
  148466. &_huff_book__44u1__long,&_huff_book__44u1__long,
  148467. &_resbook_44u_1,&_resbook_44u_1}
  148468. };
  148469. static vorbis_residue_template _res_44u_2[]={
  148470. {1,0, &_residue_44_low_un,
  148471. &_huff_book__44u2__short,&_huff_book__44u2__short,
  148472. &_resbook_44u_2,&_resbook_44u_2},
  148473. {1,0, &_residue_44_low_un,
  148474. &_huff_book__44u2__long,&_huff_book__44u2__long,
  148475. &_resbook_44u_2,&_resbook_44u_2}
  148476. };
  148477. static vorbis_residue_template _res_44u_3[]={
  148478. {1,0, &_residue_44_low_un,
  148479. &_huff_book__44u3__short,&_huff_book__44u3__short,
  148480. &_resbook_44u_3,&_resbook_44u_3},
  148481. {1,0, &_residue_44_low_un,
  148482. &_huff_book__44u3__long,&_huff_book__44u3__long,
  148483. &_resbook_44u_3,&_resbook_44u_3}
  148484. };
  148485. static vorbis_residue_template _res_44u_4[]={
  148486. {1,0, &_residue_44_low_un,
  148487. &_huff_book__44u4__short,&_huff_book__44u4__short,
  148488. &_resbook_44u_4,&_resbook_44u_4},
  148489. {1,0, &_residue_44_low_un,
  148490. &_huff_book__44u4__long,&_huff_book__44u4__long,
  148491. &_resbook_44u_4,&_resbook_44u_4}
  148492. };
  148493. static vorbis_residue_template _res_44u_5[]={
  148494. {1,0, &_residue_44_mid_un,
  148495. &_huff_book__44u5__short,&_huff_book__44u5__short,
  148496. &_resbook_44u_5,&_resbook_44u_5},
  148497. {1,0, &_residue_44_mid_un,
  148498. &_huff_book__44u5__long,&_huff_book__44u5__long,
  148499. &_resbook_44u_5,&_resbook_44u_5}
  148500. };
  148501. static vorbis_residue_template _res_44u_6[]={
  148502. {1,0, &_residue_44_mid_un,
  148503. &_huff_book__44u6__short,&_huff_book__44u6__short,
  148504. &_resbook_44u_6,&_resbook_44u_6},
  148505. {1,0, &_residue_44_mid_un,
  148506. &_huff_book__44u6__long,&_huff_book__44u6__long,
  148507. &_resbook_44u_6,&_resbook_44u_6}
  148508. };
  148509. static vorbis_residue_template _res_44u_7[]={
  148510. {1,0, &_residue_44_mid_un,
  148511. &_huff_book__44u7__short,&_huff_book__44u7__short,
  148512. &_resbook_44u_7,&_resbook_44u_7},
  148513. {1,0, &_residue_44_mid_un,
  148514. &_huff_book__44u7__long,&_huff_book__44u7__long,
  148515. &_resbook_44u_7,&_resbook_44u_7}
  148516. };
  148517. static vorbis_residue_template _res_44u_8[]={
  148518. {1,0, &_residue_44_hi_un,
  148519. &_huff_book__44u8__short,&_huff_book__44u8__short,
  148520. &_resbook_44u_8,&_resbook_44u_8},
  148521. {1,0, &_residue_44_hi_un,
  148522. &_huff_book__44u8__long,&_huff_book__44u8__long,
  148523. &_resbook_44u_8,&_resbook_44u_8}
  148524. };
  148525. static vorbis_residue_template _res_44u_9[]={
  148526. {1,0, &_residue_44_hi_un,
  148527. &_huff_book__44u9__short,&_huff_book__44u9__short,
  148528. &_resbook_44u_9,&_resbook_44u_9},
  148529. {1,0, &_residue_44_hi_un,
  148530. &_huff_book__44u9__long,&_huff_book__44u9__long,
  148531. &_resbook_44u_9,&_resbook_44u_9}
  148532. };
  148533. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  148534. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  148535. { _map_nominal_u, _res_44u_0 }, /* 0 */
  148536. { _map_nominal_u, _res_44u_1 }, /* 1 */
  148537. { _map_nominal_u, _res_44u_2 }, /* 2 */
  148538. { _map_nominal_u, _res_44u_3 }, /* 3 */
  148539. { _map_nominal_u, _res_44u_4 }, /* 4 */
  148540. { _map_nominal_u, _res_44u_5 }, /* 5 */
  148541. { _map_nominal_u, _res_44u_6 }, /* 6 */
  148542. { _map_nominal_u, _res_44u_7 }, /* 7 */
  148543. { _map_nominal_u, _res_44u_8 }, /* 8 */
  148544. { _map_nominal_u, _res_44u_9 }, /* 9 */
  148545. };
  148546. /********* End of inlined file: residue_44u.h *********/
  148547. static double rate_mapping_44_un[12]={
  148548. 32000.,48000.,60000.,70000.,80000.,86000.,
  148549. 96000.,110000.,120000.,140000.,160000.,240001.
  148550. };
  148551. ve_setup_data_template ve_setup_44_uncoupled={
  148552. 11,
  148553. rate_mapping_44_un,
  148554. quality_mapping_44,
  148555. -1,
  148556. 40000,
  148557. 50000,
  148558. blocksize_short_44,
  148559. blocksize_long_44,
  148560. _psy_tone_masteratt_44,
  148561. _psy_tone_0dB,
  148562. _psy_tone_suppress,
  148563. _vp_tonemask_adj_otherblock,
  148564. _vp_tonemask_adj_longblock,
  148565. _vp_tonemask_adj_otherblock,
  148566. _psy_noiseguards_44,
  148567. _psy_noisebias_impulse,
  148568. _psy_noisebias_padding,
  148569. _psy_noisebias_trans,
  148570. _psy_noisebias_long,
  148571. _psy_noise_suppress,
  148572. _psy_compand_44,
  148573. _psy_compand_short_mapping,
  148574. _psy_compand_long_mapping,
  148575. {_noise_start_short_44,_noise_start_long_44},
  148576. {_noise_part_short_44,_noise_part_long_44},
  148577. _noise_thresh_44,
  148578. _psy_ath_floater,
  148579. _psy_ath_abs,
  148580. _psy_lowpass_44,
  148581. _psy_global_44,
  148582. _global_mapping_44,
  148583. NULL,
  148584. _floor_books,
  148585. _floor,
  148586. _floor_short_mapping_44,
  148587. _floor_long_mapping_44,
  148588. _mapres_template_44_uncoupled
  148589. };
  148590. /********* End of inlined file: setup_44u.h *********/
  148591. /********* Start of inlined file: setup_32.h *********/
  148592. static double rate_mapping_32[12]={
  148593. 18000.,28000.,35000.,45000.,56000.,60000.,
  148594. 75000.,90000.,100000.,115000.,150000.,190000.,
  148595. };
  148596. static double rate_mapping_32_un[12]={
  148597. 30000.,42000.,52000.,64000.,72000.,78000.,
  148598. 86000.,92000.,110000.,120000.,140000.,190000.,
  148599. };
  148600. static double _psy_lowpass_32[12]={
  148601. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  148602. };
  148603. ve_setup_data_template ve_setup_32_stereo={
  148604. 11,
  148605. rate_mapping_32,
  148606. quality_mapping_44,
  148607. 2,
  148608. 26000,
  148609. 40000,
  148610. blocksize_short_44,
  148611. blocksize_long_44,
  148612. _psy_tone_masteratt_44,
  148613. _psy_tone_0dB,
  148614. _psy_tone_suppress,
  148615. _vp_tonemask_adj_otherblock,
  148616. _vp_tonemask_adj_longblock,
  148617. _vp_tonemask_adj_otherblock,
  148618. _psy_noiseguards_44,
  148619. _psy_noisebias_impulse,
  148620. _psy_noisebias_padding,
  148621. _psy_noisebias_trans,
  148622. _psy_noisebias_long,
  148623. _psy_noise_suppress,
  148624. _psy_compand_44,
  148625. _psy_compand_short_mapping,
  148626. _psy_compand_long_mapping,
  148627. {_noise_start_short_44,_noise_start_long_44},
  148628. {_noise_part_short_44,_noise_part_long_44},
  148629. _noise_thresh_44,
  148630. _psy_ath_floater,
  148631. _psy_ath_abs,
  148632. _psy_lowpass_32,
  148633. _psy_global_44,
  148634. _global_mapping_44,
  148635. _psy_stereo_modes_44,
  148636. _floor_books,
  148637. _floor,
  148638. _floor_short_mapping_44,
  148639. _floor_long_mapping_44,
  148640. _mapres_template_44_stereo
  148641. };
  148642. ve_setup_data_template ve_setup_32_uncoupled={
  148643. 11,
  148644. rate_mapping_32_un,
  148645. quality_mapping_44,
  148646. -1,
  148647. 26000,
  148648. 40000,
  148649. blocksize_short_44,
  148650. blocksize_long_44,
  148651. _psy_tone_masteratt_44,
  148652. _psy_tone_0dB,
  148653. _psy_tone_suppress,
  148654. _vp_tonemask_adj_otherblock,
  148655. _vp_tonemask_adj_longblock,
  148656. _vp_tonemask_adj_otherblock,
  148657. _psy_noiseguards_44,
  148658. _psy_noisebias_impulse,
  148659. _psy_noisebias_padding,
  148660. _psy_noisebias_trans,
  148661. _psy_noisebias_long,
  148662. _psy_noise_suppress,
  148663. _psy_compand_44,
  148664. _psy_compand_short_mapping,
  148665. _psy_compand_long_mapping,
  148666. {_noise_start_short_44,_noise_start_long_44},
  148667. {_noise_part_short_44,_noise_part_long_44},
  148668. _noise_thresh_44,
  148669. _psy_ath_floater,
  148670. _psy_ath_abs,
  148671. _psy_lowpass_32,
  148672. _psy_global_44,
  148673. _global_mapping_44,
  148674. NULL,
  148675. _floor_books,
  148676. _floor,
  148677. _floor_short_mapping_44,
  148678. _floor_long_mapping_44,
  148679. _mapres_template_44_uncoupled
  148680. };
  148681. /********* End of inlined file: setup_32.h *********/
  148682. /********* Start of inlined file: setup_8.h *********/
  148683. /********* Start of inlined file: psych_8.h *********/
  148684. static att3 _psy_tone_masteratt_8[3]={
  148685. {{ 32, 25, 12}, 0, 0}, /* 0 */
  148686. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148687. {{ 20, 0, -14}, 0, 0}, /* 0 */
  148688. };
  148689. static vp_adjblock _vp_tonemask_adj_8[3]={
  148690. /* adjust for mode zero */
  148691. /* 63 125 250 500 1 2 4 8 16 */
  148692. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  148693. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  148694. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  148695. };
  148696. static noise3 _psy_noisebias_8[3]={
  148697. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148698. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  148699. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  148700. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148701. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  148702. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  148703. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148704. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  148705. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  148706. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  148707. };
  148708. /* stereo mode by base quality level */
  148709. static adj_stereo _psy_stereo_modes_8[3]={
  148710. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  148711. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148712. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148713. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  148714. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148715. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148716. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148717. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  148718. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148719. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148720. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148721. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  148722. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148723. };
  148724. static noiseguard _psy_noiseguards_8[2]={
  148725. {10,10,-1},
  148726. {10,10,-1},
  148727. };
  148728. static compandblock _psy_compand_8[2]={
  148729. {{
  148730. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  148731. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  148732. 12,12,13,13,14,14,15, 15, /* 23dB */
  148733. 16,16,17,17,17,18,18, 19, /* 31dB */
  148734. 19,19,20,21,22,23,24, 25, /* 39dB */
  148735. }},
  148736. {{
  148737. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  148738. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  148739. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  148740. 9,10,11,12,13,14,15, 16, /* 31dB */
  148741. 17,18,19,20,21,22,23, 24, /* 39dB */
  148742. }},
  148743. };
  148744. static double _psy_lowpass_8[3]={3.,4.,4.};
  148745. static int _noise_start_8[2]={
  148746. 64,64,
  148747. };
  148748. static int _noise_part_8[2]={
  148749. 8,8,
  148750. };
  148751. static int _psy_ath_floater_8[3]={
  148752. -100,-100,-105,
  148753. };
  148754. static int _psy_ath_abs_8[3]={
  148755. -130,-130,-140,
  148756. };
  148757. /********* End of inlined file: psych_8.h *********/
  148758. /********* Start of inlined file: residue_8.h *********/
  148759. /***** residue backends *********************************************/
  148760. static static_bookblock _resbook_8s_0={
  148761. {
  148762. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  148763. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  148764. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  148765. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  148766. }
  148767. };
  148768. static static_bookblock _resbook_8s_1={
  148769. {
  148770. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  148771. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  148772. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  148773. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  148774. }
  148775. };
  148776. static vorbis_residue_template _res_8s_0[]={
  148777. {2,0, &_residue_44_mid,
  148778. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  148779. &_resbook_8s_0,&_resbook_8s_0},
  148780. };
  148781. static vorbis_residue_template _res_8s_1[]={
  148782. {2,0, &_residue_44_mid,
  148783. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  148784. &_resbook_8s_1,&_resbook_8s_1},
  148785. };
  148786. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  148787. { _map_nominal, _res_8s_0 }, /* 0 */
  148788. { _map_nominal, _res_8s_1 }, /* 1 */
  148789. };
  148790. static static_bookblock _resbook_8u_0={
  148791. {
  148792. {0},
  148793. {0,0,&_8u0__p1_0},
  148794. {0,0,&_8u0__p2_0},
  148795. {0,0,&_8u0__p3_0},
  148796. {0,0,&_8u0__p4_0},
  148797. {0,0,&_8u0__p5_0},
  148798. {&_8u0__p6_0,&_8u0__p6_1},
  148799. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  148800. }
  148801. };
  148802. static static_bookblock _resbook_8u_1={
  148803. {
  148804. {0},
  148805. {0,0,&_8u1__p1_0},
  148806. {0,0,&_8u1__p2_0},
  148807. {0,0,&_8u1__p3_0},
  148808. {0,0,&_8u1__p4_0},
  148809. {0,0,&_8u1__p5_0},
  148810. {0,0,&_8u1__p6_0},
  148811. {&_8u1__p7_0,&_8u1__p7_1},
  148812. {&_8u1__p8_0,&_8u1__p8_1},
  148813. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  148814. }
  148815. };
  148816. static vorbis_residue_template _res_8u_0[]={
  148817. {1,0, &_residue_44_low_un,
  148818. &_huff_book__8u0__single,&_huff_book__8u0__single,
  148819. &_resbook_8u_0,&_resbook_8u_0},
  148820. };
  148821. static vorbis_residue_template _res_8u_1[]={
  148822. {1,0, &_residue_44_mid_un,
  148823. &_huff_book__8u1__single,&_huff_book__8u1__single,
  148824. &_resbook_8u_1,&_resbook_8u_1},
  148825. };
  148826. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  148827. { _map_nominal_u, _res_8u_0 }, /* 0 */
  148828. { _map_nominal_u, _res_8u_1 }, /* 1 */
  148829. };
  148830. /********* End of inlined file: residue_8.h *********/
  148831. static int blocksize_8[2]={
  148832. 512,512
  148833. };
  148834. static int _floor_mapping_8[2]={
  148835. 6,6,
  148836. };
  148837. static double rate_mapping_8[3]={
  148838. 6000.,9000.,32000.,
  148839. };
  148840. static double rate_mapping_8_uncoupled[3]={
  148841. 8000.,14000.,42000.,
  148842. };
  148843. static double quality_mapping_8[3]={
  148844. -.1,.0,1.
  148845. };
  148846. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  148847. static double _global_mapping_8[3]={ 1., 2., 3. };
  148848. ve_setup_data_template ve_setup_8_stereo={
  148849. 2,
  148850. rate_mapping_8,
  148851. quality_mapping_8,
  148852. 2,
  148853. 8000,
  148854. 9000,
  148855. blocksize_8,
  148856. blocksize_8,
  148857. _psy_tone_masteratt_8,
  148858. _psy_tone_0dB,
  148859. _psy_tone_suppress,
  148860. _vp_tonemask_adj_8,
  148861. NULL,
  148862. _vp_tonemask_adj_8,
  148863. _psy_noiseguards_8,
  148864. _psy_noisebias_8,
  148865. _psy_noisebias_8,
  148866. NULL,
  148867. NULL,
  148868. _psy_noise_suppress,
  148869. _psy_compand_8,
  148870. _psy_compand_8_mapping,
  148871. NULL,
  148872. {_noise_start_8,_noise_start_8},
  148873. {_noise_part_8,_noise_part_8},
  148874. _noise_thresh_5only,
  148875. _psy_ath_floater_8,
  148876. _psy_ath_abs_8,
  148877. _psy_lowpass_8,
  148878. _psy_global_44,
  148879. _global_mapping_8,
  148880. _psy_stereo_modes_8,
  148881. _floor_books,
  148882. _floor,
  148883. _floor_mapping_8,
  148884. NULL,
  148885. _mapres_template_8_stereo
  148886. };
  148887. ve_setup_data_template ve_setup_8_uncoupled={
  148888. 2,
  148889. rate_mapping_8_uncoupled,
  148890. quality_mapping_8,
  148891. -1,
  148892. 8000,
  148893. 9000,
  148894. blocksize_8,
  148895. blocksize_8,
  148896. _psy_tone_masteratt_8,
  148897. _psy_tone_0dB,
  148898. _psy_tone_suppress,
  148899. _vp_tonemask_adj_8,
  148900. NULL,
  148901. _vp_tonemask_adj_8,
  148902. _psy_noiseguards_8,
  148903. _psy_noisebias_8,
  148904. _psy_noisebias_8,
  148905. NULL,
  148906. NULL,
  148907. _psy_noise_suppress,
  148908. _psy_compand_8,
  148909. _psy_compand_8_mapping,
  148910. NULL,
  148911. {_noise_start_8,_noise_start_8},
  148912. {_noise_part_8,_noise_part_8},
  148913. _noise_thresh_5only,
  148914. _psy_ath_floater_8,
  148915. _psy_ath_abs_8,
  148916. _psy_lowpass_8,
  148917. _psy_global_44,
  148918. _global_mapping_8,
  148919. _psy_stereo_modes_8,
  148920. _floor_books,
  148921. _floor,
  148922. _floor_mapping_8,
  148923. NULL,
  148924. _mapres_template_8_uncoupled
  148925. };
  148926. /********* End of inlined file: setup_8.h *********/
  148927. /********* Start of inlined file: setup_11.h *********/
  148928. /********* Start of inlined file: psych_11.h *********/
  148929. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  148930. static att3 _psy_tone_masteratt_11[3]={
  148931. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148932. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148933. {{ 20, 0, -14}, 0, 0}, /* 0 */
  148934. };
  148935. static vp_adjblock _vp_tonemask_adj_11[3]={
  148936. /* adjust for mode zero */
  148937. /* 63 125 250 500 1 2 4 8 16 */
  148938. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  148939. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  148940. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  148941. };
  148942. static noise3 _psy_noisebias_11[3]={
  148943. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148944. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  148945. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  148946. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148947. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  148948. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  148949. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148950. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  148951. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  148952. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  148953. };
  148954. static double _noise_thresh_11[3]={ .3,.5,.5 };
  148955. /********* End of inlined file: psych_11.h *********/
  148956. static int blocksize_11[2]={
  148957. 512,512
  148958. };
  148959. static int _floor_mapping_11[2]={
  148960. 6,6,
  148961. };
  148962. static double rate_mapping_11[3]={
  148963. 8000.,13000.,44000.,
  148964. };
  148965. static double rate_mapping_11_uncoupled[3]={
  148966. 12000.,20000.,50000.,
  148967. };
  148968. static double quality_mapping_11[3]={
  148969. -.1,.0,1.
  148970. };
  148971. ve_setup_data_template ve_setup_11_stereo={
  148972. 2,
  148973. rate_mapping_11,
  148974. quality_mapping_11,
  148975. 2,
  148976. 9000,
  148977. 15000,
  148978. blocksize_11,
  148979. blocksize_11,
  148980. _psy_tone_masteratt_11,
  148981. _psy_tone_0dB,
  148982. _psy_tone_suppress,
  148983. _vp_tonemask_adj_11,
  148984. NULL,
  148985. _vp_tonemask_adj_11,
  148986. _psy_noiseguards_8,
  148987. _psy_noisebias_11,
  148988. _psy_noisebias_11,
  148989. NULL,
  148990. NULL,
  148991. _psy_noise_suppress,
  148992. _psy_compand_8,
  148993. _psy_compand_8_mapping,
  148994. NULL,
  148995. {_noise_start_8,_noise_start_8},
  148996. {_noise_part_8,_noise_part_8},
  148997. _noise_thresh_11,
  148998. _psy_ath_floater_8,
  148999. _psy_ath_abs_8,
  149000. _psy_lowpass_11,
  149001. _psy_global_44,
  149002. _global_mapping_8,
  149003. _psy_stereo_modes_8,
  149004. _floor_books,
  149005. _floor,
  149006. _floor_mapping_11,
  149007. NULL,
  149008. _mapres_template_8_stereo
  149009. };
  149010. ve_setup_data_template ve_setup_11_uncoupled={
  149011. 2,
  149012. rate_mapping_11_uncoupled,
  149013. quality_mapping_11,
  149014. -1,
  149015. 9000,
  149016. 15000,
  149017. blocksize_11,
  149018. blocksize_11,
  149019. _psy_tone_masteratt_11,
  149020. _psy_tone_0dB,
  149021. _psy_tone_suppress,
  149022. _vp_tonemask_adj_11,
  149023. NULL,
  149024. _vp_tonemask_adj_11,
  149025. _psy_noiseguards_8,
  149026. _psy_noisebias_11,
  149027. _psy_noisebias_11,
  149028. NULL,
  149029. NULL,
  149030. _psy_noise_suppress,
  149031. _psy_compand_8,
  149032. _psy_compand_8_mapping,
  149033. NULL,
  149034. {_noise_start_8,_noise_start_8},
  149035. {_noise_part_8,_noise_part_8},
  149036. _noise_thresh_11,
  149037. _psy_ath_floater_8,
  149038. _psy_ath_abs_8,
  149039. _psy_lowpass_11,
  149040. _psy_global_44,
  149041. _global_mapping_8,
  149042. _psy_stereo_modes_8,
  149043. _floor_books,
  149044. _floor,
  149045. _floor_mapping_11,
  149046. NULL,
  149047. _mapres_template_8_uncoupled
  149048. };
  149049. /********* End of inlined file: setup_11.h *********/
  149050. /********* Start of inlined file: setup_16.h *********/
  149051. /********* Start of inlined file: psych_16.h *********/
  149052. /* stereo mode by base quality level */
  149053. static adj_stereo _psy_stereo_modes_16[4]={
  149054. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149055. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149056. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149057. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  149058. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149059. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149060. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149061. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  149062. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149063. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149064. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149065. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149066. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149067. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149068. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149069. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  149070. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149071. };
  149072. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  149073. static att3 _psy_tone_masteratt_16[4]={
  149074. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149075. {{ 25, 22, 12}, 0, 0}, /* 0 */
  149076. {{ 20, 12, 0}, 0, 0}, /* 0 */
  149077. {{ 15, 0, -14}, 0, 0}, /* 0 */
  149078. };
  149079. static vp_adjblock _vp_tonemask_adj_16[4]={
  149080. /* adjust for mode zero */
  149081. /* 63 125 250 500 1 2 4 8 16 */
  149082. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  149083. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  149084. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149085. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149086. };
  149087. static noise3 _psy_noisebias_16_short[4]={
  149088. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149089. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149090. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149091. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149092. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149093. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  149094. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149095. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149096. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  149097. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149098. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149099. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149100. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149101. };
  149102. static noise3 _psy_noisebias_16_impulse[4]={
  149103. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149104. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149105. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149106. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149107. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  149108. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  149109. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149110. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  149111. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  149112. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149113. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149114. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  149115. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149116. };
  149117. static noise3 _psy_noisebias_16[4]={
  149118. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149119. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  149120. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149121. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149122. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149123. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149124. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149125. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149126. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  149127. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149128. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149129. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149130. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149131. };
  149132. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  149133. static int _noise_start_16[3]={ 256,256,9999 };
  149134. static int _noise_part_16[4]={ 8,8,8,8 };
  149135. static int _psy_ath_floater_16[4]={
  149136. -100,-100,-100,-105,
  149137. };
  149138. static int _psy_ath_abs_16[4]={
  149139. -130,-130,-130,-140,
  149140. };
  149141. /********* End of inlined file: psych_16.h *********/
  149142. /********* Start of inlined file: residue_16.h *********/
  149143. /***** residue backends *********************************************/
  149144. static static_bookblock _resbook_16s_0={
  149145. {
  149146. {0},
  149147. {0,0,&_16c0_s_p1_0},
  149148. {0,0,&_16c0_s_p2_0},
  149149. {0,0,&_16c0_s_p3_0},
  149150. {0,0,&_16c0_s_p4_0},
  149151. {0,0,&_16c0_s_p5_0},
  149152. {0,0,&_16c0_s_p6_0},
  149153. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  149154. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  149155. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  149156. }
  149157. };
  149158. static static_bookblock _resbook_16s_1={
  149159. {
  149160. {0},
  149161. {0,0,&_16c1_s_p1_0},
  149162. {0,0,&_16c1_s_p2_0},
  149163. {0,0,&_16c1_s_p3_0},
  149164. {0,0,&_16c1_s_p4_0},
  149165. {0,0,&_16c1_s_p5_0},
  149166. {0,0,&_16c1_s_p6_0},
  149167. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  149168. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  149169. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  149170. }
  149171. };
  149172. static static_bookblock _resbook_16s_2={
  149173. {
  149174. {0},
  149175. {0,0,&_16c2_s_p1_0},
  149176. {0,0,&_16c2_s_p2_0},
  149177. {0,0,&_16c2_s_p3_0},
  149178. {0,0,&_16c2_s_p4_0},
  149179. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  149180. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  149181. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  149182. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  149183. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  149184. }
  149185. };
  149186. static vorbis_residue_template _res_16s_0[]={
  149187. {2,0, &_residue_44_mid,
  149188. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  149189. &_resbook_16s_0,&_resbook_16s_0},
  149190. };
  149191. static vorbis_residue_template _res_16s_1[]={
  149192. {2,0, &_residue_44_mid,
  149193. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  149194. &_resbook_16s_1,&_resbook_16s_1},
  149195. {2,0, &_residue_44_mid,
  149196. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  149197. &_resbook_16s_1,&_resbook_16s_1}
  149198. };
  149199. static vorbis_residue_template _res_16s_2[]={
  149200. {2,0, &_residue_44_high,
  149201. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  149202. &_resbook_16s_2,&_resbook_16s_2},
  149203. {2,0, &_residue_44_high,
  149204. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  149205. &_resbook_16s_2,&_resbook_16s_2}
  149206. };
  149207. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  149208. { _map_nominal, _res_16s_0 }, /* 0 */
  149209. { _map_nominal, _res_16s_1 }, /* 1 */
  149210. { _map_nominal, _res_16s_2 }, /* 2 */
  149211. };
  149212. static static_bookblock _resbook_16u_0={
  149213. {
  149214. {0},
  149215. {0,0,&_16u0__p1_0},
  149216. {0,0,&_16u0__p2_0},
  149217. {0,0,&_16u0__p3_0},
  149218. {0,0,&_16u0__p4_0},
  149219. {0,0,&_16u0__p5_0},
  149220. {&_16u0__p6_0,&_16u0__p6_1},
  149221. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  149222. }
  149223. };
  149224. static static_bookblock _resbook_16u_1={
  149225. {
  149226. {0},
  149227. {0,0,&_16u1__p1_0},
  149228. {0,0,&_16u1__p2_0},
  149229. {0,0,&_16u1__p3_0},
  149230. {0,0,&_16u1__p4_0},
  149231. {0,0,&_16u1__p5_0},
  149232. {0,0,&_16u1__p6_0},
  149233. {&_16u1__p7_0,&_16u1__p7_1},
  149234. {&_16u1__p8_0,&_16u1__p8_1},
  149235. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  149236. }
  149237. };
  149238. static static_bookblock _resbook_16u_2={
  149239. {
  149240. {0},
  149241. {0,0,&_16u2_p1_0},
  149242. {0,0,&_16u2_p2_0},
  149243. {0,0,&_16u2_p3_0},
  149244. {0,0,&_16u2_p4_0},
  149245. {&_16u2_p5_0,&_16u2_p5_1},
  149246. {&_16u2_p6_0,&_16u2_p6_1},
  149247. {&_16u2_p7_0,&_16u2_p7_1},
  149248. {&_16u2_p8_0,&_16u2_p8_1},
  149249. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  149250. }
  149251. };
  149252. static vorbis_residue_template _res_16u_0[]={
  149253. {1,0, &_residue_44_low_un,
  149254. &_huff_book__16u0__single,&_huff_book__16u0__single,
  149255. &_resbook_16u_0,&_resbook_16u_0},
  149256. };
  149257. static vorbis_residue_template _res_16u_1[]={
  149258. {1,0, &_residue_44_mid_un,
  149259. &_huff_book__16u1__short,&_huff_book__16u1__short,
  149260. &_resbook_16u_1,&_resbook_16u_1},
  149261. {1,0, &_residue_44_mid_un,
  149262. &_huff_book__16u1__long,&_huff_book__16u1__long,
  149263. &_resbook_16u_1,&_resbook_16u_1}
  149264. };
  149265. static vorbis_residue_template _res_16u_2[]={
  149266. {1,0, &_residue_44_hi_un,
  149267. &_huff_book__16u2__short,&_huff_book__16u2__short,
  149268. &_resbook_16u_2,&_resbook_16u_2},
  149269. {1,0, &_residue_44_hi_un,
  149270. &_huff_book__16u2__long,&_huff_book__16u2__long,
  149271. &_resbook_16u_2,&_resbook_16u_2}
  149272. };
  149273. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  149274. { _map_nominal_u, _res_16u_0 }, /* 0 */
  149275. { _map_nominal_u, _res_16u_1 }, /* 1 */
  149276. { _map_nominal_u, _res_16u_2 }, /* 2 */
  149277. };
  149278. /********* End of inlined file: residue_16.h *********/
  149279. static int blocksize_16_short[3]={
  149280. 1024,512,512
  149281. };
  149282. static int blocksize_16_long[3]={
  149283. 1024,1024,1024
  149284. };
  149285. static int _floor_mapping_16_short[3]={
  149286. 9,3,3
  149287. };
  149288. static int _floor_mapping_16[3]={
  149289. 9,9,9
  149290. };
  149291. static double rate_mapping_16[4]={
  149292. 12000.,20000.,44000.,86000.
  149293. };
  149294. static double rate_mapping_16_uncoupled[4]={
  149295. 16000.,28000.,64000.,100000.
  149296. };
  149297. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  149298. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  149299. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  149300. ve_setup_data_template ve_setup_16_stereo={
  149301. 3,
  149302. rate_mapping_16,
  149303. quality_mapping_16,
  149304. 2,
  149305. 15000,
  149306. 19000,
  149307. blocksize_16_short,
  149308. blocksize_16_long,
  149309. _psy_tone_masteratt_16,
  149310. _psy_tone_0dB,
  149311. _psy_tone_suppress,
  149312. _vp_tonemask_adj_16,
  149313. _vp_tonemask_adj_16,
  149314. _vp_tonemask_adj_16,
  149315. _psy_noiseguards_8,
  149316. _psy_noisebias_16_impulse,
  149317. _psy_noisebias_16_short,
  149318. _psy_noisebias_16_short,
  149319. _psy_noisebias_16,
  149320. _psy_noise_suppress,
  149321. _psy_compand_8,
  149322. _psy_compand_16_mapping,
  149323. _psy_compand_16_mapping,
  149324. {_noise_start_16,_noise_start_16},
  149325. { _noise_part_16, _noise_part_16},
  149326. _noise_thresh_16,
  149327. _psy_ath_floater_16,
  149328. _psy_ath_abs_16,
  149329. _psy_lowpass_16,
  149330. _psy_global_44,
  149331. _global_mapping_16,
  149332. _psy_stereo_modes_16,
  149333. _floor_books,
  149334. _floor,
  149335. _floor_mapping_16_short,
  149336. _floor_mapping_16,
  149337. _mapres_template_16_stereo
  149338. };
  149339. ve_setup_data_template ve_setup_16_uncoupled={
  149340. 3,
  149341. rate_mapping_16_uncoupled,
  149342. quality_mapping_16,
  149343. -1,
  149344. 15000,
  149345. 19000,
  149346. blocksize_16_short,
  149347. blocksize_16_long,
  149348. _psy_tone_masteratt_16,
  149349. _psy_tone_0dB,
  149350. _psy_tone_suppress,
  149351. _vp_tonemask_adj_16,
  149352. _vp_tonemask_adj_16,
  149353. _vp_tonemask_adj_16,
  149354. _psy_noiseguards_8,
  149355. _psy_noisebias_16_impulse,
  149356. _psy_noisebias_16_short,
  149357. _psy_noisebias_16_short,
  149358. _psy_noisebias_16,
  149359. _psy_noise_suppress,
  149360. _psy_compand_8,
  149361. _psy_compand_16_mapping,
  149362. _psy_compand_16_mapping,
  149363. {_noise_start_16,_noise_start_16},
  149364. { _noise_part_16, _noise_part_16},
  149365. _noise_thresh_16,
  149366. _psy_ath_floater_16,
  149367. _psy_ath_abs_16,
  149368. _psy_lowpass_16,
  149369. _psy_global_44,
  149370. _global_mapping_16,
  149371. _psy_stereo_modes_16,
  149372. _floor_books,
  149373. _floor,
  149374. _floor_mapping_16_short,
  149375. _floor_mapping_16,
  149376. _mapres_template_16_uncoupled
  149377. };
  149378. /********* End of inlined file: setup_16.h *********/
  149379. /********* Start of inlined file: setup_22.h *********/
  149380. static double rate_mapping_22[4]={
  149381. 15000.,20000.,44000.,86000.
  149382. };
  149383. static double rate_mapping_22_uncoupled[4]={
  149384. 16000.,28000.,50000.,90000.
  149385. };
  149386. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  149387. ve_setup_data_template ve_setup_22_stereo={
  149388. 3,
  149389. rate_mapping_22,
  149390. quality_mapping_16,
  149391. 2,
  149392. 19000,
  149393. 26000,
  149394. blocksize_16_short,
  149395. blocksize_16_long,
  149396. _psy_tone_masteratt_16,
  149397. _psy_tone_0dB,
  149398. _psy_tone_suppress,
  149399. _vp_tonemask_adj_16,
  149400. _vp_tonemask_adj_16,
  149401. _vp_tonemask_adj_16,
  149402. _psy_noiseguards_8,
  149403. _psy_noisebias_16_impulse,
  149404. _psy_noisebias_16_short,
  149405. _psy_noisebias_16_short,
  149406. _psy_noisebias_16,
  149407. _psy_noise_suppress,
  149408. _psy_compand_8,
  149409. _psy_compand_8_mapping,
  149410. _psy_compand_8_mapping,
  149411. {_noise_start_16,_noise_start_16},
  149412. { _noise_part_16, _noise_part_16},
  149413. _noise_thresh_16,
  149414. _psy_ath_floater_16,
  149415. _psy_ath_abs_16,
  149416. _psy_lowpass_22,
  149417. _psy_global_44,
  149418. _global_mapping_16,
  149419. _psy_stereo_modes_16,
  149420. _floor_books,
  149421. _floor,
  149422. _floor_mapping_16_short,
  149423. _floor_mapping_16,
  149424. _mapres_template_16_stereo
  149425. };
  149426. ve_setup_data_template ve_setup_22_uncoupled={
  149427. 3,
  149428. rate_mapping_22_uncoupled,
  149429. quality_mapping_16,
  149430. -1,
  149431. 19000,
  149432. 26000,
  149433. blocksize_16_short,
  149434. blocksize_16_long,
  149435. _psy_tone_masteratt_16,
  149436. _psy_tone_0dB,
  149437. _psy_tone_suppress,
  149438. _vp_tonemask_adj_16,
  149439. _vp_tonemask_adj_16,
  149440. _vp_tonemask_adj_16,
  149441. _psy_noiseguards_8,
  149442. _psy_noisebias_16_impulse,
  149443. _psy_noisebias_16_short,
  149444. _psy_noisebias_16_short,
  149445. _psy_noisebias_16,
  149446. _psy_noise_suppress,
  149447. _psy_compand_8,
  149448. _psy_compand_8_mapping,
  149449. _psy_compand_8_mapping,
  149450. {_noise_start_16,_noise_start_16},
  149451. { _noise_part_16, _noise_part_16},
  149452. _noise_thresh_16,
  149453. _psy_ath_floater_16,
  149454. _psy_ath_abs_16,
  149455. _psy_lowpass_22,
  149456. _psy_global_44,
  149457. _global_mapping_16,
  149458. _psy_stereo_modes_16,
  149459. _floor_books,
  149460. _floor,
  149461. _floor_mapping_16_short,
  149462. _floor_mapping_16,
  149463. _mapres_template_16_uncoupled
  149464. };
  149465. /********* End of inlined file: setup_22.h *********/
  149466. /********* Start of inlined file: setup_X.h *********/
  149467. static double rate_mapping_X[12]={
  149468. -1.,-1.,-1.,-1.,-1.,-1.,
  149469. -1.,-1.,-1.,-1.,-1.,-1.
  149470. };
  149471. ve_setup_data_template ve_setup_X_stereo={
  149472. 11,
  149473. rate_mapping_X,
  149474. quality_mapping_44,
  149475. 2,
  149476. 50000,
  149477. 200000,
  149478. blocksize_short_44,
  149479. blocksize_long_44,
  149480. _psy_tone_masteratt_44,
  149481. _psy_tone_0dB,
  149482. _psy_tone_suppress,
  149483. _vp_tonemask_adj_otherblock,
  149484. _vp_tonemask_adj_longblock,
  149485. _vp_tonemask_adj_otherblock,
  149486. _psy_noiseguards_44,
  149487. _psy_noisebias_impulse,
  149488. _psy_noisebias_padding,
  149489. _psy_noisebias_trans,
  149490. _psy_noisebias_long,
  149491. _psy_noise_suppress,
  149492. _psy_compand_44,
  149493. _psy_compand_short_mapping,
  149494. _psy_compand_long_mapping,
  149495. {_noise_start_short_44,_noise_start_long_44},
  149496. {_noise_part_short_44,_noise_part_long_44},
  149497. _noise_thresh_44,
  149498. _psy_ath_floater,
  149499. _psy_ath_abs,
  149500. _psy_lowpass_44,
  149501. _psy_global_44,
  149502. _global_mapping_44,
  149503. _psy_stereo_modes_44,
  149504. _floor_books,
  149505. _floor,
  149506. _floor_short_mapping_44,
  149507. _floor_long_mapping_44,
  149508. _mapres_template_44_stereo
  149509. };
  149510. ve_setup_data_template ve_setup_X_uncoupled={
  149511. 11,
  149512. rate_mapping_X,
  149513. quality_mapping_44,
  149514. -1,
  149515. 50000,
  149516. 200000,
  149517. blocksize_short_44,
  149518. blocksize_long_44,
  149519. _psy_tone_masteratt_44,
  149520. _psy_tone_0dB,
  149521. _psy_tone_suppress,
  149522. _vp_tonemask_adj_otherblock,
  149523. _vp_tonemask_adj_longblock,
  149524. _vp_tonemask_adj_otherblock,
  149525. _psy_noiseguards_44,
  149526. _psy_noisebias_impulse,
  149527. _psy_noisebias_padding,
  149528. _psy_noisebias_trans,
  149529. _psy_noisebias_long,
  149530. _psy_noise_suppress,
  149531. _psy_compand_44,
  149532. _psy_compand_short_mapping,
  149533. _psy_compand_long_mapping,
  149534. {_noise_start_short_44,_noise_start_long_44},
  149535. {_noise_part_short_44,_noise_part_long_44},
  149536. _noise_thresh_44,
  149537. _psy_ath_floater,
  149538. _psy_ath_abs,
  149539. _psy_lowpass_44,
  149540. _psy_global_44,
  149541. _global_mapping_44,
  149542. NULL,
  149543. _floor_books,
  149544. _floor,
  149545. _floor_short_mapping_44,
  149546. _floor_long_mapping_44,
  149547. _mapres_template_44_uncoupled
  149548. };
  149549. ve_setup_data_template ve_setup_XX_stereo={
  149550. 2,
  149551. rate_mapping_X,
  149552. quality_mapping_8,
  149553. 2,
  149554. 0,
  149555. 8000,
  149556. blocksize_8,
  149557. blocksize_8,
  149558. _psy_tone_masteratt_8,
  149559. _psy_tone_0dB,
  149560. _psy_tone_suppress,
  149561. _vp_tonemask_adj_8,
  149562. NULL,
  149563. _vp_tonemask_adj_8,
  149564. _psy_noiseguards_8,
  149565. _psy_noisebias_8,
  149566. _psy_noisebias_8,
  149567. NULL,
  149568. NULL,
  149569. _psy_noise_suppress,
  149570. _psy_compand_8,
  149571. _psy_compand_8_mapping,
  149572. NULL,
  149573. {_noise_start_8,_noise_start_8},
  149574. {_noise_part_8,_noise_part_8},
  149575. _noise_thresh_5only,
  149576. _psy_ath_floater_8,
  149577. _psy_ath_abs_8,
  149578. _psy_lowpass_8,
  149579. _psy_global_44,
  149580. _global_mapping_8,
  149581. _psy_stereo_modes_8,
  149582. _floor_books,
  149583. _floor,
  149584. _floor_mapping_8,
  149585. NULL,
  149586. _mapres_template_8_stereo
  149587. };
  149588. ve_setup_data_template ve_setup_XX_uncoupled={
  149589. 2,
  149590. rate_mapping_X,
  149591. quality_mapping_8,
  149592. -1,
  149593. 0,
  149594. 8000,
  149595. blocksize_8,
  149596. blocksize_8,
  149597. _psy_tone_masteratt_8,
  149598. _psy_tone_0dB,
  149599. _psy_tone_suppress,
  149600. _vp_tonemask_adj_8,
  149601. NULL,
  149602. _vp_tonemask_adj_8,
  149603. _psy_noiseguards_8,
  149604. _psy_noisebias_8,
  149605. _psy_noisebias_8,
  149606. NULL,
  149607. NULL,
  149608. _psy_noise_suppress,
  149609. _psy_compand_8,
  149610. _psy_compand_8_mapping,
  149611. NULL,
  149612. {_noise_start_8,_noise_start_8},
  149613. {_noise_part_8,_noise_part_8},
  149614. _noise_thresh_5only,
  149615. _psy_ath_floater_8,
  149616. _psy_ath_abs_8,
  149617. _psy_lowpass_8,
  149618. _psy_global_44,
  149619. _global_mapping_8,
  149620. _psy_stereo_modes_8,
  149621. _floor_books,
  149622. _floor,
  149623. _floor_mapping_8,
  149624. NULL,
  149625. _mapres_template_8_uncoupled
  149626. };
  149627. /********* End of inlined file: setup_X.h *********/
  149628. static ve_setup_data_template *setup_list[]={
  149629. &ve_setup_44_stereo,
  149630. &ve_setup_44_uncoupled,
  149631. &ve_setup_32_stereo,
  149632. &ve_setup_32_uncoupled,
  149633. &ve_setup_22_stereo,
  149634. &ve_setup_22_uncoupled,
  149635. &ve_setup_16_stereo,
  149636. &ve_setup_16_uncoupled,
  149637. &ve_setup_11_stereo,
  149638. &ve_setup_11_uncoupled,
  149639. &ve_setup_8_stereo,
  149640. &ve_setup_8_uncoupled,
  149641. &ve_setup_X_stereo,
  149642. &ve_setup_X_uncoupled,
  149643. &ve_setup_XX_stereo,
  149644. &ve_setup_XX_uncoupled,
  149645. 0
  149646. };
  149647. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  149648. if(vi && vi->codec_setup){
  149649. vi->version=0;
  149650. vi->channels=ch;
  149651. vi->rate=rate;
  149652. return(0);
  149653. }
  149654. return(OV_EINVAL);
  149655. }
  149656. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  149657. static_codebook ***books,
  149658. vorbis_info_floor1 *in,
  149659. int *x){
  149660. int i,k,is=s;
  149661. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  149662. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149663. memcpy(f,in+x[is],sizeof(*f));
  149664. /* fill in the lowpass field, even if it's temporary */
  149665. f->n=ci->blocksizes[block]>>1;
  149666. /* books */
  149667. {
  149668. int partitions=f->partitions;
  149669. int maxclass=-1;
  149670. int maxbook=-1;
  149671. for(i=0;i<partitions;i++)
  149672. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  149673. for(i=0;i<=maxclass;i++){
  149674. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  149675. f->class_book[i]+=ci->books;
  149676. for(k=0;k<(1<<f->class_subs[i]);k++){
  149677. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  149678. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  149679. }
  149680. }
  149681. for(i=0;i<=maxbook;i++)
  149682. ci->book_param[ci->books++]=books[x[is]][i];
  149683. }
  149684. /* for now, we're only using floor 1 */
  149685. ci->floor_type[ci->floors]=1;
  149686. ci->floor_param[ci->floors]=f;
  149687. ci->floors++;
  149688. return;
  149689. }
  149690. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  149691. vorbis_info_psy_global *in,
  149692. double *x){
  149693. int i,is=s;
  149694. double ds=s-is;
  149695. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149696. vorbis_info_psy_global *g=&ci->psy_g_param;
  149697. memcpy(g,in+(int)x[is],sizeof(*g));
  149698. ds=x[is]*(1.-ds)+x[is+1]*ds;
  149699. is=(int)ds;
  149700. ds-=is;
  149701. if(ds==0 && is>0){
  149702. is--;
  149703. ds=1.;
  149704. }
  149705. /* interpolate the trigger threshholds */
  149706. for(i=0;i<4;i++){
  149707. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  149708. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  149709. }
  149710. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  149711. return;
  149712. }
  149713. static void vorbis_encode_global_stereo(vorbis_info *vi,
  149714. highlevel_encode_setup *hi,
  149715. adj_stereo *p){
  149716. float s=hi->stereo_point_setting;
  149717. int i,is=s;
  149718. double ds=s-is;
  149719. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149720. vorbis_info_psy_global *g=&ci->psy_g_param;
  149721. if(p){
  149722. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  149723. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  149724. if(hi->managed){
  149725. /* interpolate the kHz threshholds */
  149726. for(i=0;i<PACKETBLOBS;i++){
  149727. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  149728. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  149729. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  149730. g->coupling_pkHz[i]=kHz;
  149731. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  149732. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  149733. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  149734. }
  149735. }else{
  149736. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  149737. for(i=0;i<PACKETBLOBS;i++){
  149738. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  149739. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  149740. g->coupling_pkHz[i]=kHz;
  149741. }
  149742. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  149743. for(i=0;i<PACKETBLOBS;i++){
  149744. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  149745. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  149746. }
  149747. }
  149748. }else{
  149749. for(i=0;i<PACKETBLOBS;i++){
  149750. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  149751. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  149752. }
  149753. }
  149754. return;
  149755. }
  149756. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  149757. int *nn_start,
  149758. int *nn_partition,
  149759. double *nn_thresh,
  149760. int block){
  149761. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149762. vorbis_info_psy *p=ci->psy_param[block];
  149763. highlevel_encode_setup *hi=&ci->hi;
  149764. int is=s;
  149765. if(block>=ci->psys)
  149766. ci->psys=block+1;
  149767. if(!p){
  149768. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  149769. ci->psy_param[block]=p;
  149770. }
  149771. memcpy(p,&_psy_info_template,sizeof(*p));
  149772. p->blockflag=block>>1;
  149773. if(hi->noise_normalize_p){
  149774. p->normal_channel_p=1;
  149775. p->normal_point_p=1;
  149776. p->normal_start=nn_start[is];
  149777. p->normal_partition=nn_partition[is];
  149778. p->normal_thresh=nn_thresh[is];
  149779. }
  149780. return;
  149781. }
  149782. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  149783. att3 *att,
  149784. int *max,
  149785. vp_adjblock *in){
  149786. int i,is=s;
  149787. double ds=s-is;
  149788. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149789. vorbis_info_psy *p=ci->psy_param[block];
  149790. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  149791. filling the values in here */
  149792. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  149793. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  149794. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  149795. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  149796. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  149797. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  149798. for(i=0;i<P_BANDS;i++)
  149799. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  149800. return;
  149801. }
  149802. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  149803. compandblock *in, double *x){
  149804. int i,is=s;
  149805. double ds=s-is;
  149806. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149807. vorbis_info_psy *p=ci->psy_param[block];
  149808. ds=x[is]*(1.-ds)+x[is+1]*ds;
  149809. is=(int)ds;
  149810. ds-=is;
  149811. if(ds==0 && is>0){
  149812. is--;
  149813. ds=1.;
  149814. }
  149815. /* interpolate the compander settings */
  149816. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  149817. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  149818. return;
  149819. }
  149820. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  149821. int *suppress){
  149822. int is=s;
  149823. double ds=s-is;
  149824. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149825. vorbis_info_psy *p=ci->psy_param[block];
  149826. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  149827. return;
  149828. }
  149829. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  149830. int *suppress,
  149831. noise3 *in,
  149832. noiseguard *guard,
  149833. double userbias){
  149834. int i,is=s,j;
  149835. double ds=s-is;
  149836. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149837. vorbis_info_psy *p=ci->psy_param[block];
  149838. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  149839. p->noisewindowlomin=guard[block].lo;
  149840. p->noisewindowhimin=guard[block].hi;
  149841. p->noisewindowfixed=guard[block].fixed;
  149842. for(j=0;j<P_NOISECURVES;j++)
  149843. for(i=0;i<P_BANDS;i++)
  149844. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  149845. /* impulse blocks may take a user specified bias to boost the
  149846. nominal/high noise encoding depth */
  149847. for(j=0;j<P_NOISECURVES;j++){
  149848. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  149849. for(i=0;i<P_BANDS;i++){
  149850. p->noiseoff[j][i]+=userbias;
  149851. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  149852. }
  149853. }
  149854. return;
  149855. }
  149856. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  149857. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149858. vorbis_info_psy *p=ci->psy_param[block];
  149859. p->ath_adjatt=ci->hi.ath_floating_dB;
  149860. p->ath_maxatt=ci->hi.ath_absolute_dB;
  149861. return;
  149862. }
  149863. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  149864. int i;
  149865. for(i=0;i<ci->books;i++)
  149866. if(ci->book_param[i]==book)return(i);
  149867. return(ci->books++);
  149868. }
  149869. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  149870. int *shortb,int *longb){
  149871. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149872. int is=s;
  149873. int blockshort=shortb[is];
  149874. int blocklong=longb[is];
  149875. ci->blocksizes[0]=blockshort;
  149876. ci->blocksizes[1]=blocklong;
  149877. }
  149878. static void vorbis_encode_residue_setup(vorbis_info *vi,
  149879. int number, int block,
  149880. vorbis_residue_template *res){
  149881. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149882. int i,n;
  149883. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  149884. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  149885. memcpy(r,res->res,sizeof(*r));
  149886. if(ci->residues<=number)ci->residues=number+1;
  149887. switch(ci->blocksizes[block]){
  149888. case 64:case 128:case 256:
  149889. r->grouping=16;
  149890. break;
  149891. default:
  149892. r->grouping=32;
  149893. break;
  149894. }
  149895. ci->residue_type[number]=res->res_type;
  149896. /* to be adjusted by lowpass/pointlimit later */
  149897. n=r->end=ci->blocksizes[block]>>1;
  149898. if(res->res_type==2)
  149899. n=r->end*=vi->channels;
  149900. /* fill in all the books */
  149901. {
  149902. int booklist=0,k;
  149903. if(ci->hi.managed){
  149904. for(i=0;i<r->partitions;i++)
  149905. for(k=0;k<3;k++)
  149906. if(res->books_base_managed->books[i][k])
  149907. r->secondstages[i]|=(1<<k);
  149908. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  149909. ci->book_param[r->groupbook]=res->book_aux_managed;
  149910. for(i=0;i<r->partitions;i++){
  149911. for(k=0;k<3;k++){
  149912. if(res->books_base_managed->books[i][k]){
  149913. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  149914. r->booklist[booklist++]=bookid;
  149915. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  149916. }
  149917. }
  149918. }
  149919. }else{
  149920. for(i=0;i<r->partitions;i++)
  149921. for(k=0;k<3;k++)
  149922. if(res->books_base->books[i][k])
  149923. r->secondstages[i]|=(1<<k);
  149924. r->groupbook=book_dup_or_new(ci,res->book_aux);
  149925. ci->book_param[r->groupbook]=res->book_aux;
  149926. for(i=0;i<r->partitions;i++){
  149927. for(k=0;k<3;k++){
  149928. if(res->books_base->books[i][k]){
  149929. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  149930. r->booklist[booklist++]=bookid;
  149931. ci->book_param[bookid]=res->books_base->books[i][k];
  149932. }
  149933. }
  149934. }
  149935. }
  149936. }
  149937. /* lowpass setup/pointlimit */
  149938. {
  149939. double freq=ci->hi.lowpass_kHz*1000.;
  149940. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  149941. double nyq=vi->rate/2.;
  149942. long blocksize=ci->blocksizes[block]>>1;
  149943. /* lowpass needs to be set in the floor and the residue. */
  149944. if(freq>nyq)freq=nyq;
  149945. /* in the floor, the granularity can be very fine; it doesn't alter
  149946. the encoding structure, only the samples used to fit the floor
  149947. approximation */
  149948. f->n=freq/nyq*blocksize;
  149949. /* this res may by limited by the maximum pointlimit of the mode,
  149950. not the lowpass. the floor is always lowpass limited. */
  149951. if(res->limit_type){
  149952. if(ci->hi.managed)
  149953. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  149954. else
  149955. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  149956. if(freq>nyq)freq=nyq;
  149957. }
  149958. /* in the residue, we're constrained, physically, by partition
  149959. boundaries. We still lowpass 'wherever', but we have to round up
  149960. here to next boundary, or the vorbis spec will round it *down* to
  149961. previous boundary in encode/decode */
  149962. if(ci->residue_type[block]==2)
  149963. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  149964. r->grouping;
  149965. else
  149966. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  149967. r->grouping;
  149968. }
  149969. }
  149970. /* we assume two maps in this encoder */
  149971. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  149972. vorbis_mapping_template *maps){
  149973. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149974. int i,j,is=s,modes=2;
  149975. vorbis_info_mapping0 *map=maps[is].map;
  149976. vorbis_info_mode *mode=_mode_template;
  149977. vorbis_residue_template *res=maps[is].res;
  149978. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  149979. for(i=0;i<modes;i++){
  149980. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  149981. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  149982. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  149983. if(i>=ci->modes)ci->modes=i+1;
  149984. ci->map_type[i]=0;
  149985. memcpy(ci->map_param[i],map+i,sizeof(*map));
  149986. if(i>=ci->maps)ci->maps=i+1;
  149987. for(j=0;j<map[i].submaps;j++)
  149988. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  149989. ,res+map[i].residuesubmap[j]);
  149990. }
  149991. }
  149992. static double setting_to_approx_bitrate(vorbis_info *vi){
  149993. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149994. highlevel_encode_setup *hi=&ci->hi;
  149995. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  149996. int is=hi->base_setting;
  149997. double ds=hi->base_setting-is;
  149998. int ch=vi->channels;
  149999. double *r=setup->rate_mapping;
  150000. if(r==NULL)
  150001. return(-1);
  150002. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  150003. }
  150004. static void get_setup_template(vorbis_info *vi,
  150005. long ch,long srate,
  150006. double req,int q_or_bitrate){
  150007. int i=0,j;
  150008. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150009. highlevel_encode_setup *hi=&ci->hi;
  150010. if(q_or_bitrate)req/=ch;
  150011. while(setup_list[i]){
  150012. if(setup_list[i]->coupling_restriction==-1 ||
  150013. setup_list[i]->coupling_restriction==ch){
  150014. if(srate>=setup_list[i]->samplerate_min_restriction &&
  150015. srate<=setup_list[i]->samplerate_max_restriction){
  150016. int mappings=setup_list[i]->mappings;
  150017. double *map=(q_or_bitrate?
  150018. setup_list[i]->rate_mapping:
  150019. setup_list[i]->quality_mapping);
  150020. /* the template matches. Does the requested quality mode
  150021. fall within this template's modes? */
  150022. if(req<map[0]){++i;continue;}
  150023. if(req>map[setup_list[i]->mappings]){++i;continue;}
  150024. for(j=0;j<mappings;j++)
  150025. if(req>=map[j] && req<map[j+1])break;
  150026. /* an all-points match */
  150027. hi->setup=setup_list[i];
  150028. if(j==mappings)
  150029. hi->base_setting=j-.001;
  150030. else{
  150031. float low=map[j];
  150032. float high=map[j+1];
  150033. float del=(req-low)/(high-low);
  150034. hi->base_setting=j+del;
  150035. }
  150036. return;
  150037. }
  150038. }
  150039. i++;
  150040. }
  150041. hi->setup=NULL;
  150042. }
  150043. /* encoders will need to use vorbis_info_init beforehand and call
  150044. vorbis_info clear when all done */
  150045. /* two interfaces; this, more detailed one, and later a convenience
  150046. layer on top */
  150047. /* the final setup call */
  150048. int vorbis_encode_setup_init(vorbis_info *vi){
  150049. int i0=0,singleblock=0;
  150050. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150051. ve_setup_data_template *setup=NULL;
  150052. highlevel_encode_setup *hi=&ci->hi;
  150053. if(ci==NULL)return(OV_EINVAL);
  150054. if(!hi->impulse_block_p)i0=1;
  150055. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  150056. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  150057. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  150058. /* again, bound this to avoid the app shooting itself int he foot
  150059. too badly */
  150060. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  150061. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  150062. /* get the appropriate setup template; matches the fetch in previous
  150063. stages */
  150064. setup=(ve_setup_data_template *)hi->setup;
  150065. if(setup==NULL)return(OV_EINVAL);
  150066. hi->set_in_stone=1;
  150067. /* choose block sizes from configured sizes as well as paying
  150068. attention to long_block_p and short_block_p. If the configured
  150069. short and long blocks are the same length, we set long_block_p
  150070. and unset short_block_p */
  150071. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  150072. setup->blocksize_short,
  150073. setup->blocksize_long);
  150074. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  150075. /* floor setup; choose proper floor params. Allocated on the floor
  150076. stack in order; if we alloc only long floor, it's 0 */
  150077. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  150078. setup->floor_books,
  150079. setup->floor_params,
  150080. setup->floor_short_mapping);
  150081. if(!singleblock)
  150082. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  150083. setup->floor_books,
  150084. setup->floor_params,
  150085. setup->floor_long_mapping);
  150086. /* setup of [mostly] short block detection and stereo*/
  150087. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  150088. setup->global_params,
  150089. setup->global_mapping);
  150090. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  150091. /* basic psych setup and noise normalization */
  150092. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150093. setup->psy_noise_normal_start[0],
  150094. setup->psy_noise_normal_partition[0],
  150095. setup->psy_noise_normal_thresh,
  150096. 0);
  150097. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150098. setup->psy_noise_normal_start[0],
  150099. setup->psy_noise_normal_partition[0],
  150100. setup->psy_noise_normal_thresh,
  150101. 1);
  150102. if(!singleblock){
  150103. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150104. setup->psy_noise_normal_start[1],
  150105. setup->psy_noise_normal_partition[1],
  150106. setup->psy_noise_normal_thresh,
  150107. 2);
  150108. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150109. setup->psy_noise_normal_start[1],
  150110. setup->psy_noise_normal_partition[1],
  150111. setup->psy_noise_normal_thresh,
  150112. 3);
  150113. }
  150114. /* tone masking setup */
  150115. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  150116. setup->psy_tone_masteratt,
  150117. setup->psy_tone_0dB,
  150118. setup->psy_tone_adj_impulse);
  150119. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  150120. setup->psy_tone_masteratt,
  150121. setup->psy_tone_0dB,
  150122. setup->psy_tone_adj_other);
  150123. if(!singleblock){
  150124. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  150125. setup->psy_tone_masteratt,
  150126. setup->psy_tone_0dB,
  150127. setup->psy_tone_adj_other);
  150128. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  150129. setup->psy_tone_masteratt,
  150130. setup->psy_tone_0dB,
  150131. setup->psy_tone_adj_long);
  150132. }
  150133. /* noise companding setup */
  150134. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  150135. setup->psy_noise_compand,
  150136. setup->psy_noise_compand_short_mapping);
  150137. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  150138. setup->psy_noise_compand,
  150139. setup->psy_noise_compand_short_mapping);
  150140. if(!singleblock){
  150141. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  150142. setup->psy_noise_compand,
  150143. setup->psy_noise_compand_long_mapping);
  150144. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  150145. setup->psy_noise_compand,
  150146. setup->psy_noise_compand_long_mapping);
  150147. }
  150148. /* peak guarding setup */
  150149. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  150150. setup->psy_tone_dBsuppress);
  150151. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  150152. setup->psy_tone_dBsuppress);
  150153. if(!singleblock){
  150154. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  150155. setup->psy_tone_dBsuppress);
  150156. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  150157. setup->psy_tone_dBsuppress);
  150158. }
  150159. /* noise bias setup */
  150160. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  150161. setup->psy_noise_dBsuppress,
  150162. setup->psy_noise_bias_impulse,
  150163. setup->psy_noiseguards,
  150164. (i0==0?hi->impulse_noisetune:0.));
  150165. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  150166. setup->psy_noise_dBsuppress,
  150167. setup->psy_noise_bias_padding,
  150168. setup->psy_noiseguards,0.);
  150169. if(!singleblock){
  150170. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  150171. setup->psy_noise_dBsuppress,
  150172. setup->psy_noise_bias_trans,
  150173. setup->psy_noiseguards,0.);
  150174. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  150175. setup->psy_noise_dBsuppress,
  150176. setup->psy_noise_bias_long,
  150177. setup->psy_noiseguards,0.);
  150178. }
  150179. vorbis_encode_ath_setup(vi,0);
  150180. vorbis_encode_ath_setup(vi,1);
  150181. if(!singleblock){
  150182. vorbis_encode_ath_setup(vi,2);
  150183. vorbis_encode_ath_setup(vi,3);
  150184. }
  150185. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  150186. /* set bitrate readonlies and management */
  150187. if(hi->bitrate_av>0)
  150188. vi->bitrate_nominal=hi->bitrate_av;
  150189. else{
  150190. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  150191. }
  150192. vi->bitrate_lower=hi->bitrate_min;
  150193. vi->bitrate_upper=hi->bitrate_max;
  150194. if(hi->bitrate_av)
  150195. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  150196. else
  150197. vi->bitrate_window=0.;
  150198. if(hi->managed){
  150199. ci->bi.avg_rate=hi->bitrate_av;
  150200. ci->bi.min_rate=hi->bitrate_min;
  150201. ci->bi.max_rate=hi->bitrate_max;
  150202. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  150203. ci->bi.reservoir_bias=
  150204. hi->bitrate_reservoir_bias;
  150205. ci->bi.slew_damp=hi->bitrate_av_damp;
  150206. }
  150207. return(0);
  150208. }
  150209. static int vorbis_encode_setup_setting(vorbis_info *vi,
  150210. long channels,
  150211. long rate){
  150212. int ret=0,i,is;
  150213. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150214. highlevel_encode_setup *hi=&ci->hi;
  150215. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  150216. double ds;
  150217. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  150218. if(ret)return(ret);
  150219. is=hi->base_setting;
  150220. ds=hi->base_setting-is;
  150221. hi->short_setting=hi->base_setting;
  150222. hi->long_setting=hi->base_setting;
  150223. hi->managed=0;
  150224. hi->impulse_block_p=1;
  150225. hi->noise_normalize_p=1;
  150226. hi->stereo_point_setting=hi->base_setting;
  150227. hi->lowpass_kHz=
  150228. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  150229. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  150230. setup->psy_ath_float[is+1]*ds;
  150231. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  150232. setup->psy_ath_abs[is+1]*ds;
  150233. hi->amplitude_track_dBpersec=-6.;
  150234. hi->trigger_setting=hi->base_setting;
  150235. for(i=0;i<4;i++){
  150236. hi->block[i].tone_mask_setting=hi->base_setting;
  150237. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  150238. hi->block[i].noise_bias_setting=hi->base_setting;
  150239. hi->block[i].noise_compand_setting=hi->base_setting;
  150240. }
  150241. return(ret);
  150242. }
  150243. int vorbis_encode_setup_vbr(vorbis_info *vi,
  150244. long channels,
  150245. long rate,
  150246. float quality){
  150247. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150248. highlevel_encode_setup *hi=&ci->hi;
  150249. quality+=.0000001;
  150250. if(quality>=1.)quality=.9999;
  150251. get_setup_template(vi,channels,rate,quality,0);
  150252. if(!hi->setup)return OV_EIMPL;
  150253. return vorbis_encode_setup_setting(vi,channels,rate);
  150254. }
  150255. int vorbis_encode_init_vbr(vorbis_info *vi,
  150256. long channels,
  150257. long rate,
  150258. float base_quality /* 0. to 1. */
  150259. ){
  150260. int ret=0;
  150261. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  150262. if(ret){
  150263. vorbis_info_clear(vi);
  150264. return ret;
  150265. }
  150266. ret=vorbis_encode_setup_init(vi);
  150267. if(ret)
  150268. vorbis_info_clear(vi);
  150269. return(ret);
  150270. }
  150271. int vorbis_encode_setup_managed(vorbis_info *vi,
  150272. long channels,
  150273. long rate,
  150274. long max_bitrate,
  150275. long nominal_bitrate,
  150276. long min_bitrate){
  150277. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150278. highlevel_encode_setup *hi=&ci->hi;
  150279. double tnominal=nominal_bitrate;
  150280. int ret=0;
  150281. if(nominal_bitrate<=0.){
  150282. if(max_bitrate>0.){
  150283. if(min_bitrate>0.)
  150284. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  150285. else
  150286. nominal_bitrate=max_bitrate*.875;
  150287. }else{
  150288. if(min_bitrate>0.){
  150289. nominal_bitrate=min_bitrate;
  150290. }else{
  150291. return(OV_EINVAL);
  150292. }
  150293. }
  150294. }
  150295. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  150296. if(!hi->setup)return OV_EIMPL;
  150297. ret=vorbis_encode_setup_setting(vi,channels,rate);
  150298. if(ret){
  150299. vorbis_info_clear(vi);
  150300. return ret;
  150301. }
  150302. /* initialize management with sane defaults */
  150303. hi->managed=1;
  150304. hi->bitrate_min=min_bitrate;
  150305. hi->bitrate_max=max_bitrate;
  150306. hi->bitrate_av=tnominal;
  150307. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  150308. hi->bitrate_reservoir=nominal_bitrate*2;
  150309. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  150310. return(ret);
  150311. }
  150312. int vorbis_encode_init(vorbis_info *vi,
  150313. long channels,
  150314. long rate,
  150315. long max_bitrate,
  150316. long nominal_bitrate,
  150317. long min_bitrate){
  150318. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  150319. max_bitrate,
  150320. nominal_bitrate,
  150321. min_bitrate);
  150322. if(ret){
  150323. vorbis_info_clear(vi);
  150324. return(ret);
  150325. }
  150326. ret=vorbis_encode_setup_init(vi);
  150327. if(ret)
  150328. vorbis_info_clear(vi);
  150329. return(ret);
  150330. }
  150331. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  150332. if(vi){
  150333. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150334. highlevel_encode_setup *hi=&ci->hi;
  150335. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  150336. if(setp && hi->set_in_stone)return(OV_EINVAL);
  150337. switch(number){
  150338. /* now deprecated *****************/
  150339. case OV_ECTL_RATEMANAGE_GET:
  150340. {
  150341. struct ovectl_ratemanage_arg *ai=
  150342. (struct ovectl_ratemanage_arg *)arg;
  150343. ai->management_active=hi->managed;
  150344. ai->bitrate_hard_window=ai->bitrate_av_window=
  150345. (double)hi->bitrate_reservoir/vi->rate;
  150346. ai->bitrate_av_window_center=1.;
  150347. ai->bitrate_hard_min=hi->bitrate_min;
  150348. ai->bitrate_hard_max=hi->bitrate_max;
  150349. ai->bitrate_av_lo=hi->bitrate_av;
  150350. ai->bitrate_av_hi=hi->bitrate_av;
  150351. }
  150352. return(0);
  150353. /* now deprecated *****************/
  150354. case OV_ECTL_RATEMANAGE_SET:
  150355. {
  150356. struct ovectl_ratemanage_arg *ai=
  150357. (struct ovectl_ratemanage_arg *)arg;
  150358. if(ai==NULL){
  150359. hi->managed=0;
  150360. }else{
  150361. hi->managed=ai->management_active;
  150362. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  150363. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  150364. }
  150365. }
  150366. return 0;
  150367. /* now deprecated *****************/
  150368. case OV_ECTL_RATEMANAGE_AVG:
  150369. {
  150370. struct ovectl_ratemanage_arg *ai=
  150371. (struct ovectl_ratemanage_arg *)arg;
  150372. if(ai==NULL){
  150373. hi->bitrate_av=0;
  150374. }else{
  150375. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  150376. }
  150377. }
  150378. return(0);
  150379. /* now deprecated *****************/
  150380. case OV_ECTL_RATEMANAGE_HARD:
  150381. {
  150382. struct ovectl_ratemanage_arg *ai=
  150383. (struct ovectl_ratemanage_arg *)arg;
  150384. if(ai==NULL){
  150385. hi->bitrate_min=0;
  150386. hi->bitrate_max=0;
  150387. }else{
  150388. hi->bitrate_min=ai->bitrate_hard_min;
  150389. hi->bitrate_max=ai->bitrate_hard_max;
  150390. hi->bitrate_reservoir=ai->bitrate_hard_window*
  150391. (hi->bitrate_max+hi->bitrate_min)*.5;
  150392. }
  150393. if(hi->bitrate_reservoir<128.)
  150394. hi->bitrate_reservoir=128.;
  150395. }
  150396. return(0);
  150397. /* replacement ratemanage interface */
  150398. case OV_ECTL_RATEMANAGE2_GET:
  150399. {
  150400. struct ovectl_ratemanage2_arg *ai=
  150401. (struct ovectl_ratemanage2_arg *)arg;
  150402. if(ai==NULL)return OV_EINVAL;
  150403. ai->management_active=hi->managed;
  150404. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  150405. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  150406. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  150407. ai->bitrate_average_damping=hi->bitrate_av_damp;
  150408. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  150409. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  150410. }
  150411. return (0);
  150412. case OV_ECTL_RATEMANAGE2_SET:
  150413. {
  150414. struct ovectl_ratemanage2_arg *ai=
  150415. (struct ovectl_ratemanage2_arg *)arg;
  150416. if(ai==NULL){
  150417. hi->managed=0;
  150418. }else{
  150419. /* sanity check; only catch invariant violations */
  150420. if(ai->bitrate_limit_min_kbps>0 &&
  150421. ai->bitrate_average_kbps>0 &&
  150422. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  150423. return OV_EINVAL;
  150424. if(ai->bitrate_limit_max_kbps>0 &&
  150425. ai->bitrate_average_kbps>0 &&
  150426. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  150427. return OV_EINVAL;
  150428. if(ai->bitrate_limit_min_kbps>0 &&
  150429. ai->bitrate_limit_max_kbps>0 &&
  150430. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  150431. return OV_EINVAL;
  150432. if(ai->bitrate_average_damping <= 0.)
  150433. return OV_EINVAL;
  150434. if(ai->bitrate_limit_reservoir_bits < 0)
  150435. return OV_EINVAL;
  150436. if(ai->bitrate_limit_reservoir_bias < 0.)
  150437. return OV_EINVAL;
  150438. if(ai->bitrate_limit_reservoir_bias > 1.)
  150439. return OV_EINVAL;
  150440. hi->managed=ai->management_active;
  150441. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  150442. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  150443. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  150444. hi->bitrate_av_damp=ai->bitrate_average_damping;
  150445. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  150446. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  150447. }
  150448. }
  150449. return 0;
  150450. case OV_ECTL_LOWPASS_GET:
  150451. {
  150452. double *farg=(double *)arg;
  150453. *farg=hi->lowpass_kHz;
  150454. }
  150455. return(0);
  150456. case OV_ECTL_LOWPASS_SET:
  150457. {
  150458. double *farg=(double *)arg;
  150459. hi->lowpass_kHz=*farg;
  150460. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  150461. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  150462. }
  150463. return(0);
  150464. case OV_ECTL_IBLOCK_GET:
  150465. {
  150466. double *farg=(double *)arg;
  150467. *farg=hi->impulse_noisetune;
  150468. }
  150469. return(0);
  150470. case OV_ECTL_IBLOCK_SET:
  150471. {
  150472. double *farg=(double *)arg;
  150473. hi->impulse_noisetune=*farg;
  150474. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  150475. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  150476. }
  150477. return(0);
  150478. }
  150479. return(OV_EIMPL);
  150480. }
  150481. return(OV_EINVAL);
  150482. }
  150483. #endif
  150484. /********* End of inlined file: vorbisenc.c *********/
  150485. /********* Start of inlined file: vorbisfile.c *********/
  150486. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  150487. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  150488. // tasks..
  150489. #ifdef _MSC_VER
  150490. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  150491. #endif
  150492. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  150493. #if JUCE_USE_OGGVORBIS
  150494. #include <stdlib.h>
  150495. #include <stdio.h>
  150496. #include <errno.h>
  150497. #include <string.h>
  150498. #include <math.h>
  150499. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  150500. one logical bitstream arranged end to end (the only form of Ogg
  150501. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  150502. multiplexing] is not allowed in Vorbis) */
  150503. /* A Vorbis file can be played beginning to end (streamed) without
  150504. worrying ahead of time about chaining (see decoder_example.c). If
  150505. we have the whole file, however, and want random access
  150506. (seeking/scrubbing) or desire to know the total length/time of a
  150507. file, we need to account for the possibility of chaining. */
  150508. /* We can handle things a number of ways; we can determine the entire
  150509. bitstream structure right off the bat, or find pieces on demand.
  150510. This example determines and caches structure for the entire
  150511. bitstream, but builds a virtual decoder on the fly when moving
  150512. between links in the chain. */
  150513. /* There are also different ways to implement seeking. Enough
  150514. information exists in an Ogg bitstream to seek to
  150515. sample-granularity positions in the output. Or, one can seek by
  150516. picking some portion of the stream roughly in the desired area if
  150517. we only want coarse navigation through the stream. */
  150518. /*************************************************************************
  150519. * Many, many internal helpers. The intention is not to be confusing;
  150520. * rampant duplication and monolithic function implementation would be
  150521. * harder to understand anyway. The high level functions are last. Begin
  150522. * grokking near the end of the file */
  150523. /* read a little more data from the file/pipe into the ogg_sync framer
  150524. */
  150525. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  150526. over 8k gets what they deserve */
  150527. static long _get_data(OggVorbis_File *vf){
  150528. errno=0;
  150529. if(vf->datasource){
  150530. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  150531. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  150532. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  150533. if(bytes==0 && errno)return(-1);
  150534. return(bytes);
  150535. }else
  150536. return(0);
  150537. }
  150538. /* save a tiny smidge of verbosity to make the code more readable */
  150539. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  150540. if(vf->datasource){
  150541. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  150542. vf->offset=offset;
  150543. ogg_sync_reset(&vf->oy);
  150544. }else{
  150545. /* shouldn't happen unless someone writes a broken callback */
  150546. return;
  150547. }
  150548. }
  150549. /* The read/seek functions track absolute position within the stream */
  150550. /* from the head of the stream, get the next page. boundary specifies
  150551. if the function is allowed to fetch more data from the stream (and
  150552. how much) or only use internally buffered data.
  150553. boundary: -1) unbounded search
  150554. 0) read no additional data; use cached only
  150555. n) search for a new page beginning for n bytes
  150556. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  150557. n) found a page at absolute offset n */
  150558. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  150559. ogg_int64_t boundary){
  150560. if(boundary>0)boundary+=vf->offset;
  150561. while(1){
  150562. long more;
  150563. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  150564. more=ogg_sync_pageseek(&vf->oy,og);
  150565. if(more<0){
  150566. /* skipped n bytes */
  150567. vf->offset-=more;
  150568. }else{
  150569. if(more==0){
  150570. /* send more paramedics */
  150571. if(!boundary)return(OV_FALSE);
  150572. {
  150573. long ret=_get_data(vf);
  150574. if(ret==0)return(OV_EOF);
  150575. if(ret<0)return(OV_EREAD);
  150576. }
  150577. }else{
  150578. /* got a page. Return the offset at the page beginning,
  150579. advance the internal offset past the page end */
  150580. ogg_int64_t ret=vf->offset;
  150581. vf->offset+=more;
  150582. return(ret);
  150583. }
  150584. }
  150585. }
  150586. }
  150587. /* find the latest page beginning before the current stream cursor
  150588. position. Much dirtier than the above as Ogg doesn't have any
  150589. backward search linkage. no 'readp' as it will certainly have to
  150590. read. */
  150591. /* returns offset or OV_EREAD, OV_FAULT */
  150592. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  150593. ogg_int64_t begin=vf->offset;
  150594. ogg_int64_t end=begin;
  150595. ogg_int64_t ret;
  150596. ogg_int64_t offset=-1;
  150597. while(offset==-1){
  150598. begin-=CHUNKSIZE;
  150599. if(begin<0)
  150600. begin=0;
  150601. _seek_helper(vf,begin);
  150602. while(vf->offset<end){
  150603. ret=_get_next_page(vf,og,end-vf->offset);
  150604. if(ret==OV_EREAD)return(OV_EREAD);
  150605. if(ret<0){
  150606. break;
  150607. }else{
  150608. offset=ret;
  150609. }
  150610. }
  150611. }
  150612. /* we have the offset. Actually snork and hold the page now */
  150613. _seek_helper(vf,offset);
  150614. ret=_get_next_page(vf,og,CHUNKSIZE);
  150615. if(ret<0)
  150616. /* this shouldn't be possible */
  150617. return(OV_EFAULT);
  150618. return(offset);
  150619. }
  150620. /* finds each bitstream link one at a time using a bisection search
  150621. (has to begin by knowing the offset of the lb's initial page).
  150622. Recurses for each link so it can alloc the link storage after
  150623. finding them all, then unroll and fill the cache at the same time */
  150624. static int _bisect_forward_serialno(OggVorbis_File *vf,
  150625. ogg_int64_t begin,
  150626. ogg_int64_t searched,
  150627. ogg_int64_t end,
  150628. long currentno,
  150629. long m){
  150630. ogg_int64_t endsearched=end;
  150631. ogg_int64_t next=end;
  150632. ogg_page og;
  150633. ogg_int64_t ret;
  150634. /* the below guards against garbage seperating the last and
  150635. first pages of two links. */
  150636. while(searched<endsearched){
  150637. ogg_int64_t bisect;
  150638. if(endsearched-searched<CHUNKSIZE){
  150639. bisect=searched;
  150640. }else{
  150641. bisect=(searched+endsearched)/2;
  150642. }
  150643. _seek_helper(vf,bisect);
  150644. ret=_get_next_page(vf,&og,-1);
  150645. if(ret==OV_EREAD)return(OV_EREAD);
  150646. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  150647. endsearched=bisect;
  150648. if(ret>=0)next=ret;
  150649. }else{
  150650. searched=ret+og.header_len+og.body_len;
  150651. }
  150652. }
  150653. _seek_helper(vf,next);
  150654. ret=_get_next_page(vf,&og,-1);
  150655. if(ret==OV_EREAD)return(OV_EREAD);
  150656. if(searched>=end || ret<0){
  150657. vf->links=m+1;
  150658. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  150659. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  150660. vf->offsets[m+1]=searched;
  150661. }else{
  150662. ret=_bisect_forward_serialno(vf,next,vf->offset,
  150663. end,ogg_page_serialno(&og),m+1);
  150664. if(ret==OV_EREAD)return(OV_EREAD);
  150665. }
  150666. vf->offsets[m]=begin;
  150667. vf->serialnos[m]=currentno;
  150668. return(0);
  150669. }
  150670. /* uses the local ogg_stream storage in vf; this is important for
  150671. non-streaming input sources */
  150672. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  150673. long *serialno,ogg_page *og_ptr){
  150674. ogg_page og;
  150675. ogg_packet op;
  150676. int i,ret;
  150677. if(!og_ptr){
  150678. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  150679. if(llret==OV_EREAD)return(OV_EREAD);
  150680. if(llret<0)return OV_ENOTVORBIS;
  150681. og_ptr=&og;
  150682. }
  150683. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  150684. if(serialno)*serialno=vf->os.serialno;
  150685. vf->ready_state=STREAMSET;
  150686. /* extract the initial header from the first page and verify that the
  150687. Ogg bitstream is in fact Vorbis data */
  150688. vorbis_info_init(vi);
  150689. vorbis_comment_init(vc);
  150690. i=0;
  150691. while(i<3){
  150692. ogg_stream_pagein(&vf->os,og_ptr);
  150693. while(i<3){
  150694. int result=ogg_stream_packetout(&vf->os,&op);
  150695. if(result==0)break;
  150696. if(result==-1){
  150697. ret=OV_EBADHEADER;
  150698. goto bail_header;
  150699. }
  150700. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  150701. goto bail_header;
  150702. }
  150703. i++;
  150704. }
  150705. if(i<3)
  150706. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  150707. ret=OV_EBADHEADER;
  150708. goto bail_header;
  150709. }
  150710. }
  150711. return 0;
  150712. bail_header:
  150713. vorbis_info_clear(vi);
  150714. vorbis_comment_clear(vc);
  150715. vf->ready_state=OPENED;
  150716. return ret;
  150717. }
  150718. /* last step of the OggVorbis_File initialization; get all the
  150719. vorbis_info structs and PCM positions. Only called by the seekable
  150720. initialization (local stream storage is hacked slightly; pay
  150721. attention to how that's done) */
  150722. /* this is void and does not propogate errors up because we want to be
  150723. able to open and use damaged bitstreams as well as we can. Just
  150724. watch out for missing information for links in the OggVorbis_File
  150725. struct */
  150726. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  150727. ogg_page og;
  150728. int i;
  150729. ogg_int64_t ret;
  150730. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  150731. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  150732. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  150733. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  150734. for(i=0;i<vf->links;i++){
  150735. if(i==0){
  150736. /* we already grabbed the initial header earlier. Just set the offset */
  150737. vf->dataoffsets[i]=dataoffset;
  150738. _seek_helper(vf,dataoffset);
  150739. }else{
  150740. /* seek to the location of the initial header */
  150741. _seek_helper(vf,vf->offsets[i]);
  150742. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  150743. vf->dataoffsets[i]=-1;
  150744. }else{
  150745. vf->dataoffsets[i]=vf->offset;
  150746. }
  150747. }
  150748. /* fetch beginning PCM offset */
  150749. if(vf->dataoffsets[i]!=-1){
  150750. ogg_int64_t accumulated=0;
  150751. long lastblock=-1;
  150752. int result;
  150753. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  150754. while(1){
  150755. ogg_packet op;
  150756. ret=_get_next_page(vf,&og,-1);
  150757. if(ret<0)
  150758. /* this should not be possible unless the file is
  150759. truncated/mangled */
  150760. break;
  150761. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  150762. break;
  150763. /* count blocksizes of all frames in the page */
  150764. ogg_stream_pagein(&vf->os,&og);
  150765. while((result=ogg_stream_packetout(&vf->os,&op))){
  150766. if(result>0){ /* ignore holes */
  150767. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  150768. if(lastblock!=-1)
  150769. accumulated+=(lastblock+thisblock)>>2;
  150770. lastblock=thisblock;
  150771. }
  150772. }
  150773. if(ogg_page_granulepos(&og)!=-1){
  150774. /* pcm offset of last packet on the first audio page */
  150775. accumulated= ogg_page_granulepos(&og)-accumulated;
  150776. break;
  150777. }
  150778. }
  150779. /* less than zero? This is a stream with samples trimmed off
  150780. the beginning, a normal occurrence; set the offset to zero */
  150781. if(accumulated<0)accumulated=0;
  150782. vf->pcmlengths[i*2]=accumulated;
  150783. }
  150784. /* get the PCM length of this link. To do this,
  150785. get the last page of the stream */
  150786. {
  150787. ogg_int64_t end=vf->offsets[i+1];
  150788. _seek_helper(vf,end);
  150789. while(1){
  150790. ret=_get_prev_page(vf,&og);
  150791. if(ret<0){
  150792. /* this should not be possible */
  150793. vorbis_info_clear(vf->vi+i);
  150794. vorbis_comment_clear(vf->vc+i);
  150795. break;
  150796. }
  150797. if(ogg_page_granulepos(&og)!=-1){
  150798. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  150799. break;
  150800. }
  150801. vf->offset=ret;
  150802. }
  150803. }
  150804. }
  150805. }
  150806. static int _make_decode_ready(OggVorbis_File *vf){
  150807. if(vf->ready_state>STREAMSET)return 0;
  150808. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  150809. if(vf->seekable){
  150810. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  150811. return OV_EBADLINK;
  150812. }else{
  150813. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  150814. return OV_EBADLINK;
  150815. }
  150816. vorbis_block_init(&vf->vd,&vf->vb);
  150817. vf->ready_state=INITSET;
  150818. vf->bittrack=0.f;
  150819. vf->samptrack=0.f;
  150820. return 0;
  150821. }
  150822. static int _open_seekable2(OggVorbis_File *vf){
  150823. long serialno=vf->current_serialno;
  150824. ogg_int64_t dataoffset=vf->offset, end;
  150825. ogg_page og;
  150826. /* we're partially open and have a first link header state in
  150827. storage in vf */
  150828. /* we can seek, so set out learning all about this file */
  150829. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  150830. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  150831. /* We get the offset for the last page of the physical bitstream.
  150832. Most OggVorbis files will contain a single logical bitstream */
  150833. end=_get_prev_page(vf,&og);
  150834. if(end<0)return(end);
  150835. /* more than one logical bitstream? */
  150836. if(ogg_page_serialno(&og)!=serialno){
  150837. /* Chained bitstream. Bisect-search each logical bitstream
  150838. section. Do so based on serial number only */
  150839. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  150840. }else{
  150841. /* Only one logical bitstream */
  150842. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  150843. }
  150844. /* the initial header memory is referenced by vf after; don't free it */
  150845. _prefetch_all_headers(vf,dataoffset);
  150846. return(ov_raw_seek(vf,0));
  150847. }
  150848. /* clear out the current logical bitstream decoder */
  150849. static void _decode_clear(OggVorbis_File *vf){
  150850. vorbis_dsp_clear(&vf->vd);
  150851. vorbis_block_clear(&vf->vb);
  150852. vf->ready_state=OPENED;
  150853. }
  150854. /* fetch and process a packet. Handles the case where we're at a
  150855. bitstream boundary and dumps the decoding machine. If the decoding
  150856. machine is unloaded, it loads it. It also keeps pcm_offset up to
  150857. date (seek and read both use this. seek uses a special hack with
  150858. readp).
  150859. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  150860. 0) need more data (only if readp==0)
  150861. 1) got a packet
  150862. */
  150863. static int _fetch_and_process_packet(OggVorbis_File *vf,
  150864. ogg_packet *op_in,
  150865. int readp,
  150866. int spanp){
  150867. ogg_page og;
  150868. /* handle one packet. Try to fetch it from current stream state */
  150869. /* extract packets from page */
  150870. while(1){
  150871. /* process a packet if we can. If the machine isn't loaded,
  150872. neither is a page */
  150873. if(vf->ready_state==INITSET){
  150874. while(1) {
  150875. ogg_packet op;
  150876. ogg_packet *op_ptr=(op_in?op_in:&op);
  150877. int result=ogg_stream_packetout(&vf->os,op_ptr);
  150878. ogg_int64_t granulepos;
  150879. op_in=NULL;
  150880. if(result==-1)return(OV_HOLE); /* hole in the data. */
  150881. if(result>0){
  150882. /* got a packet. process it */
  150883. granulepos=op_ptr->granulepos;
  150884. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  150885. header handling. The
  150886. header packets aren't
  150887. audio, so if/when we
  150888. submit them,
  150889. vorbis_synthesis will
  150890. reject them */
  150891. /* suck in the synthesis data and track bitrate */
  150892. {
  150893. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  150894. /* for proper use of libvorbis within libvorbisfile,
  150895. oldsamples will always be zero. */
  150896. if(oldsamples)return(OV_EFAULT);
  150897. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  150898. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  150899. vf->bittrack+=op_ptr->bytes*8;
  150900. }
  150901. /* update the pcm offset. */
  150902. if(granulepos!=-1 && !op_ptr->e_o_s){
  150903. int link=(vf->seekable?vf->current_link:0);
  150904. int i,samples;
  150905. /* this packet has a pcm_offset on it (the last packet
  150906. completed on a page carries the offset) After processing
  150907. (above), we know the pcm position of the *last* sample
  150908. ready to be returned. Find the offset of the *first*
  150909. As an aside, this trick is inaccurate if we begin
  150910. reading anew right at the last page; the end-of-stream
  150911. granulepos declares the last frame in the stream, and the
  150912. last packet of the last page may be a partial frame.
  150913. So, we need a previous granulepos from an in-sequence page
  150914. to have a reference point. Thus the !op_ptr->e_o_s clause
  150915. above */
  150916. if(vf->seekable && link>0)
  150917. granulepos-=vf->pcmlengths[link*2];
  150918. if(granulepos<0)granulepos=0; /* actually, this
  150919. shouldn't be possible
  150920. here unless the stream
  150921. is very broken */
  150922. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  150923. granulepos-=samples;
  150924. for(i=0;i<link;i++)
  150925. granulepos+=vf->pcmlengths[i*2+1];
  150926. vf->pcm_offset=granulepos;
  150927. }
  150928. return(1);
  150929. }
  150930. }
  150931. else
  150932. break;
  150933. }
  150934. }
  150935. if(vf->ready_state>=OPENED){
  150936. ogg_int64_t ret;
  150937. if(!readp)return(0);
  150938. if((ret=_get_next_page(vf,&og,-1))<0){
  150939. return(OV_EOF); /* eof.
  150940. leave unitialized */
  150941. }
  150942. /* bitrate tracking; add the header's bytes here, the body bytes
  150943. are done by packet above */
  150944. vf->bittrack+=og.header_len*8;
  150945. /* has our decoding just traversed a bitstream boundary? */
  150946. if(vf->ready_state==INITSET){
  150947. if(vf->current_serialno!=ogg_page_serialno(&og)){
  150948. if(!spanp)
  150949. return(OV_EOF);
  150950. _decode_clear(vf);
  150951. if(!vf->seekable){
  150952. vorbis_info_clear(vf->vi);
  150953. vorbis_comment_clear(vf->vc);
  150954. }
  150955. }
  150956. }
  150957. }
  150958. /* Do we need to load a new machine before submitting the page? */
  150959. /* This is different in the seekable and non-seekable cases.
  150960. In the seekable case, we already have all the header
  150961. information loaded and cached; we just initialize the machine
  150962. with it and continue on our merry way.
  150963. In the non-seekable (streaming) case, we'll only be at a
  150964. boundary if we just left the previous logical bitstream and
  150965. we're now nominally at the header of the next bitstream
  150966. */
  150967. if(vf->ready_state!=INITSET){
  150968. int link;
  150969. if(vf->ready_state<STREAMSET){
  150970. if(vf->seekable){
  150971. vf->current_serialno=ogg_page_serialno(&og);
  150972. /* match the serialno to bitstream section. We use this rather than
  150973. offset positions to avoid problems near logical bitstream
  150974. boundaries */
  150975. for(link=0;link<vf->links;link++)
  150976. if(vf->serialnos[link]==vf->current_serialno)break;
  150977. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  150978. stream. error out,
  150979. leave machine
  150980. uninitialized */
  150981. vf->current_link=link;
  150982. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150983. vf->ready_state=STREAMSET;
  150984. }else{
  150985. /* we're streaming */
  150986. /* fetch the three header packets, build the info struct */
  150987. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  150988. if(ret)return(ret);
  150989. vf->current_link++;
  150990. link=0;
  150991. }
  150992. }
  150993. {
  150994. int ret=_make_decode_ready(vf);
  150995. if(ret<0)return ret;
  150996. }
  150997. }
  150998. ogg_stream_pagein(&vf->os,&og);
  150999. }
  151000. }
  151001. /* if, eg, 64 bit stdio is configured by default, this will build with
  151002. fseek64 */
  151003. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  151004. if(f==NULL)return(-1);
  151005. return fseek(f,off,whence);
  151006. }
  151007. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  151008. long ibytes, ov_callbacks callbacks){
  151009. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  151010. int ret;
  151011. memset(vf,0,sizeof(*vf));
  151012. vf->datasource=f;
  151013. vf->callbacks = callbacks;
  151014. /* init the framing state */
  151015. ogg_sync_init(&vf->oy);
  151016. /* perhaps some data was previously read into a buffer for testing
  151017. against other stream types. Allow initialization from this
  151018. previously read data (as we may be reading from a non-seekable
  151019. stream) */
  151020. if(initial){
  151021. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  151022. memcpy(buffer,initial,ibytes);
  151023. ogg_sync_wrote(&vf->oy,ibytes);
  151024. }
  151025. /* can we seek? Stevens suggests the seek test was portable */
  151026. if(offsettest!=-1)vf->seekable=1;
  151027. /* No seeking yet; Set up a 'single' (current) logical bitstream
  151028. entry for partial open */
  151029. vf->links=1;
  151030. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  151031. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  151032. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  151033. /* Try to fetch the headers, maintaining all the storage */
  151034. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  151035. vf->datasource=NULL;
  151036. ov_clear(vf);
  151037. }else
  151038. vf->ready_state=PARTOPEN;
  151039. return(ret);
  151040. }
  151041. static int _ov_open2(OggVorbis_File *vf){
  151042. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  151043. vf->ready_state=OPENED;
  151044. if(vf->seekable){
  151045. int ret=_open_seekable2(vf);
  151046. if(ret){
  151047. vf->datasource=NULL;
  151048. ov_clear(vf);
  151049. }
  151050. return(ret);
  151051. }else
  151052. vf->ready_state=STREAMSET;
  151053. return 0;
  151054. }
  151055. /* clear out the OggVorbis_File struct */
  151056. int ov_clear(OggVorbis_File *vf){
  151057. if(vf){
  151058. vorbis_block_clear(&vf->vb);
  151059. vorbis_dsp_clear(&vf->vd);
  151060. ogg_stream_clear(&vf->os);
  151061. if(vf->vi && vf->links){
  151062. int i;
  151063. for(i=0;i<vf->links;i++){
  151064. vorbis_info_clear(vf->vi+i);
  151065. vorbis_comment_clear(vf->vc+i);
  151066. }
  151067. _ogg_free(vf->vi);
  151068. _ogg_free(vf->vc);
  151069. }
  151070. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  151071. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  151072. if(vf->serialnos)_ogg_free(vf->serialnos);
  151073. if(vf->offsets)_ogg_free(vf->offsets);
  151074. ogg_sync_clear(&vf->oy);
  151075. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  151076. memset(vf,0,sizeof(*vf));
  151077. }
  151078. #ifdef DEBUG_LEAKS
  151079. _VDBG_dump();
  151080. #endif
  151081. return(0);
  151082. }
  151083. /* inspects the OggVorbis file and finds/documents all the logical
  151084. bitstreams contained in it. Tries to be tolerant of logical
  151085. bitstream sections that are truncated/woogie.
  151086. return: -1) error
  151087. 0) OK
  151088. */
  151089. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151090. ov_callbacks callbacks){
  151091. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  151092. if(ret)return ret;
  151093. return _ov_open2(vf);
  151094. }
  151095. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151096. ov_callbacks callbacks = {
  151097. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151098. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151099. (int (*)(void *)) fclose,
  151100. (long (*)(void *)) ftell
  151101. };
  151102. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151103. }
  151104. /* cheap hack for game usage where downsampling is desirable; there's
  151105. no need for SRC as we can just do it cheaply in libvorbis. */
  151106. int ov_halfrate(OggVorbis_File *vf,int flag){
  151107. int i;
  151108. if(vf->vi==NULL)return OV_EINVAL;
  151109. if(!vf->seekable)return OV_EINVAL;
  151110. if(vf->ready_state>=STREAMSET)
  151111. _decode_clear(vf); /* clear out stream state; later on libvorbis
  151112. will be able to swap this on the fly, but
  151113. for now dumping the decode machine is needed
  151114. to reinit the MDCT lookups. 1.1 libvorbis
  151115. is planned to be able to switch on the fly */
  151116. for(i=0;i<vf->links;i++){
  151117. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  151118. ov_halfrate(vf,0);
  151119. return OV_EINVAL;
  151120. }
  151121. }
  151122. return 0;
  151123. }
  151124. int ov_halfrate_p(OggVorbis_File *vf){
  151125. if(vf->vi==NULL)return OV_EINVAL;
  151126. return vorbis_synthesis_halfrate_p(vf->vi);
  151127. }
  151128. /* Only partially open the vorbis file; test for Vorbisness, and load
  151129. the headers for the first chain. Do not seek (although test for
  151130. seekability). Use ov_test_open to finish opening the file, else
  151131. ov_clear to close/free it. Same return codes as open. */
  151132. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151133. ov_callbacks callbacks)
  151134. {
  151135. return _ov_open1(f,vf,initial,ibytes,callbacks);
  151136. }
  151137. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151138. ov_callbacks callbacks = {
  151139. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151140. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151141. (int (*)(void *)) fclose,
  151142. (long (*)(void *)) ftell
  151143. };
  151144. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151145. }
  151146. int ov_test_open(OggVorbis_File *vf){
  151147. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  151148. return _ov_open2(vf);
  151149. }
  151150. /* How many logical bitstreams in this physical bitstream? */
  151151. long ov_streams(OggVorbis_File *vf){
  151152. return vf->links;
  151153. }
  151154. /* Is the FILE * associated with vf seekable? */
  151155. long ov_seekable(OggVorbis_File *vf){
  151156. return vf->seekable;
  151157. }
  151158. /* returns the bitrate for a given logical bitstream or the entire
  151159. physical bitstream. If the file is open for random access, it will
  151160. find the *actual* average bitrate. If the file is streaming, it
  151161. returns the nominal bitrate (if set) else the average of the
  151162. upper/lower bounds (if set) else -1 (unset).
  151163. If you want the actual bitrate field settings, get them from the
  151164. vorbis_info structs */
  151165. long ov_bitrate(OggVorbis_File *vf,int i){
  151166. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151167. if(i>=vf->links)return(OV_EINVAL);
  151168. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  151169. if(i<0){
  151170. ogg_int64_t bits=0;
  151171. int i;
  151172. float br;
  151173. for(i=0;i<vf->links;i++)
  151174. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  151175. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  151176. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  151177. * so this is slightly transformed to make it work.
  151178. */
  151179. br = bits/ov_time_total(vf,-1);
  151180. return(rint(br));
  151181. }else{
  151182. if(vf->seekable){
  151183. /* return the actual bitrate */
  151184. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  151185. }else{
  151186. /* return nominal if set */
  151187. if(vf->vi[i].bitrate_nominal>0){
  151188. return vf->vi[i].bitrate_nominal;
  151189. }else{
  151190. if(vf->vi[i].bitrate_upper>0){
  151191. if(vf->vi[i].bitrate_lower>0){
  151192. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  151193. }else{
  151194. return vf->vi[i].bitrate_upper;
  151195. }
  151196. }
  151197. return(OV_FALSE);
  151198. }
  151199. }
  151200. }
  151201. }
  151202. /* returns the actual bitrate since last call. returns -1 if no
  151203. additional data to offer since last call (or at beginning of stream),
  151204. EINVAL if stream is only partially open
  151205. */
  151206. long ov_bitrate_instant(OggVorbis_File *vf){
  151207. int link=(vf->seekable?vf->current_link:0);
  151208. long ret;
  151209. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151210. if(vf->samptrack==0)return(OV_FALSE);
  151211. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  151212. vf->bittrack=0.f;
  151213. vf->samptrack=0.f;
  151214. return(ret);
  151215. }
  151216. /* Guess */
  151217. long ov_serialnumber(OggVorbis_File *vf,int i){
  151218. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  151219. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  151220. if(i<0){
  151221. return(vf->current_serialno);
  151222. }else{
  151223. return(vf->serialnos[i]);
  151224. }
  151225. }
  151226. /* returns: total raw (compressed) length of content if i==-1
  151227. raw (compressed) length of that logical bitstream for i==0 to n
  151228. OV_EINVAL if the stream is not seekable (we can't know the length)
  151229. or if stream is only partially open
  151230. */
  151231. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  151232. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151233. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151234. if(i<0){
  151235. ogg_int64_t acc=0;
  151236. int i;
  151237. for(i=0;i<vf->links;i++)
  151238. acc+=ov_raw_total(vf,i);
  151239. return(acc);
  151240. }else{
  151241. return(vf->offsets[i+1]-vf->offsets[i]);
  151242. }
  151243. }
  151244. /* returns: total PCM length (samples) of content if i==-1 PCM length
  151245. (samples) of that logical bitstream for i==0 to n
  151246. OV_EINVAL if the stream is not seekable (we can't know the
  151247. length) or only partially open
  151248. */
  151249. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  151250. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151251. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151252. if(i<0){
  151253. ogg_int64_t acc=0;
  151254. int i;
  151255. for(i=0;i<vf->links;i++)
  151256. acc+=ov_pcm_total(vf,i);
  151257. return(acc);
  151258. }else{
  151259. return(vf->pcmlengths[i*2+1]);
  151260. }
  151261. }
  151262. /* returns: total seconds of content if i==-1
  151263. seconds in that logical bitstream for i==0 to n
  151264. OV_EINVAL if the stream is not seekable (we can't know the
  151265. length) or only partially open
  151266. */
  151267. double ov_time_total(OggVorbis_File *vf,int i){
  151268. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151269. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151270. if(i<0){
  151271. double acc=0;
  151272. int i;
  151273. for(i=0;i<vf->links;i++)
  151274. acc+=ov_time_total(vf,i);
  151275. return(acc);
  151276. }else{
  151277. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  151278. }
  151279. }
  151280. /* seek to an offset relative to the *compressed* data. This also
  151281. scans packets to update the PCM cursor. It will cross a logical
  151282. bitstream boundary, but only if it can't get any packets out of the
  151283. tail of the bitstream we seek to (so no surprises).
  151284. returns zero on success, nonzero on failure */
  151285. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  151286. ogg_stream_state work_os;
  151287. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151288. if(!vf->seekable)
  151289. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  151290. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  151291. /* don't yet clear out decoding machine (if it's initialized), in
  151292. the case we're in the same link. Restart the decode lapping, and
  151293. let _fetch_and_process_packet deal with a potential bitstream
  151294. boundary */
  151295. vf->pcm_offset=-1;
  151296. ogg_stream_reset_serialno(&vf->os,
  151297. vf->current_serialno); /* must set serialno */
  151298. vorbis_synthesis_restart(&vf->vd);
  151299. _seek_helper(vf,pos);
  151300. /* we need to make sure the pcm_offset is set, but we don't want to
  151301. advance the raw cursor past good packets just to get to the first
  151302. with a granulepos. That's not equivalent behavior to beginning
  151303. decoding as immediately after the seek position as possible.
  151304. So, a hack. We use two stream states; a local scratch state and
  151305. the shared vf->os stream state. We use the local state to
  151306. scan, and the shared state as a buffer for later decode.
  151307. Unfortuantely, on the last page we still advance to last packet
  151308. because the granulepos on the last page is not necessarily on a
  151309. packet boundary, and we need to make sure the granpos is
  151310. correct.
  151311. */
  151312. {
  151313. ogg_page og;
  151314. ogg_packet op;
  151315. int lastblock=0;
  151316. int accblock=0;
  151317. int thisblock;
  151318. int eosflag;
  151319. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  151320. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  151321. return from not necessarily
  151322. starting from the beginning */
  151323. while(1){
  151324. if(vf->ready_state>=STREAMSET){
  151325. /* snarf/scan a packet if we can */
  151326. int result=ogg_stream_packetout(&work_os,&op);
  151327. if(result>0){
  151328. if(vf->vi[vf->current_link].codec_setup){
  151329. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  151330. if(thisblock<0){
  151331. ogg_stream_packetout(&vf->os,NULL);
  151332. thisblock=0;
  151333. }else{
  151334. if(eosflag)
  151335. ogg_stream_packetout(&vf->os,NULL);
  151336. else
  151337. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  151338. }
  151339. if(op.granulepos!=-1){
  151340. int i,link=vf->current_link;
  151341. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  151342. if(granulepos<0)granulepos=0;
  151343. for(i=0;i<link;i++)
  151344. granulepos+=vf->pcmlengths[i*2+1];
  151345. vf->pcm_offset=granulepos-accblock;
  151346. break;
  151347. }
  151348. lastblock=thisblock;
  151349. continue;
  151350. }else
  151351. ogg_stream_packetout(&vf->os,NULL);
  151352. }
  151353. }
  151354. if(!lastblock){
  151355. if(_get_next_page(vf,&og,-1)<0){
  151356. vf->pcm_offset=ov_pcm_total(vf,-1);
  151357. break;
  151358. }
  151359. }else{
  151360. /* huh? Bogus stream with packets but no granulepos */
  151361. vf->pcm_offset=-1;
  151362. break;
  151363. }
  151364. /* has our decoding just traversed a bitstream boundary? */
  151365. if(vf->ready_state>=STREAMSET)
  151366. if(vf->current_serialno!=ogg_page_serialno(&og)){
  151367. _decode_clear(vf); /* clear out stream state */
  151368. ogg_stream_clear(&work_os);
  151369. }
  151370. if(vf->ready_state<STREAMSET){
  151371. int link;
  151372. vf->current_serialno=ogg_page_serialno(&og);
  151373. for(link=0;link<vf->links;link++)
  151374. if(vf->serialnos[link]==vf->current_serialno)break;
  151375. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  151376. error out, leave
  151377. machine uninitialized */
  151378. vf->current_link=link;
  151379. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151380. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  151381. vf->ready_state=STREAMSET;
  151382. }
  151383. ogg_stream_pagein(&vf->os,&og);
  151384. ogg_stream_pagein(&work_os,&og);
  151385. eosflag=ogg_page_eos(&og);
  151386. }
  151387. }
  151388. ogg_stream_clear(&work_os);
  151389. vf->bittrack=0.f;
  151390. vf->samptrack=0.f;
  151391. return(0);
  151392. seek_error:
  151393. /* dump the machine so we're in a known state */
  151394. vf->pcm_offset=-1;
  151395. ogg_stream_clear(&work_os);
  151396. _decode_clear(vf);
  151397. return OV_EBADLINK;
  151398. }
  151399. /* Page granularity seek (faster than sample granularity because we
  151400. don't do the last bit of decode to find a specific sample).
  151401. Seek to the last [granule marked] page preceeding the specified pos
  151402. location, such that decoding past the returned point will quickly
  151403. arrive at the requested position. */
  151404. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  151405. int link=-1;
  151406. ogg_int64_t result=0;
  151407. ogg_int64_t total=ov_pcm_total(vf,-1);
  151408. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151409. if(!vf->seekable)return(OV_ENOSEEK);
  151410. if(pos<0 || pos>total)return(OV_EINVAL);
  151411. /* which bitstream section does this pcm offset occur in? */
  151412. for(link=vf->links-1;link>=0;link--){
  151413. total-=vf->pcmlengths[link*2+1];
  151414. if(pos>=total)break;
  151415. }
  151416. /* search within the logical bitstream for the page with the highest
  151417. pcm_pos preceeding (or equal to) pos. There is a danger here;
  151418. missing pages or incorrect frame number information in the
  151419. bitstream could make our task impossible. Account for that (it
  151420. would be an error condition) */
  151421. /* new search algorithm by HB (Nicholas Vinen) */
  151422. {
  151423. ogg_int64_t end=vf->offsets[link+1];
  151424. ogg_int64_t begin=vf->offsets[link];
  151425. ogg_int64_t begintime = vf->pcmlengths[link*2];
  151426. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  151427. ogg_int64_t target=pos-total+begintime;
  151428. ogg_int64_t best=begin;
  151429. ogg_page og;
  151430. while(begin<end){
  151431. ogg_int64_t bisect;
  151432. if(end-begin<CHUNKSIZE){
  151433. bisect=begin;
  151434. }else{
  151435. /* take a (pretty decent) guess. */
  151436. bisect=begin +
  151437. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  151438. if(bisect<=begin)
  151439. bisect=begin+1;
  151440. }
  151441. _seek_helper(vf,bisect);
  151442. while(begin<end){
  151443. result=_get_next_page(vf,&og,end-vf->offset);
  151444. if(result==OV_EREAD) goto seek_error;
  151445. if(result<0){
  151446. if(bisect<=begin+1)
  151447. end=begin; /* found it */
  151448. else{
  151449. if(bisect==0) goto seek_error;
  151450. bisect-=CHUNKSIZE;
  151451. if(bisect<=begin)bisect=begin+1;
  151452. _seek_helper(vf,bisect);
  151453. }
  151454. }else{
  151455. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  151456. if(granulepos==-1)continue;
  151457. if(granulepos<target){
  151458. best=result; /* raw offset of packet with granulepos */
  151459. begin=vf->offset; /* raw offset of next page */
  151460. begintime=granulepos;
  151461. if(target-begintime>44100)break;
  151462. bisect=begin; /* *not* begin + 1 */
  151463. }else{
  151464. if(bisect<=begin+1)
  151465. end=begin; /* found it */
  151466. else{
  151467. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  151468. end=result;
  151469. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  151470. if(bisect<=begin)bisect=begin+1;
  151471. _seek_helper(vf,bisect);
  151472. }else{
  151473. end=result;
  151474. endtime=granulepos;
  151475. break;
  151476. }
  151477. }
  151478. }
  151479. }
  151480. }
  151481. }
  151482. /* found our page. seek to it, update pcm offset. Easier case than
  151483. raw_seek, don't keep packets preceeding granulepos. */
  151484. {
  151485. ogg_page og;
  151486. ogg_packet op;
  151487. /* seek */
  151488. _seek_helper(vf,best);
  151489. vf->pcm_offset=-1;
  151490. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  151491. if(link!=vf->current_link){
  151492. /* Different link; dump entire decode machine */
  151493. _decode_clear(vf);
  151494. vf->current_link=link;
  151495. vf->current_serialno=ogg_page_serialno(&og);
  151496. vf->ready_state=STREAMSET;
  151497. }else{
  151498. vorbis_synthesis_restart(&vf->vd);
  151499. }
  151500. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151501. ogg_stream_pagein(&vf->os,&og);
  151502. /* pull out all but last packet; the one with granulepos */
  151503. while(1){
  151504. result=ogg_stream_packetpeek(&vf->os,&op);
  151505. if(result==0){
  151506. /* !!! the packet finishing this page originated on a
  151507. preceeding page. Keep fetching previous pages until we
  151508. get one with a granulepos or without the 'continued' flag
  151509. set. Then just use raw_seek for simplicity. */
  151510. _seek_helper(vf,best);
  151511. while(1){
  151512. result=_get_prev_page(vf,&og);
  151513. if(result<0) goto seek_error;
  151514. if(ogg_page_granulepos(&og)>-1 ||
  151515. !ogg_page_continued(&og)){
  151516. return ov_raw_seek(vf,result);
  151517. }
  151518. vf->offset=result;
  151519. }
  151520. }
  151521. if(result<0){
  151522. result = OV_EBADPACKET;
  151523. goto seek_error;
  151524. }
  151525. if(op.granulepos!=-1){
  151526. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  151527. if(vf->pcm_offset<0)vf->pcm_offset=0;
  151528. vf->pcm_offset+=total;
  151529. break;
  151530. }else
  151531. result=ogg_stream_packetout(&vf->os,NULL);
  151532. }
  151533. }
  151534. }
  151535. /* verify result */
  151536. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  151537. result=OV_EFAULT;
  151538. goto seek_error;
  151539. }
  151540. vf->bittrack=0.f;
  151541. vf->samptrack=0.f;
  151542. return(0);
  151543. seek_error:
  151544. /* dump machine so we're in a known state */
  151545. vf->pcm_offset=-1;
  151546. _decode_clear(vf);
  151547. return (int)result;
  151548. }
  151549. /* seek to a sample offset relative to the decompressed pcm stream
  151550. returns zero on success, nonzero on failure */
  151551. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  151552. int thisblock,lastblock=0;
  151553. int ret=ov_pcm_seek_page(vf,pos);
  151554. if(ret<0)return(ret);
  151555. if((ret=_make_decode_ready(vf)))return ret;
  151556. /* discard leading packets we don't need for the lapping of the
  151557. position we want; don't decode them */
  151558. while(1){
  151559. ogg_packet op;
  151560. ogg_page og;
  151561. int ret=ogg_stream_packetpeek(&vf->os,&op);
  151562. if(ret>0){
  151563. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  151564. if(thisblock<0){
  151565. ogg_stream_packetout(&vf->os,NULL);
  151566. continue; /* non audio packet */
  151567. }
  151568. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  151569. if(vf->pcm_offset+((thisblock+
  151570. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  151571. /* remove the packet from packet queue and track its granulepos */
  151572. ogg_stream_packetout(&vf->os,NULL);
  151573. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  151574. only tracking, no
  151575. pcm_decode */
  151576. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  151577. /* end of logical stream case is hard, especially with exact
  151578. length positioning. */
  151579. if(op.granulepos>-1){
  151580. int i;
  151581. /* always believe the stream markers */
  151582. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  151583. if(vf->pcm_offset<0)vf->pcm_offset=0;
  151584. for(i=0;i<vf->current_link;i++)
  151585. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  151586. }
  151587. lastblock=thisblock;
  151588. }else{
  151589. if(ret<0 && ret!=OV_HOLE)break;
  151590. /* suck in a new page */
  151591. if(_get_next_page(vf,&og,-1)<0)break;
  151592. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  151593. if(vf->ready_state<STREAMSET){
  151594. int link;
  151595. vf->current_serialno=ogg_page_serialno(&og);
  151596. for(link=0;link<vf->links;link++)
  151597. if(vf->serialnos[link]==vf->current_serialno)break;
  151598. if(link==vf->links)return(OV_EBADLINK);
  151599. vf->current_link=link;
  151600. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151601. vf->ready_state=STREAMSET;
  151602. ret=_make_decode_ready(vf);
  151603. if(ret)return ret;
  151604. lastblock=0;
  151605. }
  151606. ogg_stream_pagein(&vf->os,&og);
  151607. }
  151608. }
  151609. vf->bittrack=0.f;
  151610. vf->samptrack=0.f;
  151611. /* discard samples until we reach the desired position. Crossing a
  151612. logical bitstream boundary with abandon is OK. */
  151613. while(vf->pcm_offset<pos){
  151614. ogg_int64_t target=pos-vf->pcm_offset;
  151615. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151616. if(samples>target)samples=target;
  151617. vorbis_synthesis_read(&vf->vd,samples);
  151618. vf->pcm_offset+=samples;
  151619. if(samples<target)
  151620. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  151621. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  151622. }
  151623. return 0;
  151624. }
  151625. /* seek to a playback time relative to the decompressed pcm stream
  151626. returns zero on success, nonzero on failure */
  151627. int ov_time_seek(OggVorbis_File *vf,double seconds){
  151628. /* translate time to PCM position and call ov_pcm_seek */
  151629. int link=-1;
  151630. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  151631. double time_total=ov_time_total(vf,-1);
  151632. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151633. if(!vf->seekable)return(OV_ENOSEEK);
  151634. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  151635. /* which bitstream section does this time offset occur in? */
  151636. for(link=vf->links-1;link>=0;link--){
  151637. pcm_total-=vf->pcmlengths[link*2+1];
  151638. time_total-=ov_time_total(vf,link);
  151639. if(seconds>=time_total)break;
  151640. }
  151641. /* enough information to convert time offset to pcm offset */
  151642. {
  151643. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  151644. return(ov_pcm_seek(vf,target));
  151645. }
  151646. }
  151647. /* page-granularity version of ov_time_seek
  151648. returns zero on success, nonzero on failure */
  151649. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  151650. /* translate time to PCM position and call ov_pcm_seek */
  151651. int link=-1;
  151652. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  151653. double time_total=ov_time_total(vf,-1);
  151654. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151655. if(!vf->seekable)return(OV_ENOSEEK);
  151656. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  151657. /* which bitstream section does this time offset occur in? */
  151658. for(link=vf->links-1;link>=0;link--){
  151659. pcm_total-=vf->pcmlengths[link*2+1];
  151660. time_total-=ov_time_total(vf,link);
  151661. if(seconds>=time_total)break;
  151662. }
  151663. /* enough information to convert time offset to pcm offset */
  151664. {
  151665. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  151666. return(ov_pcm_seek_page(vf,target));
  151667. }
  151668. }
  151669. /* tell the current stream offset cursor. Note that seek followed by
  151670. tell will likely not give the set offset due to caching */
  151671. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  151672. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151673. return(vf->offset);
  151674. }
  151675. /* return PCM offset (sample) of next PCM sample to be read */
  151676. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  151677. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151678. return(vf->pcm_offset);
  151679. }
  151680. /* return time offset (seconds) of next PCM sample to be read */
  151681. double ov_time_tell(OggVorbis_File *vf){
  151682. int link=0;
  151683. ogg_int64_t pcm_total=0;
  151684. double time_total=0.f;
  151685. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151686. if(vf->seekable){
  151687. pcm_total=ov_pcm_total(vf,-1);
  151688. time_total=ov_time_total(vf,-1);
  151689. /* which bitstream section does this time offset occur in? */
  151690. for(link=vf->links-1;link>=0;link--){
  151691. pcm_total-=vf->pcmlengths[link*2+1];
  151692. time_total-=ov_time_total(vf,link);
  151693. if(vf->pcm_offset>=pcm_total)break;
  151694. }
  151695. }
  151696. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  151697. }
  151698. /* link: -1) return the vorbis_info struct for the bitstream section
  151699. currently being decoded
  151700. 0-n) to request information for a specific bitstream section
  151701. In the case of a non-seekable bitstream, any call returns the
  151702. current bitstream. NULL in the case that the machine is not
  151703. initialized */
  151704. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  151705. if(vf->seekable){
  151706. if(link<0)
  151707. if(vf->ready_state>=STREAMSET)
  151708. return vf->vi+vf->current_link;
  151709. else
  151710. return vf->vi;
  151711. else
  151712. if(link>=vf->links)
  151713. return NULL;
  151714. else
  151715. return vf->vi+link;
  151716. }else{
  151717. return vf->vi;
  151718. }
  151719. }
  151720. /* grr, strong typing, grr, no templates/inheritence, grr */
  151721. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  151722. if(vf->seekable){
  151723. if(link<0)
  151724. if(vf->ready_state>=STREAMSET)
  151725. return vf->vc+vf->current_link;
  151726. else
  151727. return vf->vc;
  151728. else
  151729. if(link>=vf->links)
  151730. return NULL;
  151731. else
  151732. return vf->vc+link;
  151733. }else{
  151734. return vf->vc;
  151735. }
  151736. }
  151737. static int host_is_big_endian() {
  151738. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  151739. unsigned char *bytewise = (unsigned char *)&pattern;
  151740. if (bytewise[0] == 0xfe) return 1;
  151741. return 0;
  151742. }
  151743. /* up to this point, everything could more or less hide the multiple
  151744. logical bitstream nature of chaining from the toplevel application
  151745. if the toplevel application didn't particularly care. However, at
  151746. the point that we actually read audio back, the multiple-section
  151747. nature must surface: Multiple bitstream sections do not necessarily
  151748. have to have the same number of channels or sampling rate.
  151749. ov_read returns the sequential logical bitstream number currently
  151750. being decoded along with the PCM data in order that the toplevel
  151751. application can take action on channel/sample rate changes. This
  151752. number will be incremented even for streamed (non-seekable) streams
  151753. (for seekable streams, it represents the actual logical bitstream
  151754. index within the physical bitstream. Note that the accessor
  151755. functions above are aware of this dichotomy).
  151756. input values: buffer) a buffer to hold packed PCM data for return
  151757. length) the byte length requested to be placed into buffer
  151758. bigendianp) should the data be packed LSB first (0) or
  151759. MSB first (1)
  151760. word) word size for output. currently 1 (byte) or
  151761. 2 (16 bit short)
  151762. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  151763. 0) EOF
  151764. n) number of bytes of PCM actually returned. The
  151765. below works on a packet-by-packet basis, so the
  151766. return length is not related to the 'length' passed
  151767. in, just guaranteed to fit.
  151768. *section) set to the logical bitstream number */
  151769. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  151770. int bigendianp,int word,int sgned,int *bitstream){
  151771. int i,j;
  151772. int host_endian = host_is_big_endian();
  151773. float **pcm;
  151774. long samples;
  151775. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151776. while(1){
  151777. if(vf->ready_state==INITSET){
  151778. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  151779. if(samples)break;
  151780. }
  151781. /* suck in another packet */
  151782. {
  151783. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  151784. if(ret==OV_EOF)
  151785. return(0);
  151786. if(ret<=0)
  151787. return(ret);
  151788. }
  151789. }
  151790. if(samples>0){
  151791. /* yay! proceed to pack data into the byte buffer */
  151792. long channels=ov_info(vf,-1)->channels;
  151793. long bytespersample=word * channels;
  151794. vorbis_fpu_control fpu;
  151795. (void) fpu; // (to avoid a warning about it being unused)
  151796. if(samples>length/bytespersample)samples=length/bytespersample;
  151797. if(samples <= 0)
  151798. return OV_EINVAL;
  151799. /* a tight loop to pack each size */
  151800. {
  151801. int val;
  151802. if(word==1){
  151803. int off=(sgned?0:128);
  151804. vorbis_fpu_setround(&fpu);
  151805. for(j=0;j<samples;j++)
  151806. for(i=0;i<channels;i++){
  151807. val=vorbis_ftoi(pcm[i][j]*128.f);
  151808. if(val>127)val=127;
  151809. else if(val<-128)val=-128;
  151810. *buffer++=val+off;
  151811. }
  151812. vorbis_fpu_restore(fpu);
  151813. }else{
  151814. int off=(sgned?0:32768);
  151815. if(host_endian==bigendianp){
  151816. if(sgned){
  151817. vorbis_fpu_setround(&fpu);
  151818. for(i=0;i<channels;i++) { /* It's faster in this order */
  151819. float *src=pcm[i];
  151820. short *dest=((short *)buffer)+i;
  151821. for(j=0;j<samples;j++) {
  151822. val=vorbis_ftoi(src[j]*32768.f);
  151823. if(val>32767)val=32767;
  151824. else if(val<-32768)val=-32768;
  151825. *dest=val;
  151826. dest+=channels;
  151827. }
  151828. }
  151829. vorbis_fpu_restore(fpu);
  151830. }else{
  151831. vorbis_fpu_setround(&fpu);
  151832. for(i=0;i<channels;i++) {
  151833. float *src=pcm[i];
  151834. short *dest=((short *)buffer)+i;
  151835. for(j=0;j<samples;j++) {
  151836. val=vorbis_ftoi(src[j]*32768.f);
  151837. if(val>32767)val=32767;
  151838. else if(val<-32768)val=-32768;
  151839. *dest=val+off;
  151840. dest+=channels;
  151841. }
  151842. }
  151843. vorbis_fpu_restore(fpu);
  151844. }
  151845. }else if(bigendianp){
  151846. vorbis_fpu_setround(&fpu);
  151847. for(j=0;j<samples;j++)
  151848. for(i=0;i<channels;i++){
  151849. val=vorbis_ftoi(pcm[i][j]*32768.f);
  151850. if(val>32767)val=32767;
  151851. else if(val<-32768)val=-32768;
  151852. val+=off;
  151853. *buffer++=(val>>8);
  151854. *buffer++=(val&0xff);
  151855. }
  151856. vorbis_fpu_restore(fpu);
  151857. }else{
  151858. int val;
  151859. vorbis_fpu_setround(&fpu);
  151860. for(j=0;j<samples;j++)
  151861. for(i=0;i<channels;i++){
  151862. val=vorbis_ftoi(pcm[i][j]*32768.f);
  151863. if(val>32767)val=32767;
  151864. else if(val<-32768)val=-32768;
  151865. val+=off;
  151866. *buffer++=(val&0xff);
  151867. *buffer++=(val>>8);
  151868. }
  151869. vorbis_fpu_restore(fpu);
  151870. }
  151871. }
  151872. }
  151873. vorbis_synthesis_read(&vf->vd,samples);
  151874. vf->pcm_offset+=samples;
  151875. if(bitstream)*bitstream=vf->current_link;
  151876. return(samples*bytespersample);
  151877. }else{
  151878. return(samples);
  151879. }
  151880. }
  151881. /* input values: pcm_channels) a float vector per channel of output
  151882. length) the sample length being read by the app
  151883. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  151884. 0) EOF
  151885. n) number of samples of PCM actually returned. The
  151886. below works on a packet-by-packet basis, so the
  151887. return length is not related to the 'length' passed
  151888. in, just guaranteed to fit.
  151889. *section) set to the logical bitstream number */
  151890. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  151891. int *bitstream){
  151892. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151893. while(1){
  151894. if(vf->ready_state==INITSET){
  151895. float **pcm;
  151896. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  151897. if(samples){
  151898. if(pcm_channels)*pcm_channels=pcm;
  151899. if(samples>length)samples=length;
  151900. vorbis_synthesis_read(&vf->vd,samples);
  151901. vf->pcm_offset+=samples;
  151902. if(bitstream)*bitstream=vf->current_link;
  151903. return samples;
  151904. }
  151905. }
  151906. /* suck in another packet */
  151907. {
  151908. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  151909. if(ret==OV_EOF)return(0);
  151910. if(ret<=0)return(ret);
  151911. }
  151912. }
  151913. }
  151914. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  151915. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  151916. ogg_int64_t off);
  151917. static void _ov_splice(float **pcm,float **lappcm,
  151918. int n1, int n2,
  151919. int ch1, int ch2,
  151920. float *w1, float *w2){
  151921. int i,j;
  151922. float *w=w1;
  151923. int n=n1;
  151924. if(n1>n2){
  151925. n=n2;
  151926. w=w2;
  151927. }
  151928. /* splice */
  151929. for(j=0;j<ch1 && j<ch2;j++){
  151930. float *s=lappcm[j];
  151931. float *d=pcm[j];
  151932. for(i=0;i<n;i++){
  151933. float wd=w[i]*w[i];
  151934. float ws=1.-wd;
  151935. d[i]=d[i]*wd + s[i]*ws;
  151936. }
  151937. }
  151938. /* window from zero */
  151939. for(;j<ch2;j++){
  151940. float *d=pcm[j];
  151941. for(i=0;i<n;i++){
  151942. float wd=w[i]*w[i];
  151943. d[i]=d[i]*wd;
  151944. }
  151945. }
  151946. }
  151947. /* make sure vf is INITSET */
  151948. static int _ov_initset(OggVorbis_File *vf){
  151949. while(1){
  151950. if(vf->ready_state==INITSET)break;
  151951. /* suck in another packet */
  151952. {
  151953. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  151954. if(ret<0 && ret!=OV_HOLE)return(ret);
  151955. }
  151956. }
  151957. return 0;
  151958. }
  151959. /* make sure vf is INITSET and that we have a primed buffer; if
  151960. we're crosslapping at a stream section boundary, this also makes
  151961. sure we're sanity checking against the right stream information */
  151962. static int _ov_initprime(OggVorbis_File *vf){
  151963. vorbis_dsp_state *vd=&vf->vd;
  151964. while(1){
  151965. if(vf->ready_state==INITSET)
  151966. if(vorbis_synthesis_pcmout(vd,NULL))break;
  151967. /* suck in another packet */
  151968. {
  151969. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  151970. if(ret<0 && ret!=OV_HOLE)return(ret);
  151971. }
  151972. }
  151973. return 0;
  151974. }
  151975. /* grab enough data for lapping from vf; this may be in the form of
  151976. unreturned, already-decoded pcm, remaining PCM we will need to
  151977. decode, or synthetic postextrapolation from last packets. */
  151978. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  151979. float **lappcm,int lapsize){
  151980. int lapcount=0,i;
  151981. float **pcm;
  151982. /* try first to decode the lapping data */
  151983. while(lapcount<lapsize){
  151984. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  151985. if(samples){
  151986. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  151987. for(i=0;i<vi->channels;i++)
  151988. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  151989. lapcount+=samples;
  151990. vorbis_synthesis_read(vd,samples);
  151991. }else{
  151992. /* suck in another packet */
  151993. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  151994. if(ret==OV_EOF)break;
  151995. }
  151996. }
  151997. if(lapcount<lapsize){
  151998. /* failed to get lapping data from normal decode; pry it from the
  151999. postextrapolation buffering, or the second half of the MDCT
  152000. from the last packet */
  152001. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  152002. if(samples==0){
  152003. for(i=0;i<vi->channels;i++)
  152004. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  152005. lapcount=lapsize;
  152006. }else{
  152007. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152008. for(i=0;i<vi->channels;i++)
  152009. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152010. lapcount+=samples;
  152011. }
  152012. }
  152013. }
  152014. /* this sets up crosslapping of a sample by using trailing data from
  152015. sample 1 and lapping it into the windowing buffer of sample 2 */
  152016. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  152017. vorbis_info *vi1,*vi2;
  152018. float **lappcm;
  152019. float **pcm;
  152020. float *w1,*w2;
  152021. int n1,n2,i,ret,hs1,hs2;
  152022. if(vf1==vf2)return(0); /* degenerate case */
  152023. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  152024. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  152025. /* the relevant overlap buffers must be pre-checked and pre-primed
  152026. before looking at settings in the event that priming would cross
  152027. a bitstream boundary. So, do it now */
  152028. ret=_ov_initset(vf1);
  152029. if(ret)return(ret);
  152030. ret=_ov_initprime(vf2);
  152031. if(ret)return(ret);
  152032. vi1=ov_info(vf1,-1);
  152033. vi2=ov_info(vf2,-1);
  152034. hs1=ov_halfrate_p(vf1);
  152035. hs2=ov_halfrate_p(vf2);
  152036. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  152037. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  152038. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  152039. w1=vorbis_window(&vf1->vd,0);
  152040. w2=vorbis_window(&vf2->vd,0);
  152041. for(i=0;i<vi1->channels;i++)
  152042. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152043. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  152044. /* have a lapping buffer from vf1; now to splice it into the lapping
  152045. buffer of vf2 */
  152046. /* consolidate and expose the buffer. */
  152047. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  152048. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  152049. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  152050. /* splice */
  152051. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  152052. /* done */
  152053. return(0);
  152054. }
  152055. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  152056. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  152057. vorbis_info *vi;
  152058. float **lappcm;
  152059. float **pcm;
  152060. float *w1,*w2;
  152061. int n1,n2,ch1,ch2,hs;
  152062. int i,ret;
  152063. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152064. ret=_ov_initset(vf);
  152065. if(ret)return(ret);
  152066. vi=ov_info(vf,-1);
  152067. hs=ov_halfrate_p(vf);
  152068. ch1=vi->channels;
  152069. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152070. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152071. persistent; even if the decode state
  152072. from this link gets dumped, this
  152073. window array continues to exist */
  152074. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152075. for(i=0;i<ch1;i++)
  152076. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152077. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152078. /* have lapping data; seek and prime the buffer */
  152079. ret=localseek(vf,pos);
  152080. if(ret)return ret;
  152081. ret=_ov_initprime(vf);
  152082. if(ret)return(ret);
  152083. /* Guard against cross-link changes; they're perfectly legal */
  152084. vi=ov_info(vf,-1);
  152085. ch2=vi->channels;
  152086. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152087. w2=vorbis_window(&vf->vd,0);
  152088. /* consolidate and expose the buffer. */
  152089. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152090. /* splice */
  152091. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152092. /* done */
  152093. return(0);
  152094. }
  152095. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152096. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  152097. }
  152098. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152099. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  152100. }
  152101. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152102. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  152103. }
  152104. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  152105. int (*localseek)(OggVorbis_File *,double)){
  152106. vorbis_info *vi;
  152107. float **lappcm;
  152108. float **pcm;
  152109. float *w1,*w2;
  152110. int n1,n2,ch1,ch2,hs;
  152111. int i,ret;
  152112. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152113. ret=_ov_initset(vf);
  152114. if(ret)return(ret);
  152115. vi=ov_info(vf,-1);
  152116. hs=ov_halfrate_p(vf);
  152117. ch1=vi->channels;
  152118. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152119. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152120. persistent; even if the decode state
  152121. from this link gets dumped, this
  152122. window array continues to exist */
  152123. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152124. for(i=0;i<ch1;i++)
  152125. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152126. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152127. /* have lapping data; seek and prime the buffer */
  152128. ret=localseek(vf,pos);
  152129. if(ret)return ret;
  152130. ret=_ov_initprime(vf);
  152131. if(ret)return(ret);
  152132. /* Guard against cross-link changes; they're perfectly legal */
  152133. vi=ov_info(vf,-1);
  152134. ch2=vi->channels;
  152135. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152136. w2=vorbis_window(&vf->vd,0);
  152137. /* consolidate and expose the buffer. */
  152138. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152139. /* splice */
  152140. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152141. /* done */
  152142. return(0);
  152143. }
  152144. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  152145. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  152146. }
  152147. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  152148. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  152149. }
  152150. #endif
  152151. /********* End of inlined file: vorbisfile.c *********/
  152152. /********* Start of inlined file: window.c *********/
  152153. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  152154. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  152155. // tasks..
  152156. #ifdef _MSC_VER
  152157. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  152158. #endif
  152159. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  152160. #if JUCE_USE_OGGVORBIS
  152161. #include <stdlib.h>
  152162. #include <math.h>
  152163. static float vwin64[32] = {
  152164. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  152165. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  152166. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  152167. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  152168. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  152169. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  152170. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  152171. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  152172. };
  152173. static float vwin128[64] = {
  152174. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  152175. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  152176. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  152177. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  152178. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  152179. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  152180. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  152181. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  152182. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  152183. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  152184. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  152185. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  152186. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  152187. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  152188. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  152189. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  152190. };
  152191. static float vwin256[128] = {
  152192. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  152193. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  152194. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  152195. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  152196. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  152197. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  152198. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  152199. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  152200. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  152201. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  152202. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  152203. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  152204. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  152205. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  152206. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  152207. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  152208. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  152209. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  152210. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  152211. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  152212. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  152213. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  152214. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  152215. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  152216. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  152217. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  152218. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  152219. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  152220. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  152221. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  152222. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  152223. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  152224. };
  152225. static float vwin512[256] = {
  152226. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  152227. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  152228. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  152229. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  152230. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  152231. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  152232. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  152233. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  152234. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  152235. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  152236. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  152237. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  152238. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  152239. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  152240. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  152241. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  152242. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  152243. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  152244. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  152245. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  152246. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  152247. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  152248. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  152249. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  152250. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  152251. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  152252. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  152253. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  152254. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  152255. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  152256. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  152257. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  152258. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  152259. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  152260. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  152261. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  152262. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  152263. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  152264. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  152265. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  152266. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  152267. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  152268. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  152269. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  152270. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  152271. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  152272. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  152273. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  152274. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  152275. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  152276. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  152277. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  152278. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  152279. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  152280. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  152281. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  152282. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  152283. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  152284. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  152285. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  152286. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  152287. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  152288. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  152289. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  152290. };
  152291. static float vwin1024[512] = {
  152292. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  152293. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  152294. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  152295. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  152296. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  152297. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  152298. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  152299. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  152300. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  152301. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  152302. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  152303. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  152304. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  152305. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  152306. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  152307. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  152308. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  152309. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  152310. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  152311. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  152312. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  152313. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  152314. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  152315. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  152316. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  152317. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  152318. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  152319. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  152320. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  152321. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  152322. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  152323. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  152324. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  152325. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  152326. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  152327. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  152328. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  152329. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  152330. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  152331. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  152332. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  152333. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  152334. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  152335. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  152336. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  152337. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  152338. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  152339. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  152340. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  152341. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  152342. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  152343. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  152344. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  152345. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  152346. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  152347. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  152348. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  152349. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  152350. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  152351. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  152352. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  152353. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  152354. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  152355. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  152356. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  152357. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  152358. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  152359. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  152360. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  152361. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  152362. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  152363. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  152364. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  152365. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  152366. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  152367. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  152368. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  152369. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  152370. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  152371. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  152372. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  152373. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  152374. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  152375. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  152376. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  152377. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  152378. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  152379. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  152380. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  152381. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  152382. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  152383. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  152384. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  152385. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  152386. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  152387. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  152388. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  152389. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  152390. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  152391. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  152392. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  152393. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  152394. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  152395. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  152396. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  152397. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  152398. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  152399. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  152400. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  152401. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  152402. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  152403. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  152404. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  152405. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  152406. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  152407. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  152408. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  152409. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  152410. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  152411. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  152412. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  152413. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  152414. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  152415. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  152416. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  152417. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  152418. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  152419. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  152420. };
  152421. static float vwin2048[1024] = {
  152422. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  152423. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  152424. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  152425. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  152426. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  152427. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  152428. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  152429. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  152430. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  152431. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  152432. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  152433. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  152434. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  152435. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  152436. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  152437. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  152438. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  152439. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  152440. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  152441. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  152442. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  152443. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  152444. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  152445. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  152446. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  152447. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  152448. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  152449. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  152450. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  152451. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  152452. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  152453. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  152454. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  152455. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  152456. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  152457. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  152458. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  152459. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  152460. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  152461. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  152462. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  152463. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  152464. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  152465. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  152466. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  152467. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  152468. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  152469. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  152470. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  152471. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  152472. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  152473. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  152474. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  152475. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  152476. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  152477. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  152478. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  152479. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  152480. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  152481. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  152482. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  152483. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  152484. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  152485. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  152486. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  152487. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  152488. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  152489. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  152490. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  152491. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  152492. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  152493. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  152494. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  152495. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  152496. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  152497. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  152498. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  152499. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  152500. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  152501. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  152502. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  152503. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  152504. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  152505. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  152506. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  152507. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  152508. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  152509. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  152510. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  152511. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  152512. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  152513. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  152514. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  152515. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  152516. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  152517. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  152518. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  152519. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  152520. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  152521. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  152522. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  152523. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  152524. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  152525. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  152526. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  152527. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  152528. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  152529. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  152530. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  152531. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  152532. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  152533. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  152534. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  152535. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  152536. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  152537. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  152538. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  152539. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  152540. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  152541. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  152542. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  152543. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  152544. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  152545. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  152546. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  152547. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  152548. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  152549. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  152550. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  152551. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  152552. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  152553. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  152554. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  152555. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  152556. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  152557. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  152558. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  152559. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  152560. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  152561. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  152562. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  152563. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  152564. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  152565. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  152566. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  152567. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  152568. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  152569. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  152570. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  152571. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  152572. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  152573. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  152574. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  152575. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  152576. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  152577. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  152578. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  152579. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  152580. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  152581. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  152582. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  152583. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  152584. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  152585. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  152586. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  152587. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  152588. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  152589. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  152590. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  152591. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  152592. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  152593. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  152594. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  152595. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  152596. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  152597. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  152598. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  152599. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  152600. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  152601. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  152602. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  152603. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  152604. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  152605. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  152606. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  152607. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  152608. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  152609. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  152610. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  152611. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  152612. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  152613. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  152614. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  152615. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  152616. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  152617. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  152618. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  152619. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  152620. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  152621. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  152622. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  152623. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  152624. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  152625. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  152626. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  152627. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  152628. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  152629. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  152630. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  152631. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  152632. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  152633. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  152634. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  152635. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  152636. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  152637. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  152638. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  152639. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  152640. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  152641. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  152642. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  152643. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  152644. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  152645. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  152646. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  152647. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  152648. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  152649. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  152650. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  152651. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  152652. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  152653. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  152654. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  152655. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  152656. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  152657. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  152658. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  152659. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  152660. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  152661. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  152662. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  152663. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  152664. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  152665. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  152666. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  152667. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  152668. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  152669. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  152670. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  152671. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  152672. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  152673. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  152674. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  152675. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  152676. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  152677. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  152678. };
  152679. static float vwin4096[2048] = {
  152680. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  152681. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  152682. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  152683. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  152684. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  152685. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  152686. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  152687. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  152688. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  152689. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  152690. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  152691. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  152692. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  152693. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  152694. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  152695. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  152696. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  152697. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  152698. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  152699. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  152700. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  152701. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  152702. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  152703. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  152704. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  152705. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  152706. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  152707. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  152708. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  152709. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  152710. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  152711. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  152712. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  152713. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  152714. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  152715. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  152716. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  152717. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  152718. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  152719. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  152720. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  152721. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  152722. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  152723. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  152724. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  152725. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  152726. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  152727. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  152728. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  152729. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  152730. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  152731. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  152732. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  152733. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  152734. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  152735. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  152736. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  152737. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  152738. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  152739. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  152740. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  152741. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  152742. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  152743. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  152744. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  152745. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  152746. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  152747. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  152748. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  152749. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  152750. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  152751. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  152752. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  152753. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  152754. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  152755. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  152756. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  152757. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  152758. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  152759. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  152760. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  152761. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  152762. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  152763. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  152764. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  152765. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  152766. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  152767. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  152768. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  152769. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  152770. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  152771. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  152772. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  152773. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  152774. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  152775. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  152776. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  152777. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  152778. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  152779. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  152780. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  152781. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  152782. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  152783. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  152784. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  152785. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  152786. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  152787. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  152788. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  152789. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  152790. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  152791. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  152792. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  152793. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  152794. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  152795. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  152796. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  152797. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  152798. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  152799. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  152800. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  152801. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  152802. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  152803. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  152804. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  152805. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  152806. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  152807. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  152808. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  152809. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  152810. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  152811. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  152812. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  152813. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  152814. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  152815. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  152816. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  152817. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  152818. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  152819. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  152820. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  152821. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  152822. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  152823. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  152824. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  152825. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  152826. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  152827. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  152828. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  152829. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  152830. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  152831. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  152832. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  152833. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  152834. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  152835. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  152836. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  152837. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  152838. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  152839. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  152840. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  152841. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  152842. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  152843. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  152844. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  152845. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  152846. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  152847. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  152848. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  152849. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  152850. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  152851. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  152852. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  152853. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  152854. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  152855. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  152856. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  152857. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  152858. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  152859. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  152860. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  152861. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  152862. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  152863. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  152864. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  152865. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  152866. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  152867. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  152868. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  152869. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  152870. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  152871. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  152872. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  152873. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  152874. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  152875. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  152876. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  152877. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  152878. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  152879. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  152880. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  152881. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  152882. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  152883. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  152884. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  152885. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  152886. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  152887. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  152888. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  152889. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  152890. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  152891. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  152892. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  152893. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  152894. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  152895. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  152896. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  152897. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  152898. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  152899. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  152900. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  152901. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  152902. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  152903. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  152904. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  152905. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  152906. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  152907. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  152908. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  152909. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  152910. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  152911. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  152912. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  152913. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  152914. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  152915. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  152916. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  152917. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  152918. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  152919. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  152920. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  152921. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  152922. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  152923. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  152924. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  152925. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  152926. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  152927. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  152928. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  152929. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  152930. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  152931. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  152932. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  152933. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  152934. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  152935. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  152936. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  152937. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  152938. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  152939. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  152940. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  152941. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  152942. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  152943. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  152944. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  152945. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  152946. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  152947. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  152948. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  152949. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  152950. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  152951. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  152952. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  152953. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  152954. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  152955. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  152956. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  152957. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  152958. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  152959. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  152960. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  152961. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  152962. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  152963. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  152964. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  152965. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  152966. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  152967. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  152968. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  152969. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  152970. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  152971. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  152972. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  152973. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  152974. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  152975. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  152976. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  152977. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  152978. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  152979. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  152980. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  152981. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  152982. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  152983. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  152984. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  152985. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  152986. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  152987. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  152988. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  152989. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  152990. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  152991. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  152992. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  152993. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  152994. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  152995. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  152996. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  152997. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  152998. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  152999. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  153000. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  153001. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  153002. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  153003. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  153004. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  153005. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  153006. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  153007. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  153008. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  153009. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  153010. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  153011. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  153012. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  153013. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  153014. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  153015. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  153016. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  153017. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  153018. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  153019. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  153020. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  153021. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  153022. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  153023. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  153024. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  153025. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  153026. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  153027. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  153028. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  153029. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  153030. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  153031. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  153032. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  153033. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  153034. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  153035. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  153036. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  153037. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  153038. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  153039. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  153040. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  153041. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  153042. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  153043. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  153044. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  153045. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  153046. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  153047. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  153048. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  153049. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  153050. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  153051. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  153052. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  153053. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  153054. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  153055. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  153056. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  153057. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  153058. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  153059. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  153060. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  153061. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  153062. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  153063. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  153064. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  153065. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  153066. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  153067. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  153068. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  153069. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  153070. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  153071. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  153072. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  153073. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  153074. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  153075. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  153076. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  153077. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  153078. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  153079. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  153080. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  153081. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  153082. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  153083. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  153084. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  153085. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  153086. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  153087. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  153088. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  153089. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  153090. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  153091. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  153092. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  153093. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  153094. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  153095. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  153096. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  153097. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  153098. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  153099. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  153100. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  153101. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  153102. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  153103. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  153104. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  153105. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  153106. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  153107. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  153108. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  153109. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  153110. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  153111. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  153112. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  153113. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  153114. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  153115. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  153116. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  153117. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  153118. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  153119. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  153120. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  153121. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  153122. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  153123. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  153124. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  153125. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  153126. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  153127. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  153128. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  153129. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  153130. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  153131. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  153132. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  153133. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  153134. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  153135. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  153136. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  153137. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  153138. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  153139. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  153140. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  153141. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  153142. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  153143. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  153144. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  153145. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  153146. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  153147. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  153148. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  153149. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  153150. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  153151. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  153152. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  153153. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  153154. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  153155. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  153156. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  153157. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  153158. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  153159. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  153160. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  153161. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  153162. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  153163. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  153164. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  153165. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  153166. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  153167. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  153168. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  153169. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  153170. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  153171. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  153172. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  153173. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  153174. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  153175. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  153176. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  153177. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  153178. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  153179. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  153180. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  153181. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  153182. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  153183. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  153184. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  153185. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  153186. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  153187. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  153188. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  153189. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  153190. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  153191. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153192. };
  153193. static float vwin8192[4096] = {
  153194. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  153195. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  153196. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  153197. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  153198. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  153199. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  153200. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  153201. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  153202. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  153203. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  153204. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  153205. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  153206. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  153207. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  153208. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  153209. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  153210. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  153211. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  153212. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  153213. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  153214. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  153215. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  153216. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  153217. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  153218. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  153219. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  153220. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  153221. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  153222. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  153223. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  153224. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  153225. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  153226. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  153227. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  153228. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  153229. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  153230. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  153231. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  153232. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  153233. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  153234. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  153235. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  153236. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  153237. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  153238. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  153239. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  153240. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  153241. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  153242. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  153243. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  153244. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  153245. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  153246. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  153247. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  153248. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  153249. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  153250. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  153251. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  153252. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  153253. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  153254. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  153255. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  153256. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  153257. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  153258. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  153259. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  153260. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  153261. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  153262. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  153263. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  153264. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  153265. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  153266. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  153267. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  153268. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  153269. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  153270. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  153271. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  153272. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  153273. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  153274. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  153275. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  153276. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  153277. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  153278. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  153279. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  153280. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  153281. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  153282. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  153283. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  153284. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  153285. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  153286. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  153287. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  153288. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  153289. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  153290. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  153291. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  153292. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  153293. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  153294. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  153295. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  153296. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  153297. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  153298. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  153299. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  153300. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  153301. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  153302. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  153303. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  153304. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  153305. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  153306. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  153307. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  153308. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  153309. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  153310. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  153311. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  153312. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  153313. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  153314. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  153315. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  153316. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  153317. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  153318. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  153319. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  153320. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  153321. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  153322. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  153323. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  153324. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  153325. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  153326. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  153327. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  153328. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  153329. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  153330. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  153331. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  153332. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  153333. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  153334. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  153335. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  153336. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  153337. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  153338. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  153339. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  153340. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  153341. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  153342. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  153343. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  153344. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  153345. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  153346. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  153347. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  153348. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  153349. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  153350. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  153351. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  153352. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  153353. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  153354. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  153355. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  153356. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  153357. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  153358. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  153359. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  153360. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  153361. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  153362. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  153363. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  153364. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  153365. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  153366. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  153367. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  153368. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  153369. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  153370. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  153371. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  153372. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  153373. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  153374. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  153375. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  153376. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  153377. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  153378. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  153379. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  153380. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  153381. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  153382. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  153383. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  153384. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  153385. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  153386. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  153387. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  153388. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  153389. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  153390. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  153391. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  153392. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  153393. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  153394. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  153395. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  153396. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  153397. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  153398. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  153399. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  153400. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  153401. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  153402. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  153403. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  153404. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  153405. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  153406. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  153407. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  153408. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  153409. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  153410. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  153411. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  153412. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  153413. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  153414. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  153415. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  153416. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  153417. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  153418. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  153419. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  153420. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  153421. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  153422. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  153423. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  153424. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  153425. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  153426. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  153427. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  153428. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  153429. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  153430. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  153431. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  153432. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  153433. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  153434. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  153435. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  153436. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  153437. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  153438. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  153439. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  153440. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  153441. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  153442. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  153443. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  153444. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  153445. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  153446. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  153447. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  153448. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  153449. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  153450. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  153451. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  153452. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  153453. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  153454. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  153455. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  153456. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  153457. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  153458. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  153459. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  153460. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  153461. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  153462. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  153463. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  153464. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  153465. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  153466. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  153467. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  153468. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  153469. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  153470. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  153471. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  153472. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  153473. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  153474. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  153475. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  153476. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  153477. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  153478. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  153479. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  153480. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  153481. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  153482. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  153483. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  153484. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  153485. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  153486. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  153487. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  153488. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  153489. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  153490. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  153491. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  153492. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  153493. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  153494. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  153495. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  153496. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  153497. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  153498. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  153499. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  153500. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  153501. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  153502. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  153503. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  153504. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  153505. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  153506. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  153507. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  153508. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  153509. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  153510. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  153511. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  153512. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  153513. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  153514. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  153515. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  153516. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  153517. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  153518. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  153519. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  153520. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  153521. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  153522. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  153523. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  153524. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  153525. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  153526. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  153527. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  153528. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  153529. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  153530. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  153531. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  153532. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  153533. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  153534. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  153535. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  153536. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  153537. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  153538. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  153539. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  153540. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  153541. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  153542. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  153543. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  153544. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  153545. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  153546. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  153547. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  153548. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  153549. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  153550. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  153551. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  153552. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  153553. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  153554. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  153555. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  153556. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  153557. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  153558. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  153559. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  153560. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  153561. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  153562. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  153563. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  153564. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  153565. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  153566. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  153567. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  153568. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  153569. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  153570. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  153571. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  153572. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  153573. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  153574. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  153575. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  153576. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  153577. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  153578. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  153579. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  153580. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  153581. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  153582. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  153583. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  153584. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  153585. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  153586. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  153587. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  153588. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  153589. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  153590. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  153591. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  153592. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  153593. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  153594. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  153595. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  153596. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  153597. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  153598. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  153599. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  153600. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  153601. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  153602. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  153603. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  153604. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  153605. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  153606. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  153607. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  153608. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  153609. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  153610. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  153611. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  153612. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  153613. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  153614. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  153615. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  153616. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  153617. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  153618. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  153619. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  153620. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  153621. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  153622. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  153623. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  153624. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  153625. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  153626. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  153627. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  153628. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  153629. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  153630. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  153631. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  153632. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  153633. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  153634. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  153635. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  153636. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  153637. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  153638. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  153639. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  153640. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  153641. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  153642. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  153643. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  153644. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  153645. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  153646. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  153647. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  153648. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  153649. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  153650. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  153651. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  153652. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  153653. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  153654. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  153655. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  153656. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  153657. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  153658. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  153659. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  153660. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  153661. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  153662. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  153663. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  153664. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  153665. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  153666. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  153667. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  153668. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  153669. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  153670. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  153671. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  153672. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  153673. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  153674. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  153675. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  153676. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  153677. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  153678. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  153679. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  153680. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  153681. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  153682. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  153683. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  153684. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  153685. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  153686. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  153687. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  153688. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  153689. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  153690. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  153691. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  153692. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  153693. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  153694. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  153695. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  153696. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  153697. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  153698. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  153699. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  153700. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  153701. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  153702. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  153703. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  153704. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  153705. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  153706. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  153707. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  153708. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  153709. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  153710. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  153711. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  153712. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  153713. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  153714. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  153715. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  153716. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  153717. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  153718. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  153719. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  153720. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  153721. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  153722. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  153723. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  153724. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  153725. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  153726. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  153727. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  153728. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  153729. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  153730. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  153731. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  153732. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  153733. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  153734. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  153735. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  153736. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  153737. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  153738. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  153739. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  153740. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  153741. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  153742. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  153743. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  153744. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  153745. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  153746. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  153747. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  153748. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  153749. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  153750. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  153751. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  153752. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  153753. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  153754. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  153755. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  153756. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  153757. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  153758. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  153759. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  153760. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  153761. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  153762. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  153763. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  153764. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  153765. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  153766. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  153767. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  153768. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  153769. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  153770. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  153771. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  153772. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  153773. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  153774. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  153775. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  153776. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  153777. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  153778. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  153779. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  153780. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  153781. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  153782. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  153783. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  153784. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  153785. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  153786. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  153787. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  153788. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  153789. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  153790. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  153791. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  153792. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  153793. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  153794. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  153795. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  153796. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  153797. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  153798. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  153799. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  153800. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  153801. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  153802. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  153803. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  153804. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  153805. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  153806. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  153807. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  153808. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  153809. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  153810. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  153811. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  153812. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  153813. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  153814. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  153815. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  153816. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  153817. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  153818. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  153819. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  153820. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  153821. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  153822. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  153823. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  153824. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  153825. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  153826. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  153827. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  153828. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  153829. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  153830. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  153831. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  153832. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  153833. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  153834. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  153835. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  153836. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  153837. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  153838. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  153839. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  153840. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  153841. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  153842. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  153843. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  153844. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  153845. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  153846. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  153847. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  153848. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  153849. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  153850. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  153851. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  153852. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  153853. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  153854. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  153855. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  153856. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  153857. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  153858. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  153859. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  153860. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  153861. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  153862. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  153863. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  153864. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  153865. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  153866. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  153867. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  153868. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  153869. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  153870. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  153871. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  153872. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  153873. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  153874. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  153875. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  153876. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  153877. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  153878. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  153879. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  153880. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  153881. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  153882. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  153883. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  153884. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  153885. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  153886. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  153887. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  153888. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  153889. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  153890. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  153891. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  153892. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  153893. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  153894. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  153895. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  153896. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  153897. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  153898. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  153899. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  153900. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  153901. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  153902. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  153903. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  153904. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  153905. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  153906. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  153907. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  153908. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  153909. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  153910. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  153911. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  153912. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  153913. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  153914. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  153915. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  153916. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  153917. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  153918. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  153919. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  153920. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  153921. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  153922. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  153923. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  153924. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  153925. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  153926. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  153927. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  153928. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  153929. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  153930. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  153931. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  153932. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  153933. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  153934. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  153935. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  153936. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  153937. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  153938. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  153939. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  153940. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  153941. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  153942. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  153943. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  153944. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  153945. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  153946. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  153947. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  153948. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  153949. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  153950. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  153951. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  153952. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  153953. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  153954. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  153955. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  153956. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  153957. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  153958. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  153959. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  153960. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  153961. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  153962. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  153963. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  153964. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  153965. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  153966. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  153967. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  153968. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  153969. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  153970. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  153971. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  153972. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  153973. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  153974. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  153975. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  153976. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  153977. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  153978. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  153979. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  153980. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  153981. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  153982. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  153983. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  153984. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  153985. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  153986. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  153987. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  153988. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  153989. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  153990. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  153991. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  153992. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  153993. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  153994. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  153995. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  153996. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  153997. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  153998. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  153999. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  154000. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  154001. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  154002. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  154003. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  154004. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  154005. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  154006. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  154007. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  154008. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  154009. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  154010. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  154011. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  154012. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  154013. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  154014. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  154015. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  154016. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  154017. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  154018. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  154019. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  154020. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  154021. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  154022. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  154023. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  154024. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  154025. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  154026. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  154027. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  154028. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  154029. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  154030. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  154031. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  154032. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  154033. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  154034. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  154035. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  154036. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  154037. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  154038. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  154039. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  154040. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  154041. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  154042. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  154043. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  154044. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  154045. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  154046. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  154047. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  154048. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  154049. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  154050. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  154051. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  154052. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  154053. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  154054. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  154055. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  154056. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  154057. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  154058. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  154059. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  154060. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  154061. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  154062. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  154063. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  154064. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  154065. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  154066. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  154067. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  154068. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  154069. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  154070. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  154071. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  154072. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  154073. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  154074. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  154075. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  154076. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  154077. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  154078. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  154079. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  154080. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  154081. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  154082. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  154083. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  154084. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  154085. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  154086. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  154087. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  154088. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  154089. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  154090. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  154091. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  154092. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  154093. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  154094. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  154095. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  154096. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  154097. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  154098. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  154099. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  154100. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  154101. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  154102. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  154103. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  154104. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  154105. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  154106. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  154107. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  154108. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  154109. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  154110. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  154111. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  154112. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  154113. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  154114. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  154115. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  154116. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  154117. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  154118. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  154119. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  154120. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  154121. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  154122. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  154123. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  154124. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  154125. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  154126. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  154127. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  154128. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  154129. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  154130. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  154131. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  154132. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  154133. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  154134. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  154135. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  154136. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  154137. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  154138. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  154139. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  154140. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  154141. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  154142. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  154143. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  154144. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  154145. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  154146. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  154147. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  154148. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  154149. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  154150. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  154151. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  154152. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  154153. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  154154. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  154155. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  154156. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  154157. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  154158. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  154159. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  154160. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  154161. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  154162. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  154163. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  154164. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  154165. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  154166. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  154167. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  154168. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  154169. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  154170. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  154171. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  154172. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  154173. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  154174. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  154175. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  154176. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  154177. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  154178. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  154179. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  154180. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  154181. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  154182. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  154183. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  154184. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  154185. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  154186. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  154187. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  154188. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  154189. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  154190. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  154191. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  154192. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  154193. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  154194. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  154195. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  154196. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  154197. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  154198. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  154199. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  154200. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  154201. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  154202. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  154203. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  154204. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  154205. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  154206. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  154207. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  154208. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  154209. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  154210. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  154211. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  154212. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  154213. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  154214. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  154215. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  154216. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154217. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154218. };
  154219. static float *vwin[8] = {
  154220. vwin64,
  154221. vwin128,
  154222. vwin256,
  154223. vwin512,
  154224. vwin1024,
  154225. vwin2048,
  154226. vwin4096,
  154227. vwin8192,
  154228. };
  154229. float *_vorbis_window_get(int n){
  154230. return vwin[n];
  154231. }
  154232. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  154233. int lW,int W,int nW){
  154234. lW=(W?lW:0);
  154235. nW=(W?nW:0);
  154236. {
  154237. float *windowLW=vwin[winno[lW]];
  154238. float *windowNW=vwin[winno[nW]];
  154239. long n=blocksizes[W];
  154240. long ln=blocksizes[lW];
  154241. long rn=blocksizes[nW];
  154242. long leftbegin=n/4-ln/4;
  154243. long leftend=leftbegin+ln/2;
  154244. long rightbegin=n/2+n/4-rn/4;
  154245. long rightend=rightbegin+rn/2;
  154246. int i,p;
  154247. for(i=0;i<leftbegin;i++)
  154248. d[i]=0.f;
  154249. for(p=0;i<leftend;i++,p++)
  154250. d[i]*=windowLW[p];
  154251. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  154252. d[i]*=windowNW[p];
  154253. for(;i<n;i++)
  154254. d[i]=0.f;
  154255. }
  154256. }
  154257. #endif
  154258. /********* End of inlined file: window.c *********/
  154259. #else
  154260. #include <vorbis/vorbisenc.h>
  154261. #include <vorbis/codec.h>
  154262. #include <vorbis/vorbisfile.h>
  154263. #endif
  154264. }
  154265. BEGIN_JUCE_NAMESPACE
  154266. using namespace OggVorbisNamespace;
  154267. #define oggFormatName TRANS("Ogg-Vorbis file")
  154268. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  154269. class OggReader : public AudioFormatReader
  154270. {
  154271. OggVorbis_File ovFile;
  154272. ov_callbacks callbacks;
  154273. AudioSampleBuffer reservoir;
  154274. int reservoirStart, samplesInReservoir;
  154275. public:
  154276. OggReader (InputStream* const inp)
  154277. : AudioFormatReader (inp, oggFormatName),
  154278. reservoir (2, 4096),
  154279. reservoirStart (0),
  154280. samplesInReservoir (0)
  154281. {
  154282. sampleRate = 0;
  154283. usesFloatingPointData = true;
  154284. callbacks.read_func = &oggReadCallback;
  154285. callbacks.seek_func = &oggSeekCallback;
  154286. callbacks.close_func = &oggCloseCallback;
  154287. callbacks.tell_func = &oggTellCallback;
  154288. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  154289. if (err == 0)
  154290. {
  154291. vorbis_info* info = ov_info (&ovFile, -1);
  154292. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  154293. numChannels = info->channels;
  154294. bitsPerSample = 16;
  154295. sampleRate = info->rate;
  154296. reservoir.setSize (numChannels,
  154297. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  154298. }
  154299. }
  154300. ~OggReader()
  154301. {
  154302. ov_clear (&ovFile);
  154303. }
  154304. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  154305. int64 startSampleInFile, int numSamples)
  154306. {
  154307. while (numSamples > 0)
  154308. {
  154309. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  154310. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  154311. {
  154312. // got a few samples overlapping, so use them before seeking..
  154313. const int numToUse = jmin (numSamples, numAvailable);
  154314. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  154315. if (destSamples[i] != 0)
  154316. memcpy (destSamples[i] + startOffsetInDestBuffer,
  154317. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  154318. sizeof (float) * numToUse);
  154319. startSampleInFile += numToUse;
  154320. numSamples -= numToUse;
  154321. startOffsetInDestBuffer += numToUse;
  154322. if (numSamples == 0)
  154323. break;
  154324. }
  154325. if (startSampleInFile < reservoirStart
  154326. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  154327. {
  154328. // buffer miss, so refill the reservoir
  154329. int bitStream = 0;
  154330. reservoirStart = jmax (0, (int) startSampleInFile);
  154331. samplesInReservoir = reservoir.getNumSamples();
  154332. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  154333. ov_pcm_seek (&ovFile, reservoirStart);
  154334. int offset = 0;
  154335. int numToRead = samplesInReservoir;
  154336. while (numToRead > 0)
  154337. {
  154338. float** dataIn = 0;
  154339. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  154340. if (samps == 0)
  154341. break;
  154342. jassert (samps <= numToRead);
  154343. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  154344. {
  154345. memcpy (reservoir.getSampleData (i, offset),
  154346. dataIn[i],
  154347. sizeof (float) * samps);
  154348. }
  154349. numToRead -= samps;
  154350. offset += samps;
  154351. }
  154352. if (numToRead > 0)
  154353. reservoir.clear (offset, numToRead);
  154354. }
  154355. }
  154356. if (numSamples > 0)
  154357. {
  154358. for (int i = numDestChannels; --i >= 0;)
  154359. if (destSamples[i] != 0)
  154360. zeromem (destSamples[i] + startOffsetInDestBuffer,
  154361. sizeof (int) * numSamples);
  154362. }
  154363. return true;
  154364. }
  154365. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  154366. {
  154367. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  154368. }
  154369. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  154370. {
  154371. InputStream* const in = (InputStream*) datasource;
  154372. if (whence == SEEK_CUR)
  154373. offset += in->getPosition();
  154374. else if (whence == SEEK_END)
  154375. offset += in->getTotalLength();
  154376. in->setPosition (offset);
  154377. return 0;
  154378. }
  154379. static int oggCloseCallback (void*)
  154380. {
  154381. return 0;
  154382. }
  154383. static long oggTellCallback (void* datasource)
  154384. {
  154385. return (long) ((InputStream*) datasource)->getPosition();
  154386. }
  154387. juce_UseDebuggingNewOperator
  154388. };
  154389. class OggWriter : public AudioFormatWriter
  154390. {
  154391. ogg_stream_state os;
  154392. ogg_page og;
  154393. ogg_packet op;
  154394. vorbis_info vi;
  154395. vorbis_comment vc;
  154396. vorbis_dsp_state vd;
  154397. vorbis_block vb;
  154398. public:
  154399. bool ok;
  154400. OggWriter (OutputStream* const out,
  154401. const double sampleRate,
  154402. const int numChannels,
  154403. const int bitsPerSample,
  154404. const int qualityIndex)
  154405. : AudioFormatWriter (out, oggFormatName,
  154406. sampleRate,
  154407. numChannels,
  154408. bitsPerSample)
  154409. {
  154410. ok = false;
  154411. vorbis_info_init (&vi);
  154412. if (vorbis_encode_init_vbr (&vi,
  154413. numChannels,
  154414. (int) sampleRate,
  154415. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  154416. {
  154417. vorbis_comment_init (&vc);
  154418. if (JUCEApplication::getInstance() != 0)
  154419. vorbis_comment_add_tag (&vc, "ENCODER",
  154420. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  154421. vorbis_analysis_init (&vd, &vi);
  154422. vorbis_block_init (&vd, &vb);
  154423. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  154424. ogg_packet header;
  154425. ogg_packet header_comm;
  154426. ogg_packet header_code;
  154427. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  154428. ogg_stream_packetin (&os, &header);
  154429. ogg_stream_packetin (&os, &header_comm);
  154430. ogg_stream_packetin (&os, &header_code);
  154431. for (;;)
  154432. {
  154433. if (ogg_stream_flush (&os, &og) == 0)
  154434. break;
  154435. output->write (og.header, og.header_len);
  154436. output->write (og.body, og.body_len);
  154437. }
  154438. ok = true;
  154439. }
  154440. }
  154441. ~OggWriter()
  154442. {
  154443. if (ok)
  154444. {
  154445. // write a zero-length packet to show ogg that we're finished..
  154446. write (0, 0);
  154447. ogg_stream_clear (&os);
  154448. vorbis_block_clear (&vb);
  154449. vorbis_dsp_clear (&vd);
  154450. vorbis_comment_clear (&vc);
  154451. vorbis_info_clear (&vi);
  154452. output->flush();
  154453. }
  154454. else
  154455. {
  154456. vorbis_info_clear (&vi);
  154457. output = 0; // to stop the base class deleting this, as it needs to be returned
  154458. // to the caller of createWriter()
  154459. }
  154460. }
  154461. bool write (const int** samplesToWrite, int numSamples)
  154462. {
  154463. if (! ok)
  154464. return false;
  154465. if (numSamples > 0)
  154466. {
  154467. const double gain = 1.0 / 0x80000000u;
  154468. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  154469. for (int i = numChannels; --i >= 0;)
  154470. {
  154471. float* const dst = vorbisBuffer[i];
  154472. const int* const src = samplesToWrite [i];
  154473. if (src != 0 && dst != 0)
  154474. {
  154475. for (int j = 0; j < numSamples; ++j)
  154476. dst[j] = (float) (src[j] * gain);
  154477. }
  154478. }
  154479. }
  154480. vorbis_analysis_wrote (&vd, numSamples);
  154481. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  154482. {
  154483. vorbis_analysis (&vb, 0);
  154484. vorbis_bitrate_addblock (&vb);
  154485. while (vorbis_bitrate_flushpacket (&vd, &op))
  154486. {
  154487. ogg_stream_packetin (&os, &op);
  154488. for (;;)
  154489. {
  154490. if (ogg_stream_pageout (&os, &og) == 0)
  154491. break;
  154492. output->write (og.header, og.header_len);
  154493. output->write (og.body, og.body_len);
  154494. if (ogg_page_eos (&og))
  154495. break;
  154496. }
  154497. }
  154498. }
  154499. return true;
  154500. }
  154501. juce_UseDebuggingNewOperator
  154502. };
  154503. OggVorbisAudioFormat::OggVorbisAudioFormat()
  154504. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  154505. {
  154506. }
  154507. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  154508. {
  154509. }
  154510. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  154511. {
  154512. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  154513. return Array <int> (rates);
  154514. }
  154515. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  154516. {
  154517. Array <int> depths;
  154518. depths.add (32);
  154519. return depths;
  154520. }
  154521. bool OggVorbisAudioFormat::canDoStereo()
  154522. {
  154523. return true;
  154524. }
  154525. bool OggVorbisAudioFormat::canDoMono()
  154526. {
  154527. return true;
  154528. }
  154529. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  154530. const bool deleteStreamIfOpeningFails)
  154531. {
  154532. OggReader* r = new OggReader (in);
  154533. if (r->sampleRate == 0)
  154534. {
  154535. if (! deleteStreamIfOpeningFails)
  154536. r->input = 0;
  154537. deleteAndZero (r);
  154538. }
  154539. return r;
  154540. }
  154541. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  154542. double sampleRate,
  154543. unsigned int numChannels,
  154544. int bitsPerSample,
  154545. const StringPairArray& /*metadataValues*/,
  154546. int qualityOptionIndex)
  154547. {
  154548. OggWriter* w = new OggWriter (out,
  154549. sampleRate,
  154550. numChannels,
  154551. bitsPerSample,
  154552. qualityOptionIndex);
  154553. if (! w->ok)
  154554. deleteAndZero (w);
  154555. return w;
  154556. }
  154557. bool OggVorbisAudioFormat::isCompressed()
  154558. {
  154559. return true;
  154560. }
  154561. const StringArray OggVorbisAudioFormat::getQualityOptions()
  154562. {
  154563. StringArray s;
  154564. s.add ("Low Quality");
  154565. s.add ("Medium Quality");
  154566. s.add ("High Quality");
  154567. return s;
  154568. }
  154569. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  154570. {
  154571. FileInputStream* const in = source.createInputStream();
  154572. if (in != 0)
  154573. {
  154574. AudioFormatReader* const r = createReaderFor (in, true);
  154575. if (r != 0)
  154576. {
  154577. const int64 numSamps = r->lengthInSamples;
  154578. delete r;
  154579. const int64 fileNumSamps = source.getSize() / 4;
  154580. const double ratio = numSamps / (double) fileNumSamps;
  154581. if (ratio > 12.0)
  154582. return 0;
  154583. else if (ratio > 6.0)
  154584. return 1;
  154585. else
  154586. return 2;
  154587. }
  154588. }
  154589. return 1;
  154590. }
  154591. END_JUCE_NAMESPACE
  154592. #endif
  154593. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  154594. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  154595. #if JUCE_MSVC
  154596. #pragma warning (push)
  154597. #endif
  154598. namespace jpeglibNamespace
  154599. {
  154600. #if JUCE_INCLUDE_JPEGLIB_CODE
  154601. extern "C"
  154602. {
  154603. #define JPEG_INTERNALS
  154604. #undef FAR
  154605. /********* Start of inlined file: jpeglib.h *********/
  154606. #ifndef JPEGLIB_H
  154607. #define JPEGLIB_H
  154608. /*
  154609. * First we include the configuration files that record how this
  154610. * installation of the JPEG library is set up. jconfig.h can be
  154611. * generated automatically for many systems. jmorecfg.h contains
  154612. * manual configuration options that most people need not worry about.
  154613. */
  154614. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  154615. /********* Start of inlined file: jconfig.h *********/
  154616. /* see jconfig.doc for explanations */
  154617. // disable all the warnings under MSVC
  154618. #ifdef _MSC_VER
  154619. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  154620. #endif
  154621. #ifdef __BORLANDC__
  154622. #pragma warn -8057
  154623. #pragma warn -8019
  154624. #pragma warn -8004
  154625. #pragma warn -8008
  154626. #endif
  154627. #define HAVE_PROTOTYPES
  154628. #define HAVE_UNSIGNED_CHAR
  154629. #define HAVE_UNSIGNED_SHORT
  154630. /* #define void char */
  154631. /* #define const */
  154632. #undef CHAR_IS_UNSIGNED
  154633. #define HAVE_STDDEF_H
  154634. #define HAVE_STDLIB_H
  154635. #undef NEED_BSD_STRINGS
  154636. #undef NEED_SYS_TYPES_H
  154637. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  154638. #undef NEED_SHORT_EXTERNAL_NAMES
  154639. #undef INCOMPLETE_TYPES_BROKEN
  154640. /* Define "boolean" as unsigned char, not int, per Windows custom */
  154641. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  154642. typedef unsigned char boolean;
  154643. #endif
  154644. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  154645. #ifdef JPEG_INTERNALS
  154646. #undef RIGHT_SHIFT_IS_UNSIGNED
  154647. #endif /* JPEG_INTERNALS */
  154648. #ifdef JPEG_CJPEG_DJPEG
  154649. #define BMP_SUPPORTED /* BMP image file format */
  154650. #define GIF_SUPPORTED /* GIF image file format */
  154651. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  154652. #undef RLE_SUPPORTED /* Utah RLE image file format */
  154653. #define TARGA_SUPPORTED /* Targa image file format */
  154654. #define TWO_FILE_COMMANDLINE /* optional */
  154655. #define USE_SETMODE /* Microsoft has setmode() */
  154656. #undef NEED_SIGNAL_CATCHER
  154657. #undef DONT_USE_B_MODE
  154658. #undef PROGRESS_REPORT /* optional */
  154659. #endif /* JPEG_CJPEG_DJPEG */
  154660. /********* End of inlined file: jconfig.h *********/
  154661. /* widely used configuration options */
  154662. #endif
  154663. /********* Start of inlined file: jmorecfg.h *********/
  154664. /*
  154665. * Define BITS_IN_JSAMPLE as either
  154666. * 8 for 8-bit sample values (the usual setting)
  154667. * 12 for 12-bit sample values
  154668. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  154669. * JPEG standard, and the IJG code does not support anything else!
  154670. * We do not support run-time selection of data precision, sorry.
  154671. */
  154672. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  154673. /*
  154674. * Maximum number of components (color channels) allowed in JPEG image.
  154675. * To meet the letter of the JPEG spec, set this to 255. However, darn
  154676. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  154677. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  154678. * really short on memory. (Each allowed component costs a hundred or so
  154679. * bytes of storage, whether actually used in an image or not.)
  154680. */
  154681. #define MAX_COMPONENTS 10 /* maximum number of image components */
  154682. /*
  154683. * Basic data types.
  154684. * You may need to change these if you have a machine with unusual data
  154685. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  154686. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  154687. * but it had better be at least 16.
  154688. */
  154689. /* Representation of a single sample (pixel element value).
  154690. * We frequently allocate large arrays of these, so it's important to keep
  154691. * them small. But if you have memory to burn and access to char or short
  154692. * arrays is very slow on your hardware, you might want to change these.
  154693. */
  154694. #if BITS_IN_JSAMPLE == 8
  154695. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  154696. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  154697. */
  154698. #ifdef HAVE_UNSIGNED_CHAR
  154699. typedef unsigned char JSAMPLE;
  154700. #define GETJSAMPLE(value) ((int) (value))
  154701. #else /* not HAVE_UNSIGNED_CHAR */
  154702. typedef char JSAMPLE;
  154703. #ifdef CHAR_IS_UNSIGNED
  154704. #define GETJSAMPLE(value) ((int) (value))
  154705. #else
  154706. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  154707. #endif /* CHAR_IS_UNSIGNED */
  154708. #endif /* HAVE_UNSIGNED_CHAR */
  154709. #define MAXJSAMPLE 255
  154710. #define CENTERJSAMPLE 128
  154711. #endif /* BITS_IN_JSAMPLE == 8 */
  154712. #if BITS_IN_JSAMPLE == 12
  154713. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  154714. * On nearly all machines "short" will do nicely.
  154715. */
  154716. typedef short JSAMPLE;
  154717. #define GETJSAMPLE(value) ((int) (value))
  154718. #define MAXJSAMPLE 4095
  154719. #define CENTERJSAMPLE 2048
  154720. #endif /* BITS_IN_JSAMPLE == 12 */
  154721. /* Representation of a DCT frequency coefficient.
  154722. * This should be a signed value of at least 16 bits; "short" is usually OK.
  154723. * Again, we allocate large arrays of these, but you can change to int
  154724. * if you have memory to burn and "short" is really slow.
  154725. */
  154726. typedef short JCOEF;
  154727. /* Compressed datastreams are represented as arrays of JOCTET.
  154728. * These must be EXACTLY 8 bits wide, at least once they are written to
  154729. * external storage. Note that when using the stdio data source/destination
  154730. * managers, this is also the data type passed to fread/fwrite.
  154731. */
  154732. #ifdef HAVE_UNSIGNED_CHAR
  154733. typedef unsigned char JOCTET;
  154734. #define GETJOCTET(value) (value)
  154735. #else /* not HAVE_UNSIGNED_CHAR */
  154736. typedef char JOCTET;
  154737. #ifdef CHAR_IS_UNSIGNED
  154738. #define GETJOCTET(value) (value)
  154739. #else
  154740. #define GETJOCTET(value) ((value) & 0xFF)
  154741. #endif /* CHAR_IS_UNSIGNED */
  154742. #endif /* HAVE_UNSIGNED_CHAR */
  154743. /* These typedefs are used for various table entries and so forth.
  154744. * They must be at least as wide as specified; but making them too big
  154745. * won't cost a huge amount of memory, so we don't provide special
  154746. * extraction code like we did for JSAMPLE. (In other words, these
  154747. * typedefs live at a different point on the speed/space tradeoff curve.)
  154748. */
  154749. /* UINT8 must hold at least the values 0..255. */
  154750. #ifdef HAVE_UNSIGNED_CHAR
  154751. typedef unsigned char UINT8;
  154752. #else /* not HAVE_UNSIGNED_CHAR */
  154753. #ifdef CHAR_IS_UNSIGNED
  154754. typedef char UINT8;
  154755. #else /* not CHAR_IS_UNSIGNED */
  154756. typedef short UINT8;
  154757. #endif /* CHAR_IS_UNSIGNED */
  154758. #endif /* HAVE_UNSIGNED_CHAR */
  154759. /* UINT16 must hold at least the values 0..65535. */
  154760. #ifdef HAVE_UNSIGNED_SHORT
  154761. typedef unsigned short UINT16;
  154762. #else /* not HAVE_UNSIGNED_SHORT */
  154763. typedef unsigned int UINT16;
  154764. #endif /* HAVE_UNSIGNED_SHORT */
  154765. /* INT16 must hold at least the values -32768..32767. */
  154766. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  154767. typedef short INT16;
  154768. #endif
  154769. /* INT32 must hold at least signed 32-bit values. */
  154770. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  154771. typedef long INT32;
  154772. #endif
  154773. /* Datatype used for image dimensions. The JPEG standard only supports
  154774. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  154775. * "unsigned int" is sufficient on all machines. However, if you need to
  154776. * handle larger images and you don't mind deviating from the spec, you
  154777. * can change this datatype.
  154778. */
  154779. typedef unsigned int JDIMENSION;
  154780. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  154781. /* These macros are used in all function definitions and extern declarations.
  154782. * You could modify them if you need to change function linkage conventions;
  154783. * in particular, you'll need to do that to make the library a Windows DLL.
  154784. * Another application is to make all functions global for use with debuggers
  154785. * or code profilers that require it.
  154786. */
  154787. /* a function called through method pointers: */
  154788. #define METHODDEF(type) static type
  154789. /* a function used only in its module: */
  154790. #define LOCAL(type) static type
  154791. /* a function referenced thru EXTERNs: */
  154792. #define GLOBAL(type) type
  154793. /* a reference to a GLOBAL function: */
  154794. #define EXTERN(type) extern type
  154795. /* This macro is used to declare a "method", that is, a function pointer.
  154796. * We want to supply prototype parameters if the compiler can cope.
  154797. * Note that the arglist parameter must be parenthesized!
  154798. * Again, you can customize this if you need special linkage keywords.
  154799. */
  154800. #ifdef HAVE_PROTOTYPES
  154801. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  154802. #else
  154803. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  154804. #endif
  154805. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  154806. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  154807. * by just saying "FAR *" where such a pointer is needed. In a few places
  154808. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  154809. */
  154810. #ifdef NEED_FAR_POINTERS
  154811. #define FAR far
  154812. #else
  154813. #define FAR
  154814. #endif
  154815. /*
  154816. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  154817. * in standard header files. Or you may have conflicts with application-
  154818. * specific header files that you want to include together with these files.
  154819. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  154820. */
  154821. #ifndef HAVE_BOOLEAN
  154822. typedef int boolean;
  154823. #endif
  154824. #ifndef FALSE /* in case these macros already exist */
  154825. #define FALSE 0 /* values of boolean */
  154826. #endif
  154827. #ifndef TRUE
  154828. #define TRUE 1
  154829. #endif
  154830. /*
  154831. * The remaining options affect code selection within the JPEG library,
  154832. * but they don't need to be visible to most applications using the library.
  154833. * To minimize application namespace pollution, the symbols won't be
  154834. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  154835. */
  154836. #ifdef JPEG_INTERNALS
  154837. #define JPEG_INTERNAL_OPTIONS
  154838. #endif
  154839. #ifdef JPEG_INTERNAL_OPTIONS
  154840. /*
  154841. * These defines indicate whether to include various optional functions.
  154842. * Undefining some of these symbols will produce a smaller but less capable
  154843. * library. Note that you can leave certain source files out of the
  154844. * compilation/linking process if you've #undef'd the corresponding symbols.
  154845. * (You may HAVE to do that if your compiler doesn't like null source files.)
  154846. */
  154847. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  154848. /* Capability options common to encoder and decoder: */
  154849. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  154850. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  154851. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  154852. /* Encoder capability options: */
  154853. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  154854. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  154855. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  154856. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  154857. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  154858. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  154859. * precision, so jchuff.c normally uses entropy optimization to compute
  154860. * usable tables for higher precision. If you don't want to do optimization,
  154861. * you'll have to supply different default Huffman tables.
  154862. * The exact same statements apply for progressive JPEG: the default tables
  154863. * don't work for progressive mode. (This may get fixed, however.)
  154864. */
  154865. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  154866. /* Decoder capability options: */
  154867. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  154868. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  154869. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  154870. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  154871. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  154872. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  154873. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  154874. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  154875. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  154876. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  154877. /* more capability options later, no doubt */
  154878. /*
  154879. * Ordering of RGB data in scanlines passed to or from the application.
  154880. * If your application wants to deal with data in the order B,G,R, just
  154881. * change these macros. You can also deal with formats such as R,G,B,X
  154882. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  154883. * the offsets will also change the order in which colormap data is organized.
  154884. * RESTRICTIONS:
  154885. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  154886. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  154887. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  154888. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  154889. * is not 3 (they don't understand about dummy color components!). So you
  154890. * can't use color quantization if you change that value.
  154891. */
  154892. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  154893. #define RGB_GREEN 1 /* Offset of Green */
  154894. #define RGB_BLUE 2 /* Offset of Blue */
  154895. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  154896. /* Definitions for speed-related optimizations. */
  154897. /* If your compiler supports inline functions, define INLINE
  154898. * as the inline keyword; otherwise define it as empty.
  154899. */
  154900. #ifndef INLINE
  154901. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  154902. #define INLINE __inline__
  154903. #endif
  154904. #ifndef INLINE
  154905. #define INLINE /* default is to define it as empty */
  154906. #endif
  154907. #endif
  154908. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  154909. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  154910. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  154911. */
  154912. #ifndef MULTIPLIER
  154913. #define MULTIPLIER int /* type for fastest integer multiply */
  154914. #endif
  154915. /* FAST_FLOAT should be either float or double, whichever is done faster
  154916. * by your compiler. (Note that this type is only used in the floating point
  154917. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  154918. * Typically, float is faster in ANSI C compilers, while double is faster in
  154919. * pre-ANSI compilers (because they insist on converting to double anyway).
  154920. * The code below therefore chooses float if we have ANSI-style prototypes.
  154921. */
  154922. #ifndef FAST_FLOAT
  154923. #ifdef HAVE_PROTOTYPES
  154924. #define FAST_FLOAT float
  154925. #else
  154926. #define FAST_FLOAT double
  154927. #endif
  154928. #endif
  154929. #endif /* JPEG_INTERNAL_OPTIONS */
  154930. /********* End of inlined file: jmorecfg.h *********/
  154931. /* seldom changed options */
  154932. /* Version ID for the JPEG library.
  154933. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  154934. */
  154935. #define JPEG_LIB_VERSION 62 /* Version 6b */
  154936. /* Various constants determining the sizes of things.
  154937. * All of these are specified by the JPEG standard, so don't change them
  154938. * if you want to be compatible.
  154939. */
  154940. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  154941. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  154942. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  154943. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  154944. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  154945. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  154946. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  154947. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  154948. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  154949. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  154950. * to handle it. We even let you do this from the jconfig.h file. However,
  154951. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  154952. * sometimes emits noncompliant files doesn't mean you should too.
  154953. */
  154954. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  154955. #ifndef D_MAX_BLOCKS_IN_MCU
  154956. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  154957. #endif
  154958. /* Data structures for images (arrays of samples and of DCT coefficients).
  154959. * On 80x86 machines, the image arrays are too big for near pointers,
  154960. * but the pointer arrays can fit in near memory.
  154961. */
  154962. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  154963. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  154964. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  154965. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  154966. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  154967. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  154968. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  154969. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  154970. /* Types for JPEG compression parameters and working tables. */
  154971. /* DCT coefficient quantization tables. */
  154972. typedef struct {
  154973. /* This array gives the coefficient quantizers in natural array order
  154974. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  154975. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  154976. */
  154977. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  154978. /* This field is used only during compression. It's initialized FALSE when
  154979. * the table is created, and set TRUE when it's been output to the file.
  154980. * You could suppress output of a table by setting this to TRUE.
  154981. * (See jpeg_suppress_tables for an example.)
  154982. */
  154983. boolean sent_table; /* TRUE when table has been output */
  154984. } JQUANT_TBL;
  154985. /* Huffman coding tables. */
  154986. typedef struct {
  154987. /* These two fields directly represent the contents of a JPEG DHT marker */
  154988. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  154989. /* length k bits; bits[0] is unused */
  154990. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  154991. /* This field is used only during compression. It's initialized FALSE when
  154992. * the table is created, and set TRUE when it's been output to the file.
  154993. * You could suppress output of a table by setting this to TRUE.
  154994. * (See jpeg_suppress_tables for an example.)
  154995. */
  154996. boolean sent_table; /* TRUE when table has been output */
  154997. } JHUFF_TBL;
  154998. /* Basic info about one component (color channel). */
  154999. typedef struct {
  155000. /* These values are fixed over the whole image. */
  155001. /* For compression, they must be supplied by parameter setup; */
  155002. /* for decompression, they are read from the SOF marker. */
  155003. int component_id; /* identifier for this component (0..255) */
  155004. int component_index; /* its index in SOF or cinfo->comp_info[] */
  155005. int h_samp_factor; /* horizontal sampling factor (1..4) */
  155006. int v_samp_factor; /* vertical sampling factor (1..4) */
  155007. int quant_tbl_no; /* quantization table selector (0..3) */
  155008. /* These values may vary between scans. */
  155009. /* For compression, they must be supplied by parameter setup; */
  155010. /* for decompression, they are read from the SOS marker. */
  155011. /* The decompressor output side may not use these variables. */
  155012. int dc_tbl_no; /* DC entropy table selector (0..3) */
  155013. int ac_tbl_no; /* AC entropy table selector (0..3) */
  155014. /* Remaining fields should be treated as private by applications. */
  155015. /* These values are computed during compression or decompression startup: */
  155016. /* Component's size in DCT blocks.
  155017. * Any dummy blocks added to complete an MCU are not counted; therefore
  155018. * these values do not depend on whether a scan is interleaved or not.
  155019. */
  155020. JDIMENSION width_in_blocks;
  155021. JDIMENSION height_in_blocks;
  155022. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  155023. * For decompression this is the size of the output from one DCT block,
  155024. * reflecting any scaling we choose to apply during the IDCT step.
  155025. * Values of 1,2,4,8 are likely to be supported. Note that different
  155026. * components may receive different IDCT scalings.
  155027. */
  155028. int DCT_scaled_size;
  155029. /* The downsampled dimensions are the component's actual, unpadded number
  155030. * of samples at the main buffer (preprocessing/compression interface), thus
  155031. * downsampled_width = ceil(image_width * Hi/Hmax)
  155032. * and similarly for height. For decompression, IDCT scaling is included, so
  155033. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  155034. */
  155035. JDIMENSION downsampled_width; /* actual width in samples */
  155036. JDIMENSION downsampled_height; /* actual height in samples */
  155037. /* This flag is used only for decompression. In cases where some of the
  155038. * components will be ignored (eg grayscale output from YCbCr image),
  155039. * we can skip most computations for the unused components.
  155040. */
  155041. boolean component_needed; /* do we need the value of this component? */
  155042. /* These values are computed before starting a scan of the component. */
  155043. /* The decompressor output side may not use these variables. */
  155044. int MCU_width; /* number of blocks per MCU, horizontally */
  155045. int MCU_height; /* number of blocks per MCU, vertically */
  155046. int MCU_blocks; /* MCU_width * MCU_height */
  155047. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  155048. int last_col_width; /* # of non-dummy blocks across in last MCU */
  155049. int last_row_height; /* # of non-dummy blocks down in last MCU */
  155050. /* Saved quantization table for component; NULL if none yet saved.
  155051. * See jdinput.c comments about the need for this information.
  155052. * This field is currently used only for decompression.
  155053. */
  155054. JQUANT_TBL * quant_table;
  155055. /* Private per-component storage for DCT or IDCT subsystem. */
  155056. void * dct_table;
  155057. } jpeg_component_info;
  155058. /* The script for encoding a multiple-scan file is an array of these: */
  155059. typedef struct {
  155060. int comps_in_scan; /* number of components encoded in this scan */
  155061. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  155062. int Ss, Se; /* progressive JPEG spectral selection parms */
  155063. int Ah, Al; /* progressive JPEG successive approx. parms */
  155064. } jpeg_scan_info;
  155065. /* The decompressor can save APPn and COM markers in a list of these: */
  155066. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  155067. struct jpeg_marker_struct {
  155068. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  155069. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  155070. unsigned int original_length; /* # bytes of data in the file */
  155071. unsigned int data_length; /* # bytes of data saved at data[] */
  155072. JOCTET FAR * data; /* the data contained in the marker */
  155073. /* the marker length word is not counted in data_length or original_length */
  155074. };
  155075. /* Known color spaces. */
  155076. typedef enum {
  155077. JCS_UNKNOWN, /* error/unspecified */
  155078. JCS_GRAYSCALE, /* monochrome */
  155079. JCS_RGB, /* red/green/blue */
  155080. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  155081. JCS_CMYK, /* C/M/Y/K */
  155082. JCS_YCCK /* Y/Cb/Cr/K */
  155083. } J_COLOR_SPACE;
  155084. /* DCT/IDCT algorithm options. */
  155085. typedef enum {
  155086. JDCT_ISLOW, /* slow but accurate integer algorithm */
  155087. JDCT_IFAST, /* faster, less accurate integer method */
  155088. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  155089. } J_DCT_METHOD;
  155090. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  155091. #define JDCT_DEFAULT JDCT_ISLOW
  155092. #endif
  155093. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  155094. #define JDCT_FASTEST JDCT_IFAST
  155095. #endif
  155096. /* Dithering options for decompression. */
  155097. typedef enum {
  155098. JDITHER_NONE, /* no dithering */
  155099. JDITHER_ORDERED, /* simple ordered dither */
  155100. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  155101. } J_DITHER_MODE;
  155102. /* Common fields between JPEG compression and decompression master structs. */
  155103. #define jpeg_common_fields \
  155104. struct jpeg_error_mgr * err; /* Error handler module */\
  155105. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  155106. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  155107. void * client_data; /* Available for use by application */\
  155108. boolean is_decompressor; /* So common code can tell which is which */\
  155109. int global_state /* For checking call sequence validity */
  155110. /* Routines that are to be used by both halves of the library are declared
  155111. * to receive a pointer to this structure. There are no actual instances of
  155112. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  155113. */
  155114. struct jpeg_common_struct {
  155115. jpeg_common_fields; /* Fields common to both master struct types */
  155116. /* Additional fields follow in an actual jpeg_compress_struct or
  155117. * jpeg_decompress_struct. All three structs must agree on these
  155118. * initial fields! (This would be a lot cleaner in C++.)
  155119. */
  155120. };
  155121. typedef struct jpeg_common_struct * j_common_ptr;
  155122. typedef struct jpeg_compress_struct * j_compress_ptr;
  155123. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  155124. /* Master record for a compression instance */
  155125. struct jpeg_compress_struct {
  155126. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  155127. /* Destination for compressed data */
  155128. struct jpeg_destination_mgr * dest;
  155129. /* Description of source image --- these fields must be filled in by
  155130. * outer application before starting compression. in_color_space must
  155131. * be correct before you can even call jpeg_set_defaults().
  155132. */
  155133. JDIMENSION image_width; /* input image width */
  155134. JDIMENSION image_height; /* input image height */
  155135. int input_components; /* # of color components in input image */
  155136. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  155137. double input_gamma; /* image gamma of input image */
  155138. /* Compression parameters --- these fields must be set before calling
  155139. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  155140. * initialize everything to reasonable defaults, then changing anything
  155141. * the application specifically wants to change. That way you won't get
  155142. * burnt when new parameters are added. Also note that there are several
  155143. * helper routines to simplify changing parameters.
  155144. */
  155145. int data_precision; /* bits of precision in image data */
  155146. int num_components; /* # of color components in JPEG image */
  155147. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155148. jpeg_component_info * comp_info;
  155149. /* comp_info[i] describes component that appears i'th in SOF */
  155150. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155151. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155152. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155153. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155154. /* ptrs to Huffman coding tables, or NULL if not defined */
  155155. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155156. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155157. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155158. int num_scans; /* # of entries in scan_info array */
  155159. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  155160. /* The default value of scan_info is NULL, which causes a single-scan
  155161. * sequential JPEG file to be emitted. To create a multi-scan file,
  155162. * set num_scans and scan_info to point to an array of scan definitions.
  155163. */
  155164. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  155165. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155166. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  155167. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155168. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  155169. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  155170. /* The restart interval can be specified in absolute MCUs by setting
  155171. * restart_interval, or in MCU rows by setting restart_in_rows
  155172. * (in which case the correct restart_interval will be figured
  155173. * for each scan).
  155174. */
  155175. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  155176. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  155177. /* Parameters controlling emission of special markers. */
  155178. boolean write_JFIF_header; /* should a JFIF marker be written? */
  155179. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  155180. UINT8 JFIF_minor_version;
  155181. /* These three values are not used by the JPEG code, merely copied */
  155182. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  155183. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  155184. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  155185. UINT8 density_unit; /* JFIF code for pixel size units */
  155186. UINT16 X_density; /* Horizontal pixel density */
  155187. UINT16 Y_density; /* Vertical pixel density */
  155188. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  155189. /* State variable: index of next scanline to be written to
  155190. * jpeg_write_scanlines(). Application may use this to control its
  155191. * processing loop, e.g., "while (next_scanline < image_height)".
  155192. */
  155193. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  155194. /* Remaining fields are known throughout compressor, but generally
  155195. * should not be touched by a surrounding application.
  155196. */
  155197. /*
  155198. * These fields are computed during compression startup
  155199. */
  155200. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  155201. int max_h_samp_factor; /* largest h_samp_factor */
  155202. int max_v_samp_factor; /* largest v_samp_factor */
  155203. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  155204. /* The coefficient controller receives data in units of MCU rows as defined
  155205. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  155206. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  155207. * "iMCU" (interleaved MCU) row.
  155208. */
  155209. /*
  155210. * These fields are valid during any one scan.
  155211. * They describe the components and MCUs actually appearing in the scan.
  155212. */
  155213. int comps_in_scan; /* # of JPEG components in this scan */
  155214. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155215. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155216. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155217. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155218. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155219. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  155220. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155221. /* i'th block in an MCU */
  155222. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155223. /*
  155224. * Links to compression subobjects (methods and private variables of modules)
  155225. */
  155226. struct jpeg_comp_master * master;
  155227. struct jpeg_c_main_controller * main;
  155228. struct jpeg_c_prep_controller * prep;
  155229. struct jpeg_c_coef_controller * coef;
  155230. struct jpeg_marker_writer * marker;
  155231. struct jpeg_color_converter * cconvert;
  155232. struct jpeg_downsampler * downsample;
  155233. struct jpeg_forward_dct * fdct;
  155234. struct jpeg_entropy_encoder * entropy;
  155235. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  155236. int script_space_size;
  155237. };
  155238. /* Master record for a decompression instance */
  155239. struct jpeg_decompress_struct {
  155240. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  155241. /* Source of compressed data */
  155242. struct jpeg_source_mgr * src;
  155243. /* Basic description of image --- filled in by jpeg_read_header(). */
  155244. /* Application may inspect these values to decide how to process image. */
  155245. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  155246. JDIMENSION image_height; /* nominal image height */
  155247. int num_components; /* # of color components in JPEG image */
  155248. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155249. /* Decompression processing parameters --- these fields must be set before
  155250. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  155251. * them to default values.
  155252. */
  155253. J_COLOR_SPACE out_color_space; /* colorspace for output */
  155254. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  155255. double output_gamma; /* image gamma wanted in output */
  155256. boolean buffered_image; /* TRUE=multiple output passes */
  155257. boolean raw_data_out; /* TRUE=downsampled data wanted */
  155258. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  155259. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  155260. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  155261. boolean quantize_colors; /* TRUE=colormapped output wanted */
  155262. /* the following are ignored if not quantize_colors: */
  155263. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  155264. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  155265. int desired_number_of_colors; /* max # colors to use in created colormap */
  155266. /* these are significant only in buffered-image mode: */
  155267. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  155268. boolean enable_external_quant;/* enable future use of external colormap */
  155269. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  155270. /* Description of actual output image that will be returned to application.
  155271. * These fields are computed by jpeg_start_decompress().
  155272. * You can also use jpeg_calc_output_dimensions() to determine these values
  155273. * in advance of calling jpeg_start_decompress().
  155274. */
  155275. JDIMENSION output_width; /* scaled image width */
  155276. JDIMENSION output_height; /* scaled image height */
  155277. int out_color_components; /* # of color components in out_color_space */
  155278. int output_components; /* # of color components returned */
  155279. /* output_components is 1 (a colormap index) when quantizing colors;
  155280. * otherwise it equals out_color_components.
  155281. */
  155282. int rec_outbuf_height; /* min recommended height of scanline buffer */
  155283. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  155284. * high, space and time will be wasted due to unnecessary data copying.
  155285. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  155286. */
  155287. /* When quantizing colors, the output colormap is described by these fields.
  155288. * The application can supply a colormap by setting colormap non-NULL before
  155289. * calling jpeg_start_decompress; otherwise a colormap is created during
  155290. * jpeg_start_decompress or jpeg_start_output.
  155291. * The map has out_color_components rows and actual_number_of_colors columns.
  155292. */
  155293. int actual_number_of_colors; /* number of entries in use */
  155294. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  155295. /* State variables: these variables indicate the progress of decompression.
  155296. * The application may examine these but must not modify them.
  155297. */
  155298. /* Row index of next scanline to be read from jpeg_read_scanlines().
  155299. * Application may use this to control its processing loop, e.g.,
  155300. * "while (output_scanline < output_height)".
  155301. */
  155302. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  155303. /* Current input scan number and number of iMCU rows completed in scan.
  155304. * These indicate the progress of the decompressor input side.
  155305. */
  155306. int input_scan_number; /* Number of SOS markers seen so far */
  155307. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  155308. /* The "output scan number" is the notional scan being displayed by the
  155309. * output side. The decompressor will not allow output scan/row number
  155310. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  155311. */
  155312. int output_scan_number; /* Nominal scan number being displayed */
  155313. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  155314. /* Current progression status. coef_bits[c][i] indicates the precision
  155315. * with which component c's DCT coefficient i (in zigzag order) is known.
  155316. * It is -1 when no data has yet been received, otherwise it is the point
  155317. * transform (shift) value for the most recent scan of the coefficient
  155318. * (thus, 0 at completion of the progression).
  155319. * This pointer is NULL when reading a non-progressive file.
  155320. */
  155321. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  155322. /* Internal JPEG parameters --- the application usually need not look at
  155323. * these fields. Note that the decompressor output side may not use
  155324. * any parameters that can change between scans.
  155325. */
  155326. /* Quantization and Huffman tables are carried forward across input
  155327. * datastreams when processing abbreviated JPEG datastreams.
  155328. */
  155329. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155330. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155331. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155332. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155333. /* ptrs to Huffman coding tables, or NULL if not defined */
  155334. /* These parameters are never carried across datastreams, since they
  155335. * are given in SOF/SOS markers or defined to be reset by SOI.
  155336. */
  155337. int data_precision; /* bits of precision in image data */
  155338. jpeg_component_info * comp_info;
  155339. /* comp_info[i] describes component that appears i'th in SOF */
  155340. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  155341. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155342. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155343. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155344. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155345. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  155346. /* These fields record data obtained from optional markers recognized by
  155347. * the JPEG library.
  155348. */
  155349. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  155350. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  155351. UINT8 JFIF_major_version; /* JFIF version number */
  155352. UINT8 JFIF_minor_version;
  155353. UINT8 density_unit; /* JFIF code for pixel size units */
  155354. UINT16 X_density; /* Horizontal pixel density */
  155355. UINT16 Y_density; /* Vertical pixel density */
  155356. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  155357. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  155358. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155359. /* Aside from the specific data retained from APPn markers known to the
  155360. * library, the uninterpreted contents of any or all APPn and COM markers
  155361. * can be saved in a list for examination by the application.
  155362. */
  155363. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  155364. /* Remaining fields are known throughout decompressor, but generally
  155365. * should not be touched by a surrounding application.
  155366. */
  155367. /*
  155368. * These fields are computed during decompression startup
  155369. */
  155370. int max_h_samp_factor; /* largest h_samp_factor */
  155371. int max_v_samp_factor; /* largest v_samp_factor */
  155372. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  155373. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  155374. /* The coefficient controller's input and output progress is measured in
  155375. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  155376. * in fully interleaved JPEG scans, but are used whether the scan is
  155377. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  155378. * rows of each component. Therefore, the IDCT output contains
  155379. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  155380. */
  155381. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  155382. /*
  155383. * These fields are valid during any one scan.
  155384. * They describe the components and MCUs actually appearing in the scan.
  155385. * Note that the decompressor output side must not use these fields.
  155386. */
  155387. int comps_in_scan; /* # of JPEG components in this scan */
  155388. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155389. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155390. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155391. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155392. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155393. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  155394. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155395. /* i'th block in an MCU */
  155396. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155397. /* This field is shared between entropy decoder and marker parser.
  155398. * It is either zero or the code of a JPEG marker that has been
  155399. * read from the data source, but has not yet been processed.
  155400. */
  155401. int unread_marker;
  155402. /*
  155403. * Links to decompression subobjects (methods, private variables of modules)
  155404. */
  155405. struct jpeg_decomp_master * master;
  155406. struct jpeg_d_main_controller * main;
  155407. struct jpeg_d_coef_controller * coef;
  155408. struct jpeg_d_post_controller * post;
  155409. struct jpeg_input_controller * inputctl;
  155410. struct jpeg_marker_reader * marker;
  155411. struct jpeg_entropy_decoder * entropy;
  155412. struct jpeg_inverse_dct * idct;
  155413. struct jpeg_upsampler * upsample;
  155414. struct jpeg_color_deconverter * cconvert;
  155415. struct jpeg_color_quantizer * cquantize;
  155416. };
  155417. /* "Object" declarations for JPEG modules that may be supplied or called
  155418. * directly by the surrounding application.
  155419. * As with all objects in the JPEG library, these structs only define the
  155420. * publicly visible methods and state variables of a module. Additional
  155421. * private fields may exist after the public ones.
  155422. */
  155423. /* Error handler object */
  155424. struct jpeg_error_mgr {
  155425. /* Error exit handler: does not return to caller */
  155426. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  155427. /* Conditionally emit a trace or warning message */
  155428. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  155429. /* Routine that actually outputs a trace or error message */
  155430. JMETHOD(void, output_message, (j_common_ptr cinfo));
  155431. /* Format a message string for the most recent JPEG error or message */
  155432. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  155433. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  155434. /* Reset error state variables at start of a new image */
  155435. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  155436. /* The message ID code and any parameters are saved here.
  155437. * A message can have one string parameter or up to 8 int parameters.
  155438. */
  155439. int msg_code;
  155440. #define JMSG_STR_PARM_MAX 80
  155441. union {
  155442. int i[8];
  155443. char s[JMSG_STR_PARM_MAX];
  155444. } msg_parm;
  155445. /* Standard state variables for error facility */
  155446. int trace_level; /* max msg_level that will be displayed */
  155447. /* For recoverable corrupt-data errors, we emit a warning message,
  155448. * but keep going unless emit_message chooses to abort. emit_message
  155449. * should count warnings in num_warnings. The surrounding application
  155450. * can check for bad data by seeing if num_warnings is nonzero at the
  155451. * end of processing.
  155452. */
  155453. long num_warnings; /* number of corrupt-data warnings */
  155454. /* These fields point to the table(s) of error message strings.
  155455. * An application can change the table pointer to switch to a different
  155456. * message list (typically, to change the language in which errors are
  155457. * reported). Some applications may wish to add additional error codes
  155458. * that will be handled by the JPEG library error mechanism; the second
  155459. * table pointer is used for this purpose.
  155460. *
  155461. * First table includes all errors generated by JPEG library itself.
  155462. * Error code 0 is reserved for a "no such error string" message.
  155463. */
  155464. const char * const * jpeg_message_table; /* Library errors */
  155465. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  155466. /* Second table can be added by application (see cjpeg/djpeg for example).
  155467. * It contains strings numbered first_addon_message..last_addon_message.
  155468. */
  155469. const char * const * addon_message_table; /* Non-library errors */
  155470. int first_addon_message; /* code for first string in addon table */
  155471. int last_addon_message; /* code for last string in addon table */
  155472. };
  155473. /* Progress monitor object */
  155474. struct jpeg_progress_mgr {
  155475. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  155476. long pass_counter; /* work units completed in this pass */
  155477. long pass_limit; /* total number of work units in this pass */
  155478. int completed_passes; /* passes completed so far */
  155479. int total_passes; /* total number of passes expected */
  155480. };
  155481. /* Data destination object for compression */
  155482. struct jpeg_destination_mgr {
  155483. JOCTET * next_output_byte; /* => next byte to write in buffer */
  155484. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  155485. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  155486. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  155487. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  155488. };
  155489. /* Data source object for decompression */
  155490. struct jpeg_source_mgr {
  155491. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  155492. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  155493. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  155494. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  155495. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  155496. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  155497. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  155498. };
  155499. /* Memory manager object.
  155500. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  155501. * and "really big" objects (virtual arrays with backing store if needed).
  155502. * The memory manager does not allow individual objects to be freed; rather,
  155503. * each created object is assigned to a pool, and whole pools can be freed
  155504. * at once. This is faster and more convenient than remembering exactly what
  155505. * to free, especially where malloc()/free() are not too speedy.
  155506. * NB: alloc routines never return NULL. They exit to error_exit if not
  155507. * successful.
  155508. */
  155509. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  155510. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  155511. #define JPOOL_NUMPOOLS 2
  155512. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  155513. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  155514. struct jpeg_memory_mgr {
  155515. /* Method pointers */
  155516. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  155517. size_t sizeofobject));
  155518. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  155519. size_t sizeofobject));
  155520. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  155521. JDIMENSION samplesperrow,
  155522. JDIMENSION numrows));
  155523. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  155524. JDIMENSION blocksperrow,
  155525. JDIMENSION numrows));
  155526. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  155527. int pool_id,
  155528. boolean pre_zero,
  155529. JDIMENSION samplesperrow,
  155530. JDIMENSION numrows,
  155531. JDIMENSION maxaccess));
  155532. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  155533. int pool_id,
  155534. boolean pre_zero,
  155535. JDIMENSION blocksperrow,
  155536. JDIMENSION numrows,
  155537. JDIMENSION maxaccess));
  155538. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  155539. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  155540. jvirt_sarray_ptr ptr,
  155541. JDIMENSION start_row,
  155542. JDIMENSION num_rows,
  155543. boolean writable));
  155544. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  155545. jvirt_barray_ptr ptr,
  155546. JDIMENSION start_row,
  155547. JDIMENSION num_rows,
  155548. boolean writable));
  155549. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  155550. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  155551. /* Limit on memory allocation for this JPEG object. (Note that this is
  155552. * merely advisory, not a guaranteed maximum; it only affects the space
  155553. * used for virtual-array buffers.) May be changed by outer application
  155554. * after creating the JPEG object.
  155555. */
  155556. long max_memory_to_use;
  155557. /* Maximum allocation request accepted by alloc_large. */
  155558. long max_alloc_chunk;
  155559. };
  155560. /* Routine signature for application-supplied marker processing methods.
  155561. * Need not pass marker code since it is stored in cinfo->unread_marker.
  155562. */
  155563. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  155564. /* Declarations for routines called by application.
  155565. * The JPP macro hides prototype parameters from compilers that can't cope.
  155566. * Note JPP requires double parentheses.
  155567. */
  155568. #ifdef HAVE_PROTOTYPES
  155569. #define JPP(arglist) arglist
  155570. #else
  155571. #define JPP(arglist) ()
  155572. #endif
  155573. /* Short forms of external names for systems with brain-damaged linkers.
  155574. * We shorten external names to be unique in the first six letters, which
  155575. * is good enough for all known systems.
  155576. * (If your compiler itself needs names to be unique in less than 15
  155577. * characters, you are out of luck. Get a better compiler.)
  155578. */
  155579. #ifdef NEED_SHORT_EXTERNAL_NAMES
  155580. #define jpeg_std_error jStdError
  155581. #define jpeg_CreateCompress jCreaCompress
  155582. #define jpeg_CreateDecompress jCreaDecompress
  155583. #define jpeg_destroy_compress jDestCompress
  155584. #define jpeg_destroy_decompress jDestDecompress
  155585. #define jpeg_stdio_dest jStdDest
  155586. #define jpeg_stdio_src jStdSrc
  155587. #define jpeg_set_defaults jSetDefaults
  155588. #define jpeg_set_colorspace jSetColorspace
  155589. #define jpeg_default_colorspace jDefColorspace
  155590. #define jpeg_set_quality jSetQuality
  155591. #define jpeg_set_linear_quality jSetLQuality
  155592. #define jpeg_add_quant_table jAddQuantTable
  155593. #define jpeg_quality_scaling jQualityScaling
  155594. #define jpeg_simple_progression jSimProgress
  155595. #define jpeg_suppress_tables jSuppressTables
  155596. #define jpeg_alloc_quant_table jAlcQTable
  155597. #define jpeg_alloc_huff_table jAlcHTable
  155598. #define jpeg_start_compress jStrtCompress
  155599. #define jpeg_write_scanlines jWrtScanlines
  155600. #define jpeg_finish_compress jFinCompress
  155601. #define jpeg_write_raw_data jWrtRawData
  155602. #define jpeg_write_marker jWrtMarker
  155603. #define jpeg_write_m_header jWrtMHeader
  155604. #define jpeg_write_m_byte jWrtMByte
  155605. #define jpeg_write_tables jWrtTables
  155606. #define jpeg_read_header jReadHeader
  155607. #define jpeg_start_decompress jStrtDecompress
  155608. #define jpeg_read_scanlines jReadScanlines
  155609. #define jpeg_finish_decompress jFinDecompress
  155610. #define jpeg_read_raw_data jReadRawData
  155611. #define jpeg_has_multiple_scans jHasMultScn
  155612. #define jpeg_start_output jStrtOutput
  155613. #define jpeg_finish_output jFinOutput
  155614. #define jpeg_input_complete jInComplete
  155615. #define jpeg_new_colormap jNewCMap
  155616. #define jpeg_consume_input jConsumeInput
  155617. #define jpeg_calc_output_dimensions jCalcDimensions
  155618. #define jpeg_save_markers jSaveMarkers
  155619. #define jpeg_set_marker_processor jSetMarker
  155620. #define jpeg_read_coefficients jReadCoefs
  155621. #define jpeg_write_coefficients jWrtCoefs
  155622. #define jpeg_copy_critical_parameters jCopyCrit
  155623. #define jpeg_abort_compress jAbrtCompress
  155624. #define jpeg_abort_decompress jAbrtDecompress
  155625. #define jpeg_abort jAbort
  155626. #define jpeg_destroy jDestroy
  155627. #define jpeg_resync_to_restart jResyncRestart
  155628. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  155629. /* Default error-management setup */
  155630. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  155631. JPP((struct jpeg_error_mgr * err));
  155632. /* Initialization of JPEG compression objects.
  155633. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  155634. * names that applications should call. These expand to calls on
  155635. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  155636. * passed for version mismatch checking.
  155637. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  155638. */
  155639. #define jpeg_create_compress(cinfo) \
  155640. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  155641. (size_t) sizeof(struct jpeg_compress_struct))
  155642. #define jpeg_create_decompress(cinfo) \
  155643. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  155644. (size_t) sizeof(struct jpeg_decompress_struct))
  155645. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  155646. int version, size_t structsize));
  155647. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  155648. int version, size_t structsize));
  155649. /* Destruction of JPEG compression objects */
  155650. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  155651. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  155652. /* Standard data source and destination managers: stdio streams. */
  155653. /* Caller is responsible for opening the file before and closing after. */
  155654. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  155655. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  155656. /* Default parameter setup for compression */
  155657. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  155658. /* Compression parameter setup aids */
  155659. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  155660. J_COLOR_SPACE colorspace));
  155661. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  155662. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  155663. boolean force_baseline));
  155664. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  155665. int scale_factor,
  155666. boolean force_baseline));
  155667. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  155668. const unsigned int *basic_table,
  155669. int scale_factor,
  155670. boolean force_baseline));
  155671. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  155672. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  155673. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  155674. boolean suppress));
  155675. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  155676. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  155677. /* Main entry points for compression */
  155678. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  155679. boolean write_all_tables));
  155680. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  155681. JSAMPARRAY scanlines,
  155682. JDIMENSION num_lines));
  155683. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  155684. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  155685. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  155686. JSAMPIMAGE data,
  155687. JDIMENSION num_lines));
  155688. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  155689. EXTERN(void) jpeg_write_marker
  155690. JPP((j_compress_ptr cinfo, int marker,
  155691. const JOCTET * dataptr, unsigned int datalen));
  155692. /* Same, but piecemeal. */
  155693. EXTERN(void) jpeg_write_m_header
  155694. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  155695. EXTERN(void) jpeg_write_m_byte
  155696. JPP((j_compress_ptr cinfo, int val));
  155697. /* Alternate compression function: just write an abbreviated table file */
  155698. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  155699. /* Decompression startup: read start of JPEG datastream to see what's there */
  155700. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  155701. boolean require_image));
  155702. /* Return value is one of: */
  155703. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  155704. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  155705. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  155706. /* If you pass require_image = TRUE (normal case), you need not check for
  155707. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  155708. * JPEG_SUSPENDED is only possible if you use a data source module that can
  155709. * give a suspension return (the stdio source module doesn't).
  155710. */
  155711. /* Main entry points for decompression */
  155712. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  155713. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  155714. JSAMPARRAY scanlines,
  155715. JDIMENSION max_lines));
  155716. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  155717. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  155718. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  155719. JSAMPIMAGE data,
  155720. JDIMENSION max_lines));
  155721. /* Additional entry points for buffered-image mode. */
  155722. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  155723. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  155724. int scan_number));
  155725. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  155726. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  155727. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  155728. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  155729. /* Return value is one of: */
  155730. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  155731. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  155732. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  155733. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  155734. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  155735. /* Precalculate output dimensions for current decompression parameters. */
  155736. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  155737. /* Control saving of COM and APPn markers into marker_list. */
  155738. EXTERN(void) jpeg_save_markers
  155739. JPP((j_decompress_ptr cinfo, int marker_code,
  155740. unsigned int length_limit));
  155741. /* Install a special processing method for COM or APPn markers. */
  155742. EXTERN(void) jpeg_set_marker_processor
  155743. JPP((j_decompress_ptr cinfo, int marker_code,
  155744. jpeg_marker_parser_method routine));
  155745. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  155746. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  155747. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  155748. jvirt_barray_ptr * coef_arrays));
  155749. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  155750. j_compress_ptr dstinfo));
  155751. /* If you choose to abort compression or decompression before completing
  155752. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  155753. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  155754. * if you're done with the JPEG object, but if you want to clean it up and
  155755. * reuse it, call this:
  155756. */
  155757. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  155758. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  155759. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  155760. * flavor of JPEG object. These may be more convenient in some places.
  155761. */
  155762. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  155763. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  155764. /* Default restart-marker-resync procedure for use by data source modules */
  155765. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  155766. int desired));
  155767. /* These marker codes are exported since applications and data source modules
  155768. * are likely to want to use them.
  155769. */
  155770. #define JPEG_RST0 0xD0 /* RST0 marker code */
  155771. #define JPEG_EOI 0xD9 /* EOI marker code */
  155772. #define JPEG_APP0 0xE0 /* APP0 marker code */
  155773. #define JPEG_COM 0xFE /* COM marker code */
  155774. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  155775. * for structure definitions that are never filled in, keep it quiet by
  155776. * supplying dummy definitions for the various substructures.
  155777. */
  155778. #ifdef INCOMPLETE_TYPES_BROKEN
  155779. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  155780. struct jvirt_sarray_control { long dummy; };
  155781. struct jvirt_barray_control { long dummy; };
  155782. struct jpeg_comp_master { long dummy; };
  155783. struct jpeg_c_main_controller { long dummy; };
  155784. struct jpeg_c_prep_controller { long dummy; };
  155785. struct jpeg_c_coef_controller { long dummy; };
  155786. struct jpeg_marker_writer { long dummy; };
  155787. struct jpeg_color_converter { long dummy; };
  155788. struct jpeg_downsampler { long dummy; };
  155789. struct jpeg_forward_dct { long dummy; };
  155790. struct jpeg_entropy_encoder { long dummy; };
  155791. struct jpeg_decomp_master { long dummy; };
  155792. struct jpeg_d_main_controller { long dummy; };
  155793. struct jpeg_d_coef_controller { long dummy; };
  155794. struct jpeg_d_post_controller { long dummy; };
  155795. struct jpeg_input_controller { long dummy; };
  155796. struct jpeg_marker_reader { long dummy; };
  155797. struct jpeg_entropy_decoder { long dummy; };
  155798. struct jpeg_inverse_dct { long dummy; };
  155799. struct jpeg_upsampler { long dummy; };
  155800. struct jpeg_color_deconverter { long dummy; };
  155801. struct jpeg_color_quantizer { long dummy; };
  155802. #endif /* JPEG_INTERNALS */
  155803. #endif /* INCOMPLETE_TYPES_BROKEN */
  155804. /*
  155805. * The JPEG library modules define JPEG_INTERNALS before including this file.
  155806. * The internal structure declarations are read only when that is true.
  155807. * Applications using the library should not include jpegint.h, but may wish
  155808. * to include jerror.h.
  155809. */
  155810. #ifdef JPEG_INTERNALS
  155811. /********* Start of inlined file: jpegint.h *********/
  155812. /* Declarations for both compression & decompression */
  155813. typedef enum { /* Operating modes for buffer controllers */
  155814. JBUF_PASS_THRU, /* Plain stripwise operation */
  155815. /* Remaining modes require a full-image buffer to have been created */
  155816. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  155817. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  155818. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  155819. } J_BUF_MODE;
  155820. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  155821. #define CSTATE_START 100 /* after create_compress */
  155822. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  155823. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  155824. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  155825. #define DSTATE_START 200 /* after create_decompress */
  155826. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  155827. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  155828. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  155829. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  155830. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  155831. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  155832. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  155833. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  155834. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  155835. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  155836. /* Declarations for compression modules */
  155837. /* Master control module */
  155838. struct jpeg_comp_master {
  155839. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  155840. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  155841. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  155842. /* State variables made visible to other modules */
  155843. boolean call_pass_startup; /* True if pass_startup must be called */
  155844. boolean is_last_pass; /* True during last pass */
  155845. };
  155846. /* Main buffer control (downsampled-data buffer) */
  155847. struct jpeg_c_main_controller {
  155848. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  155849. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  155850. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  155851. JDIMENSION in_rows_avail));
  155852. };
  155853. /* Compression preprocessing (downsampling input buffer control) */
  155854. struct jpeg_c_prep_controller {
  155855. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  155856. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  155857. JSAMPARRAY input_buf,
  155858. JDIMENSION *in_row_ctr,
  155859. JDIMENSION in_rows_avail,
  155860. JSAMPIMAGE output_buf,
  155861. JDIMENSION *out_row_group_ctr,
  155862. JDIMENSION out_row_groups_avail));
  155863. };
  155864. /* Coefficient buffer control */
  155865. struct jpeg_c_coef_controller {
  155866. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  155867. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  155868. JSAMPIMAGE input_buf));
  155869. };
  155870. /* Colorspace conversion */
  155871. struct jpeg_color_converter {
  155872. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  155873. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  155874. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155875. JDIMENSION output_row, int num_rows));
  155876. };
  155877. /* Downsampling */
  155878. struct jpeg_downsampler {
  155879. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  155880. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  155881. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  155882. JSAMPIMAGE output_buf,
  155883. JDIMENSION out_row_group_index));
  155884. boolean need_context_rows; /* TRUE if need rows above & below */
  155885. };
  155886. /* Forward DCT (also controls coefficient quantization) */
  155887. struct jpeg_forward_dct {
  155888. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  155889. /* perhaps this should be an array??? */
  155890. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  155891. jpeg_component_info * compptr,
  155892. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  155893. JDIMENSION start_row, JDIMENSION start_col,
  155894. JDIMENSION num_blocks));
  155895. };
  155896. /* Entropy encoding */
  155897. struct jpeg_entropy_encoder {
  155898. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  155899. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  155900. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  155901. };
  155902. /* Marker writing */
  155903. struct jpeg_marker_writer {
  155904. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  155905. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  155906. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  155907. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  155908. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  155909. /* These routines are exported to allow insertion of extra markers */
  155910. /* Probably only COM and APPn markers should be written this way */
  155911. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  155912. unsigned int datalen));
  155913. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  155914. };
  155915. /* Declarations for decompression modules */
  155916. /* Master control module */
  155917. struct jpeg_decomp_master {
  155918. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  155919. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  155920. /* State variables made visible to other modules */
  155921. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  155922. };
  155923. /* Input control module */
  155924. struct jpeg_input_controller {
  155925. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  155926. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  155927. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  155928. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  155929. /* State variables made visible to other modules */
  155930. boolean has_multiple_scans; /* True if file has multiple scans */
  155931. boolean eoi_reached; /* True when EOI has been consumed */
  155932. };
  155933. /* Main buffer control (downsampled-data buffer) */
  155934. struct jpeg_d_main_controller {
  155935. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  155936. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  155937. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  155938. JDIMENSION out_rows_avail));
  155939. };
  155940. /* Coefficient buffer control */
  155941. struct jpeg_d_coef_controller {
  155942. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  155943. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  155944. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  155945. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  155946. JSAMPIMAGE output_buf));
  155947. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  155948. jvirt_barray_ptr *coef_arrays;
  155949. };
  155950. /* Decompression postprocessing (color quantization buffer control) */
  155951. struct jpeg_d_post_controller {
  155952. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  155953. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  155954. JSAMPIMAGE input_buf,
  155955. JDIMENSION *in_row_group_ctr,
  155956. JDIMENSION in_row_groups_avail,
  155957. JSAMPARRAY output_buf,
  155958. JDIMENSION *out_row_ctr,
  155959. JDIMENSION out_rows_avail));
  155960. };
  155961. /* Marker reading & parsing */
  155962. struct jpeg_marker_reader {
  155963. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  155964. /* Read markers until SOS or EOI.
  155965. * Returns same codes as are defined for jpeg_consume_input:
  155966. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  155967. */
  155968. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  155969. /* Read a restart marker --- exported for use by entropy decoder only */
  155970. jpeg_marker_parser_method read_restart_marker;
  155971. /* State of marker reader --- nominally internal, but applications
  155972. * supplying COM or APPn handlers might like to know the state.
  155973. */
  155974. boolean saw_SOI; /* found SOI? */
  155975. boolean saw_SOF; /* found SOF? */
  155976. int next_restart_num; /* next restart number expected (0-7) */
  155977. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  155978. };
  155979. /* Entropy decoding */
  155980. struct jpeg_entropy_decoder {
  155981. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155982. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  155983. JBLOCKROW *MCU_data));
  155984. /* This is here to share code between baseline and progressive decoders; */
  155985. /* other modules probably should not use it */
  155986. boolean insufficient_data; /* set TRUE after emitting warning */
  155987. };
  155988. /* Inverse DCT (also performs dequantization) */
  155989. typedef JMETHOD(void, inverse_DCT_method_ptr,
  155990. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  155991. JCOEFPTR coef_block,
  155992. JSAMPARRAY output_buf, JDIMENSION output_col));
  155993. struct jpeg_inverse_dct {
  155994. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155995. /* It is useful to allow each component to have a separate IDCT method. */
  155996. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  155997. };
  155998. /* Upsampling (note that upsampler must also call color converter) */
  155999. struct jpeg_upsampler {
  156000. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156001. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  156002. JSAMPIMAGE input_buf,
  156003. JDIMENSION *in_row_group_ctr,
  156004. JDIMENSION in_row_groups_avail,
  156005. JSAMPARRAY output_buf,
  156006. JDIMENSION *out_row_ctr,
  156007. JDIMENSION out_rows_avail));
  156008. boolean need_context_rows; /* TRUE if need rows above & below */
  156009. };
  156010. /* Colorspace conversion */
  156011. struct jpeg_color_deconverter {
  156012. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156013. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  156014. JSAMPIMAGE input_buf, JDIMENSION input_row,
  156015. JSAMPARRAY output_buf, int num_rows));
  156016. };
  156017. /* Color quantization or color precision reduction */
  156018. struct jpeg_color_quantizer {
  156019. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  156020. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  156021. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  156022. int num_rows));
  156023. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  156024. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  156025. };
  156026. /* Miscellaneous useful macros */
  156027. #undef MAX
  156028. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  156029. #undef MIN
  156030. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  156031. /* We assume that right shift corresponds to signed division by 2 with
  156032. * rounding towards minus infinity. This is correct for typical "arithmetic
  156033. * shift" instructions that shift in copies of the sign bit. But some
  156034. * C compilers implement >> with an unsigned shift. For these machines you
  156035. * must define RIGHT_SHIFT_IS_UNSIGNED.
  156036. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  156037. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  156038. * included in the variables of any routine using RIGHT_SHIFT.
  156039. */
  156040. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  156041. #define SHIFT_TEMPS INT32 shift_temp;
  156042. #define RIGHT_SHIFT(x,shft) \
  156043. ((shift_temp = (x)) < 0 ? \
  156044. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  156045. (shift_temp >> (shft)))
  156046. #else
  156047. #define SHIFT_TEMPS
  156048. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  156049. #endif
  156050. /* Short forms of external names for systems with brain-damaged linkers. */
  156051. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156052. #define jinit_compress_master jICompress
  156053. #define jinit_c_master_control jICMaster
  156054. #define jinit_c_main_controller jICMainC
  156055. #define jinit_c_prep_controller jICPrepC
  156056. #define jinit_c_coef_controller jICCoefC
  156057. #define jinit_color_converter jICColor
  156058. #define jinit_downsampler jIDownsampler
  156059. #define jinit_forward_dct jIFDCT
  156060. #define jinit_huff_encoder jIHEncoder
  156061. #define jinit_phuff_encoder jIPHEncoder
  156062. #define jinit_marker_writer jIMWriter
  156063. #define jinit_master_decompress jIDMaster
  156064. #define jinit_d_main_controller jIDMainC
  156065. #define jinit_d_coef_controller jIDCoefC
  156066. #define jinit_d_post_controller jIDPostC
  156067. #define jinit_input_controller jIInCtlr
  156068. #define jinit_marker_reader jIMReader
  156069. #define jinit_huff_decoder jIHDecoder
  156070. #define jinit_phuff_decoder jIPHDecoder
  156071. #define jinit_inverse_dct jIIDCT
  156072. #define jinit_upsampler jIUpsampler
  156073. #define jinit_color_deconverter jIDColor
  156074. #define jinit_1pass_quantizer jI1Quant
  156075. #define jinit_2pass_quantizer jI2Quant
  156076. #define jinit_merged_upsampler jIMUpsampler
  156077. #define jinit_memory_mgr jIMemMgr
  156078. #define jdiv_round_up jDivRound
  156079. #define jround_up jRound
  156080. #define jcopy_sample_rows jCopySamples
  156081. #define jcopy_block_row jCopyBlocks
  156082. #define jzero_far jZeroFar
  156083. #define jpeg_zigzag_order jZIGTable
  156084. #define jpeg_natural_order jZAGTable
  156085. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156086. /* Compression module initialization routines */
  156087. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  156088. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  156089. boolean transcode_only));
  156090. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  156091. boolean need_full_buffer));
  156092. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  156093. boolean need_full_buffer));
  156094. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  156095. boolean need_full_buffer));
  156096. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  156097. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  156098. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  156099. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  156100. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  156101. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  156102. /* Decompression module initialization routines */
  156103. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  156104. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  156105. boolean need_full_buffer));
  156106. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  156107. boolean need_full_buffer));
  156108. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  156109. boolean need_full_buffer));
  156110. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  156111. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  156112. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  156113. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  156114. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  156115. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  156116. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  156117. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  156118. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  156119. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  156120. /* Memory manager initialization */
  156121. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  156122. /* Utility routines in jutils.c */
  156123. EXTERN(long) jdiv_round_up JPP((long a, long b));
  156124. EXTERN(long) jround_up JPP((long a, long b));
  156125. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  156126. JSAMPARRAY output_array, int dest_row,
  156127. int num_rows, JDIMENSION num_cols));
  156128. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  156129. JDIMENSION num_blocks));
  156130. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  156131. /* Constant tables in jutils.c */
  156132. #if 0 /* This table is not actually needed in v6a */
  156133. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  156134. #endif
  156135. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  156136. /* Suppress undefined-structure complaints if necessary. */
  156137. #ifdef INCOMPLETE_TYPES_BROKEN
  156138. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  156139. struct jvirt_sarray_control { long dummy; };
  156140. struct jvirt_barray_control { long dummy; };
  156141. #endif
  156142. #endif /* INCOMPLETE_TYPES_BROKEN */
  156143. /********* End of inlined file: jpegint.h *********/
  156144. /* fetch private declarations */
  156145. /********* Start of inlined file: jerror.h *********/
  156146. /*
  156147. * To define the enum list of message codes, include this file without
  156148. * defining macro JMESSAGE. To create a message string table, include it
  156149. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  156150. */
  156151. #ifndef JMESSAGE
  156152. #ifndef JERROR_H
  156153. /* First time through, define the enum list */
  156154. #define JMAKE_ENUM_LIST
  156155. #else
  156156. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  156157. #define JMESSAGE(code,string)
  156158. #endif /* JERROR_H */
  156159. #endif /* JMESSAGE */
  156160. #ifdef JMAKE_ENUM_LIST
  156161. typedef enum {
  156162. #define JMESSAGE(code,string) code ,
  156163. #endif /* JMAKE_ENUM_LIST */
  156164. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  156165. /* For maintenance convenience, list is alphabetical by message code name */
  156166. JMESSAGE(JERR_ARITH_NOTIMPL,
  156167. "Sorry, there are legal restrictions on arithmetic coding")
  156168. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  156169. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  156170. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  156171. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  156172. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  156173. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  156174. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  156175. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  156176. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  156177. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  156178. JMESSAGE(JERR_BAD_LIB_VERSION,
  156179. "Wrong JPEG library version: library is %d, caller expects %d")
  156180. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  156181. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  156182. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  156183. JMESSAGE(JERR_BAD_PROGRESSION,
  156184. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  156185. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  156186. "Invalid progressive parameters at scan script entry %d")
  156187. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  156188. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  156189. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  156190. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  156191. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  156192. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  156193. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  156194. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  156195. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  156196. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  156197. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  156198. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  156199. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  156200. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  156201. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  156202. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  156203. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  156204. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  156205. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  156206. JMESSAGE(JERR_FILE_READ, "Input file read error")
  156207. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  156208. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  156209. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  156210. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  156211. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  156212. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  156213. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  156214. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  156215. "Cannot transcode due to multiple use of quantization table %d")
  156216. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  156217. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  156218. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  156219. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  156220. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  156221. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  156222. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  156223. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  156224. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  156225. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  156226. JMESSAGE(JERR_QUANT_COMPONENTS,
  156227. "Cannot quantize more than %d color components")
  156228. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  156229. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  156230. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  156231. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  156232. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  156233. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  156234. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  156235. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  156236. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  156237. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  156238. JMESSAGE(JERR_TFILE_WRITE,
  156239. "Write failed on temporary file --- out of disk space?")
  156240. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  156241. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  156242. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  156243. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  156244. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  156245. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  156246. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  156247. JMESSAGE(JMSG_VERSION, JVERSION)
  156248. JMESSAGE(JTRC_16BIT_TABLES,
  156249. "Caution: quantization tables are too coarse for baseline JPEG")
  156250. JMESSAGE(JTRC_ADOBE,
  156251. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  156252. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  156253. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  156254. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  156255. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  156256. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  156257. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  156258. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  156259. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  156260. JMESSAGE(JTRC_EOI, "End Of Image")
  156261. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  156262. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  156263. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  156264. "Warning: thumbnail image size does not match data length %u")
  156265. JMESSAGE(JTRC_JFIF_EXTENSION,
  156266. "JFIF extension marker: type 0x%02x, length %u")
  156267. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  156268. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  156269. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  156270. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  156271. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  156272. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  156273. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  156274. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  156275. JMESSAGE(JTRC_RST, "RST%d")
  156276. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  156277. "Smoothing not supported with nonstandard sampling ratios")
  156278. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  156279. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  156280. JMESSAGE(JTRC_SOI, "Start of Image")
  156281. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  156282. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  156283. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  156284. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  156285. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  156286. JMESSAGE(JTRC_THUMB_JPEG,
  156287. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  156288. JMESSAGE(JTRC_THUMB_PALETTE,
  156289. "JFIF extension marker: palette thumbnail image, length %u")
  156290. JMESSAGE(JTRC_THUMB_RGB,
  156291. "JFIF extension marker: RGB thumbnail image, length %u")
  156292. JMESSAGE(JTRC_UNKNOWN_IDS,
  156293. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  156294. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  156295. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  156296. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  156297. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  156298. "Inconsistent progression sequence for component %d coefficient %d")
  156299. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  156300. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  156301. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  156302. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  156303. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  156304. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  156305. JMESSAGE(JWRN_MUST_RESYNC,
  156306. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  156307. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  156308. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  156309. #ifdef JMAKE_ENUM_LIST
  156310. JMSG_LASTMSGCODE
  156311. } J_MESSAGE_CODE;
  156312. #undef JMAKE_ENUM_LIST
  156313. #endif /* JMAKE_ENUM_LIST */
  156314. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  156315. #undef JMESSAGE
  156316. #ifndef JERROR_H
  156317. #define JERROR_H
  156318. /* Macros to simplify using the error and trace message stuff */
  156319. /* The first parameter is either type of cinfo pointer */
  156320. /* Fatal errors (print message and exit) */
  156321. #define ERREXIT(cinfo,code) \
  156322. ((cinfo)->err->msg_code = (code), \
  156323. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156324. #define ERREXIT1(cinfo,code,p1) \
  156325. ((cinfo)->err->msg_code = (code), \
  156326. (cinfo)->err->msg_parm.i[0] = (p1), \
  156327. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156328. #define ERREXIT2(cinfo,code,p1,p2) \
  156329. ((cinfo)->err->msg_code = (code), \
  156330. (cinfo)->err->msg_parm.i[0] = (p1), \
  156331. (cinfo)->err->msg_parm.i[1] = (p2), \
  156332. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156333. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  156334. ((cinfo)->err->msg_code = (code), \
  156335. (cinfo)->err->msg_parm.i[0] = (p1), \
  156336. (cinfo)->err->msg_parm.i[1] = (p2), \
  156337. (cinfo)->err->msg_parm.i[2] = (p3), \
  156338. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156339. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  156340. ((cinfo)->err->msg_code = (code), \
  156341. (cinfo)->err->msg_parm.i[0] = (p1), \
  156342. (cinfo)->err->msg_parm.i[1] = (p2), \
  156343. (cinfo)->err->msg_parm.i[2] = (p3), \
  156344. (cinfo)->err->msg_parm.i[3] = (p4), \
  156345. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156346. #define ERREXITS(cinfo,code,str) \
  156347. ((cinfo)->err->msg_code = (code), \
  156348. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  156349. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156350. #define MAKESTMT(stuff) do { stuff } while (0)
  156351. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  156352. #define WARNMS(cinfo,code) \
  156353. ((cinfo)->err->msg_code = (code), \
  156354. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156355. #define WARNMS1(cinfo,code,p1) \
  156356. ((cinfo)->err->msg_code = (code), \
  156357. (cinfo)->err->msg_parm.i[0] = (p1), \
  156358. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156359. #define WARNMS2(cinfo,code,p1,p2) \
  156360. ((cinfo)->err->msg_code = (code), \
  156361. (cinfo)->err->msg_parm.i[0] = (p1), \
  156362. (cinfo)->err->msg_parm.i[1] = (p2), \
  156363. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156364. /* Informational/debugging messages */
  156365. #define TRACEMS(cinfo,lvl,code) \
  156366. ((cinfo)->err->msg_code = (code), \
  156367. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156368. #define TRACEMS1(cinfo,lvl,code,p1) \
  156369. ((cinfo)->err->msg_code = (code), \
  156370. (cinfo)->err->msg_parm.i[0] = (p1), \
  156371. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156372. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  156373. ((cinfo)->err->msg_code = (code), \
  156374. (cinfo)->err->msg_parm.i[0] = (p1), \
  156375. (cinfo)->err->msg_parm.i[1] = (p2), \
  156376. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156377. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  156378. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156379. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  156380. (cinfo)->err->msg_code = (code); \
  156381. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156382. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  156383. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156384. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156385. (cinfo)->err->msg_code = (code); \
  156386. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156387. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  156388. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156389. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156390. _mp[4] = (p5); \
  156391. (cinfo)->err->msg_code = (code); \
  156392. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156393. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  156394. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156395. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156396. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  156397. (cinfo)->err->msg_code = (code); \
  156398. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156399. #define TRACEMSS(cinfo,lvl,code,str) \
  156400. ((cinfo)->err->msg_code = (code), \
  156401. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  156402. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156403. #endif /* JERROR_H */
  156404. /********* End of inlined file: jerror.h *********/
  156405. /* fetch error codes too */
  156406. #endif
  156407. #endif /* JPEGLIB_H */
  156408. /********* End of inlined file: jpeglib.h *********/
  156409. /********* Start of inlined file: jcapimin.c *********/
  156410. #define JPEG_INTERNALS
  156411. /********* Start of inlined file: jinclude.h *********/
  156412. /* Include auto-config file to find out which system include files we need. */
  156413. #ifndef __jinclude_h__
  156414. #define __jinclude_h__
  156415. /********* Start of inlined file: jconfig.h *********/
  156416. /* see jconfig.doc for explanations */
  156417. // disable all the warnings under MSVC
  156418. #ifdef _MSC_VER
  156419. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  156420. #endif
  156421. #ifdef __BORLANDC__
  156422. #pragma warn -8057
  156423. #pragma warn -8019
  156424. #pragma warn -8004
  156425. #pragma warn -8008
  156426. #endif
  156427. #define HAVE_PROTOTYPES
  156428. #define HAVE_UNSIGNED_CHAR
  156429. #define HAVE_UNSIGNED_SHORT
  156430. /* #define void char */
  156431. /* #define const */
  156432. #undef CHAR_IS_UNSIGNED
  156433. #define HAVE_STDDEF_H
  156434. #define HAVE_STDLIB_H
  156435. #undef NEED_BSD_STRINGS
  156436. #undef NEED_SYS_TYPES_H
  156437. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  156438. #undef NEED_SHORT_EXTERNAL_NAMES
  156439. #undef INCOMPLETE_TYPES_BROKEN
  156440. /* Define "boolean" as unsigned char, not int, per Windows custom */
  156441. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  156442. typedef unsigned char boolean;
  156443. #endif
  156444. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  156445. #ifdef JPEG_INTERNALS
  156446. #undef RIGHT_SHIFT_IS_UNSIGNED
  156447. #endif /* JPEG_INTERNALS */
  156448. #ifdef JPEG_CJPEG_DJPEG
  156449. #define BMP_SUPPORTED /* BMP image file format */
  156450. #define GIF_SUPPORTED /* GIF image file format */
  156451. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  156452. #undef RLE_SUPPORTED /* Utah RLE image file format */
  156453. #define TARGA_SUPPORTED /* Targa image file format */
  156454. #define TWO_FILE_COMMANDLINE /* optional */
  156455. #define USE_SETMODE /* Microsoft has setmode() */
  156456. #undef NEED_SIGNAL_CATCHER
  156457. #undef DONT_USE_B_MODE
  156458. #undef PROGRESS_REPORT /* optional */
  156459. #endif /* JPEG_CJPEG_DJPEG */
  156460. /********* End of inlined file: jconfig.h *********/
  156461. /* auto configuration options */
  156462. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  156463. /*
  156464. * We need the NULL macro and size_t typedef.
  156465. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  156466. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  156467. * pull in <sys/types.h> as well.
  156468. * Note that the core JPEG library does not require <stdio.h>;
  156469. * only the default error handler and data source/destination modules do.
  156470. * But we must pull it in because of the references to FILE in jpeglib.h.
  156471. * You can remove those references if you want to compile without <stdio.h>.
  156472. */
  156473. #ifdef HAVE_STDDEF_H
  156474. #include <stddef.h>
  156475. #endif
  156476. #ifdef HAVE_STDLIB_H
  156477. #include <stdlib.h>
  156478. #endif
  156479. #ifdef NEED_SYS_TYPES_H
  156480. #include <sys/types.h>
  156481. #endif
  156482. #include <stdio.h>
  156483. /*
  156484. * We need memory copying and zeroing functions, plus strncpy().
  156485. * ANSI and System V implementations declare these in <string.h>.
  156486. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  156487. * Some systems may declare memset and memcpy in <memory.h>.
  156488. *
  156489. * NOTE: we assume the size parameters to these functions are of type size_t.
  156490. * Change the casts in these macros if not!
  156491. */
  156492. #ifdef NEED_BSD_STRINGS
  156493. #include <strings.h>
  156494. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  156495. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  156496. #else /* not BSD, assume ANSI/SysV string lib */
  156497. #include <string.h>
  156498. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  156499. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  156500. #endif
  156501. /*
  156502. * In ANSI C, and indeed any rational implementation, size_t is also the
  156503. * type returned by sizeof(). However, it seems there are some irrational
  156504. * implementations out there, in which sizeof() returns an int even though
  156505. * size_t is defined as long or unsigned long. To ensure consistent results
  156506. * we always use this SIZEOF() macro in place of using sizeof() directly.
  156507. */
  156508. #define SIZEOF(object) ((size_t) sizeof(object))
  156509. /*
  156510. * The modules that use fread() and fwrite() always invoke them through
  156511. * these macros. On some systems you may need to twiddle the argument casts.
  156512. * CAUTION: argument order is different from underlying functions!
  156513. */
  156514. #define JFREAD(file,buf,sizeofbuf) \
  156515. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  156516. #define JFWRITE(file,buf,sizeofbuf) \
  156517. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  156518. typedef enum { /* JPEG marker codes */
  156519. M_SOF0 = 0xc0,
  156520. M_SOF1 = 0xc1,
  156521. M_SOF2 = 0xc2,
  156522. M_SOF3 = 0xc3,
  156523. M_SOF5 = 0xc5,
  156524. M_SOF6 = 0xc6,
  156525. M_SOF7 = 0xc7,
  156526. M_JPG = 0xc8,
  156527. M_SOF9 = 0xc9,
  156528. M_SOF10 = 0xca,
  156529. M_SOF11 = 0xcb,
  156530. M_SOF13 = 0xcd,
  156531. M_SOF14 = 0xce,
  156532. M_SOF15 = 0xcf,
  156533. M_DHT = 0xc4,
  156534. M_DAC = 0xcc,
  156535. M_RST0 = 0xd0,
  156536. M_RST1 = 0xd1,
  156537. M_RST2 = 0xd2,
  156538. M_RST3 = 0xd3,
  156539. M_RST4 = 0xd4,
  156540. M_RST5 = 0xd5,
  156541. M_RST6 = 0xd6,
  156542. M_RST7 = 0xd7,
  156543. M_SOI = 0xd8,
  156544. M_EOI = 0xd9,
  156545. M_SOS = 0xda,
  156546. M_DQT = 0xdb,
  156547. M_DNL = 0xdc,
  156548. M_DRI = 0xdd,
  156549. M_DHP = 0xde,
  156550. M_EXP = 0xdf,
  156551. M_APP0 = 0xe0,
  156552. M_APP1 = 0xe1,
  156553. M_APP2 = 0xe2,
  156554. M_APP3 = 0xe3,
  156555. M_APP4 = 0xe4,
  156556. M_APP5 = 0xe5,
  156557. M_APP6 = 0xe6,
  156558. M_APP7 = 0xe7,
  156559. M_APP8 = 0xe8,
  156560. M_APP9 = 0xe9,
  156561. M_APP10 = 0xea,
  156562. M_APP11 = 0xeb,
  156563. M_APP12 = 0xec,
  156564. M_APP13 = 0xed,
  156565. M_APP14 = 0xee,
  156566. M_APP15 = 0xef,
  156567. M_JPG0 = 0xf0,
  156568. M_JPG13 = 0xfd,
  156569. M_COM = 0xfe,
  156570. M_TEM = 0x01,
  156571. M_ERROR = 0x100
  156572. } JPEG_MARKER;
  156573. /*
  156574. * Figure F.12: extend sign bit.
  156575. * On some machines, a shift and add will be faster than a table lookup.
  156576. */
  156577. #ifdef AVOID_TABLES
  156578. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  156579. #else
  156580. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  156581. static const int extend_test[16] = /* entry n is 2**(n-1) */
  156582. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  156583. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  156584. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  156585. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  156586. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  156587. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  156588. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  156589. #endif /* AVOID_TABLES */
  156590. #endif
  156591. /********* End of inlined file: jinclude.h *********/
  156592. /*
  156593. * Initialization of a JPEG compression object.
  156594. * The error manager must already be set up (in case memory manager fails).
  156595. */
  156596. GLOBAL(void)
  156597. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  156598. {
  156599. int i;
  156600. /* Guard against version mismatches between library and caller. */
  156601. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  156602. if (version != JPEG_LIB_VERSION)
  156603. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  156604. if (structsize != SIZEOF(struct jpeg_compress_struct))
  156605. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  156606. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  156607. /* For debugging purposes, we zero the whole master structure.
  156608. * But the application has already set the err pointer, and may have set
  156609. * client_data, so we have to save and restore those fields.
  156610. * Note: if application hasn't set client_data, tools like Purify may
  156611. * complain here.
  156612. */
  156613. {
  156614. struct jpeg_error_mgr * err = cinfo->err;
  156615. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  156616. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  156617. cinfo->err = err;
  156618. cinfo->client_data = client_data;
  156619. }
  156620. cinfo->is_decompressor = FALSE;
  156621. /* Initialize a memory manager instance for this object */
  156622. jinit_memory_mgr((j_common_ptr) cinfo);
  156623. /* Zero out pointers to permanent structures. */
  156624. cinfo->progress = NULL;
  156625. cinfo->dest = NULL;
  156626. cinfo->comp_info = NULL;
  156627. for (i = 0; i < NUM_QUANT_TBLS; i++)
  156628. cinfo->quant_tbl_ptrs[i] = NULL;
  156629. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  156630. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  156631. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  156632. }
  156633. cinfo->script_space = NULL;
  156634. cinfo->input_gamma = 1.0; /* in case application forgets */
  156635. /* OK, I'm ready */
  156636. cinfo->global_state = CSTATE_START;
  156637. }
  156638. /*
  156639. * Destruction of a JPEG compression object
  156640. */
  156641. GLOBAL(void)
  156642. jpeg_destroy_compress (j_compress_ptr cinfo)
  156643. {
  156644. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  156645. }
  156646. /*
  156647. * Abort processing of a JPEG compression operation,
  156648. * but don't destroy the object itself.
  156649. */
  156650. GLOBAL(void)
  156651. jpeg_abort_compress (j_compress_ptr cinfo)
  156652. {
  156653. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  156654. }
  156655. /*
  156656. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  156657. * Marks all currently defined tables as already written (if suppress)
  156658. * or not written (if !suppress). This will control whether they get emitted
  156659. * by a subsequent jpeg_start_compress call.
  156660. *
  156661. * This routine is exported for use by applications that want to produce
  156662. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  156663. * since it is called by jpeg_start_compress, we put it here --- otherwise
  156664. * jcparam.o would be linked whether the application used it or not.
  156665. */
  156666. GLOBAL(void)
  156667. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  156668. {
  156669. int i;
  156670. JQUANT_TBL * qtbl;
  156671. JHUFF_TBL * htbl;
  156672. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  156673. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  156674. qtbl->sent_table = suppress;
  156675. }
  156676. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  156677. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  156678. htbl->sent_table = suppress;
  156679. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  156680. htbl->sent_table = suppress;
  156681. }
  156682. }
  156683. /*
  156684. * Finish JPEG compression.
  156685. *
  156686. * If a multipass operating mode was selected, this may do a great deal of
  156687. * work including most of the actual output.
  156688. */
  156689. GLOBAL(void)
  156690. jpeg_finish_compress (j_compress_ptr cinfo)
  156691. {
  156692. JDIMENSION iMCU_row;
  156693. if (cinfo->global_state == CSTATE_SCANNING ||
  156694. cinfo->global_state == CSTATE_RAW_OK) {
  156695. /* Terminate first pass */
  156696. if (cinfo->next_scanline < cinfo->image_height)
  156697. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  156698. (*cinfo->master->finish_pass) (cinfo);
  156699. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  156700. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156701. /* Perform any remaining passes */
  156702. while (! cinfo->master->is_last_pass) {
  156703. (*cinfo->master->prepare_for_pass) (cinfo);
  156704. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  156705. if (cinfo->progress != NULL) {
  156706. cinfo->progress->pass_counter = (long) iMCU_row;
  156707. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  156708. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  156709. }
  156710. /* We bypass the main controller and invoke coef controller directly;
  156711. * all work is being done from the coefficient buffer.
  156712. */
  156713. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  156714. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  156715. }
  156716. (*cinfo->master->finish_pass) (cinfo);
  156717. }
  156718. /* Write EOI, do final cleanup */
  156719. (*cinfo->marker->write_file_trailer) (cinfo);
  156720. (*cinfo->dest->term_destination) (cinfo);
  156721. /* We can use jpeg_abort to release memory and reset global_state */
  156722. jpeg_abort((j_common_ptr) cinfo);
  156723. }
  156724. /*
  156725. * Write a special marker.
  156726. * This is only recommended for writing COM or APPn markers.
  156727. * Must be called after jpeg_start_compress() and before
  156728. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  156729. */
  156730. GLOBAL(void)
  156731. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  156732. const JOCTET *dataptr, unsigned int datalen)
  156733. {
  156734. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  156735. if (cinfo->next_scanline != 0 ||
  156736. (cinfo->global_state != CSTATE_SCANNING &&
  156737. cinfo->global_state != CSTATE_RAW_OK &&
  156738. cinfo->global_state != CSTATE_WRCOEFS))
  156739. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156740. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  156741. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  156742. while (datalen--) {
  156743. (*write_marker_byte) (cinfo, *dataptr);
  156744. dataptr++;
  156745. }
  156746. }
  156747. /* Same, but piecemeal. */
  156748. GLOBAL(void)
  156749. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  156750. {
  156751. if (cinfo->next_scanline != 0 ||
  156752. (cinfo->global_state != CSTATE_SCANNING &&
  156753. cinfo->global_state != CSTATE_RAW_OK &&
  156754. cinfo->global_state != CSTATE_WRCOEFS))
  156755. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156756. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  156757. }
  156758. GLOBAL(void)
  156759. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  156760. {
  156761. (*cinfo->marker->write_marker_byte) (cinfo, val);
  156762. }
  156763. /*
  156764. * Alternate compression function: just write an abbreviated table file.
  156765. * Before calling this, all parameters and a data destination must be set up.
  156766. *
  156767. * To produce a pair of files containing abbreviated tables and abbreviated
  156768. * image data, one would proceed as follows:
  156769. *
  156770. * initialize JPEG object
  156771. * set JPEG parameters
  156772. * set destination to table file
  156773. * jpeg_write_tables(cinfo);
  156774. * set destination to image file
  156775. * jpeg_start_compress(cinfo, FALSE);
  156776. * write data...
  156777. * jpeg_finish_compress(cinfo);
  156778. *
  156779. * jpeg_write_tables has the side effect of marking all tables written
  156780. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  156781. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  156782. */
  156783. GLOBAL(void)
  156784. jpeg_write_tables (j_compress_ptr cinfo)
  156785. {
  156786. if (cinfo->global_state != CSTATE_START)
  156787. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156788. /* (Re)initialize error mgr and destination modules */
  156789. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  156790. (*cinfo->dest->init_destination) (cinfo);
  156791. /* Initialize the marker writer ... bit of a crock to do it here. */
  156792. jinit_marker_writer(cinfo);
  156793. /* Write them tables! */
  156794. (*cinfo->marker->write_tables_only) (cinfo);
  156795. /* And clean up. */
  156796. (*cinfo->dest->term_destination) (cinfo);
  156797. /*
  156798. * In library releases up through v6a, we called jpeg_abort() here to free
  156799. * any working memory allocated by the destination manager and marker
  156800. * writer. Some applications had a problem with that: they allocated space
  156801. * of their own from the library memory manager, and didn't want it to go
  156802. * away during write_tables. So now we do nothing. This will cause a
  156803. * memory leak if an app calls write_tables repeatedly without doing a full
  156804. * compression cycle or otherwise resetting the JPEG object. However, that
  156805. * seems less bad than unexpectedly freeing memory in the normal case.
  156806. * An app that prefers the old behavior can call jpeg_abort for itself after
  156807. * each call to jpeg_write_tables().
  156808. */
  156809. }
  156810. /********* End of inlined file: jcapimin.c *********/
  156811. /********* Start of inlined file: jcapistd.c *********/
  156812. #define JPEG_INTERNALS
  156813. /*
  156814. * Compression initialization.
  156815. * Before calling this, all parameters and a data destination must be set up.
  156816. *
  156817. * We require a write_all_tables parameter as a failsafe check when writing
  156818. * multiple datastreams from the same compression object. Since prior runs
  156819. * will have left all the tables marked sent_table=TRUE, a subsequent run
  156820. * would emit an abbreviated stream (no tables) by default. This may be what
  156821. * is wanted, but for safety's sake it should not be the default behavior:
  156822. * programmers should have to make a deliberate choice to emit abbreviated
  156823. * images. Therefore the documentation and examples should encourage people
  156824. * to pass write_all_tables=TRUE; then it will take active thought to do the
  156825. * wrong thing.
  156826. */
  156827. GLOBAL(void)
  156828. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  156829. {
  156830. if (cinfo->global_state != CSTATE_START)
  156831. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156832. if (write_all_tables)
  156833. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  156834. /* (Re)initialize error mgr and destination modules */
  156835. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  156836. (*cinfo->dest->init_destination) (cinfo);
  156837. /* Perform master selection of active modules */
  156838. jinit_compress_master(cinfo);
  156839. /* Set up for the first pass */
  156840. (*cinfo->master->prepare_for_pass) (cinfo);
  156841. /* Ready for application to drive first pass through jpeg_write_scanlines
  156842. * or jpeg_write_raw_data.
  156843. */
  156844. cinfo->next_scanline = 0;
  156845. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  156846. }
  156847. /*
  156848. * Write some scanlines of data to the JPEG compressor.
  156849. *
  156850. * The return value will be the number of lines actually written.
  156851. * This should be less than the supplied num_lines only in case that
  156852. * the data destination module has requested suspension of the compressor,
  156853. * or if more than image_height scanlines are passed in.
  156854. *
  156855. * Note: we warn about excess calls to jpeg_write_scanlines() since
  156856. * this likely signals an application programmer error. However,
  156857. * excess scanlines passed in the last valid call are *silently* ignored,
  156858. * so that the application need not adjust num_lines for end-of-image
  156859. * when using a multiple-scanline buffer.
  156860. */
  156861. GLOBAL(JDIMENSION)
  156862. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  156863. JDIMENSION num_lines)
  156864. {
  156865. JDIMENSION row_ctr, rows_left;
  156866. if (cinfo->global_state != CSTATE_SCANNING)
  156867. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156868. if (cinfo->next_scanline >= cinfo->image_height)
  156869. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  156870. /* Call progress monitor hook if present */
  156871. if (cinfo->progress != NULL) {
  156872. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  156873. cinfo->progress->pass_limit = (long) cinfo->image_height;
  156874. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  156875. }
  156876. /* Give master control module another chance if this is first call to
  156877. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  156878. * delayed so that application can write COM, etc, markers between
  156879. * jpeg_start_compress and jpeg_write_scanlines.
  156880. */
  156881. if (cinfo->master->call_pass_startup)
  156882. (*cinfo->master->pass_startup) (cinfo);
  156883. /* Ignore any extra scanlines at bottom of image. */
  156884. rows_left = cinfo->image_height - cinfo->next_scanline;
  156885. if (num_lines > rows_left)
  156886. num_lines = rows_left;
  156887. row_ctr = 0;
  156888. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  156889. cinfo->next_scanline += row_ctr;
  156890. return row_ctr;
  156891. }
  156892. /*
  156893. * Alternate entry point to write raw data.
  156894. * Processes exactly one iMCU row per call, unless suspended.
  156895. */
  156896. GLOBAL(JDIMENSION)
  156897. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  156898. JDIMENSION num_lines)
  156899. {
  156900. JDIMENSION lines_per_iMCU_row;
  156901. if (cinfo->global_state != CSTATE_RAW_OK)
  156902. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156903. if (cinfo->next_scanline >= cinfo->image_height) {
  156904. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  156905. return 0;
  156906. }
  156907. /* Call progress monitor hook if present */
  156908. if (cinfo->progress != NULL) {
  156909. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  156910. cinfo->progress->pass_limit = (long) cinfo->image_height;
  156911. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  156912. }
  156913. /* Give master control module another chance if this is first call to
  156914. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  156915. * delayed so that application can write COM, etc, markers between
  156916. * jpeg_start_compress and jpeg_write_raw_data.
  156917. */
  156918. if (cinfo->master->call_pass_startup)
  156919. (*cinfo->master->pass_startup) (cinfo);
  156920. /* Verify that at least one iMCU row has been passed. */
  156921. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  156922. if (num_lines < lines_per_iMCU_row)
  156923. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  156924. /* Directly compress the row. */
  156925. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  156926. /* If compressor did not consume the whole row, suspend processing. */
  156927. return 0;
  156928. }
  156929. /* OK, we processed one iMCU row. */
  156930. cinfo->next_scanline += lines_per_iMCU_row;
  156931. return lines_per_iMCU_row;
  156932. }
  156933. /********* End of inlined file: jcapistd.c *********/
  156934. /********* Start of inlined file: jccoefct.c *********/
  156935. #define JPEG_INTERNALS
  156936. /* We use a full-image coefficient buffer when doing Huffman optimization,
  156937. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  156938. * step is run during the first pass, and subsequent passes need only read
  156939. * the buffered coefficients.
  156940. */
  156941. #ifdef ENTROPY_OPT_SUPPORTED
  156942. #define FULL_COEF_BUFFER_SUPPORTED
  156943. #else
  156944. #ifdef C_MULTISCAN_FILES_SUPPORTED
  156945. #define FULL_COEF_BUFFER_SUPPORTED
  156946. #endif
  156947. #endif
  156948. /* Private buffer controller object */
  156949. typedef struct {
  156950. struct jpeg_c_coef_controller pub; /* public fields */
  156951. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  156952. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  156953. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  156954. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  156955. /* For single-pass compression, it's sufficient to buffer just one MCU
  156956. * (although this may prove a bit slow in practice). We allocate a
  156957. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  156958. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  156959. * it's not really very big; this is to keep the module interfaces unchanged
  156960. * when a large coefficient buffer is necessary.)
  156961. * In multi-pass modes, this array points to the current MCU's blocks
  156962. * within the virtual arrays.
  156963. */
  156964. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  156965. /* In multi-pass modes, we need a virtual block array for each component. */
  156966. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  156967. } my_coef_controller;
  156968. typedef my_coef_controller * my_coef_ptr;
  156969. /* Forward declarations */
  156970. METHODDEF(boolean) compress_data
  156971. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156972. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156973. METHODDEF(boolean) compress_first_pass
  156974. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156975. METHODDEF(boolean) compress_output
  156976. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156977. #endif
  156978. LOCAL(void)
  156979. start_iMCU_row (j_compress_ptr cinfo)
  156980. /* Reset within-iMCU-row counters for a new row */
  156981. {
  156982. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156983. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  156984. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  156985. * But at the bottom of the image, process only what's left.
  156986. */
  156987. if (cinfo->comps_in_scan > 1) {
  156988. coef->MCU_rows_per_iMCU_row = 1;
  156989. } else {
  156990. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  156991. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  156992. else
  156993. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  156994. }
  156995. coef->mcu_ctr = 0;
  156996. coef->MCU_vert_offset = 0;
  156997. }
  156998. /*
  156999. * Initialize for a processing pass.
  157000. */
  157001. METHODDEF(void)
  157002. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  157003. {
  157004. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157005. coef->iMCU_row_num = 0;
  157006. start_iMCU_row(cinfo);
  157007. switch (pass_mode) {
  157008. case JBUF_PASS_THRU:
  157009. if (coef->whole_image[0] != NULL)
  157010. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157011. coef->pub.compress_data = compress_data;
  157012. break;
  157013. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157014. case JBUF_SAVE_AND_PASS:
  157015. if (coef->whole_image[0] == NULL)
  157016. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157017. coef->pub.compress_data = compress_first_pass;
  157018. break;
  157019. case JBUF_CRANK_DEST:
  157020. if (coef->whole_image[0] == NULL)
  157021. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157022. coef->pub.compress_data = compress_output;
  157023. break;
  157024. #endif
  157025. default:
  157026. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157027. break;
  157028. }
  157029. }
  157030. /*
  157031. * Process some data in the single-pass case.
  157032. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157033. * per call, ie, v_samp_factor block rows for each component in the image.
  157034. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157035. *
  157036. * NB: input_buf contains a plane for each component in image,
  157037. * which we index according to the component's SOF position.
  157038. */
  157039. METHODDEF(boolean)
  157040. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157041. {
  157042. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157043. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157044. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  157045. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157046. int blkn, bi, ci, yindex, yoffset, blockcnt;
  157047. JDIMENSION ypos, xpos;
  157048. jpeg_component_info *compptr;
  157049. /* Loop to write as much as one whole iMCU row */
  157050. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157051. yoffset++) {
  157052. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  157053. MCU_col_num++) {
  157054. /* Determine where data comes from in input_buf and do the DCT thing.
  157055. * Each call on forward_DCT processes a horizontal row of DCT blocks
  157056. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  157057. * sequentially. Dummy blocks at the right or bottom edge are filled in
  157058. * specially. The data in them does not matter for image reconstruction,
  157059. * so we fill them with values that will encode to the smallest amount of
  157060. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  157061. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  157062. */
  157063. blkn = 0;
  157064. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157065. compptr = cinfo->cur_comp_info[ci];
  157066. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  157067. : compptr->last_col_width;
  157068. xpos = MCU_col_num * compptr->MCU_sample_width;
  157069. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  157070. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157071. if (coef->iMCU_row_num < last_iMCU_row ||
  157072. yoffset+yindex < compptr->last_row_height) {
  157073. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157074. input_buf[compptr->component_index],
  157075. coef->MCU_buffer[blkn],
  157076. ypos, xpos, (JDIMENSION) blockcnt);
  157077. if (blockcnt < compptr->MCU_width) {
  157078. /* Create some dummy blocks at the right edge of the image. */
  157079. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  157080. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  157081. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  157082. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  157083. }
  157084. }
  157085. } else {
  157086. /* Create a row of dummy blocks at the bottom of the image. */
  157087. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  157088. compptr->MCU_width * SIZEOF(JBLOCK));
  157089. for (bi = 0; bi < compptr->MCU_width; bi++) {
  157090. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  157091. }
  157092. }
  157093. blkn += compptr->MCU_width;
  157094. ypos += DCTSIZE;
  157095. }
  157096. }
  157097. /* Try to write the MCU. In event of a suspension failure, we will
  157098. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  157099. */
  157100. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157101. /* Suspension forced; update state counters and exit */
  157102. coef->MCU_vert_offset = yoffset;
  157103. coef->mcu_ctr = MCU_col_num;
  157104. return FALSE;
  157105. }
  157106. }
  157107. /* Completed an MCU row, but perhaps not an iMCU row */
  157108. coef->mcu_ctr = 0;
  157109. }
  157110. /* Completed the iMCU row, advance counters for next one */
  157111. coef->iMCU_row_num++;
  157112. start_iMCU_row(cinfo);
  157113. return TRUE;
  157114. }
  157115. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157116. /*
  157117. * Process some data in the first pass of a multi-pass case.
  157118. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157119. * per call, ie, v_samp_factor block rows for each component in the image.
  157120. * This amount of data is read from the source buffer, DCT'd and quantized,
  157121. * and saved into the virtual arrays. We also generate suitable dummy blocks
  157122. * as needed at the right and lower edges. (The dummy blocks are constructed
  157123. * in the virtual arrays, which have been padded appropriately.) This makes
  157124. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  157125. *
  157126. * We must also emit the data to the entropy encoder. This is conveniently
  157127. * done by calling compress_output() after we've loaded the current strip
  157128. * of the virtual arrays.
  157129. *
  157130. * NB: input_buf contains a plane for each component in image. All
  157131. * components are DCT'd and loaded into the virtual arrays in this pass.
  157132. * However, it may be that only a subset of the components are emitted to
  157133. * the entropy encoder during this first pass; be careful about looking
  157134. * at the scan-dependent variables (MCU dimensions, etc).
  157135. */
  157136. METHODDEF(boolean)
  157137. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157138. {
  157139. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157140. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157141. JDIMENSION blocks_across, MCUs_across, MCUindex;
  157142. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  157143. JCOEF lastDC;
  157144. jpeg_component_info *compptr;
  157145. JBLOCKARRAY buffer;
  157146. JBLOCKROW thisblockrow, lastblockrow;
  157147. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157148. ci++, compptr++) {
  157149. /* Align the virtual buffer for this component. */
  157150. buffer = (*cinfo->mem->access_virt_barray)
  157151. ((j_common_ptr) cinfo, coef->whole_image[ci],
  157152. coef->iMCU_row_num * compptr->v_samp_factor,
  157153. (JDIMENSION) compptr->v_samp_factor, TRUE);
  157154. /* Count non-dummy DCT block rows in this iMCU row. */
  157155. if (coef->iMCU_row_num < last_iMCU_row)
  157156. block_rows = compptr->v_samp_factor;
  157157. else {
  157158. /* NB: can't use last_row_height here, since may not be set! */
  157159. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  157160. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  157161. }
  157162. blocks_across = compptr->width_in_blocks;
  157163. h_samp_factor = compptr->h_samp_factor;
  157164. /* Count number of dummy blocks to be added at the right margin. */
  157165. ndummy = (int) (blocks_across % h_samp_factor);
  157166. if (ndummy > 0)
  157167. ndummy = h_samp_factor - ndummy;
  157168. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  157169. * on forward_DCT processes a complete horizontal row of DCT blocks.
  157170. */
  157171. for (block_row = 0; block_row < block_rows; block_row++) {
  157172. thisblockrow = buffer[block_row];
  157173. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157174. input_buf[ci], thisblockrow,
  157175. (JDIMENSION) (block_row * DCTSIZE),
  157176. (JDIMENSION) 0, blocks_across);
  157177. if (ndummy > 0) {
  157178. /* Create dummy blocks at the right edge of the image. */
  157179. thisblockrow += blocks_across; /* => first dummy block */
  157180. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  157181. lastDC = thisblockrow[-1][0];
  157182. for (bi = 0; bi < ndummy; bi++) {
  157183. thisblockrow[bi][0] = lastDC;
  157184. }
  157185. }
  157186. }
  157187. /* If at end of image, create dummy block rows as needed.
  157188. * The tricky part here is that within each MCU, we want the DC values
  157189. * of the dummy blocks to match the last real block's DC value.
  157190. * This squeezes a few more bytes out of the resulting file...
  157191. */
  157192. if (coef->iMCU_row_num == last_iMCU_row) {
  157193. blocks_across += ndummy; /* include lower right corner */
  157194. MCUs_across = blocks_across / h_samp_factor;
  157195. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  157196. block_row++) {
  157197. thisblockrow = buffer[block_row];
  157198. lastblockrow = buffer[block_row-1];
  157199. jzero_far((void FAR *) thisblockrow,
  157200. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  157201. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  157202. lastDC = lastblockrow[h_samp_factor-1][0];
  157203. for (bi = 0; bi < h_samp_factor; bi++) {
  157204. thisblockrow[bi][0] = lastDC;
  157205. }
  157206. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  157207. lastblockrow += h_samp_factor;
  157208. }
  157209. }
  157210. }
  157211. }
  157212. /* NB: compress_output will increment iMCU_row_num if successful.
  157213. * A suspension return will result in redoing all the work above next time.
  157214. */
  157215. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  157216. return compress_output(cinfo, input_buf);
  157217. }
  157218. /*
  157219. * Process some data in subsequent passes of a multi-pass case.
  157220. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157221. * per call, ie, v_samp_factor block rows for each component in the scan.
  157222. * The data is obtained from the virtual arrays and fed to the entropy coder.
  157223. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157224. *
  157225. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  157226. */
  157227. METHODDEF(boolean)
  157228. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157229. {
  157230. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157231. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157232. int blkn, ci, xindex, yindex, yoffset;
  157233. JDIMENSION start_col;
  157234. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  157235. JBLOCKROW buffer_ptr;
  157236. jpeg_component_info *compptr;
  157237. /* Align the virtual buffers for the components used in this scan.
  157238. * NB: during first pass, this is safe only because the buffers will
  157239. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  157240. */
  157241. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157242. compptr = cinfo->cur_comp_info[ci];
  157243. buffer[ci] = (*cinfo->mem->access_virt_barray)
  157244. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  157245. coef->iMCU_row_num * compptr->v_samp_factor,
  157246. (JDIMENSION) compptr->v_samp_factor, FALSE);
  157247. }
  157248. /* Loop to process one whole iMCU row */
  157249. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157250. yoffset++) {
  157251. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  157252. MCU_col_num++) {
  157253. /* Construct list of pointers to DCT blocks belonging to this MCU */
  157254. blkn = 0; /* index of current DCT block within MCU */
  157255. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157256. compptr = cinfo->cur_comp_info[ci];
  157257. start_col = MCU_col_num * compptr->MCU_width;
  157258. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157259. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  157260. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  157261. coef->MCU_buffer[blkn++] = buffer_ptr++;
  157262. }
  157263. }
  157264. }
  157265. /* Try to write the MCU. */
  157266. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157267. /* Suspension forced; update state counters and exit */
  157268. coef->MCU_vert_offset = yoffset;
  157269. coef->mcu_ctr = MCU_col_num;
  157270. return FALSE;
  157271. }
  157272. }
  157273. /* Completed an MCU row, but perhaps not an iMCU row */
  157274. coef->mcu_ctr = 0;
  157275. }
  157276. /* Completed the iMCU row, advance counters for next one */
  157277. coef->iMCU_row_num++;
  157278. start_iMCU_row(cinfo);
  157279. return TRUE;
  157280. }
  157281. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  157282. /*
  157283. * Initialize coefficient buffer controller.
  157284. */
  157285. GLOBAL(void)
  157286. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  157287. {
  157288. my_coef_ptr coef;
  157289. coef = (my_coef_ptr)
  157290. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157291. SIZEOF(my_coef_controller));
  157292. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  157293. coef->pub.start_pass = start_pass_coef;
  157294. /* Create the coefficient buffer. */
  157295. if (need_full_buffer) {
  157296. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157297. /* Allocate a full-image virtual array for each component, */
  157298. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  157299. int ci;
  157300. jpeg_component_info *compptr;
  157301. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157302. ci++, compptr++) {
  157303. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  157304. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  157305. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  157306. (long) compptr->h_samp_factor),
  157307. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  157308. (long) compptr->v_samp_factor),
  157309. (JDIMENSION) compptr->v_samp_factor);
  157310. }
  157311. #else
  157312. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157313. #endif
  157314. } else {
  157315. /* We only need a single-MCU buffer. */
  157316. JBLOCKROW buffer;
  157317. int i;
  157318. buffer = (JBLOCKROW)
  157319. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157320. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  157321. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  157322. coef->MCU_buffer[i] = buffer + i;
  157323. }
  157324. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  157325. }
  157326. }
  157327. /********* End of inlined file: jccoefct.c *********/
  157328. /********* Start of inlined file: jccolor.c *********/
  157329. #define JPEG_INTERNALS
  157330. /* Private subobject */
  157331. typedef struct {
  157332. struct jpeg_color_converter pub; /* public fields */
  157333. /* Private state for RGB->YCC conversion */
  157334. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  157335. } my_color_converter;
  157336. typedef my_color_converter * my_cconvert_ptr;
  157337. /**************** RGB -> YCbCr conversion: most common case **************/
  157338. /*
  157339. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  157340. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  157341. * The conversion equations to be implemented are therefore
  157342. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  157343. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  157344. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  157345. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  157346. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  157347. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  157348. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  157349. * were not represented exactly. Now we sacrifice exact representation of
  157350. * maximum red and maximum blue in order to get exact grayscales.
  157351. *
  157352. * To avoid floating-point arithmetic, we represent the fractional constants
  157353. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  157354. * the products by 2^16, with appropriate rounding, to get the correct answer.
  157355. *
  157356. * For even more speed, we avoid doing any multiplications in the inner loop
  157357. * by precalculating the constants times R,G,B for all possible values.
  157358. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  157359. * for 12-bit samples it is still acceptable. It's not very reasonable for
  157360. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  157361. * colorspace anyway.
  157362. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  157363. * in the tables to save adding them separately in the inner loop.
  157364. */
  157365. #define SCALEBITS 16 /* speediest right-shift on some machines */
  157366. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  157367. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  157368. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  157369. /* We allocate one big table and divide it up into eight parts, instead of
  157370. * doing eight alloc_small requests. This lets us use a single table base
  157371. * address, which can be held in a register in the inner loops on many
  157372. * machines (more than can hold all eight addresses, anyway).
  157373. */
  157374. #define R_Y_OFF 0 /* offset to R => Y section */
  157375. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  157376. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  157377. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  157378. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  157379. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  157380. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  157381. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  157382. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  157383. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  157384. /*
  157385. * Initialize for RGB->YCC colorspace conversion.
  157386. */
  157387. METHODDEF(void)
  157388. rgb_ycc_start (j_compress_ptr cinfo)
  157389. {
  157390. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157391. INT32 * rgb_ycc_tab;
  157392. INT32 i;
  157393. /* Allocate and fill in the conversion tables. */
  157394. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  157395. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157396. (TABLE_SIZE * SIZEOF(INT32)));
  157397. for (i = 0; i <= MAXJSAMPLE; i++) {
  157398. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  157399. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  157400. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  157401. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  157402. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  157403. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  157404. * This ensures that the maximum output will round to MAXJSAMPLE
  157405. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  157406. */
  157407. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  157408. /* B=>Cb and R=>Cr tables are the same
  157409. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  157410. */
  157411. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  157412. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  157413. }
  157414. }
  157415. /*
  157416. * Convert some rows of samples to the JPEG colorspace.
  157417. *
  157418. * Note that we change from the application's interleaved-pixel format
  157419. * to our internal noninterleaved, one-plane-per-component format.
  157420. * The input buffer is therefore three times as wide as the output buffer.
  157421. *
  157422. * A starting row offset is provided only for the output buffer. The caller
  157423. * can easily adjust the passed input_buf value to accommodate any row
  157424. * offset required on that side.
  157425. */
  157426. METHODDEF(void)
  157427. rgb_ycc_convert (j_compress_ptr cinfo,
  157428. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157429. JDIMENSION output_row, int num_rows)
  157430. {
  157431. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157432. register int r, g, b;
  157433. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157434. register JSAMPROW inptr;
  157435. register JSAMPROW outptr0, outptr1, outptr2;
  157436. register JDIMENSION col;
  157437. JDIMENSION num_cols = cinfo->image_width;
  157438. while (--num_rows >= 0) {
  157439. inptr = *input_buf++;
  157440. outptr0 = output_buf[0][output_row];
  157441. outptr1 = output_buf[1][output_row];
  157442. outptr2 = output_buf[2][output_row];
  157443. output_row++;
  157444. for (col = 0; col < num_cols; col++) {
  157445. r = GETJSAMPLE(inptr[RGB_RED]);
  157446. g = GETJSAMPLE(inptr[RGB_GREEN]);
  157447. b = GETJSAMPLE(inptr[RGB_BLUE]);
  157448. inptr += RGB_PIXELSIZE;
  157449. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  157450. * must be too; we do not need an explicit range-limiting operation.
  157451. * Hence the value being shifted is never negative, and we don't
  157452. * need the general RIGHT_SHIFT macro.
  157453. */
  157454. /* Y */
  157455. outptr0[col] = (JSAMPLE)
  157456. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  157457. >> SCALEBITS);
  157458. /* Cb */
  157459. outptr1[col] = (JSAMPLE)
  157460. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  157461. >> SCALEBITS);
  157462. /* Cr */
  157463. outptr2[col] = (JSAMPLE)
  157464. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  157465. >> SCALEBITS);
  157466. }
  157467. }
  157468. }
  157469. /**************** Cases other than RGB -> YCbCr **************/
  157470. /*
  157471. * Convert some rows of samples to the JPEG colorspace.
  157472. * This version handles RGB->grayscale conversion, which is the same
  157473. * as the RGB->Y portion of RGB->YCbCr.
  157474. * We assume rgb_ycc_start has been called (we only use the Y tables).
  157475. */
  157476. METHODDEF(void)
  157477. rgb_gray_convert (j_compress_ptr cinfo,
  157478. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157479. JDIMENSION output_row, int num_rows)
  157480. {
  157481. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157482. register int r, g, b;
  157483. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157484. register JSAMPROW inptr;
  157485. register JSAMPROW outptr;
  157486. register JDIMENSION col;
  157487. JDIMENSION num_cols = cinfo->image_width;
  157488. while (--num_rows >= 0) {
  157489. inptr = *input_buf++;
  157490. outptr = output_buf[0][output_row];
  157491. output_row++;
  157492. for (col = 0; col < num_cols; col++) {
  157493. r = GETJSAMPLE(inptr[RGB_RED]);
  157494. g = GETJSAMPLE(inptr[RGB_GREEN]);
  157495. b = GETJSAMPLE(inptr[RGB_BLUE]);
  157496. inptr += RGB_PIXELSIZE;
  157497. /* Y */
  157498. outptr[col] = (JSAMPLE)
  157499. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  157500. >> SCALEBITS);
  157501. }
  157502. }
  157503. }
  157504. /*
  157505. * Convert some rows of samples to the JPEG colorspace.
  157506. * This version handles Adobe-style CMYK->YCCK conversion,
  157507. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  157508. * conversion as above, while passing K (black) unchanged.
  157509. * We assume rgb_ycc_start has been called.
  157510. */
  157511. METHODDEF(void)
  157512. cmyk_ycck_convert (j_compress_ptr cinfo,
  157513. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157514. JDIMENSION output_row, int num_rows)
  157515. {
  157516. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157517. register int r, g, b;
  157518. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157519. register JSAMPROW inptr;
  157520. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  157521. register JDIMENSION col;
  157522. JDIMENSION num_cols = cinfo->image_width;
  157523. while (--num_rows >= 0) {
  157524. inptr = *input_buf++;
  157525. outptr0 = output_buf[0][output_row];
  157526. outptr1 = output_buf[1][output_row];
  157527. outptr2 = output_buf[2][output_row];
  157528. outptr3 = output_buf[3][output_row];
  157529. output_row++;
  157530. for (col = 0; col < num_cols; col++) {
  157531. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  157532. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  157533. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  157534. /* K passes through as-is */
  157535. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  157536. inptr += 4;
  157537. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  157538. * must be too; we do not need an explicit range-limiting operation.
  157539. * Hence the value being shifted is never negative, and we don't
  157540. * need the general RIGHT_SHIFT macro.
  157541. */
  157542. /* Y */
  157543. outptr0[col] = (JSAMPLE)
  157544. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  157545. >> SCALEBITS);
  157546. /* Cb */
  157547. outptr1[col] = (JSAMPLE)
  157548. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  157549. >> SCALEBITS);
  157550. /* Cr */
  157551. outptr2[col] = (JSAMPLE)
  157552. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  157553. >> SCALEBITS);
  157554. }
  157555. }
  157556. }
  157557. /*
  157558. * Convert some rows of samples to the JPEG colorspace.
  157559. * This version handles grayscale output with no conversion.
  157560. * The source can be either plain grayscale or YCbCr (since Y == gray).
  157561. */
  157562. METHODDEF(void)
  157563. grayscale_convert (j_compress_ptr cinfo,
  157564. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157565. JDIMENSION output_row, int num_rows)
  157566. {
  157567. register JSAMPROW inptr;
  157568. register JSAMPROW outptr;
  157569. register JDIMENSION col;
  157570. JDIMENSION num_cols = cinfo->image_width;
  157571. int instride = cinfo->input_components;
  157572. while (--num_rows >= 0) {
  157573. inptr = *input_buf++;
  157574. outptr = output_buf[0][output_row];
  157575. output_row++;
  157576. for (col = 0; col < num_cols; col++) {
  157577. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  157578. inptr += instride;
  157579. }
  157580. }
  157581. }
  157582. /*
  157583. * Convert some rows of samples to the JPEG colorspace.
  157584. * This version handles multi-component colorspaces without conversion.
  157585. * We assume input_components == num_components.
  157586. */
  157587. METHODDEF(void)
  157588. null_convert (j_compress_ptr cinfo,
  157589. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157590. JDIMENSION output_row, int num_rows)
  157591. {
  157592. register JSAMPROW inptr;
  157593. register JSAMPROW outptr;
  157594. register JDIMENSION col;
  157595. register int ci;
  157596. int nc = cinfo->num_components;
  157597. JDIMENSION num_cols = cinfo->image_width;
  157598. while (--num_rows >= 0) {
  157599. /* It seems fastest to make a separate pass for each component. */
  157600. for (ci = 0; ci < nc; ci++) {
  157601. inptr = *input_buf;
  157602. outptr = output_buf[ci][output_row];
  157603. for (col = 0; col < num_cols; col++) {
  157604. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  157605. inptr += nc;
  157606. }
  157607. }
  157608. input_buf++;
  157609. output_row++;
  157610. }
  157611. }
  157612. /*
  157613. * Empty method for start_pass.
  157614. */
  157615. METHODDEF(void)
  157616. null_method (j_compress_ptr cinfo)
  157617. {
  157618. /* no work needed */
  157619. }
  157620. /*
  157621. * Module initialization routine for input colorspace conversion.
  157622. */
  157623. GLOBAL(void)
  157624. jinit_color_converter (j_compress_ptr cinfo)
  157625. {
  157626. my_cconvert_ptr cconvert;
  157627. cconvert = (my_cconvert_ptr)
  157628. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157629. SIZEOF(my_color_converter));
  157630. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  157631. /* set start_pass to null method until we find out differently */
  157632. cconvert->pub.start_pass = null_method;
  157633. /* Make sure input_components agrees with in_color_space */
  157634. switch (cinfo->in_color_space) {
  157635. case JCS_GRAYSCALE:
  157636. if (cinfo->input_components != 1)
  157637. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157638. break;
  157639. case JCS_RGB:
  157640. #if RGB_PIXELSIZE != 3
  157641. if (cinfo->input_components != RGB_PIXELSIZE)
  157642. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157643. break;
  157644. #endif /* else share code with YCbCr */
  157645. case JCS_YCbCr:
  157646. if (cinfo->input_components != 3)
  157647. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157648. break;
  157649. case JCS_CMYK:
  157650. case JCS_YCCK:
  157651. if (cinfo->input_components != 4)
  157652. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157653. break;
  157654. default: /* JCS_UNKNOWN can be anything */
  157655. if (cinfo->input_components < 1)
  157656. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157657. break;
  157658. }
  157659. /* Check num_components, set conversion method based on requested space */
  157660. switch (cinfo->jpeg_color_space) {
  157661. case JCS_GRAYSCALE:
  157662. if (cinfo->num_components != 1)
  157663. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157664. if (cinfo->in_color_space == JCS_GRAYSCALE)
  157665. cconvert->pub.color_convert = grayscale_convert;
  157666. else if (cinfo->in_color_space == JCS_RGB) {
  157667. cconvert->pub.start_pass = rgb_ycc_start;
  157668. cconvert->pub.color_convert = rgb_gray_convert;
  157669. } else if (cinfo->in_color_space == JCS_YCbCr)
  157670. cconvert->pub.color_convert = grayscale_convert;
  157671. else
  157672. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157673. break;
  157674. case JCS_RGB:
  157675. if (cinfo->num_components != 3)
  157676. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157677. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  157678. cconvert->pub.color_convert = null_convert;
  157679. else
  157680. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157681. break;
  157682. case JCS_YCbCr:
  157683. if (cinfo->num_components != 3)
  157684. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157685. if (cinfo->in_color_space == JCS_RGB) {
  157686. cconvert->pub.start_pass = rgb_ycc_start;
  157687. cconvert->pub.color_convert = rgb_ycc_convert;
  157688. } else if (cinfo->in_color_space == JCS_YCbCr)
  157689. cconvert->pub.color_convert = null_convert;
  157690. else
  157691. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157692. break;
  157693. case JCS_CMYK:
  157694. if (cinfo->num_components != 4)
  157695. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157696. if (cinfo->in_color_space == JCS_CMYK)
  157697. cconvert->pub.color_convert = null_convert;
  157698. else
  157699. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157700. break;
  157701. case JCS_YCCK:
  157702. if (cinfo->num_components != 4)
  157703. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157704. if (cinfo->in_color_space == JCS_CMYK) {
  157705. cconvert->pub.start_pass = rgb_ycc_start;
  157706. cconvert->pub.color_convert = cmyk_ycck_convert;
  157707. } else if (cinfo->in_color_space == JCS_YCCK)
  157708. cconvert->pub.color_convert = null_convert;
  157709. else
  157710. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157711. break;
  157712. default: /* allow null conversion of JCS_UNKNOWN */
  157713. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  157714. cinfo->num_components != cinfo->input_components)
  157715. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157716. cconvert->pub.color_convert = null_convert;
  157717. break;
  157718. }
  157719. }
  157720. /********* End of inlined file: jccolor.c *********/
  157721. #undef FIX
  157722. /********* Start of inlined file: jcdctmgr.c *********/
  157723. #define JPEG_INTERNALS
  157724. /********* Start of inlined file: jdct.h *********/
  157725. /*
  157726. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  157727. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  157728. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  157729. * implementations use an array of type FAST_FLOAT, instead.)
  157730. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  157731. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  157732. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  157733. * convention improves accuracy in integer implementations and saves some
  157734. * work in floating-point ones.
  157735. * Quantization of the output coefficients is done by jcdctmgr.c.
  157736. */
  157737. #ifndef __jdct_h__
  157738. #define __jdct_h__
  157739. #if BITS_IN_JSAMPLE == 8
  157740. typedef int DCTELEM; /* 16 or 32 bits is fine */
  157741. #else
  157742. typedef INT32 DCTELEM; /* must have 32 bits */
  157743. #endif
  157744. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  157745. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  157746. /*
  157747. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  157748. * to an output sample array. The routine must dequantize the input data as
  157749. * well as perform the IDCT; for dequantization, it uses the multiplier table
  157750. * pointed to by compptr->dct_table. The output data is to be placed into the
  157751. * sample array starting at a specified column. (Any row offset needed will
  157752. * be applied to the array pointer before it is passed to the IDCT code.)
  157753. * Note that the number of samples emitted by the IDCT routine is
  157754. * DCT_scaled_size * DCT_scaled_size.
  157755. */
  157756. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  157757. /*
  157758. * Each IDCT routine has its own ideas about the best dct_table element type.
  157759. */
  157760. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  157761. #if BITS_IN_JSAMPLE == 8
  157762. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  157763. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  157764. #else
  157765. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  157766. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  157767. #endif
  157768. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  157769. /*
  157770. * Each IDCT routine is responsible for range-limiting its results and
  157771. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  157772. * be quite far out of range if the input data is corrupt, so a bulletproof
  157773. * range-limiting step is required. We use a mask-and-table-lookup method
  157774. * to do the combined operations quickly. See the comments with
  157775. * prepare_range_limit_table (in jdmaster.c) for more info.
  157776. */
  157777. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  157778. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  157779. /* Short forms of external names for systems with brain-damaged linkers. */
  157780. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157781. #define jpeg_fdct_islow jFDislow
  157782. #define jpeg_fdct_ifast jFDifast
  157783. #define jpeg_fdct_float jFDfloat
  157784. #define jpeg_idct_islow jRDislow
  157785. #define jpeg_idct_ifast jRDifast
  157786. #define jpeg_idct_float jRDfloat
  157787. #define jpeg_idct_4x4 jRD4x4
  157788. #define jpeg_idct_2x2 jRD2x2
  157789. #define jpeg_idct_1x1 jRD1x1
  157790. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157791. /* Extern declarations for the forward and inverse DCT routines. */
  157792. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  157793. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  157794. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  157795. EXTERN(void) jpeg_idct_islow
  157796. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157797. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157798. EXTERN(void) jpeg_idct_ifast
  157799. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157800. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157801. EXTERN(void) jpeg_idct_float
  157802. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157803. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157804. EXTERN(void) jpeg_idct_4x4
  157805. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157806. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157807. EXTERN(void) jpeg_idct_2x2
  157808. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157809. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157810. EXTERN(void) jpeg_idct_1x1
  157811. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157812. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157813. /*
  157814. * Macros for handling fixed-point arithmetic; these are used by many
  157815. * but not all of the DCT/IDCT modules.
  157816. *
  157817. * All values are expected to be of type INT32.
  157818. * Fractional constants are scaled left by CONST_BITS bits.
  157819. * CONST_BITS is defined within each module using these macros,
  157820. * and may differ from one module to the next.
  157821. */
  157822. #define ONE ((INT32) 1)
  157823. #define CONST_SCALE (ONE << CONST_BITS)
  157824. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  157825. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  157826. * thus causing a lot of useless floating-point operations at run time.
  157827. */
  157828. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  157829. /* Descale and correctly round an INT32 value that's scaled by N bits.
  157830. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  157831. * the fudge factor is correct for either sign of X.
  157832. */
  157833. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  157834. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  157835. * This macro is used only when the two inputs will actually be no more than
  157836. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  157837. * full 32x32 multiply. This provides a useful speedup on many machines.
  157838. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  157839. * in C, but some C compilers will do the right thing if you provide the
  157840. * correct combination of casts.
  157841. */
  157842. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  157843. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  157844. #endif
  157845. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  157846. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  157847. #endif
  157848. #ifndef MULTIPLY16C16 /* default definition */
  157849. #define MULTIPLY16C16(var,const) ((var) * (const))
  157850. #endif
  157851. /* Same except both inputs are variables. */
  157852. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  157853. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  157854. #endif
  157855. #ifndef MULTIPLY16V16 /* default definition */
  157856. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  157857. #endif
  157858. #endif
  157859. /********* End of inlined file: jdct.h *********/
  157860. /* Private declarations for DCT subsystem */
  157861. /* Private subobject for this module */
  157862. typedef struct {
  157863. struct jpeg_forward_dct pub; /* public fields */
  157864. /* Pointer to the DCT routine actually in use */
  157865. forward_DCT_method_ptr do_dct;
  157866. /* The actual post-DCT divisors --- not identical to the quant table
  157867. * entries, because of scaling (especially for an unnormalized DCT).
  157868. * Each table is given in normal array order.
  157869. */
  157870. DCTELEM * divisors[NUM_QUANT_TBLS];
  157871. #ifdef DCT_FLOAT_SUPPORTED
  157872. /* Same as above for the floating-point case. */
  157873. float_DCT_method_ptr do_float_dct;
  157874. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  157875. #endif
  157876. } my_fdct_controller;
  157877. typedef my_fdct_controller * my_fdct_ptr;
  157878. /*
  157879. * Initialize for a processing pass.
  157880. * Verify that all referenced Q-tables are present, and set up
  157881. * the divisor table for each one.
  157882. * In the current implementation, DCT of all components is done during
  157883. * the first pass, even if only some components will be output in the
  157884. * first scan. Hence all components should be examined here.
  157885. */
  157886. METHODDEF(void)
  157887. start_pass_fdctmgr (j_compress_ptr cinfo)
  157888. {
  157889. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157890. int ci, qtblno, i;
  157891. jpeg_component_info *compptr;
  157892. JQUANT_TBL * qtbl;
  157893. DCTELEM * dtbl;
  157894. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157895. ci++, compptr++) {
  157896. qtblno = compptr->quant_tbl_no;
  157897. /* Make sure specified quantization table is present */
  157898. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  157899. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  157900. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  157901. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  157902. /* Compute divisors for this quant table */
  157903. /* We may do this more than once for same table, but it's not a big deal */
  157904. switch (cinfo->dct_method) {
  157905. #ifdef DCT_ISLOW_SUPPORTED
  157906. case JDCT_ISLOW:
  157907. /* For LL&M IDCT method, divisors are equal to raw quantization
  157908. * coefficients multiplied by 8 (to counteract scaling).
  157909. */
  157910. if (fdct->divisors[qtblno] == NULL) {
  157911. fdct->divisors[qtblno] = (DCTELEM *)
  157912. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157913. DCTSIZE2 * SIZEOF(DCTELEM));
  157914. }
  157915. dtbl = fdct->divisors[qtblno];
  157916. for (i = 0; i < DCTSIZE2; i++) {
  157917. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  157918. }
  157919. break;
  157920. #endif
  157921. #ifdef DCT_IFAST_SUPPORTED
  157922. case JDCT_IFAST:
  157923. {
  157924. /* For AA&N IDCT method, divisors are equal to quantization
  157925. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  157926. * scalefactor[0] = 1
  157927. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  157928. * We apply a further scale factor of 8.
  157929. */
  157930. #define CONST_BITS 14
  157931. static const INT16 aanscales[DCTSIZE2] = {
  157932. /* precomputed values scaled up by 14 bits */
  157933. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  157934. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  157935. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  157936. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  157937. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  157938. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  157939. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  157940. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  157941. };
  157942. SHIFT_TEMPS
  157943. if (fdct->divisors[qtblno] == NULL) {
  157944. fdct->divisors[qtblno] = (DCTELEM *)
  157945. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157946. DCTSIZE2 * SIZEOF(DCTELEM));
  157947. }
  157948. dtbl = fdct->divisors[qtblno];
  157949. for (i = 0; i < DCTSIZE2; i++) {
  157950. dtbl[i] = (DCTELEM)
  157951. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  157952. (INT32) aanscales[i]),
  157953. CONST_BITS-3);
  157954. }
  157955. }
  157956. break;
  157957. #endif
  157958. #ifdef DCT_FLOAT_SUPPORTED
  157959. case JDCT_FLOAT:
  157960. {
  157961. /* For float AA&N IDCT method, divisors are equal to quantization
  157962. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  157963. * scalefactor[0] = 1
  157964. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  157965. * We apply a further scale factor of 8.
  157966. * What's actually stored is 1/divisor so that the inner loop can
  157967. * use a multiplication rather than a division.
  157968. */
  157969. FAST_FLOAT * fdtbl;
  157970. int row, col;
  157971. static const double aanscalefactor[DCTSIZE] = {
  157972. 1.0, 1.387039845, 1.306562965, 1.175875602,
  157973. 1.0, 0.785694958, 0.541196100, 0.275899379
  157974. };
  157975. if (fdct->float_divisors[qtblno] == NULL) {
  157976. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  157977. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157978. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  157979. }
  157980. fdtbl = fdct->float_divisors[qtblno];
  157981. i = 0;
  157982. for (row = 0; row < DCTSIZE; row++) {
  157983. for (col = 0; col < DCTSIZE; col++) {
  157984. fdtbl[i] = (FAST_FLOAT)
  157985. (1.0 / (((double) qtbl->quantval[i] *
  157986. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  157987. i++;
  157988. }
  157989. }
  157990. }
  157991. break;
  157992. #endif
  157993. default:
  157994. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157995. break;
  157996. }
  157997. }
  157998. }
  157999. /*
  158000. * Perform forward DCT on one or more blocks of a component.
  158001. *
  158002. * The input samples are taken from the sample_data[] array starting at
  158003. * position start_row/start_col, and moving to the right for any additional
  158004. * blocks. The quantized coefficients are returned in coef_blocks[].
  158005. */
  158006. METHODDEF(void)
  158007. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158008. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158009. JDIMENSION start_row, JDIMENSION start_col,
  158010. JDIMENSION num_blocks)
  158011. /* This version is used for integer DCT implementations. */
  158012. {
  158013. /* This routine is heavily used, so it's worth coding it tightly. */
  158014. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158015. forward_DCT_method_ptr do_dct = fdct->do_dct;
  158016. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  158017. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158018. JDIMENSION bi;
  158019. sample_data += start_row; /* fold in the vertical offset once */
  158020. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158021. /* Load data into workspace, applying unsigned->signed conversion */
  158022. { register DCTELEM *workspaceptr;
  158023. register JSAMPROW elemptr;
  158024. register int elemr;
  158025. workspaceptr = workspace;
  158026. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158027. elemptr = sample_data[elemr] + start_col;
  158028. #if DCTSIZE == 8 /* unroll the inner loop */
  158029. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158030. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158031. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158032. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158033. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158034. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158035. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158036. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158037. #else
  158038. { register int elemc;
  158039. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158040. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158041. }
  158042. }
  158043. #endif
  158044. }
  158045. }
  158046. /* Perform the DCT */
  158047. (*do_dct) (workspace);
  158048. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158049. { register DCTELEM temp, qval;
  158050. register int i;
  158051. register JCOEFPTR output_ptr = coef_blocks[bi];
  158052. for (i = 0; i < DCTSIZE2; i++) {
  158053. qval = divisors[i];
  158054. temp = workspace[i];
  158055. /* Divide the coefficient value by qval, ensuring proper rounding.
  158056. * Since C does not specify the direction of rounding for negative
  158057. * quotients, we have to force the dividend positive for portability.
  158058. *
  158059. * In most files, at least half of the output values will be zero
  158060. * (at default quantization settings, more like three-quarters...)
  158061. * so we should ensure that this case is fast. On many machines,
  158062. * a comparison is enough cheaper than a divide to make a special test
  158063. * a win. Since both inputs will be nonnegative, we need only test
  158064. * for a < b to discover whether a/b is 0.
  158065. * If your machine's division is fast enough, define FAST_DIVIDE.
  158066. */
  158067. #ifdef FAST_DIVIDE
  158068. #define DIVIDE_BY(a,b) a /= b
  158069. #else
  158070. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  158071. #endif
  158072. if (temp < 0) {
  158073. temp = -temp;
  158074. temp += qval>>1; /* for rounding */
  158075. DIVIDE_BY(temp, qval);
  158076. temp = -temp;
  158077. } else {
  158078. temp += qval>>1; /* for rounding */
  158079. DIVIDE_BY(temp, qval);
  158080. }
  158081. output_ptr[i] = (JCOEF) temp;
  158082. }
  158083. }
  158084. }
  158085. }
  158086. #ifdef DCT_FLOAT_SUPPORTED
  158087. METHODDEF(void)
  158088. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158089. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158090. JDIMENSION start_row, JDIMENSION start_col,
  158091. JDIMENSION num_blocks)
  158092. /* This version is used for floating-point DCT implementations. */
  158093. {
  158094. /* This routine is heavily used, so it's worth coding it tightly. */
  158095. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158096. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  158097. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  158098. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158099. JDIMENSION bi;
  158100. sample_data += start_row; /* fold in the vertical offset once */
  158101. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158102. /* Load data into workspace, applying unsigned->signed conversion */
  158103. { register FAST_FLOAT *workspaceptr;
  158104. register JSAMPROW elemptr;
  158105. register int elemr;
  158106. workspaceptr = workspace;
  158107. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158108. elemptr = sample_data[elemr] + start_col;
  158109. #if DCTSIZE == 8 /* unroll the inner loop */
  158110. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158111. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158112. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158113. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158114. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158115. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158116. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158117. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158118. #else
  158119. { register int elemc;
  158120. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158121. *workspaceptr++ = (FAST_FLOAT)
  158122. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158123. }
  158124. }
  158125. #endif
  158126. }
  158127. }
  158128. /* Perform the DCT */
  158129. (*do_dct) (workspace);
  158130. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158131. { register FAST_FLOAT temp;
  158132. register int i;
  158133. register JCOEFPTR output_ptr = coef_blocks[bi];
  158134. for (i = 0; i < DCTSIZE2; i++) {
  158135. /* Apply the quantization and scaling factor */
  158136. temp = workspace[i] * divisors[i];
  158137. /* Round to nearest integer.
  158138. * Since C does not specify the direction of rounding for negative
  158139. * quotients, we have to force the dividend positive for portability.
  158140. * The maximum coefficient size is +-16K (for 12-bit data), so this
  158141. * code should work for either 16-bit or 32-bit ints.
  158142. */
  158143. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  158144. }
  158145. }
  158146. }
  158147. }
  158148. #endif /* DCT_FLOAT_SUPPORTED */
  158149. /*
  158150. * Initialize FDCT manager.
  158151. */
  158152. GLOBAL(void)
  158153. jinit_forward_dct (j_compress_ptr cinfo)
  158154. {
  158155. my_fdct_ptr fdct;
  158156. int i;
  158157. fdct = (my_fdct_ptr)
  158158. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158159. SIZEOF(my_fdct_controller));
  158160. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  158161. fdct->pub.start_pass = start_pass_fdctmgr;
  158162. switch (cinfo->dct_method) {
  158163. #ifdef DCT_ISLOW_SUPPORTED
  158164. case JDCT_ISLOW:
  158165. fdct->pub.forward_DCT = forward_DCT;
  158166. fdct->do_dct = jpeg_fdct_islow;
  158167. break;
  158168. #endif
  158169. #ifdef DCT_IFAST_SUPPORTED
  158170. case JDCT_IFAST:
  158171. fdct->pub.forward_DCT = forward_DCT;
  158172. fdct->do_dct = jpeg_fdct_ifast;
  158173. break;
  158174. #endif
  158175. #ifdef DCT_FLOAT_SUPPORTED
  158176. case JDCT_FLOAT:
  158177. fdct->pub.forward_DCT = forward_DCT_float;
  158178. fdct->do_float_dct = jpeg_fdct_float;
  158179. break;
  158180. #endif
  158181. default:
  158182. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158183. break;
  158184. }
  158185. /* Mark divisor tables unallocated */
  158186. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158187. fdct->divisors[i] = NULL;
  158188. #ifdef DCT_FLOAT_SUPPORTED
  158189. fdct->float_divisors[i] = NULL;
  158190. #endif
  158191. }
  158192. }
  158193. /********* End of inlined file: jcdctmgr.c *********/
  158194. #undef CONST_BITS
  158195. /********* Start of inlined file: jchuff.c *********/
  158196. #define JPEG_INTERNALS
  158197. /********* Start of inlined file: jchuff.h *********/
  158198. /* The legal range of a DCT coefficient is
  158199. * -1024 .. +1023 for 8-bit data;
  158200. * -16384 .. +16383 for 12-bit data.
  158201. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  158202. */
  158203. #ifndef _jchuff_h_
  158204. #define _jchuff_h_
  158205. #if BITS_IN_JSAMPLE == 8
  158206. #define MAX_COEF_BITS 10
  158207. #else
  158208. #define MAX_COEF_BITS 14
  158209. #endif
  158210. /* Derived data constructed for each Huffman table */
  158211. typedef struct {
  158212. unsigned int ehufco[256]; /* code for each symbol */
  158213. char ehufsi[256]; /* length of code for each symbol */
  158214. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  158215. } c_derived_tbl;
  158216. /* Short forms of external names for systems with brain-damaged linkers. */
  158217. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158218. #define jpeg_make_c_derived_tbl jMkCDerived
  158219. #define jpeg_gen_optimal_table jGenOptTbl
  158220. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158221. /* Expand a Huffman table definition into the derived format */
  158222. EXTERN(void) jpeg_make_c_derived_tbl
  158223. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  158224. c_derived_tbl ** pdtbl));
  158225. /* Generate an optimal table definition given the specified counts */
  158226. EXTERN(void) jpeg_gen_optimal_table
  158227. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  158228. #endif
  158229. /********* End of inlined file: jchuff.h *********/
  158230. /* Declarations shared with jcphuff.c */
  158231. /* Expanded entropy encoder object for Huffman encoding.
  158232. *
  158233. * The savable_state subrecord contains fields that change within an MCU,
  158234. * but must not be updated permanently until we complete the MCU.
  158235. */
  158236. typedef struct {
  158237. INT32 put_buffer; /* current bit-accumulation buffer */
  158238. int put_bits; /* # of bits now in it */
  158239. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  158240. } savable_state;
  158241. /* This macro is to work around compilers with missing or broken
  158242. * structure assignment. You'll need to fix this code if you have
  158243. * such a compiler and you change MAX_COMPS_IN_SCAN.
  158244. */
  158245. #ifndef NO_STRUCT_ASSIGN
  158246. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  158247. #else
  158248. #if MAX_COMPS_IN_SCAN == 4
  158249. #define ASSIGN_STATE(dest,src) \
  158250. ((dest).put_buffer = (src).put_buffer, \
  158251. (dest).put_bits = (src).put_bits, \
  158252. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  158253. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  158254. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  158255. (dest).last_dc_val[3] = (src).last_dc_val[3])
  158256. #endif
  158257. #endif
  158258. typedef struct {
  158259. struct jpeg_entropy_encoder pub; /* public fields */
  158260. savable_state saved; /* Bit buffer & DC state at start of MCU */
  158261. /* These fields are NOT loaded into local working state. */
  158262. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  158263. int next_restart_num; /* next restart number to write (0-7) */
  158264. /* Pointers to derived tables (these workspaces have image lifespan) */
  158265. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  158266. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  158267. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  158268. long * dc_count_ptrs[NUM_HUFF_TBLS];
  158269. long * ac_count_ptrs[NUM_HUFF_TBLS];
  158270. #endif
  158271. } huff_entropy_encoder;
  158272. typedef huff_entropy_encoder * huff_entropy_ptr;
  158273. /* Working state while writing an MCU.
  158274. * This struct contains all the fields that are needed by subroutines.
  158275. */
  158276. typedef struct {
  158277. JOCTET * next_output_byte; /* => next byte to write in buffer */
  158278. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  158279. savable_state cur; /* Current bit buffer & DC state */
  158280. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  158281. } working_state;
  158282. /* Forward declarations */
  158283. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  158284. JBLOCKROW *MCU_data));
  158285. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  158286. #ifdef ENTROPY_OPT_SUPPORTED
  158287. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  158288. JBLOCKROW *MCU_data));
  158289. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  158290. #endif
  158291. /*
  158292. * Initialize for a Huffman-compressed scan.
  158293. * If gather_statistics is TRUE, we do not output anything during the scan,
  158294. * just count the Huffman symbols used and generate Huffman code tables.
  158295. */
  158296. METHODDEF(void)
  158297. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  158298. {
  158299. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158300. int ci, dctbl, actbl;
  158301. jpeg_component_info * compptr;
  158302. if (gather_statistics) {
  158303. #ifdef ENTROPY_OPT_SUPPORTED
  158304. entropy->pub.encode_mcu = encode_mcu_gather;
  158305. entropy->pub.finish_pass = finish_pass_gather;
  158306. #else
  158307. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158308. #endif
  158309. } else {
  158310. entropy->pub.encode_mcu = encode_mcu_huff;
  158311. entropy->pub.finish_pass = finish_pass_huff;
  158312. }
  158313. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158314. compptr = cinfo->cur_comp_info[ci];
  158315. dctbl = compptr->dc_tbl_no;
  158316. actbl = compptr->ac_tbl_no;
  158317. if (gather_statistics) {
  158318. #ifdef ENTROPY_OPT_SUPPORTED
  158319. /* Check for invalid table indexes */
  158320. /* (make_c_derived_tbl does this in the other path) */
  158321. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  158322. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  158323. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  158324. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  158325. /* Allocate and zero the statistics tables */
  158326. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  158327. if (entropy->dc_count_ptrs[dctbl] == NULL)
  158328. entropy->dc_count_ptrs[dctbl] = (long *)
  158329. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158330. 257 * SIZEOF(long));
  158331. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  158332. if (entropy->ac_count_ptrs[actbl] == NULL)
  158333. entropy->ac_count_ptrs[actbl] = (long *)
  158334. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158335. 257 * SIZEOF(long));
  158336. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  158337. #endif
  158338. } else {
  158339. /* Compute derived values for Huffman tables */
  158340. /* We may do this more than once for a table, but it's not expensive */
  158341. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  158342. & entropy->dc_derived_tbls[dctbl]);
  158343. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  158344. & entropy->ac_derived_tbls[actbl]);
  158345. }
  158346. /* Initialize DC predictions to 0 */
  158347. entropy->saved.last_dc_val[ci] = 0;
  158348. }
  158349. /* Initialize bit buffer to empty */
  158350. entropy->saved.put_buffer = 0;
  158351. entropy->saved.put_bits = 0;
  158352. /* Initialize restart stuff */
  158353. entropy->restarts_to_go = cinfo->restart_interval;
  158354. entropy->next_restart_num = 0;
  158355. }
  158356. /*
  158357. * Compute the derived values for a Huffman table.
  158358. * This routine also performs some validation checks on the table.
  158359. *
  158360. * Note this is also used by jcphuff.c.
  158361. */
  158362. GLOBAL(void)
  158363. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  158364. c_derived_tbl ** pdtbl)
  158365. {
  158366. JHUFF_TBL *htbl;
  158367. c_derived_tbl *dtbl;
  158368. int p, i, l, lastp, si, maxsymbol;
  158369. char huffsize[257];
  158370. unsigned int huffcode[257];
  158371. unsigned int code;
  158372. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  158373. * paralleling the order of the symbols themselves in htbl->huffval[].
  158374. */
  158375. /* Find the input Huffman table */
  158376. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  158377. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  158378. htbl =
  158379. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  158380. if (htbl == NULL)
  158381. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  158382. /* Allocate a workspace if we haven't already done so. */
  158383. if (*pdtbl == NULL)
  158384. *pdtbl = (c_derived_tbl *)
  158385. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158386. SIZEOF(c_derived_tbl));
  158387. dtbl = *pdtbl;
  158388. /* Figure C.1: make table of Huffman code length for each symbol */
  158389. p = 0;
  158390. for (l = 1; l <= 16; l++) {
  158391. i = (int) htbl->bits[l];
  158392. if (i < 0 || p + i > 256) /* protect against table overrun */
  158393. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158394. while (i--)
  158395. huffsize[p++] = (char) l;
  158396. }
  158397. huffsize[p] = 0;
  158398. lastp = p;
  158399. /* Figure C.2: generate the codes themselves */
  158400. /* We also validate that the counts represent a legal Huffman code tree. */
  158401. code = 0;
  158402. si = huffsize[0];
  158403. p = 0;
  158404. while (huffsize[p]) {
  158405. while (((int) huffsize[p]) == si) {
  158406. huffcode[p++] = code;
  158407. code++;
  158408. }
  158409. /* code is now 1 more than the last code used for codelength si; but
  158410. * it must still fit in si bits, since no code is allowed to be all ones.
  158411. */
  158412. if (((INT32) code) >= (((INT32) 1) << si))
  158413. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158414. code <<= 1;
  158415. si++;
  158416. }
  158417. /* Figure C.3: generate encoding tables */
  158418. /* These are code and size indexed by symbol value */
  158419. /* Set all codeless symbols to have code length 0;
  158420. * this lets us detect duplicate VAL entries here, and later
  158421. * allows emit_bits to detect any attempt to emit such symbols.
  158422. */
  158423. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  158424. /* This is also a convenient place to check for out-of-range
  158425. * and duplicated VAL entries. We allow 0..255 for AC symbols
  158426. * but only 0..15 for DC. (We could constrain them further
  158427. * based on data depth and mode, but this seems enough.)
  158428. */
  158429. maxsymbol = isDC ? 15 : 255;
  158430. for (p = 0; p < lastp; p++) {
  158431. i = htbl->huffval[p];
  158432. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  158433. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158434. dtbl->ehufco[i] = huffcode[p];
  158435. dtbl->ehufsi[i] = huffsize[p];
  158436. }
  158437. }
  158438. /* Outputting bytes to the file */
  158439. /* Emit a byte, taking 'action' if must suspend. */
  158440. #define emit_byte(state,val,action) \
  158441. { *(state)->next_output_byte++ = (JOCTET) (val); \
  158442. if (--(state)->free_in_buffer == 0) \
  158443. if (! dump_buffer(state)) \
  158444. { action; } }
  158445. LOCAL(boolean)
  158446. dump_buffer (working_state * state)
  158447. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  158448. {
  158449. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  158450. if (! (*dest->empty_output_buffer) (state->cinfo))
  158451. return FALSE;
  158452. /* After a successful buffer dump, must reset buffer pointers */
  158453. state->next_output_byte = dest->next_output_byte;
  158454. state->free_in_buffer = dest->free_in_buffer;
  158455. return TRUE;
  158456. }
  158457. /* Outputting bits to the file */
  158458. /* Only the right 24 bits of put_buffer are used; the valid bits are
  158459. * left-justified in this part. At most 16 bits can be passed to emit_bits
  158460. * in one call, and we never retain more than 7 bits in put_buffer
  158461. * between calls, so 24 bits are sufficient.
  158462. */
  158463. INLINE
  158464. LOCAL(boolean)
  158465. emit_bits (working_state * state, unsigned int code, int size)
  158466. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  158467. {
  158468. /* This routine is heavily used, so it's worth coding tightly. */
  158469. register INT32 put_buffer = (INT32) code;
  158470. register int put_bits = state->cur.put_bits;
  158471. /* if size is 0, caller used an invalid Huffman table entry */
  158472. if (size == 0)
  158473. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  158474. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  158475. put_bits += size; /* new number of bits in buffer */
  158476. put_buffer <<= 24 - put_bits; /* align incoming bits */
  158477. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  158478. while (put_bits >= 8) {
  158479. int c = (int) ((put_buffer >> 16) & 0xFF);
  158480. emit_byte(state, c, return FALSE);
  158481. if (c == 0xFF) { /* need to stuff a zero byte? */
  158482. emit_byte(state, 0, return FALSE);
  158483. }
  158484. put_buffer <<= 8;
  158485. put_bits -= 8;
  158486. }
  158487. state->cur.put_buffer = put_buffer; /* update state variables */
  158488. state->cur.put_bits = put_bits;
  158489. return TRUE;
  158490. }
  158491. LOCAL(boolean)
  158492. flush_bits (working_state * state)
  158493. {
  158494. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  158495. return FALSE;
  158496. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  158497. state->cur.put_bits = 0;
  158498. return TRUE;
  158499. }
  158500. /* Encode a single block's worth of coefficients */
  158501. LOCAL(boolean)
  158502. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  158503. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  158504. {
  158505. register int temp, temp2;
  158506. register int nbits;
  158507. register int k, r, i;
  158508. /* Encode the DC coefficient difference per section F.1.2.1 */
  158509. temp = temp2 = block[0] - last_dc_val;
  158510. if (temp < 0) {
  158511. temp = -temp; /* temp is abs value of input */
  158512. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  158513. /* This code assumes we are on a two's complement machine */
  158514. temp2--;
  158515. }
  158516. /* Find the number of bits needed for the magnitude of the coefficient */
  158517. nbits = 0;
  158518. while (temp) {
  158519. nbits++;
  158520. temp >>= 1;
  158521. }
  158522. /* Check for out-of-range coefficient values.
  158523. * Since we're encoding a difference, the range limit is twice as much.
  158524. */
  158525. if (nbits > MAX_COEF_BITS+1)
  158526. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  158527. /* Emit the Huffman-coded symbol for the number of bits */
  158528. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  158529. return FALSE;
  158530. /* Emit that number of bits of the value, if positive, */
  158531. /* or the complement of its magnitude, if negative. */
  158532. if (nbits) /* emit_bits rejects calls with size 0 */
  158533. if (! emit_bits(state, (unsigned int) temp2, nbits))
  158534. return FALSE;
  158535. /* Encode the AC coefficients per section F.1.2.2 */
  158536. r = 0; /* r = run length of zeros */
  158537. for (k = 1; k < DCTSIZE2; k++) {
  158538. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  158539. r++;
  158540. } else {
  158541. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  158542. while (r > 15) {
  158543. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  158544. return FALSE;
  158545. r -= 16;
  158546. }
  158547. temp2 = temp;
  158548. if (temp < 0) {
  158549. temp = -temp; /* temp is abs value of input */
  158550. /* This code assumes we are on a two's complement machine */
  158551. temp2--;
  158552. }
  158553. /* Find the number of bits needed for the magnitude of the coefficient */
  158554. nbits = 1; /* there must be at least one 1 bit */
  158555. while ((temp >>= 1))
  158556. nbits++;
  158557. /* Check for out-of-range coefficient values */
  158558. if (nbits > MAX_COEF_BITS)
  158559. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  158560. /* Emit Huffman symbol for run length / number of bits */
  158561. i = (r << 4) + nbits;
  158562. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  158563. return FALSE;
  158564. /* Emit that number of bits of the value, if positive, */
  158565. /* or the complement of its magnitude, if negative. */
  158566. if (! emit_bits(state, (unsigned int) temp2, nbits))
  158567. return FALSE;
  158568. r = 0;
  158569. }
  158570. }
  158571. /* If the last coef(s) were zero, emit an end-of-block code */
  158572. if (r > 0)
  158573. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  158574. return FALSE;
  158575. return TRUE;
  158576. }
  158577. /*
  158578. * Emit a restart marker & resynchronize predictions.
  158579. */
  158580. LOCAL(boolean)
  158581. emit_restart (working_state * state, int restart_num)
  158582. {
  158583. int ci;
  158584. if (! flush_bits(state))
  158585. return FALSE;
  158586. emit_byte(state, 0xFF, return FALSE);
  158587. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  158588. /* Re-initialize DC predictions to 0 */
  158589. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  158590. state->cur.last_dc_val[ci] = 0;
  158591. /* The restart counter is not updated until we successfully write the MCU. */
  158592. return TRUE;
  158593. }
  158594. /*
  158595. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  158596. */
  158597. METHODDEF(boolean)
  158598. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  158599. {
  158600. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158601. working_state state;
  158602. int blkn, ci;
  158603. jpeg_component_info * compptr;
  158604. /* Load up working state */
  158605. state.next_output_byte = cinfo->dest->next_output_byte;
  158606. state.free_in_buffer = cinfo->dest->free_in_buffer;
  158607. ASSIGN_STATE(state.cur, entropy->saved);
  158608. state.cinfo = cinfo;
  158609. /* Emit restart marker if needed */
  158610. if (cinfo->restart_interval) {
  158611. if (entropy->restarts_to_go == 0)
  158612. if (! emit_restart(&state, entropy->next_restart_num))
  158613. return FALSE;
  158614. }
  158615. /* Encode the MCU data blocks */
  158616. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  158617. ci = cinfo->MCU_membership[blkn];
  158618. compptr = cinfo->cur_comp_info[ci];
  158619. if (! encode_one_block(&state,
  158620. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  158621. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  158622. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  158623. return FALSE;
  158624. /* Update last_dc_val */
  158625. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  158626. }
  158627. /* Completed MCU, so update state */
  158628. cinfo->dest->next_output_byte = state.next_output_byte;
  158629. cinfo->dest->free_in_buffer = state.free_in_buffer;
  158630. ASSIGN_STATE(entropy->saved, state.cur);
  158631. /* Update restart-interval state too */
  158632. if (cinfo->restart_interval) {
  158633. if (entropy->restarts_to_go == 0) {
  158634. entropy->restarts_to_go = cinfo->restart_interval;
  158635. entropy->next_restart_num++;
  158636. entropy->next_restart_num &= 7;
  158637. }
  158638. entropy->restarts_to_go--;
  158639. }
  158640. return TRUE;
  158641. }
  158642. /*
  158643. * Finish up at the end of a Huffman-compressed scan.
  158644. */
  158645. METHODDEF(void)
  158646. finish_pass_huff (j_compress_ptr cinfo)
  158647. {
  158648. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158649. working_state state;
  158650. /* Load up working state ... flush_bits needs it */
  158651. state.next_output_byte = cinfo->dest->next_output_byte;
  158652. state.free_in_buffer = cinfo->dest->free_in_buffer;
  158653. ASSIGN_STATE(state.cur, entropy->saved);
  158654. state.cinfo = cinfo;
  158655. /* Flush out the last data */
  158656. if (! flush_bits(&state))
  158657. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158658. /* Update state */
  158659. cinfo->dest->next_output_byte = state.next_output_byte;
  158660. cinfo->dest->free_in_buffer = state.free_in_buffer;
  158661. ASSIGN_STATE(entropy->saved, state.cur);
  158662. }
  158663. /*
  158664. * Huffman coding optimization.
  158665. *
  158666. * We first scan the supplied data and count the number of uses of each symbol
  158667. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  158668. * Then we build a Huffman coding tree for the observed counts.
  158669. * Symbols which are not needed at all for the particular image are not
  158670. * assigned any code, which saves space in the DHT marker as well as in
  158671. * the compressed data.
  158672. */
  158673. #ifdef ENTROPY_OPT_SUPPORTED
  158674. /* Process a single block's worth of coefficients */
  158675. LOCAL(void)
  158676. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  158677. long dc_counts[], long ac_counts[])
  158678. {
  158679. register int temp;
  158680. register int nbits;
  158681. register int k, r;
  158682. /* Encode the DC coefficient difference per section F.1.2.1 */
  158683. temp = block[0] - last_dc_val;
  158684. if (temp < 0)
  158685. temp = -temp;
  158686. /* Find the number of bits needed for the magnitude of the coefficient */
  158687. nbits = 0;
  158688. while (temp) {
  158689. nbits++;
  158690. temp >>= 1;
  158691. }
  158692. /* Check for out-of-range coefficient values.
  158693. * Since we're encoding a difference, the range limit is twice as much.
  158694. */
  158695. if (nbits > MAX_COEF_BITS+1)
  158696. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  158697. /* Count the Huffman symbol for the number of bits */
  158698. dc_counts[nbits]++;
  158699. /* Encode the AC coefficients per section F.1.2.2 */
  158700. r = 0; /* r = run length of zeros */
  158701. for (k = 1; k < DCTSIZE2; k++) {
  158702. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  158703. r++;
  158704. } else {
  158705. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  158706. while (r > 15) {
  158707. ac_counts[0xF0]++;
  158708. r -= 16;
  158709. }
  158710. /* Find the number of bits needed for the magnitude of the coefficient */
  158711. if (temp < 0)
  158712. temp = -temp;
  158713. /* Find the number of bits needed for the magnitude of the coefficient */
  158714. nbits = 1; /* there must be at least one 1 bit */
  158715. while ((temp >>= 1))
  158716. nbits++;
  158717. /* Check for out-of-range coefficient values */
  158718. if (nbits > MAX_COEF_BITS)
  158719. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  158720. /* Count Huffman symbol for run length / number of bits */
  158721. ac_counts[(r << 4) + nbits]++;
  158722. r = 0;
  158723. }
  158724. }
  158725. /* If the last coef(s) were zero, emit an end-of-block code */
  158726. if (r > 0)
  158727. ac_counts[0]++;
  158728. }
  158729. /*
  158730. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  158731. * No data is actually output, so no suspension return is possible.
  158732. */
  158733. METHODDEF(boolean)
  158734. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  158735. {
  158736. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158737. int blkn, ci;
  158738. jpeg_component_info * compptr;
  158739. /* Take care of restart intervals if needed */
  158740. if (cinfo->restart_interval) {
  158741. if (entropy->restarts_to_go == 0) {
  158742. /* Re-initialize DC predictions to 0 */
  158743. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  158744. entropy->saved.last_dc_val[ci] = 0;
  158745. /* Update restart state */
  158746. entropy->restarts_to_go = cinfo->restart_interval;
  158747. }
  158748. entropy->restarts_to_go--;
  158749. }
  158750. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  158751. ci = cinfo->MCU_membership[blkn];
  158752. compptr = cinfo->cur_comp_info[ci];
  158753. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  158754. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  158755. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  158756. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  158757. }
  158758. return TRUE;
  158759. }
  158760. /*
  158761. * Generate the best Huffman code table for the given counts, fill htbl.
  158762. * Note this is also used by jcphuff.c.
  158763. *
  158764. * The JPEG standard requires that no symbol be assigned a codeword of all
  158765. * one bits (so that padding bits added at the end of a compressed segment
  158766. * can't look like a valid code). Because of the canonical ordering of
  158767. * codewords, this just means that there must be an unused slot in the
  158768. * longest codeword length category. Section K.2 of the JPEG spec suggests
  158769. * reserving such a slot by pretending that symbol 256 is a valid symbol
  158770. * with count 1. In theory that's not optimal; giving it count zero but
  158771. * including it in the symbol set anyway should give a better Huffman code.
  158772. * But the theoretically better code actually seems to come out worse in
  158773. * practice, because it produces more all-ones bytes (which incur stuffed
  158774. * zero bytes in the final file). In any case the difference is tiny.
  158775. *
  158776. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  158777. * If some symbols have a very small but nonzero probability, the Huffman tree
  158778. * must be adjusted to meet the code length restriction. We currently use
  158779. * the adjustment method suggested in JPEG section K.2. This method is *not*
  158780. * optimal; it may not choose the best possible limited-length code. But
  158781. * typically only very-low-frequency symbols will be given less-than-optimal
  158782. * lengths, so the code is almost optimal. Experimental comparisons against
  158783. * an optimal limited-length-code algorithm indicate that the difference is
  158784. * microscopic --- usually less than a hundredth of a percent of total size.
  158785. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  158786. */
  158787. GLOBAL(void)
  158788. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  158789. {
  158790. #define MAX_CLEN 32 /* assumed maximum initial code length */
  158791. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  158792. int codesize[257]; /* codesize[k] = code length of symbol k */
  158793. int others[257]; /* next symbol in current branch of tree */
  158794. int c1, c2;
  158795. int p, i, j;
  158796. long v;
  158797. /* This algorithm is explained in section K.2 of the JPEG standard */
  158798. MEMZERO(bits, SIZEOF(bits));
  158799. MEMZERO(codesize, SIZEOF(codesize));
  158800. for (i = 0; i < 257; i++)
  158801. others[i] = -1; /* init links to empty */
  158802. freq[256] = 1; /* make sure 256 has a nonzero count */
  158803. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  158804. * that no real symbol is given code-value of all ones, because 256
  158805. * will be placed last in the largest codeword category.
  158806. */
  158807. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  158808. for (;;) {
  158809. /* Find the smallest nonzero frequency, set c1 = its symbol */
  158810. /* In case of ties, take the larger symbol number */
  158811. c1 = -1;
  158812. v = 1000000000L;
  158813. for (i = 0; i <= 256; i++) {
  158814. if (freq[i] && freq[i] <= v) {
  158815. v = freq[i];
  158816. c1 = i;
  158817. }
  158818. }
  158819. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  158820. /* In case of ties, take the larger symbol number */
  158821. c2 = -1;
  158822. v = 1000000000L;
  158823. for (i = 0; i <= 256; i++) {
  158824. if (freq[i] && freq[i] <= v && i != c1) {
  158825. v = freq[i];
  158826. c2 = i;
  158827. }
  158828. }
  158829. /* Done if we've merged everything into one frequency */
  158830. if (c2 < 0)
  158831. break;
  158832. /* Else merge the two counts/trees */
  158833. freq[c1] += freq[c2];
  158834. freq[c2] = 0;
  158835. /* Increment the codesize of everything in c1's tree branch */
  158836. codesize[c1]++;
  158837. while (others[c1] >= 0) {
  158838. c1 = others[c1];
  158839. codesize[c1]++;
  158840. }
  158841. others[c1] = c2; /* chain c2 onto c1's tree branch */
  158842. /* Increment the codesize of everything in c2's tree branch */
  158843. codesize[c2]++;
  158844. while (others[c2] >= 0) {
  158845. c2 = others[c2];
  158846. codesize[c2]++;
  158847. }
  158848. }
  158849. /* Now count the number of symbols of each code length */
  158850. for (i = 0; i <= 256; i++) {
  158851. if (codesize[i]) {
  158852. /* The JPEG standard seems to think that this can't happen, */
  158853. /* but I'm paranoid... */
  158854. if (codesize[i] > MAX_CLEN)
  158855. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  158856. bits[codesize[i]]++;
  158857. }
  158858. }
  158859. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  158860. * Huffman procedure assigned any such lengths, we must adjust the coding.
  158861. * Here is what the JPEG spec says about how this next bit works:
  158862. * Since symbols are paired for the longest Huffman code, the symbols are
  158863. * removed from this length category two at a time. The prefix for the pair
  158864. * (which is one bit shorter) is allocated to one of the pair; then,
  158865. * skipping the BITS entry for that prefix length, a code word from the next
  158866. * shortest nonzero BITS entry is converted into a prefix for two code words
  158867. * one bit longer.
  158868. */
  158869. for (i = MAX_CLEN; i > 16; i--) {
  158870. while (bits[i] > 0) {
  158871. j = i - 2; /* find length of new prefix to be used */
  158872. while (bits[j] == 0)
  158873. j--;
  158874. bits[i] -= 2; /* remove two symbols */
  158875. bits[i-1]++; /* one goes in this length */
  158876. bits[j+1] += 2; /* two new symbols in this length */
  158877. bits[j]--; /* symbol of this length is now a prefix */
  158878. }
  158879. }
  158880. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  158881. while (bits[i] == 0) /* find largest codelength still in use */
  158882. i--;
  158883. bits[i]--;
  158884. /* Return final symbol counts (only for lengths 0..16) */
  158885. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  158886. /* Return a list of the symbols sorted by code length */
  158887. /* It's not real clear to me why we don't need to consider the codelength
  158888. * changes made above, but the JPEG spec seems to think this works.
  158889. */
  158890. p = 0;
  158891. for (i = 1; i <= MAX_CLEN; i++) {
  158892. for (j = 0; j <= 255; j++) {
  158893. if (codesize[j] == i) {
  158894. htbl->huffval[p] = (UINT8) j;
  158895. p++;
  158896. }
  158897. }
  158898. }
  158899. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  158900. htbl->sent_table = FALSE;
  158901. }
  158902. /*
  158903. * Finish up a statistics-gathering pass and create the new Huffman tables.
  158904. */
  158905. METHODDEF(void)
  158906. finish_pass_gather (j_compress_ptr cinfo)
  158907. {
  158908. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158909. int ci, dctbl, actbl;
  158910. jpeg_component_info * compptr;
  158911. JHUFF_TBL **htblptr;
  158912. boolean did_dc[NUM_HUFF_TBLS];
  158913. boolean did_ac[NUM_HUFF_TBLS];
  158914. /* It's important not to apply jpeg_gen_optimal_table more than once
  158915. * per table, because it clobbers the input frequency counts!
  158916. */
  158917. MEMZERO(did_dc, SIZEOF(did_dc));
  158918. MEMZERO(did_ac, SIZEOF(did_ac));
  158919. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158920. compptr = cinfo->cur_comp_info[ci];
  158921. dctbl = compptr->dc_tbl_no;
  158922. actbl = compptr->ac_tbl_no;
  158923. if (! did_dc[dctbl]) {
  158924. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  158925. if (*htblptr == NULL)
  158926. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  158927. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  158928. did_dc[dctbl] = TRUE;
  158929. }
  158930. if (! did_ac[actbl]) {
  158931. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  158932. if (*htblptr == NULL)
  158933. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  158934. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  158935. did_ac[actbl] = TRUE;
  158936. }
  158937. }
  158938. }
  158939. #endif /* ENTROPY_OPT_SUPPORTED */
  158940. /*
  158941. * Module initialization routine for Huffman entropy encoding.
  158942. */
  158943. GLOBAL(void)
  158944. jinit_huff_encoder (j_compress_ptr cinfo)
  158945. {
  158946. huff_entropy_ptr entropy;
  158947. int i;
  158948. entropy = (huff_entropy_ptr)
  158949. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158950. SIZEOF(huff_entropy_encoder));
  158951. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  158952. entropy->pub.start_pass = start_pass_huff;
  158953. /* Mark tables unallocated */
  158954. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158955. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  158956. #ifdef ENTROPY_OPT_SUPPORTED
  158957. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  158958. #endif
  158959. }
  158960. }
  158961. /********* End of inlined file: jchuff.c *********/
  158962. #undef emit_byte
  158963. /********* Start of inlined file: jcinit.c *********/
  158964. #define JPEG_INTERNALS
  158965. /*
  158966. * Master selection of compression modules.
  158967. * This is done once at the start of processing an image. We determine
  158968. * which modules will be used and give them appropriate initialization calls.
  158969. */
  158970. GLOBAL(void)
  158971. jinit_compress_master (j_compress_ptr cinfo)
  158972. {
  158973. /* Initialize master control (includes parameter checking/processing) */
  158974. jinit_c_master_control(cinfo, FALSE /* full compression */);
  158975. /* Preprocessing */
  158976. if (! cinfo->raw_data_in) {
  158977. jinit_color_converter(cinfo);
  158978. jinit_downsampler(cinfo);
  158979. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  158980. }
  158981. /* Forward DCT */
  158982. jinit_forward_dct(cinfo);
  158983. /* Entropy encoding: either Huffman or arithmetic coding. */
  158984. if (cinfo->arith_code) {
  158985. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  158986. } else {
  158987. if (cinfo->progressive_mode) {
  158988. #ifdef C_PROGRESSIVE_SUPPORTED
  158989. jinit_phuff_encoder(cinfo);
  158990. #else
  158991. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158992. #endif
  158993. } else
  158994. jinit_huff_encoder(cinfo);
  158995. }
  158996. /* Need a full-image coefficient buffer in any multi-pass mode. */
  158997. jinit_c_coef_controller(cinfo,
  158998. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  158999. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  159000. jinit_marker_writer(cinfo);
  159001. /* We can now tell the memory manager to allocate virtual arrays. */
  159002. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  159003. /* Write the datastream header (SOI) immediately.
  159004. * Frame and scan headers are postponed till later.
  159005. * This lets application insert special markers after the SOI.
  159006. */
  159007. (*cinfo->marker->write_file_header) (cinfo);
  159008. }
  159009. /********* End of inlined file: jcinit.c *********/
  159010. /********* Start of inlined file: jcmainct.c *********/
  159011. #define JPEG_INTERNALS
  159012. /* Note: currently, there is no operating mode in which a full-image buffer
  159013. * is needed at this step. If there were, that mode could not be used with
  159014. * "raw data" input, since this module is bypassed in that case. However,
  159015. * we've left the code here for possible use in special applications.
  159016. */
  159017. #undef FULL_MAIN_BUFFER_SUPPORTED
  159018. /* Private buffer controller object */
  159019. typedef struct {
  159020. struct jpeg_c_main_controller pub; /* public fields */
  159021. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  159022. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  159023. boolean suspended; /* remember if we suspended output */
  159024. J_BUF_MODE pass_mode; /* current operating mode */
  159025. /* If using just a strip buffer, this points to the entire set of buffers
  159026. * (we allocate one for each component). In the full-image case, this
  159027. * points to the currently accessible strips of the virtual arrays.
  159028. */
  159029. JSAMPARRAY buffer[MAX_COMPONENTS];
  159030. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159031. /* If using full-image storage, this array holds pointers to virtual-array
  159032. * control blocks for each component. Unused if not full-image storage.
  159033. */
  159034. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  159035. #endif
  159036. } my_main_controller;
  159037. typedef my_main_controller * my_main_ptr;
  159038. /* Forward declarations */
  159039. METHODDEF(void) process_data_simple_main
  159040. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159041. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159042. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159043. METHODDEF(void) process_data_buffer_main
  159044. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159045. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159046. #endif
  159047. /*
  159048. * Initialize for a processing pass.
  159049. */
  159050. METHODDEF(void)
  159051. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  159052. {
  159053. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159054. /* Do nothing in raw-data mode. */
  159055. if (cinfo->raw_data_in)
  159056. return;
  159057. main_->cur_iMCU_row = 0; /* initialize counters */
  159058. main_->rowgroup_ctr = 0;
  159059. main_->suspended = FALSE;
  159060. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  159061. switch (pass_mode) {
  159062. case JBUF_PASS_THRU:
  159063. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159064. if (main_->whole_image[0] != NULL)
  159065. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159066. #endif
  159067. main_->pub.process_data = process_data_simple_main;
  159068. break;
  159069. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159070. case JBUF_SAVE_SOURCE:
  159071. case JBUF_CRANK_DEST:
  159072. case JBUF_SAVE_AND_PASS:
  159073. if (main_->whole_image[0] == NULL)
  159074. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159075. main_->pub.process_data = process_data_buffer_main;
  159076. break;
  159077. #endif
  159078. default:
  159079. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159080. break;
  159081. }
  159082. }
  159083. /*
  159084. * Process some data.
  159085. * This routine handles the simple pass-through mode,
  159086. * where we have only a strip buffer.
  159087. */
  159088. METHODDEF(void)
  159089. process_data_simple_main (j_compress_ptr cinfo,
  159090. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159091. JDIMENSION in_rows_avail)
  159092. {
  159093. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159094. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159095. /* Read input data if we haven't filled the main buffer yet */
  159096. if (main_->rowgroup_ctr < DCTSIZE)
  159097. (*cinfo->prep->pre_process_data) (cinfo,
  159098. input_buf, in_row_ctr, in_rows_avail,
  159099. main_->buffer, &main_->rowgroup_ctr,
  159100. (JDIMENSION) DCTSIZE);
  159101. /* If we don't have a full iMCU row buffered, return to application for
  159102. * more data. Note that preprocessor will always pad to fill the iMCU row
  159103. * at the bottom of the image.
  159104. */
  159105. if (main_->rowgroup_ctr != DCTSIZE)
  159106. return;
  159107. /* Send the completed row to the compressor */
  159108. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  159109. /* If compressor did not consume the whole row, then we must need to
  159110. * suspend processing and return to the application. In this situation
  159111. * we pretend we didn't yet consume the last input row; otherwise, if
  159112. * it happened to be the last row of the image, the application would
  159113. * think we were done.
  159114. */
  159115. if (! main_->suspended) {
  159116. (*in_row_ctr)--;
  159117. main_->suspended = TRUE;
  159118. }
  159119. return;
  159120. }
  159121. /* We did finish the row. Undo our little suspension hack if a previous
  159122. * call suspended; then mark the main buffer empty.
  159123. */
  159124. if (main_->suspended) {
  159125. (*in_row_ctr)++;
  159126. main_->suspended = FALSE;
  159127. }
  159128. main_->rowgroup_ctr = 0;
  159129. main_->cur_iMCU_row++;
  159130. }
  159131. }
  159132. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159133. /*
  159134. * Process some data.
  159135. * This routine handles all of the modes that use a full-size buffer.
  159136. */
  159137. METHODDEF(void)
  159138. process_data_buffer_main (j_compress_ptr cinfo,
  159139. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159140. JDIMENSION in_rows_avail)
  159141. {
  159142. my_main_ptr main = (my_main_ptr) cinfo->main;
  159143. int ci;
  159144. jpeg_component_info *compptr;
  159145. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  159146. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159147. /* Realign the virtual buffers if at the start of an iMCU row. */
  159148. if (main->rowgroup_ctr == 0) {
  159149. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159150. ci++, compptr++) {
  159151. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  159152. ((j_common_ptr) cinfo, main->whole_image[ci],
  159153. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  159154. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  159155. }
  159156. /* In a read pass, pretend we just read some source data. */
  159157. if (! writing) {
  159158. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  159159. main->rowgroup_ctr = DCTSIZE;
  159160. }
  159161. }
  159162. /* If a write pass, read input data until the current iMCU row is full. */
  159163. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  159164. if (writing) {
  159165. (*cinfo->prep->pre_process_data) (cinfo,
  159166. input_buf, in_row_ctr, in_rows_avail,
  159167. main->buffer, &main->rowgroup_ctr,
  159168. (JDIMENSION) DCTSIZE);
  159169. /* Return to application if we need more data to fill the iMCU row. */
  159170. if (main->rowgroup_ctr < DCTSIZE)
  159171. return;
  159172. }
  159173. /* Emit data, unless this is a sink-only pass. */
  159174. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  159175. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  159176. /* If compressor did not consume the whole row, then we must need to
  159177. * suspend processing and return to the application. In this situation
  159178. * we pretend we didn't yet consume the last input row; otherwise, if
  159179. * it happened to be the last row of the image, the application would
  159180. * think we were done.
  159181. */
  159182. if (! main->suspended) {
  159183. (*in_row_ctr)--;
  159184. main->suspended = TRUE;
  159185. }
  159186. return;
  159187. }
  159188. /* We did finish the row. Undo our little suspension hack if a previous
  159189. * call suspended; then mark the main buffer empty.
  159190. */
  159191. if (main->suspended) {
  159192. (*in_row_ctr)++;
  159193. main->suspended = FALSE;
  159194. }
  159195. }
  159196. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  159197. main->rowgroup_ctr = 0;
  159198. main->cur_iMCU_row++;
  159199. }
  159200. }
  159201. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  159202. /*
  159203. * Initialize main buffer controller.
  159204. */
  159205. GLOBAL(void)
  159206. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  159207. {
  159208. my_main_ptr main_;
  159209. int ci;
  159210. jpeg_component_info *compptr;
  159211. main_ = (my_main_ptr)
  159212. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159213. SIZEOF(my_main_controller));
  159214. cinfo->main = (struct jpeg_c_main_controller *) main_;
  159215. main_->pub.start_pass = start_pass_main;
  159216. /* We don't need to create a buffer in raw-data mode. */
  159217. if (cinfo->raw_data_in)
  159218. return;
  159219. /* Create the buffer. It holds downsampled data, so each component
  159220. * may be of a different size.
  159221. */
  159222. if (need_full_buffer) {
  159223. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159224. /* Allocate a full-image virtual array for each component */
  159225. /* Note we pad the bottom to a multiple of the iMCU height */
  159226. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159227. ci++, compptr++) {
  159228. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  159229. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  159230. compptr->width_in_blocks * DCTSIZE,
  159231. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  159232. (long) compptr->v_samp_factor) * DCTSIZE,
  159233. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159234. }
  159235. #else
  159236. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159237. #endif
  159238. } else {
  159239. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159240. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  159241. #endif
  159242. /* Allocate a strip buffer for each component */
  159243. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159244. ci++, compptr++) {
  159245. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  159246. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159247. compptr->width_in_blocks * DCTSIZE,
  159248. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159249. }
  159250. }
  159251. }
  159252. /********* End of inlined file: jcmainct.c *********/
  159253. /********* Start of inlined file: jcmarker.c *********/
  159254. #define JPEG_INTERNALS
  159255. /* Private state */
  159256. typedef struct {
  159257. struct jpeg_marker_writer pub; /* public fields */
  159258. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  159259. } my_marker_writer;
  159260. typedef my_marker_writer * my_marker_ptr;
  159261. /*
  159262. * Basic output routines.
  159263. *
  159264. * Note that we do not support suspension while writing a marker.
  159265. * Therefore, an application using suspension must ensure that there is
  159266. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  159267. * calling jpeg_start_compress, and enough space to write the trailing EOI
  159268. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  159269. * modes are not supported at all with suspension, so those two are the only
  159270. * points where markers will be written.
  159271. */
  159272. LOCAL(void)
  159273. emit_byte (j_compress_ptr cinfo, int val)
  159274. /* Emit a byte */
  159275. {
  159276. struct jpeg_destination_mgr * dest = cinfo->dest;
  159277. *(dest->next_output_byte)++ = (JOCTET) val;
  159278. if (--dest->free_in_buffer == 0) {
  159279. if (! (*dest->empty_output_buffer) (cinfo))
  159280. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159281. }
  159282. }
  159283. LOCAL(void)
  159284. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  159285. /* Emit a marker code */
  159286. {
  159287. emit_byte(cinfo, 0xFF);
  159288. emit_byte(cinfo, (int) mark);
  159289. }
  159290. LOCAL(void)
  159291. emit_2bytes (j_compress_ptr cinfo, int value)
  159292. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  159293. {
  159294. emit_byte(cinfo, (value >> 8) & 0xFF);
  159295. emit_byte(cinfo, value & 0xFF);
  159296. }
  159297. /*
  159298. * Routines to write specific marker types.
  159299. */
  159300. LOCAL(int)
  159301. emit_dqt (j_compress_ptr cinfo, int index)
  159302. /* Emit a DQT marker */
  159303. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  159304. {
  159305. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  159306. int prec;
  159307. int i;
  159308. if (qtbl == NULL)
  159309. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  159310. prec = 0;
  159311. for (i = 0; i < DCTSIZE2; i++) {
  159312. if (qtbl->quantval[i] > 255)
  159313. prec = 1;
  159314. }
  159315. if (! qtbl->sent_table) {
  159316. emit_marker(cinfo, M_DQT);
  159317. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  159318. emit_byte(cinfo, index + (prec<<4));
  159319. for (i = 0; i < DCTSIZE2; i++) {
  159320. /* The table entries must be emitted in zigzag order. */
  159321. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  159322. if (prec)
  159323. emit_byte(cinfo, (int) (qval >> 8));
  159324. emit_byte(cinfo, (int) (qval & 0xFF));
  159325. }
  159326. qtbl->sent_table = TRUE;
  159327. }
  159328. return prec;
  159329. }
  159330. LOCAL(void)
  159331. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  159332. /* Emit a DHT marker */
  159333. {
  159334. JHUFF_TBL * htbl;
  159335. int length, i;
  159336. if (is_ac) {
  159337. htbl = cinfo->ac_huff_tbl_ptrs[index];
  159338. index += 0x10; /* output index has AC bit set */
  159339. } else {
  159340. htbl = cinfo->dc_huff_tbl_ptrs[index];
  159341. }
  159342. if (htbl == NULL)
  159343. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  159344. if (! htbl->sent_table) {
  159345. emit_marker(cinfo, M_DHT);
  159346. length = 0;
  159347. for (i = 1; i <= 16; i++)
  159348. length += htbl->bits[i];
  159349. emit_2bytes(cinfo, length + 2 + 1 + 16);
  159350. emit_byte(cinfo, index);
  159351. for (i = 1; i <= 16; i++)
  159352. emit_byte(cinfo, htbl->bits[i]);
  159353. for (i = 0; i < length; i++)
  159354. emit_byte(cinfo, htbl->huffval[i]);
  159355. htbl->sent_table = TRUE;
  159356. }
  159357. }
  159358. LOCAL(void)
  159359. emit_dac (j_compress_ptr cinfo)
  159360. /* Emit a DAC marker */
  159361. /* Since the useful info is so small, we want to emit all the tables in */
  159362. /* one DAC marker. Therefore this routine does its own scan of the table. */
  159363. {
  159364. #ifdef C_ARITH_CODING_SUPPORTED
  159365. char dc_in_use[NUM_ARITH_TBLS];
  159366. char ac_in_use[NUM_ARITH_TBLS];
  159367. int length, i;
  159368. jpeg_component_info *compptr;
  159369. for (i = 0; i < NUM_ARITH_TBLS; i++)
  159370. dc_in_use[i] = ac_in_use[i] = 0;
  159371. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159372. compptr = cinfo->cur_comp_info[i];
  159373. dc_in_use[compptr->dc_tbl_no] = 1;
  159374. ac_in_use[compptr->ac_tbl_no] = 1;
  159375. }
  159376. length = 0;
  159377. for (i = 0; i < NUM_ARITH_TBLS; i++)
  159378. length += dc_in_use[i] + ac_in_use[i];
  159379. emit_marker(cinfo, M_DAC);
  159380. emit_2bytes(cinfo, length*2 + 2);
  159381. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  159382. if (dc_in_use[i]) {
  159383. emit_byte(cinfo, i);
  159384. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  159385. }
  159386. if (ac_in_use[i]) {
  159387. emit_byte(cinfo, i + 0x10);
  159388. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  159389. }
  159390. }
  159391. #endif /* C_ARITH_CODING_SUPPORTED */
  159392. }
  159393. LOCAL(void)
  159394. emit_dri (j_compress_ptr cinfo)
  159395. /* Emit a DRI marker */
  159396. {
  159397. emit_marker(cinfo, M_DRI);
  159398. emit_2bytes(cinfo, 4); /* fixed length */
  159399. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  159400. }
  159401. LOCAL(void)
  159402. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  159403. /* Emit a SOF marker */
  159404. {
  159405. int ci;
  159406. jpeg_component_info *compptr;
  159407. emit_marker(cinfo, code);
  159408. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  159409. /* Make sure image isn't bigger than SOF field can handle */
  159410. if ((long) cinfo->image_height > 65535L ||
  159411. (long) cinfo->image_width > 65535L)
  159412. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  159413. emit_byte(cinfo, cinfo->data_precision);
  159414. emit_2bytes(cinfo, (int) cinfo->image_height);
  159415. emit_2bytes(cinfo, (int) cinfo->image_width);
  159416. emit_byte(cinfo, cinfo->num_components);
  159417. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159418. ci++, compptr++) {
  159419. emit_byte(cinfo, compptr->component_id);
  159420. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  159421. emit_byte(cinfo, compptr->quant_tbl_no);
  159422. }
  159423. }
  159424. LOCAL(void)
  159425. emit_sos (j_compress_ptr cinfo)
  159426. /* Emit a SOS marker */
  159427. {
  159428. int i, td, ta;
  159429. jpeg_component_info *compptr;
  159430. emit_marker(cinfo, M_SOS);
  159431. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  159432. emit_byte(cinfo, cinfo->comps_in_scan);
  159433. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159434. compptr = cinfo->cur_comp_info[i];
  159435. emit_byte(cinfo, compptr->component_id);
  159436. td = compptr->dc_tbl_no;
  159437. ta = compptr->ac_tbl_no;
  159438. if (cinfo->progressive_mode) {
  159439. /* Progressive mode: only DC or only AC tables are used in one scan;
  159440. * furthermore, Huffman coding of DC refinement uses no table at all.
  159441. * We emit 0 for unused field(s); this is recommended by the P&M text
  159442. * but does not seem to be specified in the standard.
  159443. */
  159444. if (cinfo->Ss == 0) {
  159445. ta = 0; /* DC scan */
  159446. if (cinfo->Ah != 0 && !cinfo->arith_code)
  159447. td = 0; /* no DC table either */
  159448. } else {
  159449. td = 0; /* AC scan */
  159450. }
  159451. }
  159452. emit_byte(cinfo, (td << 4) + ta);
  159453. }
  159454. emit_byte(cinfo, cinfo->Ss);
  159455. emit_byte(cinfo, cinfo->Se);
  159456. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  159457. }
  159458. LOCAL(void)
  159459. emit_jfif_app0 (j_compress_ptr cinfo)
  159460. /* Emit a JFIF-compliant APP0 marker */
  159461. {
  159462. /*
  159463. * Length of APP0 block (2 bytes)
  159464. * Block ID (4 bytes - ASCII "JFIF")
  159465. * Zero byte (1 byte to terminate the ID string)
  159466. * Version Major, Minor (2 bytes - major first)
  159467. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  159468. * Xdpu (2 bytes - dots per unit horizontal)
  159469. * Ydpu (2 bytes - dots per unit vertical)
  159470. * Thumbnail X size (1 byte)
  159471. * Thumbnail Y size (1 byte)
  159472. */
  159473. emit_marker(cinfo, M_APP0);
  159474. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  159475. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  159476. emit_byte(cinfo, 0x46);
  159477. emit_byte(cinfo, 0x49);
  159478. emit_byte(cinfo, 0x46);
  159479. emit_byte(cinfo, 0);
  159480. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  159481. emit_byte(cinfo, cinfo->JFIF_minor_version);
  159482. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  159483. emit_2bytes(cinfo, (int) cinfo->X_density);
  159484. emit_2bytes(cinfo, (int) cinfo->Y_density);
  159485. emit_byte(cinfo, 0); /* No thumbnail image */
  159486. emit_byte(cinfo, 0);
  159487. }
  159488. LOCAL(void)
  159489. emit_adobe_app14 (j_compress_ptr cinfo)
  159490. /* Emit an Adobe APP14 marker */
  159491. {
  159492. /*
  159493. * Length of APP14 block (2 bytes)
  159494. * Block ID (5 bytes - ASCII "Adobe")
  159495. * Version Number (2 bytes - currently 100)
  159496. * Flags0 (2 bytes - currently 0)
  159497. * Flags1 (2 bytes - currently 0)
  159498. * Color transform (1 byte)
  159499. *
  159500. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  159501. * now in circulation seem to use Version = 100, so that's what we write.
  159502. *
  159503. * We write the color transform byte as 1 if the JPEG color space is
  159504. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  159505. * whether the encoder performed a transformation, which is pretty useless.
  159506. */
  159507. emit_marker(cinfo, M_APP14);
  159508. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  159509. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  159510. emit_byte(cinfo, 0x64);
  159511. emit_byte(cinfo, 0x6F);
  159512. emit_byte(cinfo, 0x62);
  159513. emit_byte(cinfo, 0x65);
  159514. emit_2bytes(cinfo, 100); /* Version */
  159515. emit_2bytes(cinfo, 0); /* Flags0 */
  159516. emit_2bytes(cinfo, 0); /* Flags1 */
  159517. switch (cinfo->jpeg_color_space) {
  159518. case JCS_YCbCr:
  159519. emit_byte(cinfo, 1); /* Color transform = 1 */
  159520. break;
  159521. case JCS_YCCK:
  159522. emit_byte(cinfo, 2); /* Color transform = 2 */
  159523. break;
  159524. default:
  159525. emit_byte(cinfo, 0); /* Color transform = 0 */
  159526. break;
  159527. }
  159528. }
  159529. /*
  159530. * These routines allow writing an arbitrary marker with parameters.
  159531. * The only intended use is to emit COM or APPn markers after calling
  159532. * write_file_header and before calling write_frame_header.
  159533. * Other uses are not guaranteed to produce desirable results.
  159534. * Counting the parameter bytes properly is the caller's responsibility.
  159535. */
  159536. METHODDEF(void)
  159537. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  159538. /* Emit an arbitrary marker header */
  159539. {
  159540. if (datalen > (unsigned int) 65533) /* safety check */
  159541. ERREXIT(cinfo, JERR_BAD_LENGTH);
  159542. emit_marker(cinfo, (JPEG_MARKER) marker);
  159543. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  159544. }
  159545. METHODDEF(void)
  159546. write_marker_byte (j_compress_ptr cinfo, int val)
  159547. /* Emit one byte of marker parameters following write_marker_header */
  159548. {
  159549. emit_byte(cinfo, val);
  159550. }
  159551. /*
  159552. * Write datastream header.
  159553. * This consists of an SOI and optional APPn markers.
  159554. * We recommend use of the JFIF marker, but not the Adobe marker,
  159555. * when using YCbCr or grayscale data. The JFIF marker should NOT
  159556. * be used for any other JPEG colorspace. The Adobe marker is helpful
  159557. * to distinguish RGB, CMYK, and YCCK colorspaces.
  159558. * Note that an application can write additional header markers after
  159559. * jpeg_start_compress returns.
  159560. */
  159561. METHODDEF(void)
  159562. write_file_header (j_compress_ptr cinfo)
  159563. {
  159564. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  159565. emit_marker(cinfo, M_SOI); /* first the SOI */
  159566. /* SOI is defined to reset restart interval to 0 */
  159567. marker->last_restart_interval = 0;
  159568. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  159569. emit_jfif_app0(cinfo);
  159570. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  159571. emit_adobe_app14(cinfo);
  159572. }
  159573. /*
  159574. * Write frame header.
  159575. * This consists of DQT and SOFn markers.
  159576. * Note that we do not emit the SOF until we have emitted the DQT(s).
  159577. * This avoids compatibility problems with incorrect implementations that
  159578. * try to error-check the quant table numbers as soon as they see the SOF.
  159579. */
  159580. METHODDEF(void)
  159581. write_frame_header (j_compress_ptr cinfo)
  159582. {
  159583. int ci, prec;
  159584. boolean is_baseline;
  159585. jpeg_component_info *compptr;
  159586. /* Emit DQT for each quantization table.
  159587. * Note that emit_dqt() suppresses any duplicate tables.
  159588. */
  159589. prec = 0;
  159590. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159591. ci++, compptr++) {
  159592. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  159593. }
  159594. /* now prec is nonzero iff there are any 16-bit quant tables. */
  159595. /* Check for a non-baseline specification.
  159596. * Note we assume that Huffman table numbers won't be changed later.
  159597. */
  159598. if (cinfo->arith_code || cinfo->progressive_mode ||
  159599. cinfo->data_precision != 8) {
  159600. is_baseline = FALSE;
  159601. } else {
  159602. is_baseline = TRUE;
  159603. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159604. ci++, compptr++) {
  159605. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  159606. is_baseline = FALSE;
  159607. }
  159608. if (prec && is_baseline) {
  159609. is_baseline = FALSE;
  159610. /* If it's baseline except for quantizer size, warn the user */
  159611. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  159612. }
  159613. }
  159614. /* Emit the proper SOF marker */
  159615. if (cinfo->arith_code) {
  159616. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  159617. } else {
  159618. if (cinfo->progressive_mode)
  159619. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  159620. else if (is_baseline)
  159621. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  159622. else
  159623. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  159624. }
  159625. }
  159626. /*
  159627. * Write scan header.
  159628. * This consists of DHT or DAC markers, optional DRI, and SOS.
  159629. * Compressed data will be written following the SOS.
  159630. */
  159631. METHODDEF(void)
  159632. write_scan_header (j_compress_ptr cinfo)
  159633. {
  159634. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  159635. int i;
  159636. jpeg_component_info *compptr;
  159637. if (cinfo->arith_code) {
  159638. /* Emit arith conditioning info. We may have some duplication
  159639. * if the file has multiple scans, but it's so small it's hardly
  159640. * worth worrying about.
  159641. */
  159642. emit_dac(cinfo);
  159643. } else {
  159644. /* Emit Huffman tables.
  159645. * Note that emit_dht() suppresses any duplicate tables.
  159646. */
  159647. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159648. compptr = cinfo->cur_comp_info[i];
  159649. if (cinfo->progressive_mode) {
  159650. /* Progressive mode: only DC or only AC tables are used in one scan */
  159651. if (cinfo->Ss == 0) {
  159652. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  159653. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  159654. } else {
  159655. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  159656. }
  159657. } else {
  159658. /* Sequential mode: need both DC and AC tables */
  159659. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  159660. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  159661. }
  159662. }
  159663. }
  159664. /* Emit DRI if required --- note that DRI value could change for each scan.
  159665. * We avoid wasting space with unnecessary DRIs, however.
  159666. */
  159667. if (cinfo->restart_interval != marker->last_restart_interval) {
  159668. emit_dri(cinfo);
  159669. marker->last_restart_interval = cinfo->restart_interval;
  159670. }
  159671. emit_sos(cinfo);
  159672. }
  159673. /*
  159674. * Write datastream trailer.
  159675. */
  159676. METHODDEF(void)
  159677. write_file_trailer (j_compress_ptr cinfo)
  159678. {
  159679. emit_marker(cinfo, M_EOI);
  159680. }
  159681. /*
  159682. * Write an abbreviated table-specification datastream.
  159683. * This consists of SOI, DQT and DHT tables, and EOI.
  159684. * Any table that is defined and not marked sent_table = TRUE will be
  159685. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  159686. */
  159687. METHODDEF(void)
  159688. write_tables_only (j_compress_ptr cinfo)
  159689. {
  159690. int i;
  159691. emit_marker(cinfo, M_SOI);
  159692. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  159693. if (cinfo->quant_tbl_ptrs[i] != NULL)
  159694. (void) emit_dqt(cinfo, i);
  159695. }
  159696. if (! cinfo->arith_code) {
  159697. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  159698. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  159699. emit_dht(cinfo, i, FALSE);
  159700. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  159701. emit_dht(cinfo, i, TRUE);
  159702. }
  159703. }
  159704. emit_marker(cinfo, M_EOI);
  159705. }
  159706. /*
  159707. * Initialize the marker writer module.
  159708. */
  159709. GLOBAL(void)
  159710. jinit_marker_writer (j_compress_ptr cinfo)
  159711. {
  159712. my_marker_ptr marker;
  159713. /* Create the subobject */
  159714. marker = (my_marker_ptr)
  159715. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159716. SIZEOF(my_marker_writer));
  159717. cinfo->marker = (struct jpeg_marker_writer *) marker;
  159718. /* Initialize method pointers */
  159719. marker->pub.write_file_header = write_file_header;
  159720. marker->pub.write_frame_header = write_frame_header;
  159721. marker->pub.write_scan_header = write_scan_header;
  159722. marker->pub.write_file_trailer = write_file_trailer;
  159723. marker->pub.write_tables_only = write_tables_only;
  159724. marker->pub.write_marker_header = write_marker_header;
  159725. marker->pub.write_marker_byte = write_marker_byte;
  159726. /* Initialize private state */
  159727. marker->last_restart_interval = 0;
  159728. }
  159729. /********* End of inlined file: jcmarker.c *********/
  159730. /********* Start of inlined file: jcmaster.c *********/
  159731. #define JPEG_INTERNALS
  159732. /* Private state */
  159733. typedef enum {
  159734. main_pass, /* input data, also do first output step */
  159735. huff_opt_pass, /* Huffman code optimization pass */
  159736. output_pass /* data output pass */
  159737. } c_pass_type;
  159738. typedef struct {
  159739. struct jpeg_comp_master pub; /* public fields */
  159740. c_pass_type pass_type; /* the type of the current pass */
  159741. int pass_number; /* # of passes completed */
  159742. int total_passes; /* total # of passes needed */
  159743. int scan_number; /* current index in scan_info[] */
  159744. } my_comp_master;
  159745. typedef my_comp_master * my_master_ptr;
  159746. /*
  159747. * Support routines that do various essential calculations.
  159748. */
  159749. LOCAL(void)
  159750. initial_setup (j_compress_ptr cinfo)
  159751. /* Do computations that are needed before master selection phase */
  159752. {
  159753. int ci;
  159754. jpeg_component_info *compptr;
  159755. long samplesperrow;
  159756. JDIMENSION jd_samplesperrow;
  159757. /* Sanity check on image dimensions */
  159758. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  159759. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  159760. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  159761. /* Make sure image isn't bigger than I can handle */
  159762. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  159763. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  159764. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  159765. /* Width of an input scanline must be representable as JDIMENSION. */
  159766. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  159767. jd_samplesperrow = (JDIMENSION) samplesperrow;
  159768. if ((long) jd_samplesperrow != samplesperrow)
  159769. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  159770. /* For now, precision must match compiled-in value... */
  159771. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  159772. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  159773. /* Check that number of components won't exceed internal array sizes */
  159774. if (cinfo->num_components > MAX_COMPONENTS)
  159775. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  159776. MAX_COMPONENTS);
  159777. /* Compute maximum sampling factors; check factor validity */
  159778. cinfo->max_h_samp_factor = 1;
  159779. cinfo->max_v_samp_factor = 1;
  159780. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159781. ci++, compptr++) {
  159782. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  159783. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  159784. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  159785. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  159786. compptr->h_samp_factor);
  159787. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  159788. compptr->v_samp_factor);
  159789. }
  159790. /* Compute dimensions of components */
  159791. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159792. ci++, compptr++) {
  159793. /* Fill in the correct component_index value; don't rely on application */
  159794. compptr->component_index = ci;
  159795. /* For compression, we never do DCT scaling. */
  159796. compptr->DCT_scaled_size = DCTSIZE;
  159797. /* Size in DCT blocks */
  159798. compptr->width_in_blocks = (JDIMENSION)
  159799. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  159800. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  159801. compptr->height_in_blocks = (JDIMENSION)
  159802. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  159803. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  159804. /* Size in samples */
  159805. compptr->downsampled_width = (JDIMENSION)
  159806. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  159807. (long) cinfo->max_h_samp_factor);
  159808. compptr->downsampled_height = (JDIMENSION)
  159809. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  159810. (long) cinfo->max_v_samp_factor);
  159811. /* Mark component needed (this flag isn't actually used for compression) */
  159812. compptr->component_needed = TRUE;
  159813. }
  159814. /* Compute number of fully interleaved MCU rows (number of times that
  159815. * main controller will call coefficient controller).
  159816. */
  159817. cinfo->total_iMCU_rows = (JDIMENSION)
  159818. jdiv_round_up((long) cinfo->image_height,
  159819. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  159820. }
  159821. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159822. LOCAL(void)
  159823. validate_script (j_compress_ptr cinfo)
  159824. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  159825. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  159826. */
  159827. {
  159828. const jpeg_scan_info * scanptr;
  159829. int scanno, ncomps, ci, coefi, thisi;
  159830. int Ss, Se, Ah, Al;
  159831. boolean component_sent[MAX_COMPONENTS];
  159832. #ifdef C_PROGRESSIVE_SUPPORTED
  159833. int * last_bitpos_ptr;
  159834. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  159835. /* -1 until that coefficient has been seen; then last Al for it */
  159836. #endif
  159837. if (cinfo->num_scans <= 0)
  159838. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  159839. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  159840. * for progressive JPEG, no scan can have this.
  159841. */
  159842. scanptr = cinfo->scan_info;
  159843. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  159844. #ifdef C_PROGRESSIVE_SUPPORTED
  159845. cinfo->progressive_mode = TRUE;
  159846. last_bitpos_ptr = & last_bitpos[0][0];
  159847. for (ci = 0; ci < cinfo->num_components; ci++)
  159848. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  159849. *last_bitpos_ptr++ = -1;
  159850. #else
  159851. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159852. #endif
  159853. } else {
  159854. cinfo->progressive_mode = FALSE;
  159855. for (ci = 0; ci < cinfo->num_components; ci++)
  159856. component_sent[ci] = FALSE;
  159857. }
  159858. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  159859. /* Validate component indexes */
  159860. ncomps = scanptr->comps_in_scan;
  159861. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  159862. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  159863. for (ci = 0; ci < ncomps; ci++) {
  159864. thisi = scanptr->component_index[ci];
  159865. if (thisi < 0 || thisi >= cinfo->num_components)
  159866. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  159867. /* Components must appear in SOF order within each scan */
  159868. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  159869. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  159870. }
  159871. /* Validate progression parameters */
  159872. Ss = scanptr->Ss;
  159873. Se = scanptr->Se;
  159874. Ah = scanptr->Ah;
  159875. Al = scanptr->Al;
  159876. if (cinfo->progressive_mode) {
  159877. #ifdef C_PROGRESSIVE_SUPPORTED
  159878. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  159879. * seems wrong: the upper bound ought to depend on data precision.
  159880. * Perhaps they really meant 0..N+1 for N-bit precision.
  159881. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  159882. * out-of-range reconstructed DC values during the first DC scan,
  159883. * which might cause problems for some decoders.
  159884. */
  159885. #if BITS_IN_JSAMPLE == 8
  159886. #define MAX_AH_AL 10
  159887. #else
  159888. #define MAX_AH_AL 13
  159889. #endif
  159890. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  159891. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  159892. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159893. if (Ss == 0) {
  159894. if (Se != 0) /* DC and AC together not OK */
  159895. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159896. } else {
  159897. if (ncomps != 1) /* AC scans must be for only one component */
  159898. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159899. }
  159900. for (ci = 0; ci < ncomps; ci++) {
  159901. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  159902. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  159903. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159904. for (coefi = Ss; coefi <= Se; coefi++) {
  159905. if (last_bitpos_ptr[coefi] < 0) {
  159906. /* first scan of this coefficient */
  159907. if (Ah != 0)
  159908. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159909. } else {
  159910. /* not first scan */
  159911. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  159912. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159913. }
  159914. last_bitpos_ptr[coefi] = Al;
  159915. }
  159916. }
  159917. #endif
  159918. } else {
  159919. /* For sequential JPEG, all progression parameters must be these: */
  159920. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  159921. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159922. /* Make sure components are not sent twice */
  159923. for (ci = 0; ci < ncomps; ci++) {
  159924. thisi = scanptr->component_index[ci];
  159925. if (component_sent[thisi])
  159926. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  159927. component_sent[thisi] = TRUE;
  159928. }
  159929. }
  159930. }
  159931. /* Now verify that everything got sent. */
  159932. if (cinfo->progressive_mode) {
  159933. #ifdef C_PROGRESSIVE_SUPPORTED
  159934. /* For progressive mode, we only check that at least some DC data
  159935. * got sent for each component; the spec does not require that all bits
  159936. * of all coefficients be transmitted. Would it be wiser to enforce
  159937. * transmission of all coefficient bits??
  159938. */
  159939. for (ci = 0; ci < cinfo->num_components; ci++) {
  159940. if (last_bitpos[ci][0] < 0)
  159941. ERREXIT(cinfo, JERR_MISSING_DATA);
  159942. }
  159943. #endif
  159944. } else {
  159945. for (ci = 0; ci < cinfo->num_components; ci++) {
  159946. if (! component_sent[ci])
  159947. ERREXIT(cinfo, JERR_MISSING_DATA);
  159948. }
  159949. }
  159950. }
  159951. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  159952. LOCAL(void)
  159953. select_scan_parameters (j_compress_ptr cinfo)
  159954. /* Set up the scan parameters for the current scan */
  159955. {
  159956. int ci;
  159957. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159958. if (cinfo->scan_info != NULL) {
  159959. /* Prepare for current scan --- the script is already validated */
  159960. my_master_ptr master = (my_master_ptr) cinfo->master;
  159961. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  159962. cinfo->comps_in_scan = scanptr->comps_in_scan;
  159963. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  159964. cinfo->cur_comp_info[ci] =
  159965. &cinfo->comp_info[scanptr->component_index[ci]];
  159966. }
  159967. cinfo->Ss = scanptr->Ss;
  159968. cinfo->Se = scanptr->Se;
  159969. cinfo->Ah = scanptr->Ah;
  159970. cinfo->Al = scanptr->Al;
  159971. }
  159972. else
  159973. #endif
  159974. {
  159975. /* Prepare for single sequential-JPEG scan containing all components */
  159976. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  159977. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  159978. MAX_COMPS_IN_SCAN);
  159979. cinfo->comps_in_scan = cinfo->num_components;
  159980. for (ci = 0; ci < cinfo->num_components; ci++) {
  159981. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  159982. }
  159983. cinfo->Ss = 0;
  159984. cinfo->Se = DCTSIZE2-1;
  159985. cinfo->Ah = 0;
  159986. cinfo->Al = 0;
  159987. }
  159988. }
  159989. LOCAL(void)
  159990. per_scan_setup (j_compress_ptr cinfo)
  159991. /* Do computations that are needed before processing a JPEG scan */
  159992. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  159993. {
  159994. int ci, mcublks, tmp;
  159995. jpeg_component_info *compptr;
  159996. if (cinfo->comps_in_scan == 1) {
  159997. /* Noninterleaved (single-component) scan */
  159998. compptr = cinfo->cur_comp_info[0];
  159999. /* Overall image size in MCUs */
  160000. cinfo->MCUs_per_row = compptr->width_in_blocks;
  160001. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  160002. /* For noninterleaved scan, always one block per MCU */
  160003. compptr->MCU_width = 1;
  160004. compptr->MCU_height = 1;
  160005. compptr->MCU_blocks = 1;
  160006. compptr->MCU_sample_width = DCTSIZE;
  160007. compptr->last_col_width = 1;
  160008. /* For noninterleaved scans, it is convenient to define last_row_height
  160009. * as the number of block rows present in the last iMCU row.
  160010. */
  160011. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  160012. if (tmp == 0) tmp = compptr->v_samp_factor;
  160013. compptr->last_row_height = tmp;
  160014. /* Prepare array describing MCU composition */
  160015. cinfo->blocks_in_MCU = 1;
  160016. cinfo->MCU_membership[0] = 0;
  160017. } else {
  160018. /* Interleaved (multi-component) scan */
  160019. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  160020. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  160021. MAX_COMPS_IN_SCAN);
  160022. /* Overall image size in MCUs */
  160023. cinfo->MCUs_per_row = (JDIMENSION)
  160024. jdiv_round_up((long) cinfo->image_width,
  160025. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  160026. cinfo->MCU_rows_in_scan = (JDIMENSION)
  160027. jdiv_round_up((long) cinfo->image_height,
  160028. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160029. cinfo->blocks_in_MCU = 0;
  160030. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160031. compptr = cinfo->cur_comp_info[ci];
  160032. /* Sampling factors give # of blocks of component in each MCU */
  160033. compptr->MCU_width = compptr->h_samp_factor;
  160034. compptr->MCU_height = compptr->v_samp_factor;
  160035. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  160036. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  160037. /* Figure number of non-dummy blocks in last MCU column & row */
  160038. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  160039. if (tmp == 0) tmp = compptr->MCU_width;
  160040. compptr->last_col_width = tmp;
  160041. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  160042. if (tmp == 0) tmp = compptr->MCU_height;
  160043. compptr->last_row_height = tmp;
  160044. /* Prepare array describing MCU composition */
  160045. mcublks = compptr->MCU_blocks;
  160046. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  160047. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  160048. while (mcublks-- > 0) {
  160049. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  160050. }
  160051. }
  160052. }
  160053. /* Convert restart specified in rows to actual MCU count. */
  160054. /* Note that count must fit in 16 bits, so we provide limiting. */
  160055. if (cinfo->restart_in_rows > 0) {
  160056. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  160057. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  160058. }
  160059. }
  160060. /*
  160061. * Per-pass setup.
  160062. * This is called at the beginning of each pass. We determine which modules
  160063. * will be active during this pass and give them appropriate start_pass calls.
  160064. * We also set is_last_pass to indicate whether any more passes will be
  160065. * required.
  160066. */
  160067. METHODDEF(void)
  160068. prepare_for_pass (j_compress_ptr cinfo)
  160069. {
  160070. my_master_ptr master = (my_master_ptr) cinfo->master;
  160071. switch (master->pass_type) {
  160072. case main_pass:
  160073. /* Initial pass: will collect input data, and do either Huffman
  160074. * optimization or data output for the first scan.
  160075. */
  160076. select_scan_parameters(cinfo);
  160077. per_scan_setup(cinfo);
  160078. if (! cinfo->raw_data_in) {
  160079. (*cinfo->cconvert->start_pass) (cinfo);
  160080. (*cinfo->downsample->start_pass) (cinfo);
  160081. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  160082. }
  160083. (*cinfo->fdct->start_pass) (cinfo);
  160084. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  160085. (*cinfo->coef->start_pass) (cinfo,
  160086. (master->total_passes > 1 ?
  160087. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  160088. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  160089. if (cinfo->optimize_coding) {
  160090. /* No immediate data output; postpone writing frame/scan headers */
  160091. master->pub.call_pass_startup = FALSE;
  160092. } else {
  160093. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  160094. master->pub.call_pass_startup = TRUE;
  160095. }
  160096. break;
  160097. #ifdef ENTROPY_OPT_SUPPORTED
  160098. case huff_opt_pass:
  160099. /* Do Huffman optimization for a scan after the first one. */
  160100. select_scan_parameters(cinfo);
  160101. per_scan_setup(cinfo);
  160102. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  160103. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  160104. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160105. master->pub.call_pass_startup = FALSE;
  160106. break;
  160107. }
  160108. /* Special case: Huffman DC refinement scans need no Huffman table
  160109. * and therefore we can skip the optimization pass for them.
  160110. */
  160111. master->pass_type = output_pass;
  160112. master->pass_number++;
  160113. /*FALLTHROUGH*/
  160114. #endif
  160115. case output_pass:
  160116. /* Do a data-output pass. */
  160117. /* We need not repeat per-scan setup if prior optimization pass did it. */
  160118. if (! cinfo->optimize_coding) {
  160119. select_scan_parameters(cinfo);
  160120. per_scan_setup(cinfo);
  160121. }
  160122. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  160123. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160124. /* We emit frame/scan headers now */
  160125. if (master->scan_number == 0)
  160126. (*cinfo->marker->write_frame_header) (cinfo);
  160127. (*cinfo->marker->write_scan_header) (cinfo);
  160128. master->pub.call_pass_startup = FALSE;
  160129. break;
  160130. default:
  160131. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160132. }
  160133. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  160134. /* Set up progress monitor's pass info if present */
  160135. if (cinfo->progress != NULL) {
  160136. cinfo->progress->completed_passes = master->pass_number;
  160137. cinfo->progress->total_passes = master->total_passes;
  160138. }
  160139. }
  160140. /*
  160141. * Special start-of-pass hook.
  160142. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  160143. * In single-pass processing, we need this hook because we don't want to
  160144. * write frame/scan headers during jpeg_start_compress; we want to let the
  160145. * application write COM markers etc. between jpeg_start_compress and the
  160146. * jpeg_write_scanlines loop.
  160147. * In multi-pass processing, this routine is not used.
  160148. */
  160149. METHODDEF(void)
  160150. pass_startup (j_compress_ptr cinfo)
  160151. {
  160152. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  160153. (*cinfo->marker->write_frame_header) (cinfo);
  160154. (*cinfo->marker->write_scan_header) (cinfo);
  160155. }
  160156. /*
  160157. * Finish up at end of pass.
  160158. */
  160159. METHODDEF(void)
  160160. finish_pass_master (j_compress_ptr cinfo)
  160161. {
  160162. my_master_ptr master = (my_master_ptr) cinfo->master;
  160163. /* The entropy coder always needs an end-of-pass call,
  160164. * either to analyze statistics or to flush its output buffer.
  160165. */
  160166. (*cinfo->entropy->finish_pass) (cinfo);
  160167. /* Update state for next pass */
  160168. switch (master->pass_type) {
  160169. case main_pass:
  160170. /* next pass is either output of scan 0 (after optimization)
  160171. * or output of scan 1 (if no optimization).
  160172. */
  160173. master->pass_type = output_pass;
  160174. if (! cinfo->optimize_coding)
  160175. master->scan_number++;
  160176. break;
  160177. case huff_opt_pass:
  160178. /* next pass is always output of current scan */
  160179. master->pass_type = output_pass;
  160180. break;
  160181. case output_pass:
  160182. /* next pass is either optimization or output of next scan */
  160183. if (cinfo->optimize_coding)
  160184. master->pass_type = huff_opt_pass;
  160185. master->scan_number++;
  160186. break;
  160187. }
  160188. master->pass_number++;
  160189. }
  160190. /*
  160191. * Initialize master compression control.
  160192. */
  160193. GLOBAL(void)
  160194. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  160195. {
  160196. my_master_ptr master;
  160197. master = (my_master_ptr)
  160198. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160199. SIZEOF(my_comp_master));
  160200. cinfo->master = (struct jpeg_comp_master *) master;
  160201. master->pub.prepare_for_pass = prepare_for_pass;
  160202. master->pub.pass_startup = pass_startup;
  160203. master->pub.finish_pass = finish_pass_master;
  160204. master->pub.is_last_pass = FALSE;
  160205. /* Validate parameters, determine derived values */
  160206. initial_setup(cinfo);
  160207. if (cinfo->scan_info != NULL) {
  160208. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160209. validate_script(cinfo);
  160210. #else
  160211. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160212. #endif
  160213. } else {
  160214. cinfo->progressive_mode = FALSE;
  160215. cinfo->num_scans = 1;
  160216. }
  160217. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  160218. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  160219. /* Initialize my private state */
  160220. if (transcode_only) {
  160221. /* no main pass in transcoding */
  160222. if (cinfo->optimize_coding)
  160223. master->pass_type = huff_opt_pass;
  160224. else
  160225. master->pass_type = output_pass;
  160226. } else {
  160227. /* for normal compression, first pass is always this type: */
  160228. master->pass_type = main_pass;
  160229. }
  160230. master->scan_number = 0;
  160231. master->pass_number = 0;
  160232. if (cinfo->optimize_coding)
  160233. master->total_passes = cinfo->num_scans * 2;
  160234. else
  160235. master->total_passes = cinfo->num_scans;
  160236. }
  160237. /********* End of inlined file: jcmaster.c *********/
  160238. /********* Start of inlined file: jcomapi.c *********/
  160239. #define JPEG_INTERNALS
  160240. /*
  160241. * Abort processing of a JPEG compression or decompression operation,
  160242. * but don't destroy the object itself.
  160243. *
  160244. * For this, we merely clean up all the nonpermanent memory pools.
  160245. * Note that temp files (virtual arrays) are not allowed to belong to
  160246. * the permanent pool, so we will be able to close all temp files here.
  160247. * Closing a data source or destination, if necessary, is the application's
  160248. * responsibility.
  160249. */
  160250. GLOBAL(void)
  160251. jpeg_abort (j_common_ptr cinfo)
  160252. {
  160253. int pool;
  160254. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  160255. if (cinfo->mem == NULL)
  160256. return;
  160257. /* Releasing pools in reverse order might help avoid fragmentation
  160258. * with some (brain-damaged) malloc libraries.
  160259. */
  160260. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  160261. (*cinfo->mem->free_pool) (cinfo, pool);
  160262. }
  160263. /* Reset overall state for possible reuse of object */
  160264. if (cinfo->is_decompressor) {
  160265. cinfo->global_state = DSTATE_START;
  160266. /* Try to keep application from accessing now-deleted marker list.
  160267. * A bit kludgy to do it here, but this is the most central place.
  160268. */
  160269. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  160270. } else {
  160271. cinfo->global_state = CSTATE_START;
  160272. }
  160273. }
  160274. /*
  160275. * Destruction of a JPEG object.
  160276. *
  160277. * Everything gets deallocated except the master jpeg_compress_struct itself
  160278. * and the error manager struct. Both of these are supplied by the application
  160279. * and must be freed, if necessary, by the application. (Often they are on
  160280. * the stack and so don't need to be freed anyway.)
  160281. * Closing a data source or destination, if necessary, is the application's
  160282. * responsibility.
  160283. */
  160284. GLOBAL(void)
  160285. jpeg_destroy (j_common_ptr cinfo)
  160286. {
  160287. /* We need only tell the memory manager to release everything. */
  160288. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  160289. if (cinfo->mem != NULL)
  160290. (*cinfo->mem->self_destruct) (cinfo);
  160291. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  160292. cinfo->global_state = 0; /* mark it destroyed */
  160293. }
  160294. /*
  160295. * Convenience routines for allocating quantization and Huffman tables.
  160296. * (Would jutils.c be a more reasonable place to put these?)
  160297. */
  160298. GLOBAL(JQUANT_TBL *)
  160299. jpeg_alloc_quant_table (j_common_ptr cinfo)
  160300. {
  160301. JQUANT_TBL *tbl;
  160302. tbl = (JQUANT_TBL *)
  160303. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  160304. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160305. return tbl;
  160306. }
  160307. GLOBAL(JHUFF_TBL *)
  160308. jpeg_alloc_huff_table (j_common_ptr cinfo)
  160309. {
  160310. JHUFF_TBL *tbl;
  160311. tbl = (JHUFF_TBL *)
  160312. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  160313. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160314. return tbl;
  160315. }
  160316. /********* End of inlined file: jcomapi.c *********/
  160317. /********* Start of inlined file: jcparam.c *********/
  160318. #define JPEG_INTERNALS
  160319. /*
  160320. * Quantization table setup routines
  160321. */
  160322. GLOBAL(void)
  160323. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  160324. const unsigned int *basic_table,
  160325. int scale_factor, boolean force_baseline)
  160326. /* Define a quantization table equal to the basic_table times
  160327. * a scale factor (given as a percentage).
  160328. * If force_baseline is TRUE, the computed quantization table entries
  160329. * are limited to 1..255 for JPEG baseline compatibility.
  160330. */
  160331. {
  160332. JQUANT_TBL ** qtblptr;
  160333. int i;
  160334. long temp;
  160335. /* Safety check to ensure start_compress not called yet. */
  160336. if (cinfo->global_state != CSTATE_START)
  160337. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160338. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  160339. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  160340. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  160341. if (*qtblptr == NULL)
  160342. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  160343. for (i = 0; i < DCTSIZE2; i++) {
  160344. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  160345. /* limit the values to the valid range */
  160346. if (temp <= 0L) temp = 1L;
  160347. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  160348. if (force_baseline && temp > 255L)
  160349. temp = 255L; /* limit to baseline range if requested */
  160350. (*qtblptr)->quantval[i] = (UINT16) temp;
  160351. }
  160352. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  160353. (*qtblptr)->sent_table = FALSE;
  160354. }
  160355. GLOBAL(void)
  160356. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  160357. boolean force_baseline)
  160358. /* Set or change the 'quality' (quantization) setting, using default tables
  160359. * and a straight percentage-scaling quality scale. In most cases it's better
  160360. * to use jpeg_set_quality (below); this entry point is provided for
  160361. * applications that insist on a linear percentage scaling.
  160362. */
  160363. {
  160364. /* These are the sample quantization tables given in JPEG spec section K.1.
  160365. * The spec says that the values given produce "good" quality, and
  160366. * when divided by 2, "very good" quality.
  160367. */
  160368. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  160369. 16, 11, 10, 16, 24, 40, 51, 61,
  160370. 12, 12, 14, 19, 26, 58, 60, 55,
  160371. 14, 13, 16, 24, 40, 57, 69, 56,
  160372. 14, 17, 22, 29, 51, 87, 80, 62,
  160373. 18, 22, 37, 56, 68, 109, 103, 77,
  160374. 24, 35, 55, 64, 81, 104, 113, 92,
  160375. 49, 64, 78, 87, 103, 121, 120, 101,
  160376. 72, 92, 95, 98, 112, 100, 103, 99
  160377. };
  160378. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  160379. 17, 18, 24, 47, 99, 99, 99, 99,
  160380. 18, 21, 26, 66, 99, 99, 99, 99,
  160381. 24, 26, 56, 99, 99, 99, 99, 99,
  160382. 47, 66, 99, 99, 99, 99, 99, 99,
  160383. 99, 99, 99, 99, 99, 99, 99, 99,
  160384. 99, 99, 99, 99, 99, 99, 99, 99,
  160385. 99, 99, 99, 99, 99, 99, 99, 99,
  160386. 99, 99, 99, 99, 99, 99, 99, 99
  160387. };
  160388. /* Set up two quantization tables using the specified scaling */
  160389. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  160390. scale_factor, force_baseline);
  160391. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  160392. scale_factor, force_baseline);
  160393. }
  160394. GLOBAL(int)
  160395. jpeg_quality_scaling (int quality)
  160396. /* Convert a user-specified quality rating to a percentage scaling factor
  160397. * for an underlying quantization table, using our recommended scaling curve.
  160398. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  160399. */
  160400. {
  160401. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  160402. if (quality <= 0) quality = 1;
  160403. if (quality > 100) quality = 100;
  160404. /* The basic table is used as-is (scaling 100) for a quality of 50.
  160405. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  160406. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  160407. * to make all the table entries 1 (hence, minimum quantization loss).
  160408. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  160409. */
  160410. if (quality < 50)
  160411. quality = 5000 / quality;
  160412. else
  160413. quality = 200 - quality*2;
  160414. return quality;
  160415. }
  160416. GLOBAL(void)
  160417. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  160418. /* Set or change the 'quality' (quantization) setting, using default tables.
  160419. * This is the standard quality-adjusting entry point for typical user
  160420. * interfaces; only those who want detailed control over quantization tables
  160421. * would use the preceding three routines directly.
  160422. */
  160423. {
  160424. /* Convert user 0-100 rating to percentage scaling */
  160425. quality = jpeg_quality_scaling(quality);
  160426. /* Set up standard quality tables */
  160427. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  160428. }
  160429. /*
  160430. * Huffman table setup routines
  160431. */
  160432. LOCAL(void)
  160433. add_huff_table (j_compress_ptr cinfo,
  160434. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  160435. /* Define a Huffman table */
  160436. {
  160437. int nsymbols, len;
  160438. if (*htblptr == NULL)
  160439. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160440. /* Copy the number-of-symbols-of-each-code-length counts */
  160441. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  160442. /* Validate the counts. We do this here mainly so we can copy the right
  160443. * number of symbols from the val[] array, without risking marching off
  160444. * the end of memory. jchuff.c will do a more thorough test later.
  160445. */
  160446. nsymbols = 0;
  160447. for (len = 1; len <= 16; len++)
  160448. nsymbols += bits[len];
  160449. if (nsymbols < 1 || nsymbols > 256)
  160450. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160451. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  160452. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  160453. (*htblptr)->sent_table = FALSE;
  160454. }
  160455. LOCAL(void)
  160456. std_huff_tables (j_compress_ptr cinfo)
  160457. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  160458. /* IMPORTANT: these are only valid for 8-bit data precision! */
  160459. {
  160460. static const UINT8 bits_dc_luminance[17] =
  160461. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  160462. static const UINT8 val_dc_luminance[] =
  160463. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  160464. static const UINT8 bits_dc_chrominance[17] =
  160465. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  160466. static const UINT8 val_dc_chrominance[] =
  160467. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  160468. static const UINT8 bits_ac_luminance[17] =
  160469. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  160470. static const UINT8 val_ac_luminance[] =
  160471. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  160472. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  160473. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  160474. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  160475. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  160476. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  160477. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  160478. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  160479. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  160480. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  160481. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  160482. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  160483. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  160484. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  160485. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  160486. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  160487. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  160488. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  160489. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  160490. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  160491. 0xf9, 0xfa };
  160492. static const UINT8 bits_ac_chrominance[17] =
  160493. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  160494. static const UINT8 val_ac_chrominance[] =
  160495. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  160496. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  160497. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  160498. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  160499. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  160500. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  160501. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  160502. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  160503. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  160504. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  160505. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  160506. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  160507. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  160508. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  160509. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  160510. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  160511. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  160512. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  160513. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  160514. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  160515. 0xf9, 0xfa };
  160516. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  160517. bits_dc_luminance, val_dc_luminance);
  160518. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  160519. bits_ac_luminance, val_ac_luminance);
  160520. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  160521. bits_dc_chrominance, val_dc_chrominance);
  160522. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  160523. bits_ac_chrominance, val_ac_chrominance);
  160524. }
  160525. /*
  160526. * Default parameter setup for compression.
  160527. *
  160528. * Applications that don't choose to use this routine must do their
  160529. * own setup of all these parameters. Alternately, you can call this
  160530. * to establish defaults and then alter parameters selectively. This
  160531. * is the recommended approach since, if we add any new parameters,
  160532. * your code will still work (they'll be set to reasonable defaults).
  160533. */
  160534. GLOBAL(void)
  160535. jpeg_set_defaults (j_compress_ptr cinfo)
  160536. {
  160537. int i;
  160538. /* Safety check to ensure start_compress not called yet. */
  160539. if (cinfo->global_state != CSTATE_START)
  160540. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160541. /* Allocate comp_info array large enough for maximum component count.
  160542. * Array is made permanent in case application wants to compress
  160543. * multiple images at same param settings.
  160544. */
  160545. if (cinfo->comp_info == NULL)
  160546. cinfo->comp_info = (jpeg_component_info *)
  160547. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  160548. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  160549. /* Initialize everything not dependent on the color space */
  160550. cinfo->data_precision = BITS_IN_JSAMPLE;
  160551. /* Set up two quantization tables using default quality of 75 */
  160552. jpeg_set_quality(cinfo, 75, TRUE);
  160553. /* Set up two Huffman tables */
  160554. std_huff_tables(cinfo);
  160555. /* Initialize default arithmetic coding conditioning */
  160556. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  160557. cinfo->arith_dc_L[i] = 0;
  160558. cinfo->arith_dc_U[i] = 1;
  160559. cinfo->arith_ac_K[i] = 5;
  160560. }
  160561. /* Default is no multiple-scan output */
  160562. cinfo->scan_info = NULL;
  160563. cinfo->num_scans = 0;
  160564. /* Expect normal source image, not raw downsampled data */
  160565. cinfo->raw_data_in = FALSE;
  160566. /* Use Huffman coding, not arithmetic coding, by default */
  160567. cinfo->arith_code = FALSE;
  160568. /* By default, don't do extra passes to optimize entropy coding */
  160569. cinfo->optimize_coding = FALSE;
  160570. /* The standard Huffman tables are only valid for 8-bit data precision.
  160571. * If the precision is higher, force optimization on so that usable
  160572. * tables will be computed. This test can be removed if default tables
  160573. * are supplied that are valid for the desired precision.
  160574. */
  160575. if (cinfo->data_precision > 8)
  160576. cinfo->optimize_coding = TRUE;
  160577. /* By default, use the simpler non-cosited sampling alignment */
  160578. cinfo->CCIR601_sampling = FALSE;
  160579. /* No input smoothing */
  160580. cinfo->smoothing_factor = 0;
  160581. /* DCT algorithm preference */
  160582. cinfo->dct_method = JDCT_DEFAULT;
  160583. /* No restart markers */
  160584. cinfo->restart_interval = 0;
  160585. cinfo->restart_in_rows = 0;
  160586. /* Fill in default JFIF marker parameters. Note that whether the marker
  160587. * will actually be written is determined by jpeg_set_colorspace.
  160588. *
  160589. * By default, the library emits JFIF version code 1.01.
  160590. * An application that wants to emit JFIF 1.02 extension markers should set
  160591. * JFIF_minor_version to 2. We could probably get away with just defaulting
  160592. * to 1.02, but there may still be some decoders in use that will complain
  160593. * about that; saying 1.01 should minimize compatibility problems.
  160594. */
  160595. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  160596. cinfo->JFIF_minor_version = 1;
  160597. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  160598. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  160599. cinfo->Y_density = 1;
  160600. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  160601. jpeg_default_colorspace(cinfo);
  160602. }
  160603. /*
  160604. * Select an appropriate JPEG colorspace for in_color_space.
  160605. */
  160606. GLOBAL(void)
  160607. jpeg_default_colorspace (j_compress_ptr cinfo)
  160608. {
  160609. switch (cinfo->in_color_space) {
  160610. case JCS_GRAYSCALE:
  160611. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  160612. break;
  160613. case JCS_RGB:
  160614. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  160615. break;
  160616. case JCS_YCbCr:
  160617. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  160618. break;
  160619. case JCS_CMYK:
  160620. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  160621. break;
  160622. case JCS_YCCK:
  160623. jpeg_set_colorspace(cinfo, JCS_YCCK);
  160624. break;
  160625. case JCS_UNKNOWN:
  160626. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  160627. break;
  160628. default:
  160629. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  160630. }
  160631. }
  160632. /*
  160633. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  160634. */
  160635. GLOBAL(void)
  160636. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  160637. {
  160638. jpeg_component_info * compptr;
  160639. int ci;
  160640. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  160641. (compptr = &cinfo->comp_info[index], \
  160642. compptr->component_id = (id), \
  160643. compptr->h_samp_factor = (hsamp), \
  160644. compptr->v_samp_factor = (vsamp), \
  160645. compptr->quant_tbl_no = (quant), \
  160646. compptr->dc_tbl_no = (dctbl), \
  160647. compptr->ac_tbl_no = (actbl) )
  160648. /* Safety check to ensure start_compress not called yet. */
  160649. if (cinfo->global_state != CSTATE_START)
  160650. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160651. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  160652. * tables 1 for chrominance components.
  160653. */
  160654. cinfo->jpeg_color_space = colorspace;
  160655. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  160656. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  160657. switch (colorspace) {
  160658. case JCS_GRAYSCALE:
  160659. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  160660. cinfo->num_components = 1;
  160661. /* JFIF specifies component ID 1 */
  160662. SET_COMP(0, 1, 1,1, 0, 0,0);
  160663. break;
  160664. case JCS_RGB:
  160665. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  160666. cinfo->num_components = 3;
  160667. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  160668. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  160669. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  160670. break;
  160671. case JCS_YCbCr:
  160672. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  160673. cinfo->num_components = 3;
  160674. /* JFIF specifies component IDs 1,2,3 */
  160675. /* We default to 2x2 subsamples of chrominance */
  160676. SET_COMP(0, 1, 2,2, 0, 0,0);
  160677. SET_COMP(1, 2, 1,1, 1, 1,1);
  160678. SET_COMP(2, 3, 1,1, 1, 1,1);
  160679. break;
  160680. case JCS_CMYK:
  160681. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  160682. cinfo->num_components = 4;
  160683. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  160684. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  160685. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  160686. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  160687. break;
  160688. case JCS_YCCK:
  160689. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  160690. cinfo->num_components = 4;
  160691. SET_COMP(0, 1, 2,2, 0, 0,0);
  160692. SET_COMP(1, 2, 1,1, 1, 1,1);
  160693. SET_COMP(2, 3, 1,1, 1, 1,1);
  160694. SET_COMP(3, 4, 2,2, 0, 0,0);
  160695. break;
  160696. case JCS_UNKNOWN:
  160697. cinfo->num_components = cinfo->input_components;
  160698. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  160699. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160700. MAX_COMPONENTS);
  160701. for (ci = 0; ci < cinfo->num_components; ci++) {
  160702. SET_COMP(ci, ci, 1,1, 0, 0,0);
  160703. }
  160704. break;
  160705. default:
  160706. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  160707. }
  160708. }
  160709. #ifdef C_PROGRESSIVE_SUPPORTED
  160710. LOCAL(jpeg_scan_info *)
  160711. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  160712. int Ss, int Se, int Ah, int Al)
  160713. /* Support routine: generate one scan for specified component */
  160714. {
  160715. scanptr->comps_in_scan = 1;
  160716. scanptr->component_index[0] = ci;
  160717. scanptr->Ss = Ss;
  160718. scanptr->Se = Se;
  160719. scanptr->Ah = Ah;
  160720. scanptr->Al = Al;
  160721. scanptr++;
  160722. return scanptr;
  160723. }
  160724. LOCAL(jpeg_scan_info *)
  160725. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  160726. int Ss, int Se, int Ah, int Al)
  160727. /* Support routine: generate one scan for each component */
  160728. {
  160729. int ci;
  160730. for (ci = 0; ci < ncomps; ci++) {
  160731. scanptr->comps_in_scan = 1;
  160732. scanptr->component_index[0] = ci;
  160733. scanptr->Ss = Ss;
  160734. scanptr->Se = Se;
  160735. scanptr->Ah = Ah;
  160736. scanptr->Al = Al;
  160737. scanptr++;
  160738. }
  160739. return scanptr;
  160740. }
  160741. LOCAL(jpeg_scan_info *)
  160742. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  160743. /* Support routine: generate interleaved DC scan if possible, else N scans */
  160744. {
  160745. int ci;
  160746. if (ncomps <= MAX_COMPS_IN_SCAN) {
  160747. /* Single interleaved DC scan */
  160748. scanptr->comps_in_scan = ncomps;
  160749. for (ci = 0; ci < ncomps; ci++)
  160750. scanptr->component_index[ci] = ci;
  160751. scanptr->Ss = scanptr->Se = 0;
  160752. scanptr->Ah = Ah;
  160753. scanptr->Al = Al;
  160754. scanptr++;
  160755. } else {
  160756. /* Noninterleaved DC scan for each component */
  160757. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  160758. }
  160759. return scanptr;
  160760. }
  160761. /*
  160762. * Create a recommended progressive-JPEG script.
  160763. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  160764. */
  160765. GLOBAL(void)
  160766. jpeg_simple_progression (j_compress_ptr cinfo)
  160767. {
  160768. int ncomps = cinfo->num_components;
  160769. int nscans;
  160770. jpeg_scan_info * scanptr;
  160771. /* Safety check to ensure start_compress not called yet. */
  160772. if (cinfo->global_state != CSTATE_START)
  160773. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160774. /* Figure space needed for script. Calculation must match code below! */
  160775. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  160776. /* Custom script for YCbCr color images. */
  160777. nscans = 10;
  160778. } else {
  160779. /* All-purpose script for other color spaces. */
  160780. if (ncomps > MAX_COMPS_IN_SCAN)
  160781. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  160782. else
  160783. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  160784. }
  160785. /* Allocate space for script.
  160786. * We need to put it in the permanent pool in case the application performs
  160787. * multiple compressions without changing the settings. To avoid a memory
  160788. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  160789. * object, we try to re-use previously allocated space, and we allocate
  160790. * enough space to handle YCbCr even if initially asked for grayscale.
  160791. */
  160792. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  160793. cinfo->script_space_size = MAX(nscans, 10);
  160794. cinfo->script_space = (jpeg_scan_info *)
  160795. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  160796. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  160797. }
  160798. scanptr = cinfo->script_space;
  160799. cinfo->scan_info = scanptr;
  160800. cinfo->num_scans = nscans;
  160801. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  160802. /* Custom script for YCbCr color images. */
  160803. /* Initial DC scan */
  160804. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  160805. /* Initial AC scan: get some luma data out in a hurry */
  160806. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  160807. /* Chroma data is too small to be worth expending many scans on */
  160808. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  160809. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  160810. /* Complete spectral selection for luma AC */
  160811. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  160812. /* Refine next bit of luma AC */
  160813. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  160814. /* Finish DC successive approximation */
  160815. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  160816. /* Finish AC successive approximation */
  160817. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  160818. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  160819. /* Luma bottom bit comes last since it's usually largest scan */
  160820. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  160821. } else {
  160822. /* All-purpose script for other color spaces. */
  160823. /* Successive approximation first pass */
  160824. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  160825. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  160826. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  160827. /* Successive approximation second pass */
  160828. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  160829. /* Successive approximation final pass */
  160830. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  160831. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  160832. }
  160833. }
  160834. #endif /* C_PROGRESSIVE_SUPPORTED */
  160835. /********* End of inlined file: jcparam.c *********/
  160836. /********* Start of inlined file: jcphuff.c *********/
  160837. #define JPEG_INTERNALS
  160838. #ifdef C_PROGRESSIVE_SUPPORTED
  160839. /* Expanded entropy encoder object for progressive Huffman encoding. */
  160840. typedef struct {
  160841. struct jpeg_entropy_encoder pub; /* public fields */
  160842. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  160843. boolean gather_statistics;
  160844. /* Bit-level coding status.
  160845. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  160846. */
  160847. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160848. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160849. INT32 put_buffer; /* current bit-accumulation buffer */
  160850. int put_bits; /* # of bits now in it */
  160851. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  160852. /* Coding status for DC components */
  160853. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  160854. /* Coding status for AC components */
  160855. int ac_tbl_no; /* the table number of the single component */
  160856. unsigned int EOBRUN; /* run length of EOBs */
  160857. unsigned int BE; /* # of buffered correction bits before MCU */
  160858. char * bit_buffer; /* buffer for correction bits (1 per char) */
  160859. /* packing correction bits tightly would save some space but cost time... */
  160860. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  160861. int next_restart_num; /* next restart number to write (0-7) */
  160862. /* Pointers to derived tables (these workspaces have image lifespan).
  160863. * Since any one scan codes only DC or only AC, we only need one set
  160864. * of tables, not one for DC and one for AC.
  160865. */
  160866. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  160867. /* Statistics tables for optimization; again, one set is enough */
  160868. long * count_ptrs[NUM_HUFF_TBLS];
  160869. } phuff_entropy_encoder;
  160870. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  160871. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  160872. * buffer can hold. Larger sizes may slightly improve compression, but
  160873. * 1000 is already well into the realm of overkill.
  160874. * The minimum safe size is 64 bits.
  160875. */
  160876. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  160877. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  160878. * We assume that int right shift is unsigned if INT32 right shift is,
  160879. * which should be safe.
  160880. */
  160881. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160882. #define ISHIFT_TEMPS int ishift_temp;
  160883. #define IRIGHT_SHIFT(x,shft) \
  160884. ((ishift_temp = (x)) < 0 ? \
  160885. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  160886. (ishift_temp >> (shft)))
  160887. #else
  160888. #define ISHIFT_TEMPS
  160889. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  160890. #endif
  160891. /* Forward declarations */
  160892. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  160893. JBLOCKROW *MCU_data));
  160894. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  160895. JBLOCKROW *MCU_data));
  160896. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  160897. JBLOCKROW *MCU_data));
  160898. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  160899. JBLOCKROW *MCU_data));
  160900. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  160901. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  160902. /*
  160903. * Initialize for a Huffman-compressed scan using progressive JPEG.
  160904. */
  160905. METHODDEF(void)
  160906. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  160907. {
  160908. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160909. boolean is_DC_band;
  160910. int ci, tbl;
  160911. jpeg_component_info * compptr;
  160912. entropy->cinfo = cinfo;
  160913. entropy->gather_statistics = gather_statistics;
  160914. is_DC_band = (cinfo->Ss == 0);
  160915. /* We assume jcmaster.c already validated the scan parameters. */
  160916. /* Select execution routines */
  160917. if (cinfo->Ah == 0) {
  160918. if (is_DC_band)
  160919. entropy->pub.encode_mcu = encode_mcu_DC_first;
  160920. else
  160921. entropy->pub.encode_mcu = encode_mcu_AC_first;
  160922. } else {
  160923. if (is_DC_band)
  160924. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  160925. else {
  160926. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  160927. /* AC refinement needs a correction bit buffer */
  160928. if (entropy->bit_buffer == NULL)
  160929. entropy->bit_buffer = (char *)
  160930. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160931. MAX_CORR_BITS * SIZEOF(char));
  160932. }
  160933. }
  160934. if (gather_statistics)
  160935. entropy->pub.finish_pass = finish_pass_gather_phuff;
  160936. else
  160937. entropy->pub.finish_pass = finish_pass_phuff;
  160938. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  160939. * for AC coefficients.
  160940. */
  160941. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160942. compptr = cinfo->cur_comp_info[ci];
  160943. /* Initialize DC predictions to 0 */
  160944. entropy->last_dc_val[ci] = 0;
  160945. /* Get table index */
  160946. if (is_DC_band) {
  160947. if (cinfo->Ah != 0) /* DC refinement needs no table */
  160948. continue;
  160949. tbl = compptr->dc_tbl_no;
  160950. } else {
  160951. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  160952. }
  160953. if (gather_statistics) {
  160954. /* Check for invalid table index */
  160955. /* (make_c_derived_tbl does this in the other path) */
  160956. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  160957. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  160958. /* Allocate and zero the statistics tables */
  160959. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  160960. if (entropy->count_ptrs[tbl] == NULL)
  160961. entropy->count_ptrs[tbl] = (long *)
  160962. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160963. 257 * SIZEOF(long));
  160964. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  160965. } else {
  160966. /* Compute derived values for Huffman table */
  160967. /* We may do this more than once for a table, but it's not expensive */
  160968. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  160969. & entropy->derived_tbls[tbl]);
  160970. }
  160971. }
  160972. /* Initialize AC stuff */
  160973. entropy->EOBRUN = 0;
  160974. entropy->BE = 0;
  160975. /* Initialize bit buffer to empty */
  160976. entropy->put_buffer = 0;
  160977. entropy->put_bits = 0;
  160978. /* Initialize restart stuff */
  160979. entropy->restarts_to_go = cinfo->restart_interval;
  160980. entropy->next_restart_num = 0;
  160981. }
  160982. /* Outputting bytes to the file.
  160983. * NB: these must be called only when actually outputting,
  160984. * that is, entropy->gather_statistics == FALSE.
  160985. */
  160986. /* Emit a byte */
  160987. #define emit_byte(entropy,val) \
  160988. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  160989. if (--(entropy)->free_in_buffer == 0) \
  160990. dump_buffer_p(entropy); }
  160991. LOCAL(void)
  160992. dump_buffer_p (phuff_entropy_ptr entropy)
  160993. /* Empty the output buffer; we do not support suspension in this module. */
  160994. {
  160995. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  160996. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  160997. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  160998. /* After a successful buffer dump, must reset buffer pointers */
  160999. entropy->next_output_byte = dest->next_output_byte;
  161000. entropy->free_in_buffer = dest->free_in_buffer;
  161001. }
  161002. /* Outputting bits to the file */
  161003. /* Only the right 24 bits of put_buffer are used; the valid bits are
  161004. * left-justified in this part. At most 16 bits can be passed to emit_bits
  161005. * in one call, and we never retain more than 7 bits in put_buffer
  161006. * between calls, so 24 bits are sufficient.
  161007. */
  161008. INLINE
  161009. LOCAL(void)
  161010. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  161011. /* Emit some bits, unless we are in gather mode */
  161012. {
  161013. /* This routine is heavily used, so it's worth coding tightly. */
  161014. register INT32 put_buffer = (INT32) code;
  161015. register int put_bits = entropy->put_bits;
  161016. /* if size is 0, caller used an invalid Huffman table entry */
  161017. if (size == 0)
  161018. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161019. if (entropy->gather_statistics)
  161020. return; /* do nothing if we're only getting stats */
  161021. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  161022. put_bits += size; /* new number of bits in buffer */
  161023. put_buffer <<= 24 - put_bits; /* align incoming bits */
  161024. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  161025. while (put_bits >= 8) {
  161026. int c = (int) ((put_buffer >> 16) & 0xFF);
  161027. emit_byte(entropy, c);
  161028. if (c == 0xFF) { /* need to stuff a zero byte? */
  161029. emit_byte(entropy, 0);
  161030. }
  161031. put_buffer <<= 8;
  161032. put_bits -= 8;
  161033. }
  161034. entropy->put_buffer = put_buffer; /* update variables */
  161035. entropy->put_bits = put_bits;
  161036. }
  161037. LOCAL(void)
  161038. flush_bits_p (phuff_entropy_ptr entropy)
  161039. {
  161040. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  161041. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  161042. entropy->put_bits = 0;
  161043. }
  161044. /*
  161045. * Emit (or just count) a Huffman symbol.
  161046. */
  161047. INLINE
  161048. LOCAL(void)
  161049. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  161050. {
  161051. if (entropy->gather_statistics)
  161052. entropy->count_ptrs[tbl_no][symbol]++;
  161053. else {
  161054. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  161055. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  161056. }
  161057. }
  161058. /*
  161059. * Emit bits from a correction bit buffer.
  161060. */
  161061. LOCAL(void)
  161062. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  161063. unsigned int nbits)
  161064. {
  161065. if (entropy->gather_statistics)
  161066. return; /* no real work */
  161067. while (nbits > 0) {
  161068. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  161069. bufstart++;
  161070. nbits--;
  161071. }
  161072. }
  161073. /*
  161074. * Emit any pending EOBRUN symbol.
  161075. */
  161076. LOCAL(void)
  161077. emit_eobrun (phuff_entropy_ptr entropy)
  161078. {
  161079. register int temp, nbits;
  161080. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  161081. temp = entropy->EOBRUN;
  161082. nbits = 0;
  161083. while ((temp >>= 1))
  161084. nbits++;
  161085. /* safety check: shouldn't happen given limited correction-bit buffer */
  161086. if (nbits > 14)
  161087. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161088. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  161089. if (nbits)
  161090. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  161091. entropy->EOBRUN = 0;
  161092. /* Emit any buffered correction bits */
  161093. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  161094. entropy->BE = 0;
  161095. }
  161096. }
  161097. /*
  161098. * Emit a restart marker & resynchronize predictions.
  161099. */
  161100. LOCAL(void)
  161101. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  161102. {
  161103. int ci;
  161104. emit_eobrun(entropy);
  161105. if (! entropy->gather_statistics) {
  161106. flush_bits_p(entropy);
  161107. emit_byte(entropy, 0xFF);
  161108. emit_byte(entropy, JPEG_RST0 + restart_num);
  161109. }
  161110. if (entropy->cinfo->Ss == 0) {
  161111. /* Re-initialize DC predictions to 0 */
  161112. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  161113. entropy->last_dc_val[ci] = 0;
  161114. } else {
  161115. /* Re-initialize all AC-related fields to 0 */
  161116. entropy->EOBRUN = 0;
  161117. entropy->BE = 0;
  161118. }
  161119. }
  161120. /*
  161121. * MCU encoding for DC initial scan (either spectral selection,
  161122. * or first pass of successive approximation).
  161123. */
  161124. METHODDEF(boolean)
  161125. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161126. {
  161127. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161128. register int temp, temp2;
  161129. register int nbits;
  161130. int blkn, ci;
  161131. int Al = cinfo->Al;
  161132. JBLOCKROW block;
  161133. jpeg_component_info * compptr;
  161134. ISHIFT_TEMPS
  161135. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161136. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161137. /* Emit restart marker if needed */
  161138. if (cinfo->restart_interval)
  161139. if (entropy->restarts_to_go == 0)
  161140. emit_restart_p(entropy, entropy->next_restart_num);
  161141. /* Encode the MCU data blocks */
  161142. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161143. block = MCU_data[blkn];
  161144. ci = cinfo->MCU_membership[blkn];
  161145. compptr = cinfo->cur_comp_info[ci];
  161146. /* Compute the DC value after the required point transform by Al.
  161147. * This is simply an arithmetic right shift.
  161148. */
  161149. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  161150. /* DC differences are figured on the point-transformed values. */
  161151. temp = temp2 - entropy->last_dc_val[ci];
  161152. entropy->last_dc_val[ci] = temp2;
  161153. /* Encode the DC coefficient difference per section G.1.2.1 */
  161154. temp2 = temp;
  161155. if (temp < 0) {
  161156. temp = -temp; /* temp is abs value of input */
  161157. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  161158. /* This code assumes we are on a two's complement machine */
  161159. temp2--;
  161160. }
  161161. /* Find the number of bits needed for the magnitude of the coefficient */
  161162. nbits = 0;
  161163. while (temp) {
  161164. nbits++;
  161165. temp >>= 1;
  161166. }
  161167. /* Check for out-of-range coefficient values.
  161168. * Since we're encoding a difference, the range limit is twice as much.
  161169. */
  161170. if (nbits > MAX_COEF_BITS+1)
  161171. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161172. /* Count/emit the Huffman-coded symbol for the number of bits */
  161173. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  161174. /* Emit that number of bits of the value, if positive, */
  161175. /* or the complement of its magnitude, if negative. */
  161176. if (nbits) /* emit_bits rejects calls with size 0 */
  161177. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161178. }
  161179. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161180. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161181. /* Update restart-interval state too */
  161182. if (cinfo->restart_interval) {
  161183. if (entropy->restarts_to_go == 0) {
  161184. entropy->restarts_to_go = cinfo->restart_interval;
  161185. entropy->next_restart_num++;
  161186. entropy->next_restart_num &= 7;
  161187. }
  161188. entropy->restarts_to_go--;
  161189. }
  161190. return TRUE;
  161191. }
  161192. /*
  161193. * MCU encoding for AC initial scan (either spectral selection,
  161194. * or first pass of successive approximation).
  161195. */
  161196. METHODDEF(boolean)
  161197. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161198. {
  161199. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161200. register int temp, temp2;
  161201. register int nbits;
  161202. register int r, k;
  161203. int Se = cinfo->Se;
  161204. int Al = cinfo->Al;
  161205. JBLOCKROW block;
  161206. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161207. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161208. /* Emit restart marker if needed */
  161209. if (cinfo->restart_interval)
  161210. if (entropy->restarts_to_go == 0)
  161211. emit_restart_p(entropy, entropy->next_restart_num);
  161212. /* Encode the MCU data block */
  161213. block = MCU_data[0];
  161214. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  161215. r = 0; /* r = run length of zeros */
  161216. for (k = cinfo->Ss; k <= Se; k++) {
  161217. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  161218. r++;
  161219. continue;
  161220. }
  161221. /* We must apply the point transform by Al. For AC coefficients this
  161222. * is an integer division with rounding towards 0. To do this portably
  161223. * in C, we shift after obtaining the absolute value; so the code is
  161224. * interwoven with finding the abs value (temp) and output bits (temp2).
  161225. */
  161226. if (temp < 0) {
  161227. temp = -temp; /* temp is abs value of input */
  161228. temp >>= Al; /* apply the point transform */
  161229. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  161230. temp2 = ~temp;
  161231. } else {
  161232. temp >>= Al; /* apply the point transform */
  161233. temp2 = temp;
  161234. }
  161235. /* Watch out for case that nonzero coef is zero after point transform */
  161236. if (temp == 0) {
  161237. r++;
  161238. continue;
  161239. }
  161240. /* Emit any pending EOBRUN */
  161241. if (entropy->EOBRUN > 0)
  161242. emit_eobrun(entropy);
  161243. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  161244. while (r > 15) {
  161245. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161246. r -= 16;
  161247. }
  161248. /* Find the number of bits needed for the magnitude of the coefficient */
  161249. nbits = 1; /* there must be at least one 1 bit */
  161250. while ((temp >>= 1))
  161251. nbits++;
  161252. /* Check for out-of-range coefficient values */
  161253. if (nbits > MAX_COEF_BITS)
  161254. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161255. /* Count/emit Huffman symbol for run length / number of bits */
  161256. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  161257. /* Emit that number of bits of the value, if positive, */
  161258. /* or the complement of its magnitude, if negative. */
  161259. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161260. r = 0; /* reset zero run length */
  161261. }
  161262. if (r > 0) { /* If there are trailing zeroes, */
  161263. entropy->EOBRUN++; /* count an EOB */
  161264. if (entropy->EOBRUN == 0x7FFF)
  161265. emit_eobrun(entropy); /* force it out to avoid overflow */
  161266. }
  161267. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161268. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161269. /* Update restart-interval state too */
  161270. if (cinfo->restart_interval) {
  161271. if (entropy->restarts_to_go == 0) {
  161272. entropy->restarts_to_go = cinfo->restart_interval;
  161273. entropy->next_restart_num++;
  161274. entropy->next_restart_num &= 7;
  161275. }
  161276. entropy->restarts_to_go--;
  161277. }
  161278. return TRUE;
  161279. }
  161280. /*
  161281. * MCU encoding for DC successive approximation refinement scan.
  161282. * Note: we assume such scans can be multi-component, although the spec
  161283. * is not very clear on the point.
  161284. */
  161285. METHODDEF(boolean)
  161286. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161287. {
  161288. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161289. register int temp;
  161290. int blkn;
  161291. int Al = cinfo->Al;
  161292. JBLOCKROW block;
  161293. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161294. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161295. /* Emit restart marker if needed */
  161296. if (cinfo->restart_interval)
  161297. if (entropy->restarts_to_go == 0)
  161298. emit_restart_p(entropy, entropy->next_restart_num);
  161299. /* Encode the MCU data blocks */
  161300. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161301. block = MCU_data[blkn];
  161302. /* We simply emit the Al'th bit of the DC coefficient value. */
  161303. temp = (*block)[0];
  161304. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  161305. }
  161306. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161307. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161308. /* Update restart-interval state too */
  161309. if (cinfo->restart_interval) {
  161310. if (entropy->restarts_to_go == 0) {
  161311. entropy->restarts_to_go = cinfo->restart_interval;
  161312. entropy->next_restart_num++;
  161313. entropy->next_restart_num &= 7;
  161314. }
  161315. entropy->restarts_to_go--;
  161316. }
  161317. return TRUE;
  161318. }
  161319. /*
  161320. * MCU encoding for AC successive approximation refinement scan.
  161321. */
  161322. METHODDEF(boolean)
  161323. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161324. {
  161325. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161326. register int temp;
  161327. register int r, k;
  161328. int EOB;
  161329. char *BR_buffer;
  161330. unsigned int BR;
  161331. int Se = cinfo->Se;
  161332. int Al = cinfo->Al;
  161333. JBLOCKROW block;
  161334. int absvalues[DCTSIZE2];
  161335. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161336. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161337. /* Emit restart marker if needed */
  161338. if (cinfo->restart_interval)
  161339. if (entropy->restarts_to_go == 0)
  161340. emit_restart_p(entropy, entropy->next_restart_num);
  161341. /* Encode the MCU data block */
  161342. block = MCU_data[0];
  161343. /* It is convenient to make a pre-pass to determine the transformed
  161344. * coefficients' absolute values and the EOB position.
  161345. */
  161346. EOB = 0;
  161347. for (k = cinfo->Ss; k <= Se; k++) {
  161348. temp = (*block)[jpeg_natural_order[k]];
  161349. /* We must apply the point transform by Al. For AC coefficients this
  161350. * is an integer division with rounding towards 0. To do this portably
  161351. * in C, we shift after obtaining the absolute value.
  161352. */
  161353. if (temp < 0)
  161354. temp = -temp; /* temp is abs value of input */
  161355. temp >>= Al; /* apply the point transform */
  161356. absvalues[k] = temp; /* save abs value for main pass */
  161357. if (temp == 1)
  161358. EOB = k; /* EOB = index of last newly-nonzero coef */
  161359. }
  161360. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  161361. r = 0; /* r = run length of zeros */
  161362. BR = 0; /* BR = count of buffered bits added now */
  161363. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  161364. for (k = cinfo->Ss; k <= Se; k++) {
  161365. if ((temp = absvalues[k]) == 0) {
  161366. r++;
  161367. continue;
  161368. }
  161369. /* Emit any required ZRLs, but not if they can be folded into EOB */
  161370. while (r > 15 && k <= EOB) {
  161371. /* emit any pending EOBRUN and the BE correction bits */
  161372. emit_eobrun(entropy);
  161373. /* Emit ZRL */
  161374. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161375. r -= 16;
  161376. /* Emit buffered correction bits that must be associated with ZRL */
  161377. emit_buffered_bits(entropy, BR_buffer, BR);
  161378. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  161379. BR = 0;
  161380. }
  161381. /* If the coef was previously nonzero, it only needs a correction bit.
  161382. * NOTE: a straight translation of the spec's figure G.7 would suggest
  161383. * that we also need to test r > 15. But if r > 15, we can only get here
  161384. * if k > EOB, which implies that this coefficient is not 1.
  161385. */
  161386. if (temp > 1) {
  161387. /* The correction bit is the next bit of the absolute value. */
  161388. BR_buffer[BR++] = (char) (temp & 1);
  161389. continue;
  161390. }
  161391. /* Emit any pending EOBRUN and the BE correction bits */
  161392. emit_eobrun(entropy);
  161393. /* Count/emit Huffman symbol for run length / number of bits */
  161394. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  161395. /* Emit output bit for newly-nonzero coef */
  161396. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  161397. emit_bits_p(entropy, (unsigned int) temp, 1);
  161398. /* Emit buffered correction bits that must be associated with this code */
  161399. emit_buffered_bits(entropy, BR_buffer, BR);
  161400. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  161401. BR = 0;
  161402. r = 0; /* reset zero run length */
  161403. }
  161404. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  161405. entropy->EOBRUN++; /* count an EOB */
  161406. entropy->BE += BR; /* concat my correction bits to older ones */
  161407. /* We force out the EOB if we risk either:
  161408. * 1. overflow of the EOB counter;
  161409. * 2. overflow of the correction bit buffer during the next MCU.
  161410. */
  161411. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  161412. emit_eobrun(entropy);
  161413. }
  161414. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161415. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161416. /* Update restart-interval state too */
  161417. if (cinfo->restart_interval) {
  161418. if (entropy->restarts_to_go == 0) {
  161419. entropy->restarts_to_go = cinfo->restart_interval;
  161420. entropy->next_restart_num++;
  161421. entropy->next_restart_num &= 7;
  161422. }
  161423. entropy->restarts_to_go--;
  161424. }
  161425. return TRUE;
  161426. }
  161427. /*
  161428. * Finish up at the end of a Huffman-compressed progressive scan.
  161429. */
  161430. METHODDEF(void)
  161431. finish_pass_phuff (j_compress_ptr cinfo)
  161432. {
  161433. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161434. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161435. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161436. /* Flush out any buffered data */
  161437. emit_eobrun(entropy);
  161438. flush_bits_p(entropy);
  161439. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161440. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161441. }
  161442. /*
  161443. * Finish up a statistics-gathering pass and create the new Huffman tables.
  161444. */
  161445. METHODDEF(void)
  161446. finish_pass_gather_phuff (j_compress_ptr cinfo)
  161447. {
  161448. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161449. boolean is_DC_band;
  161450. int ci, tbl;
  161451. jpeg_component_info * compptr;
  161452. JHUFF_TBL **htblptr;
  161453. boolean did[NUM_HUFF_TBLS];
  161454. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  161455. emit_eobrun(entropy);
  161456. is_DC_band = (cinfo->Ss == 0);
  161457. /* It's important not to apply jpeg_gen_optimal_table more than once
  161458. * per table, because it clobbers the input frequency counts!
  161459. */
  161460. MEMZERO(did, SIZEOF(did));
  161461. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161462. compptr = cinfo->cur_comp_info[ci];
  161463. if (is_DC_band) {
  161464. if (cinfo->Ah != 0) /* DC refinement needs no table */
  161465. continue;
  161466. tbl = compptr->dc_tbl_no;
  161467. } else {
  161468. tbl = compptr->ac_tbl_no;
  161469. }
  161470. if (! did[tbl]) {
  161471. if (is_DC_band)
  161472. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  161473. else
  161474. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  161475. if (*htblptr == NULL)
  161476. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161477. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  161478. did[tbl] = TRUE;
  161479. }
  161480. }
  161481. }
  161482. /*
  161483. * Module initialization routine for progressive Huffman entropy encoding.
  161484. */
  161485. GLOBAL(void)
  161486. jinit_phuff_encoder (j_compress_ptr cinfo)
  161487. {
  161488. phuff_entropy_ptr entropy;
  161489. int i;
  161490. entropy = (phuff_entropy_ptr)
  161491. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161492. SIZEOF(phuff_entropy_encoder));
  161493. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  161494. entropy->pub.start_pass = start_pass_phuff;
  161495. /* Mark tables unallocated */
  161496. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161497. entropy->derived_tbls[i] = NULL;
  161498. entropy->count_ptrs[i] = NULL;
  161499. }
  161500. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  161501. }
  161502. #endif /* C_PROGRESSIVE_SUPPORTED */
  161503. /********* End of inlined file: jcphuff.c *********/
  161504. /********* Start of inlined file: jcprepct.c *********/
  161505. #define JPEG_INTERNALS
  161506. /* At present, jcsample.c can request context rows only for smoothing.
  161507. * In the future, we might also need context rows for CCIR601 sampling
  161508. * or other more-complex downsampling procedures. The code to support
  161509. * context rows should be compiled only if needed.
  161510. */
  161511. #ifdef INPUT_SMOOTHING_SUPPORTED
  161512. #define CONTEXT_ROWS_SUPPORTED
  161513. #endif
  161514. /*
  161515. * For the simple (no-context-row) case, we just need to buffer one
  161516. * row group's worth of pixels for the downsampling step. At the bottom of
  161517. * the image, we pad to a full row group by replicating the last pixel row.
  161518. * The downsampler's last output row is then replicated if needed to pad
  161519. * out to a full iMCU row.
  161520. *
  161521. * When providing context rows, we must buffer three row groups' worth of
  161522. * pixels. Three row groups are physically allocated, but the row pointer
  161523. * arrays are made five row groups high, with the extra pointers above and
  161524. * below "wrapping around" to point to the last and first real row groups.
  161525. * This allows the downsampler to access the proper context rows.
  161526. * At the top and bottom of the image, we create dummy context rows by
  161527. * copying the first or last real pixel row. This copying could be avoided
  161528. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  161529. * trouble on the compression side.
  161530. */
  161531. /* Private buffer controller object */
  161532. typedef struct {
  161533. struct jpeg_c_prep_controller pub; /* public fields */
  161534. /* Downsampling input buffer. This buffer holds color-converted data
  161535. * until we have enough to do a downsample step.
  161536. */
  161537. JSAMPARRAY color_buf[MAX_COMPONENTS];
  161538. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  161539. int next_buf_row; /* index of next row to store in color_buf */
  161540. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  161541. int this_row_group; /* starting row index of group to process */
  161542. int next_buf_stop; /* downsample when we reach this index */
  161543. #endif
  161544. } my_prep_controller;
  161545. typedef my_prep_controller * my_prep_ptr;
  161546. /*
  161547. * Initialize for a processing pass.
  161548. */
  161549. METHODDEF(void)
  161550. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161551. {
  161552. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  161553. if (pass_mode != JBUF_PASS_THRU)
  161554. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161555. /* Initialize total-height counter for detecting bottom of image */
  161556. prep->rows_to_go = cinfo->image_height;
  161557. /* Mark the conversion buffer empty */
  161558. prep->next_buf_row = 0;
  161559. #ifdef CONTEXT_ROWS_SUPPORTED
  161560. /* Preset additional state variables for context mode.
  161561. * These aren't used in non-context mode, so we needn't test which mode.
  161562. */
  161563. prep->this_row_group = 0;
  161564. /* Set next_buf_stop to stop after two row groups have been read in. */
  161565. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  161566. #endif
  161567. }
  161568. /*
  161569. * Expand an image vertically from height input_rows to height output_rows,
  161570. * by duplicating the bottom row.
  161571. */
  161572. LOCAL(void)
  161573. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  161574. int input_rows, int output_rows)
  161575. {
  161576. register int row;
  161577. for (row = input_rows; row < output_rows; row++) {
  161578. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  161579. 1, num_cols);
  161580. }
  161581. }
  161582. /*
  161583. * Process some data in the simple no-context case.
  161584. *
  161585. * Preprocessor output data is counted in "row groups". A row group
  161586. * is defined to be v_samp_factor sample rows of each component.
  161587. * Downsampling will produce this much data from each max_v_samp_factor
  161588. * input rows.
  161589. */
  161590. METHODDEF(void)
  161591. pre_process_data (j_compress_ptr cinfo,
  161592. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161593. JDIMENSION in_rows_avail,
  161594. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  161595. JDIMENSION out_row_groups_avail)
  161596. {
  161597. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  161598. int numrows, ci;
  161599. JDIMENSION inrows;
  161600. jpeg_component_info * compptr;
  161601. while (*in_row_ctr < in_rows_avail &&
  161602. *out_row_group_ctr < out_row_groups_avail) {
  161603. /* Do color conversion to fill the conversion buffer. */
  161604. inrows = in_rows_avail - *in_row_ctr;
  161605. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  161606. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  161607. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  161608. prep->color_buf,
  161609. (JDIMENSION) prep->next_buf_row,
  161610. numrows);
  161611. *in_row_ctr += numrows;
  161612. prep->next_buf_row += numrows;
  161613. prep->rows_to_go -= numrows;
  161614. /* If at bottom of image, pad to fill the conversion buffer. */
  161615. if (prep->rows_to_go == 0 &&
  161616. prep->next_buf_row < cinfo->max_v_samp_factor) {
  161617. for (ci = 0; ci < cinfo->num_components; ci++) {
  161618. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  161619. prep->next_buf_row, cinfo->max_v_samp_factor);
  161620. }
  161621. prep->next_buf_row = cinfo->max_v_samp_factor;
  161622. }
  161623. /* If we've filled the conversion buffer, empty it. */
  161624. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  161625. (*cinfo->downsample->downsample) (cinfo,
  161626. prep->color_buf, (JDIMENSION) 0,
  161627. output_buf, *out_row_group_ctr);
  161628. prep->next_buf_row = 0;
  161629. (*out_row_group_ctr)++;
  161630. }
  161631. /* If at bottom of image, pad the output to a full iMCU height.
  161632. * Note we assume the caller is providing a one-iMCU-height output buffer!
  161633. */
  161634. if (prep->rows_to_go == 0 &&
  161635. *out_row_group_ctr < out_row_groups_avail) {
  161636. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161637. ci++, compptr++) {
  161638. expand_bottom_edge(output_buf[ci],
  161639. compptr->width_in_blocks * DCTSIZE,
  161640. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  161641. (int) (out_row_groups_avail * compptr->v_samp_factor));
  161642. }
  161643. *out_row_group_ctr = out_row_groups_avail;
  161644. break; /* can exit outer loop without test */
  161645. }
  161646. }
  161647. }
  161648. #ifdef CONTEXT_ROWS_SUPPORTED
  161649. /*
  161650. * Process some data in the context case.
  161651. */
  161652. METHODDEF(void)
  161653. pre_process_context (j_compress_ptr cinfo,
  161654. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161655. JDIMENSION in_rows_avail,
  161656. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  161657. JDIMENSION out_row_groups_avail)
  161658. {
  161659. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  161660. int numrows, ci;
  161661. int buf_height = cinfo->max_v_samp_factor * 3;
  161662. JDIMENSION inrows;
  161663. while (*out_row_group_ctr < out_row_groups_avail) {
  161664. if (*in_row_ctr < in_rows_avail) {
  161665. /* Do color conversion to fill the conversion buffer. */
  161666. inrows = in_rows_avail - *in_row_ctr;
  161667. numrows = prep->next_buf_stop - prep->next_buf_row;
  161668. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  161669. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  161670. prep->color_buf,
  161671. (JDIMENSION) prep->next_buf_row,
  161672. numrows);
  161673. /* Pad at top of image, if first time through */
  161674. if (prep->rows_to_go == cinfo->image_height) {
  161675. for (ci = 0; ci < cinfo->num_components; ci++) {
  161676. int row;
  161677. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  161678. jcopy_sample_rows(prep->color_buf[ci], 0,
  161679. prep->color_buf[ci], -row,
  161680. 1, cinfo->image_width);
  161681. }
  161682. }
  161683. }
  161684. *in_row_ctr += numrows;
  161685. prep->next_buf_row += numrows;
  161686. prep->rows_to_go -= numrows;
  161687. } else {
  161688. /* Return for more data, unless we are at the bottom of the image. */
  161689. if (prep->rows_to_go != 0)
  161690. break;
  161691. /* When at bottom of image, pad to fill the conversion buffer. */
  161692. if (prep->next_buf_row < prep->next_buf_stop) {
  161693. for (ci = 0; ci < cinfo->num_components; ci++) {
  161694. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  161695. prep->next_buf_row, prep->next_buf_stop);
  161696. }
  161697. prep->next_buf_row = prep->next_buf_stop;
  161698. }
  161699. }
  161700. /* If we've gotten enough data, downsample a row group. */
  161701. if (prep->next_buf_row == prep->next_buf_stop) {
  161702. (*cinfo->downsample->downsample) (cinfo,
  161703. prep->color_buf,
  161704. (JDIMENSION) prep->this_row_group,
  161705. output_buf, *out_row_group_ctr);
  161706. (*out_row_group_ctr)++;
  161707. /* Advance pointers with wraparound as necessary. */
  161708. prep->this_row_group += cinfo->max_v_samp_factor;
  161709. if (prep->this_row_group >= buf_height)
  161710. prep->this_row_group = 0;
  161711. if (prep->next_buf_row >= buf_height)
  161712. prep->next_buf_row = 0;
  161713. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  161714. }
  161715. }
  161716. }
  161717. /*
  161718. * Create the wrapped-around downsampling input buffer needed for context mode.
  161719. */
  161720. LOCAL(void)
  161721. create_context_buffer (j_compress_ptr cinfo)
  161722. {
  161723. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  161724. int rgroup_height = cinfo->max_v_samp_factor;
  161725. int ci, i;
  161726. jpeg_component_info * compptr;
  161727. JSAMPARRAY true_buffer, fake_buffer;
  161728. /* Grab enough space for fake row pointers for all the components;
  161729. * we need five row groups' worth of pointers for each component.
  161730. */
  161731. fake_buffer = (JSAMPARRAY)
  161732. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161733. (cinfo->num_components * 5 * rgroup_height) *
  161734. SIZEOF(JSAMPROW));
  161735. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161736. ci++, compptr++) {
  161737. /* Allocate the actual buffer space (3 row groups) for this component.
  161738. * We make the buffer wide enough to allow the downsampler to edge-expand
  161739. * horizontally within the buffer, if it so chooses.
  161740. */
  161741. true_buffer = (*cinfo->mem->alloc_sarray)
  161742. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161743. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  161744. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  161745. (JDIMENSION) (3 * rgroup_height));
  161746. /* Copy true buffer row pointers into the middle of the fake row array */
  161747. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  161748. 3 * rgroup_height * SIZEOF(JSAMPROW));
  161749. /* Fill in the above and below wraparound pointers */
  161750. for (i = 0; i < rgroup_height; i++) {
  161751. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  161752. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  161753. }
  161754. prep->color_buf[ci] = fake_buffer + rgroup_height;
  161755. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  161756. }
  161757. }
  161758. #endif /* CONTEXT_ROWS_SUPPORTED */
  161759. /*
  161760. * Initialize preprocessing controller.
  161761. */
  161762. GLOBAL(void)
  161763. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161764. {
  161765. my_prep_ptr prep;
  161766. int ci;
  161767. jpeg_component_info * compptr;
  161768. if (need_full_buffer) /* safety check */
  161769. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161770. prep = (my_prep_ptr)
  161771. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161772. SIZEOF(my_prep_controller));
  161773. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  161774. prep->pub.start_pass = start_pass_prep;
  161775. /* Allocate the color conversion buffer.
  161776. * We make the buffer wide enough to allow the downsampler to edge-expand
  161777. * horizontally within the buffer, if it so chooses.
  161778. */
  161779. if (cinfo->downsample->need_context_rows) {
  161780. /* Set up to provide context rows */
  161781. #ifdef CONTEXT_ROWS_SUPPORTED
  161782. prep->pub.pre_process_data = pre_process_context;
  161783. create_context_buffer(cinfo);
  161784. #else
  161785. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161786. #endif
  161787. } else {
  161788. /* No context, just make it tall enough for one row group */
  161789. prep->pub.pre_process_data = pre_process_data;
  161790. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161791. ci++, compptr++) {
  161792. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  161793. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161794. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  161795. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  161796. (JDIMENSION) cinfo->max_v_samp_factor);
  161797. }
  161798. }
  161799. }
  161800. /********* End of inlined file: jcprepct.c *********/
  161801. /********* Start of inlined file: jcsample.c *********/
  161802. #define JPEG_INTERNALS
  161803. /* Pointer to routine to downsample a single component */
  161804. typedef JMETHOD(void, downsample1_ptr,
  161805. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161806. JSAMPARRAY input_data, JSAMPARRAY output_data));
  161807. /* Private subobject */
  161808. typedef struct {
  161809. struct jpeg_downsampler pub; /* public fields */
  161810. /* Downsampling method pointers, one per component */
  161811. downsample1_ptr methods[MAX_COMPONENTS];
  161812. } my_downsampler;
  161813. typedef my_downsampler * my_downsample_ptr;
  161814. /*
  161815. * Initialize for a downsampling pass.
  161816. */
  161817. METHODDEF(void)
  161818. start_pass_downsample (j_compress_ptr cinfo)
  161819. {
  161820. /* no work for now */
  161821. }
  161822. /*
  161823. * Expand a component horizontally from width input_cols to width output_cols,
  161824. * by duplicating the rightmost samples.
  161825. */
  161826. LOCAL(void)
  161827. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  161828. JDIMENSION input_cols, JDIMENSION output_cols)
  161829. {
  161830. register JSAMPROW ptr;
  161831. register JSAMPLE pixval;
  161832. register int count;
  161833. int row;
  161834. int numcols = (int) (output_cols - input_cols);
  161835. if (numcols > 0) {
  161836. for (row = 0; row < num_rows; row++) {
  161837. ptr = image_data[row] + input_cols;
  161838. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  161839. for (count = numcols; count > 0; count--)
  161840. *ptr++ = pixval;
  161841. }
  161842. }
  161843. }
  161844. /*
  161845. * Do downsampling for a whole row group (all components).
  161846. *
  161847. * In this version we simply downsample each component independently.
  161848. */
  161849. METHODDEF(void)
  161850. sep_downsample (j_compress_ptr cinfo,
  161851. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161852. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  161853. {
  161854. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  161855. int ci;
  161856. jpeg_component_info * compptr;
  161857. JSAMPARRAY in_ptr, out_ptr;
  161858. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161859. ci++, compptr++) {
  161860. in_ptr = input_buf[ci] + in_row_index;
  161861. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  161862. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  161863. }
  161864. }
  161865. /*
  161866. * Downsample pixel values of a single component.
  161867. * One row group is processed per call.
  161868. * This version handles arbitrary integral sampling ratios, without smoothing.
  161869. * Note that this version is not actually used for customary sampling ratios.
  161870. */
  161871. METHODDEF(void)
  161872. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161873. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161874. {
  161875. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  161876. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  161877. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161878. JSAMPROW inptr, outptr;
  161879. INT32 outvalue;
  161880. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  161881. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  161882. numpix = h_expand * v_expand;
  161883. numpix2 = numpix/2;
  161884. /* Expand input data enough to let all the output samples be generated
  161885. * by the standard loop. Special-casing padded output would be more
  161886. * efficient.
  161887. */
  161888. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  161889. cinfo->image_width, output_cols * h_expand);
  161890. inrow = 0;
  161891. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161892. outptr = output_data[outrow];
  161893. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  161894. outcol++, outcol_h += h_expand) {
  161895. outvalue = 0;
  161896. for (v = 0; v < v_expand; v++) {
  161897. inptr = input_data[inrow+v] + outcol_h;
  161898. for (h = 0; h < h_expand; h++) {
  161899. outvalue += (INT32) GETJSAMPLE(*inptr++);
  161900. }
  161901. }
  161902. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  161903. }
  161904. inrow += v_expand;
  161905. }
  161906. }
  161907. /*
  161908. * Downsample pixel values of a single component.
  161909. * This version handles the special case of a full-size component,
  161910. * without smoothing.
  161911. */
  161912. METHODDEF(void)
  161913. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161914. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161915. {
  161916. /* Copy the data */
  161917. jcopy_sample_rows(input_data, 0, output_data, 0,
  161918. cinfo->max_v_samp_factor, cinfo->image_width);
  161919. /* Edge-expand */
  161920. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  161921. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  161922. }
  161923. /*
  161924. * Downsample pixel values of a single component.
  161925. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  161926. * without smoothing.
  161927. *
  161928. * A note about the "bias" calculations: when rounding fractional values to
  161929. * integer, we do not want to always round 0.5 up to the next integer.
  161930. * If we did that, we'd introduce a noticeable bias towards larger values.
  161931. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  161932. * alternate pixel locations (a simple ordered dither pattern).
  161933. */
  161934. METHODDEF(void)
  161935. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161936. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161937. {
  161938. int outrow;
  161939. JDIMENSION outcol;
  161940. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161941. register JSAMPROW inptr, outptr;
  161942. register int bias;
  161943. /* Expand input data enough to let all the output samples be generated
  161944. * by the standard loop. Special-casing padded output would be more
  161945. * efficient.
  161946. */
  161947. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  161948. cinfo->image_width, output_cols * 2);
  161949. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161950. outptr = output_data[outrow];
  161951. inptr = input_data[outrow];
  161952. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  161953. for (outcol = 0; outcol < output_cols; outcol++) {
  161954. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  161955. + bias) >> 1);
  161956. bias ^= 1; /* 0=>1, 1=>0 */
  161957. inptr += 2;
  161958. }
  161959. }
  161960. }
  161961. /*
  161962. * Downsample pixel values of a single component.
  161963. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  161964. * without smoothing.
  161965. */
  161966. METHODDEF(void)
  161967. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161968. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161969. {
  161970. int inrow, outrow;
  161971. JDIMENSION outcol;
  161972. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161973. register JSAMPROW inptr0, inptr1, outptr;
  161974. register int bias;
  161975. /* Expand input data enough to let all the output samples be generated
  161976. * by the standard loop. Special-casing padded output would be more
  161977. * efficient.
  161978. */
  161979. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  161980. cinfo->image_width, output_cols * 2);
  161981. inrow = 0;
  161982. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161983. outptr = output_data[outrow];
  161984. inptr0 = input_data[inrow];
  161985. inptr1 = input_data[inrow+1];
  161986. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  161987. for (outcol = 0; outcol < output_cols; outcol++) {
  161988. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161989. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  161990. + bias) >> 2);
  161991. bias ^= 3; /* 1=>2, 2=>1 */
  161992. inptr0 += 2; inptr1 += 2;
  161993. }
  161994. inrow += 2;
  161995. }
  161996. }
  161997. #ifdef INPUT_SMOOTHING_SUPPORTED
  161998. /*
  161999. * Downsample pixel values of a single component.
  162000. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162001. * with smoothing. One row of context is required.
  162002. */
  162003. METHODDEF(void)
  162004. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162005. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162006. {
  162007. int inrow, outrow;
  162008. JDIMENSION colctr;
  162009. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162010. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  162011. INT32 membersum, neighsum, memberscale, neighscale;
  162012. /* Expand input data enough to let all the output samples be generated
  162013. * by the standard loop. Special-casing padded output would be more
  162014. * efficient.
  162015. */
  162016. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162017. cinfo->image_width, output_cols * 2);
  162018. /* We don't bother to form the individual "smoothed" input pixel values;
  162019. * we can directly compute the output which is the average of the four
  162020. * smoothed values. Each of the four member pixels contributes a fraction
  162021. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  162022. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  162023. * output. The four corner-adjacent neighbor pixels contribute a fraction
  162024. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  162025. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  162026. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  162027. * factors are scaled by 2^16 = 65536.
  162028. * Also recall that SF = smoothing_factor / 1024.
  162029. */
  162030. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  162031. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  162032. inrow = 0;
  162033. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162034. outptr = output_data[outrow];
  162035. inptr0 = input_data[inrow];
  162036. inptr1 = input_data[inrow+1];
  162037. above_ptr = input_data[inrow-1];
  162038. below_ptr = input_data[inrow+2];
  162039. /* Special case for first column: pretend column -1 is same as column 0 */
  162040. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162041. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162042. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162043. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162044. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  162045. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  162046. neighsum += neighsum;
  162047. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  162048. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  162049. membersum = membersum * memberscale + neighsum * neighscale;
  162050. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162051. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162052. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162053. /* sum of pixels directly mapped to this output element */
  162054. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162055. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162056. /* sum of edge-neighbor pixels */
  162057. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162058. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162059. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  162060. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  162061. /* The edge-neighbors count twice as much as corner-neighbors */
  162062. neighsum += neighsum;
  162063. /* Add in the corner-neighbors */
  162064. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  162065. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  162066. /* form final output scaled up by 2^16 */
  162067. membersum = membersum * memberscale + neighsum * neighscale;
  162068. /* round, descale and output it */
  162069. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162070. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162071. }
  162072. /* Special case for last column */
  162073. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162074. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162075. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162076. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162077. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  162078. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  162079. neighsum += neighsum;
  162080. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  162081. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  162082. membersum = membersum * memberscale + neighsum * neighscale;
  162083. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162084. inrow += 2;
  162085. }
  162086. }
  162087. /*
  162088. * Downsample pixel values of a single component.
  162089. * This version handles the special case of a full-size component,
  162090. * with smoothing. One row of context is required.
  162091. */
  162092. METHODDEF(void)
  162093. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  162094. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162095. {
  162096. int outrow;
  162097. JDIMENSION colctr;
  162098. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162099. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  162100. INT32 membersum, neighsum, memberscale, neighscale;
  162101. int colsum, lastcolsum, nextcolsum;
  162102. /* Expand input data enough to let all the output samples be generated
  162103. * by the standard loop. Special-casing padded output would be more
  162104. * efficient.
  162105. */
  162106. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162107. cinfo->image_width, output_cols);
  162108. /* Each of the eight neighbor pixels contributes a fraction SF to the
  162109. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  162110. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  162111. * Also recall that SF = smoothing_factor / 1024.
  162112. */
  162113. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  162114. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  162115. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162116. outptr = output_data[outrow];
  162117. inptr = input_data[outrow];
  162118. above_ptr = input_data[outrow-1];
  162119. below_ptr = input_data[outrow+1];
  162120. /* Special case for first column */
  162121. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  162122. GETJSAMPLE(*inptr);
  162123. membersum = GETJSAMPLE(*inptr++);
  162124. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162125. GETJSAMPLE(*inptr);
  162126. neighsum = colsum + (colsum - membersum) + nextcolsum;
  162127. membersum = membersum * memberscale + neighsum * neighscale;
  162128. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162129. lastcolsum = colsum; colsum = nextcolsum;
  162130. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162131. membersum = GETJSAMPLE(*inptr++);
  162132. above_ptr++; below_ptr++;
  162133. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162134. GETJSAMPLE(*inptr);
  162135. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  162136. membersum = membersum * memberscale + neighsum * neighscale;
  162137. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162138. lastcolsum = colsum; colsum = nextcolsum;
  162139. }
  162140. /* Special case for last column */
  162141. membersum = GETJSAMPLE(*inptr);
  162142. neighsum = lastcolsum + (colsum - membersum) + colsum;
  162143. membersum = membersum * memberscale + neighsum * neighscale;
  162144. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162145. }
  162146. }
  162147. #endif /* INPUT_SMOOTHING_SUPPORTED */
  162148. /*
  162149. * Module initialization routine for downsampling.
  162150. * Note that we must select a routine for each component.
  162151. */
  162152. GLOBAL(void)
  162153. jinit_downsampler (j_compress_ptr cinfo)
  162154. {
  162155. my_downsample_ptr downsample;
  162156. int ci;
  162157. jpeg_component_info * compptr;
  162158. boolean smoothok = TRUE;
  162159. downsample = (my_downsample_ptr)
  162160. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162161. SIZEOF(my_downsampler));
  162162. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  162163. downsample->pub.start_pass = start_pass_downsample;
  162164. downsample->pub.downsample = sep_downsample;
  162165. downsample->pub.need_context_rows = FALSE;
  162166. if (cinfo->CCIR601_sampling)
  162167. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  162168. /* Verify we can handle the sampling factors, and set up method pointers */
  162169. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162170. ci++, compptr++) {
  162171. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  162172. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162173. #ifdef INPUT_SMOOTHING_SUPPORTED
  162174. if (cinfo->smoothing_factor) {
  162175. downsample->methods[ci] = fullsize_smooth_downsample;
  162176. downsample->pub.need_context_rows = TRUE;
  162177. } else
  162178. #endif
  162179. downsample->methods[ci] = fullsize_downsample;
  162180. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162181. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162182. smoothok = FALSE;
  162183. downsample->methods[ci] = h2v1_downsample;
  162184. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162185. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  162186. #ifdef INPUT_SMOOTHING_SUPPORTED
  162187. if (cinfo->smoothing_factor) {
  162188. downsample->methods[ci] = h2v2_smooth_downsample;
  162189. downsample->pub.need_context_rows = TRUE;
  162190. } else
  162191. #endif
  162192. downsample->methods[ci] = h2v2_downsample;
  162193. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  162194. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  162195. smoothok = FALSE;
  162196. downsample->methods[ci] = int_downsample;
  162197. } else
  162198. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  162199. }
  162200. #ifdef INPUT_SMOOTHING_SUPPORTED
  162201. if (cinfo->smoothing_factor && !smoothok)
  162202. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  162203. #endif
  162204. }
  162205. /********* End of inlined file: jcsample.c *********/
  162206. /********* Start of inlined file: jctrans.c *********/
  162207. #define JPEG_INTERNALS
  162208. /* Forward declarations */
  162209. LOCAL(void) transencode_master_selection
  162210. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162211. LOCAL(void) transencode_coef_controller
  162212. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162213. /*
  162214. * Compression initialization for writing raw-coefficient data.
  162215. * Before calling this, all parameters and a data destination must be set up.
  162216. * Call jpeg_finish_compress() to actually write the data.
  162217. *
  162218. * The number of passed virtual arrays must match cinfo->num_components.
  162219. * Note that the virtual arrays need not be filled or even realized at
  162220. * the time write_coefficients is called; indeed, if the virtual arrays
  162221. * were requested from this compression object's memory manager, they
  162222. * typically will be realized during this routine and filled afterwards.
  162223. */
  162224. GLOBAL(void)
  162225. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  162226. {
  162227. if (cinfo->global_state != CSTATE_START)
  162228. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162229. /* Mark all tables to be written */
  162230. jpeg_suppress_tables(cinfo, FALSE);
  162231. /* (Re)initialize error mgr and destination modules */
  162232. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162233. (*cinfo->dest->init_destination) (cinfo);
  162234. /* Perform master selection of active modules */
  162235. transencode_master_selection(cinfo, coef_arrays);
  162236. /* Wait for jpeg_finish_compress() call */
  162237. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  162238. cinfo->global_state = CSTATE_WRCOEFS;
  162239. }
  162240. /*
  162241. * Initialize the compression object with default parameters,
  162242. * then copy from the source object all parameters needed for lossless
  162243. * transcoding. Parameters that can be varied without loss (such as
  162244. * scan script and Huffman optimization) are left in their default states.
  162245. */
  162246. GLOBAL(void)
  162247. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  162248. j_compress_ptr dstinfo)
  162249. {
  162250. JQUANT_TBL ** qtblptr;
  162251. jpeg_component_info *incomp, *outcomp;
  162252. JQUANT_TBL *c_quant, *slot_quant;
  162253. int tblno, ci, coefi;
  162254. /* Safety check to ensure start_compress not called yet. */
  162255. if (dstinfo->global_state != CSTATE_START)
  162256. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  162257. /* Copy fundamental image dimensions */
  162258. dstinfo->image_width = srcinfo->image_width;
  162259. dstinfo->image_height = srcinfo->image_height;
  162260. dstinfo->input_components = srcinfo->num_components;
  162261. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  162262. /* Initialize all parameters to default values */
  162263. jpeg_set_defaults(dstinfo);
  162264. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  162265. * Fix it to get the right header markers for the image colorspace.
  162266. */
  162267. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  162268. dstinfo->data_precision = srcinfo->data_precision;
  162269. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  162270. /* Copy the source's quantization tables. */
  162271. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  162272. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  162273. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  162274. if (*qtblptr == NULL)
  162275. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  162276. MEMCOPY((*qtblptr)->quantval,
  162277. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  162278. SIZEOF((*qtblptr)->quantval));
  162279. (*qtblptr)->sent_table = FALSE;
  162280. }
  162281. }
  162282. /* Copy the source's per-component info.
  162283. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  162284. */
  162285. dstinfo->num_components = srcinfo->num_components;
  162286. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  162287. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  162288. MAX_COMPONENTS);
  162289. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  162290. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  162291. outcomp->component_id = incomp->component_id;
  162292. outcomp->h_samp_factor = incomp->h_samp_factor;
  162293. outcomp->v_samp_factor = incomp->v_samp_factor;
  162294. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  162295. /* Make sure saved quantization table for component matches the qtable
  162296. * slot. If not, the input file re-used this qtable slot.
  162297. * IJG encoder currently cannot duplicate this.
  162298. */
  162299. tblno = outcomp->quant_tbl_no;
  162300. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  162301. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  162302. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  162303. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  162304. c_quant = incomp->quant_table;
  162305. if (c_quant != NULL) {
  162306. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  162307. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  162308. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  162309. }
  162310. }
  162311. /* Note: we do not copy the source's Huffman table assignments;
  162312. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  162313. */
  162314. }
  162315. /* Also copy JFIF version and resolution information, if available.
  162316. * Strictly speaking this isn't "critical" info, but it's nearly
  162317. * always appropriate to copy it if available. In particular,
  162318. * if the application chooses to copy JFIF 1.02 extension markers from
  162319. * the source file, we need to copy the version to make sure we don't
  162320. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  162321. * We will *not*, however, copy version info from mislabeled "2.01" files.
  162322. */
  162323. if (srcinfo->saw_JFIF_marker) {
  162324. if (srcinfo->JFIF_major_version == 1) {
  162325. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  162326. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  162327. }
  162328. dstinfo->density_unit = srcinfo->density_unit;
  162329. dstinfo->X_density = srcinfo->X_density;
  162330. dstinfo->Y_density = srcinfo->Y_density;
  162331. }
  162332. }
  162333. /*
  162334. * Master selection of compression modules for transcoding.
  162335. * This substitutes for jcinit.c's initialization of the full compressor.
  162336. */
  162337. LOCAL(void)
  162338. transencode_master_selection (j_compress_ptr cinfo,
  162339. jvirt_barray_ptr * coef_arrays)
  162340. {
  162341. /* Although we don't actually use input_components for transcoding,
  162342. * jcmaster.c's initial_setup will complain if input_components is 0.
  162343. */
  162344. cinfo->input_components = 1;
  162345. /* Initialize master control (includes parameter checking/processing) */
  162346. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  162347. /* Entropy encoding: either Huffman or arithmetic coding. */
  162348. if (cinfo->arith_code) {
  162349. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  162350. } else {
  162351. if (cinfo->progressive_mode) {
  162352. #ifdef C_PROGRESSIVE_SUPPORTED
  162353. jinit_phuff_encoder(cinfo);
  162354. #else
  162355. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162356. #endif
  162357. } else
  162358. jinit_huff_encoder(cinfo);
  162359. }
  162360. /* We need a special coefficient buffer controller. */
  162361. transencode_coef_controller(cinfo, coef_arrays);
  162362. jinit_marker_writer(cinfo);
  162363. /* We can now tell the memory manager to allocate virtual arrays. */
  162364. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  162365. /* Write the datastream header (SOI, JFIF) immediately.
  162366. * Frame and scan headers are postponed till later.
  162367. * This lets application insert special markers after the SOI.
  162368. */
  162369. (*cinfo->marker->write_file_header) (cinfo);
  162370. }
  162371. /*
  162372. * The rest of this file is a special implementation of the coefficient
  162373. * buffer controller. This is similar to jccoefct.c, but it handles only
  162374. * output from presupplied virtual arrays. Furthermore, we generate any
  162375. * dummy padding blocks on-the-fly rather than expecting them to be present
  162376. * in the arrays.
  162377. */
  162378. /* Private buffer controller object */
  162379. typedef struct {
  162380. struct jpeg_c_coef_controller pub; /* public fields */
  162381. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162382. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162383. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162384. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162385. /* Virtual block array for each component. */
  162386. jvirt_barray_ptr * whole_image;
  162387. /* Workspace for constructing dummy blocks at right/bottom edges. */
  162388. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  162389. } my_coef_controller2;
  162390. typedef my_coef_controller2 * my_coef_ptr2;
  162391. LOCAL(void)
  162392. start_iMCU_row2 (j_compress_ptr cinfo)
  162393. /* Reset within-iMCU-row counters for a new row */
  162394. {
  162395. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162396. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162397. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162398. * But at the bottom of the image, process only what's left.
  162399. */
  162400. if (cinfo->comps_in_scan > 1) {
  162401. coef->MCU_rows_per_iMCU_row = 1;
  162402. } else {
  162403. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162404. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162405. else
  162406. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162407. }
  162408. coef->mcu_ctr = 0;
  162409. coef->MCU_vert_offset = 0;
  162410. }
  162411. /*
  162412. * Initialize for a processing pass.
  162413. */
  162414. METHODDEF(void)
  162415. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162416. {
  162417. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162418. if (pass_mode != JBUF_CRANK_DEST)
  162419. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162420. coef->iMCU_row_num = 0;
  162421. start_iMCU_row2(cinfo);
  162422. }
  162423. /*
  162424. * Process some data.
  162425. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162426. * per call, ie, v_samp_factor block rows for each component in the scan.
  162427. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162428. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162429. *
  162430. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162431. */
  162432. METHODDEF(boolean)
  162433. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162434. {
  162435. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162436. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162437. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162438. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162439. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  162440. JDIMENSION start_col;
  162441. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162442. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162443. JBLOCKROW buffer_ptr;
  162444. jpeg_component_info *compptr;
  162445. /* Align the virtual buffers for the components used in this scan. */
  162446. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162447. compptr = cinfo->cur_comp_info[ci];
  162448. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162449. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162450. coef->iMCU_row_num * compptr->v_samp_factor,
  162451. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162452. }
  162453. /* Loop to process one whole iMCU row */
  162454. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162455. yoffset++) {
  162456. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162457. MCU_col_num++) {
  162458. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162459. blkn = 0; /* index of current DCT block within MCU */
  162460. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162461. compptr = cinfo->cur_comp_info[ci];
  162462. start_col = MCU_col_num * compptr->MCU_width;
  162463. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162464. : compptr->last_col_width;
  162465. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162466. if (coef->iMCU_row_num < last_iMCU_row ||
  162467. yindex+yoffset < compptr->last_row_height) {
  162468. /* Fill in pointers to real blocks in this row */
  162469. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162470. for (xindex = 0; xindex < blockcnt; xindex++)
  162471. MCU_buffer[blkn++] = buffer_ptr++;
  162472. } else {
  162473. /* At bottom of image, need a whole row of dummy blocks */
  162474. xindex = 0;
  162475. }
  162476. /* Fill in any dummy blocks needed in this row.
  162477. * Dummy blocks are filled in the same way as in jccoefct.c:
  162478. * all zeroes in the AC entries, DC entries equal to previous
  162479. * block's DC value. The init routine has already zeroed the
  162480. * AC entries, so we need only set the DC entries correctly.
  162481. */
  162482. for (; xindex < compptr->MCU_width; xindex++) {
  162483. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  162484. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  162485. blkn++;
  162486. }
  162487. }
  162488. }
  162489. /* Try to write the MCU. */
  162490. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  162491. /* Suspension forced; update state counters and exit */
  162492. coef->MCU_vert_offset = yoffset;
  162493. coef->mcu_ctr = MCU_col_num;
  162494. return FALSE;
  162495. }
  162496. }
  162497. /* Completed an MCU row, but perhaps not an iMCU row */
  162498. coef->mcu_ctr = 0;
  162499. }
  162500. /* Completed the iMCU row, advance counters for next one */
  162501. coef->iMCU_row_num++;
  162502. start_iMCU_row2(cinfo);
  162503. return TRUE;
  162504. }
  162505. /*
  162506. * Initialize coefficient buffer controller.
  162507. *
  162508. * Each passed coefficient array must be the right size for that
  162509. * coefficient: width_in_blocks wide and height_in_blocks high,
  162510. * with unitheight at least v_samp_factor.
  162511. */
  162512. LOCAL(void)
  162513. transencode_coef_controller (j_compress_ptr cinfo,
  162514. jvirt_barray_ptr * coef_arrays)
  162515. {
  162516. my_coef_ptr2 coef;
  162517. JBLOCKROW buffer;
  162518. int i;
  162519. coef = (my_coef_ptr2)
  162520. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162521. SIZEOF(my_coef_controller2));
  162522. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162523. coef->pub.start_pass = start_pass_coef2;
  162524. coef->pub.compress_data = compress_output2;
  162525. /* Save pointer to virtual arrays */
  162526. coef->whole_image = coef_arrays;
  162527. /* Allocate and pre-zero space for dummy DCT blocks. */
  162528. buffer = (JBLOCKROW)
  162529. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162530. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162531. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162532. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162533. coef->dummy_buffer[i] = buffer + i;
  162534. }
  162535. }
  162536. /********* End of inlined file: jctrans.c *********/
  162537. /********* Start of inlined file: jdapistd.c *********/
  162538. #define JPEG_INTERNALS
  162539. /* Forward declarations */
  162540. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  162541. /*
  162542. * Decompression initialization.
  162543. * jpeg_read_header must be completed before calling this.
  162544. *
  162545. * If a multipass operating mode was selected, this will do all but the
  162546. * last pass, and thus may take a great deal of time.
  162547. *
  162548. * Returns FALSE if suspended. The return value need be inspected only if
  162549. * a suspending data source is used.
  162550. */
  162551. GLOBAL(boolean)
  162552. jpeg_start_decompress (j_decompress_ptr cinfo)
  162553. {
  162554. if (cinfo->global_state == DSTATE_READY) {
  162555. /* First call: initialize master control, select active modules */
  162556. jinit_master_decompress(cinfo);
  162557. if (cinfo->buffered_image) {
  162558. /* No more work here; expecting jpeg_start_output next */
  162559. cinfo->global_state = DSTATE_BUFIMAGE;
  162560. return TRUE;
  162561. }
  162562. cinfo->global_state = DSTATE_PRELOAD;
  162563. }
  162564. if (cinfo->global_state == DSTATE_PRELOAD) {
  162565. /* If file has multiple scans, absorb them all into the coef buffer */
  162566. if (cinfo->inputctl->has_multiple_scans) {
  162567. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162568. for (;;) {
  162569. int retcode;
  162570. /* Call progress monitor hook if present */
  162571. if (cinfo->progress != NULL)
  162572. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162573. /* Absorb some more input */
  162574. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162575. if (retcode == JPEG_SUSPENDED)
  162576. return FALSE;
  162577. if (retcode == JPEG_REACHED_EOI)
  162578. break;
  162579. /* Advance progress counter if appropriate */
  162580. if (cinfo->progress != NULL &&
  162581. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  162582. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  162583. /* jdmaster underestimated number of scans; ratchet up one scan */
  162584. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  162585. }
  162586. }
  162587. }
  162588. #else
  162589. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162590. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162591. }
  162592. cinfo->output_scan_number = cinfo->input_scan_number;
  162593. } else if (cinfo->global_state != DSTATE_PRESCAN)
  162594. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162595. /* Perform any dummy output passes, and set up for the final pass */
  162596. return output_pass_setup(cinfo);
  162597. }
  162598. /*
  162599. * Set up for an output pass, and perform any dummy pass(es) needed.
  162600. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  162601. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  162602. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  162603. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  162604. */
  162605. LOCAL(boolean)
  162606. output_pass_setup (j_decompress_ptr cinfo)
  162607. {
  162608. if (cinfo->global_state != DSTATE_PRESCAN) {
  162609. /* First call: do pass setup */
  162610. (*cinfo->master->prepare_for_output_pass) (cinfo);
  162611. cinfo->output_scanline = 0;
  162612. cinfo->global_state = DSTATE_PRESCAN;
  162613. }
  162614. /* Loop over any required dummy passes */
  162615. while (cinfo->master->is_dummy_pass) {
  162616. #ifdef QUANT_2PASS_SUPPORTED
  162617. /* Crank through the dummy pass */
  162618. while (cinfo->output_scanline < cinfo->output_height) {
  162619. JDIMENSION last_scanline;
  162620. /* Call progress monitor hook if present */
  162621. if (cinfo->progress != NULL) {
  162622. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  162623. cinfo->progress->pass_limit = (long) cinfo->output_height;
  162624. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162625. }
  162626. /* Process some data */
  162627. last_scanline = cinfo->output_scanline;
  162628. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  162629. &cinfo->output_scanline, (JDIMENSION) 0);
  162630. if (cinfo->output_scanline == last_scanline)
  162631. return FALSE; /* No progress made, must suspend */
  162632. }
  162633. /* Finish up dummy pass, and set up for another one */
  162634. (*cinfo->master->finish_output_pass) (cinfo);
  162635. (*cinfo->master->prepare_for_output_pass) (cinfo);
  162636. cinfo->output_scanline = 0;
  162637. #else
  162638. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162639. #endif /* QUANT_2PASS_SUPPORTED */
  162640. }
  162641. /* Ready for application to drive output pass through
  162642. * jpeg_read_scanlines or jpeg_read_raw_data.
  162643. */
  162644. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  162645. return TRUE;
  162646. }
  162647. /*
  162648. * Read some scanlines of data from the JPEG decompressor.
  162649. *
  162650. * The return value will be the number of lines actually read.
  162651. * This may be less than the number requested in several cases,
  162652. * including bottom of image, data source suspension, and operating
  162653. * modes that emit multiple scanlines at a time.
  162654. *
  162655. * Note: we warn about excess calls to jpeg_read_scanlines() since
  162656. * this likely signals an application programmer error. However,
  162657. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  162658. */
  162659. GLOBAL(JDIMENSION)
  162660. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  162661. JDIMENSION max_lines)
  162662. {
  162663. JDIMENSION row_ctr;
  162664. if (cinfo->global_state != DSTATE_SCANNING)
  162665. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162666. if (cinfo->output_scanline >= cinfo->output_height) {
  162667. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162668. return 0;
  162669. }
  162670. /* Call progress monitor hook if present */
  162671. if (cinfo->progress != NULL) {
  162672. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  162673. cinfo->progress->pass_limit = (long) cinfo->output_height;
  162674. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162675. }
  162676. /* Process some data */
  162677. row_ctr = 0;
  162678. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  162679. cinfo->output_scanline += row_ctr;
  162680. return row_ctr;
  162681. }
  162682. /*
  162683. * Alternate entry point to read raw data.
  162684. * Processes exactly one iMCU row per call, unless suspended.
  162685. */
  162686. GLOBAL(JDIMENSION)
  162687. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  162688. JDIMENSION max_lines)
  162689. {
  162690. JDIMENSION lines_per_iMCU_row;
  162691. if (cinfo->global_state != DSTATE_RAW_OK)
  162692. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162693. if (cinfo->output_scanline >= cinfo->output_height) {
  162694. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162695. return 0;
  162696. }
  162697. /* Call progress monitor hook if present */
  162698. if (cinfo->progress != NULL) {
  162699. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  162700. cinfo->progress->pass_limit = (long) cinfo->output_height;
  162701. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162702. }
  162703. /* Verify that at least one iMCU row can be returned. */
  162704. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  162705. if (max_lines < lines_per_iMCU_row)
  162706. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162707. /* Decompress directly into user's buffer. */
  162708. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  162709. return 0; /* suspension forced, can do nothing more */
  162710. /* OK, we processed one iMCU row. */
  162711. cinfo->output_scanline += lines_per_iMCU_row;
  162712. return lines_per_iMCU_row;
  162713. }
  162714. /* Additional entry points for buffered-image mode. */
  162715. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162716. /*
  162717. * Initialize for an output pass in buffered-image mode.
  162718. */
  162719. GLOBAL(boolean)
  162720. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  162721. {
  162722. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  162723. cinfo->global_state != DSTATE_PRESCAN)
  162724. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162725. /* Limit scan number to valid range */
  162726. if (scan_number <= 0)
  162727. scan_number = 1;
  162728. if (cinfo->inputctl->eoi_reached &&
  162729. scan_number > cinfo->input_scan_number)
  162730. scan_number = cinfo->input_scan_number;
  162731. cinfo->output_scan_number = scan_number;
  162732. /* Perform any dummy output passes, and set up for the real pass */
  162733. return output_pass_setup(cinfo);
  162734. }
  162735. /*
  162736. * Finish up after an output pass in buffered-image mode.
  162737. *
  162738. * Returns FALSE if suspended. The return value need be inspected only if
  162739. * a suspending data source is used.
  162740. */
  162741. GLOBAL(boolean)
  162742. jpeg_finish_output (j_decompress_ptr cinfo)
  162743. {
  162744. if ((cinfo->global_state == DSTATE_SCANNING ||
  162745. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  162746. /* Terminate this pass. */
  162747. /* We do not require the whole pass to have been completed. */
  162748. (*cinfo->master->finish_output_pass) (cinfo);
  162749. cinfo->global_state = DSTATE_BUFPOST;
  162750. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  162751. /* BUFPOST = repeat call after a suspension, anything else is error */
  162752. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162753. }
  162754. /* Read markers looking for SOS or EOI */
  162755. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  162756. ! cinfo->inputctl->eoi_reached) {
  162757. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  162758. return FALSE; /* Suspend, come back later */
  162759. }
  162760. cinfo->global_state = DSTATE_BUFIMAGE;
  162761. return TRUE;
  162762. }
  162763. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162764. /********* End of inlined file: jdapistd.c *********/
  162765. /********* Start of inlined file: jdapimin.c *********/
  162766. #define JPEG_INTERNALS
  162767. /*
  162768. * Initialization of a JPEG decompression object.
  162769. * The error manager must already be set up (in case memory manager fails).
  162770. */
  162771. GLOBAL(void)
  162772. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  162773. {
  162774. int i;
  162775. /* Guard against version mismatches between library and caller. */
  162776. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  162777. if (version != JPEG_LIB_VERSION)
  162778. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  162779. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  162780. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  162781. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  162782. /* For debugging purposes, we zero the whole master structure.
  162783. * But the application has already set the err pointer, and may have set
  162784. * client_data, so we have to save and restore those fields.
  162785. * Note: if application hasn't set client_data, tools like Purify may
  162786. * complain here.
  162787. */
  162788. {
  162789. struct jpeg_error_mgr * err = cinfo->err;
  162790. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  162791. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  162792. cinfo->err = err;
  162793. cinfo->client_data = client_data;
  162794. }
  162795. cinfo->is_decompressor = TRUE;
  162796. /* Initialize a memory manager instance for this object */
  162797. jinit_memory_mgr((j_common_ptr) cinfo);
  162798. /* Zero out pointers to permanent structures. */
  162799. cinfo->progress = NULL;
  162800. cinfo->src = NULL;
  162801. for (i = 0; i < NUM_QUANT_TBLS; i++)
  162802. cinfo->quant_tbl_ptrs[i] = NULL;
  162803. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162804. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  162805. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  162806. }
  162807. /* Initialize marker processor so application can override methods
  162808. * for COM, APPn markers before calling jpeg_read_header.
  162809. */
  162810. cinfo->marker_list = NULL;
  162811. jinit_marker_reader(cinfo);
  162812. /* And initialize the overall input controller. */
  162813. jinit_input_controller(cinfo);
  162814. /* OK, I'm ready */
  162815. cinfo->global_state = DSTATE_START;
  162816. }
  162817. /*
  162818. * Destruction of a JPEG decompression object
  162819. */
  162820. GLOBAL(void)
  162821. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  162822. {
  162823. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  162824. }
  162825. /*
  162826. * Abort processing of a JPEG decompression operation,
  162827. * but don't destroy the object itself.
  162828. */
  162829. GLOBAL(void)
  162830. jpeg_abort_decompress (j_decompress_ptr cinfo)
  162831. {
  162832. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  162833. }
  162834. /*
  162835. * Set default decompression parameters.
  162836. */
  162837. LOCAL(void)
  162838. default_decompress_parms (j_decompress_ptr cinfo)
  162839. {
  162840. /* Guess the input colorspace, and set output colorspace accordingly. */
  162841. /* (Wish JPEG committee had provided a real way to specify this...) */
  162842. /* Note application may override our guesses. */
  162843. switch (cinfo->num_components) {
  162844. case 1:
  162845. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  162846. cinfo->out_color_space = JCS_GRAYSCALE;
  162847. break;
  162848. case 3:
  162849. if (cinfo->saw_JFIF_marker) {
  162850. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  162851. } else if (cinfo->saw_Adobe_marker) {
  162852. switch (cinfo->Adobe_transform) {
  162853. case 0:
  162854. cinfo->jpeg_color_space = JCS_RGB;
  162855. break;
  162856. case 1:
  162857. cinfo->jpeg_color_space = JCS_YCbCr;
  162858. break;
  162859. default:
  162860. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  162861. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  162862. break;
  162863. }
  162864. } else {
  162865. /* Saw no special markers, try to guess from the component IDs */
  162866. int cid0 = cinfo->comp_info[0].component_id;
  162867. int cid1 = cinfo->comp_info[1].component_id;
  162868. int cid2 = cinfo->comp_info[2].component_id;
  162869. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  162870. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  162871. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  162872. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  162873. else {
  162874. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  162875. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  162876. }
  162877. }
  162878. /* Always guess RGB is proper output colorspace. */
  162879. cinfo->out_color_space = JCS_RGB;
  162880. break;
  162881. case 4:
  162882. if (cinfo->saw_Adobe_marker) {
  162883. switch (cinfo->Adobe_transform) {
  162884. case 0:
  162885. cinfo->jpeg_color_space = JCS_CMYK;
  162886. break;
  162887. case 2:
  162888. cinfo->jpeg_color_space = JCS_YCCK;
  162889. break;
  162890. default:
  162891. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  162892. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  162893. break;
  162894. }
  162895. } else {
  162896. /* No special markers, assume straight CMYK. */
  162897. cinfo->jpeg_color_space = JCS_CMYK;
  162898. }
  162899. cinfo->out_color_space = JCS_CMYK;
  162900. break;
  162901. default:
  162902. cinfo->jpeg_color_space = JCS_UNKNOWN;
  162903. cinfo->out_color_space = JCS_UNKNOWN;
  162904. break;
  162905. }
  162906. /* Set defaults for other decompression parameters. */
  162907. cinfo->scale_num = 1; /* 1:1 scaling */
  162908. cinfo->scale_denom = 1;
  162909. cinfo->output_gamma = 1.0;
  162910. cinfo->buffered_image = FALSE;
  162911. cinfo->raw_data_out = FALSE;
  162912. cinfo->dct_method = JDCT_DEFAULT;
  162913. cinfo->do_fancy_upsampling = TRUE;
  162914. cinfo->do_block_smoothing = TRUE;
  162915. cinfo->quantize_colors = FALSE;
  162916. /* We set these in case application only sets quantize_colors. */
  162917. cinfo->dither_mode = JDITHER_FS;
  162918. #ifdef QUANT_2PASS_SUPPORTED
  162919. cinfo->two_pass_quantize = TRUE;
  162920. #else
  162921. cinfo->two_pass_quantize = FALSE;
  162922. #endif
  162923. cinfo->desired_number_of_colors = 256;
  162924. cinfo->colormap = NULL;
  162925. /* Initialize for no mode change in buffered-image mode. */
  162926. cinfo->enable_1pass_quant = FALSE;
  162927. cinfo->enable_external_quant = FALSE;
  162928. cinfo->enable_2pass_quant = FALSE;
  162929. }
  162930. /*
  162931. * Decompression startup: read start of JPEG datastream to see what's there.
  162932. * Need only initialize JPEG object and supply a data source before calling.
  162933. *
  162934. * This routine will read as far as the first SOS marker (ie, actual start of
  162935. * compressed data), and will save all tables and parameters in the JPEG
  162936. * object. It will also initialize the decompression parameters to default
  162937. * values, and finally return JPEG_HEADER_OK. On return, the application may
  162938. * adjust the decompression parameters and then call jpeg_start_decompress.
  162939. * (Or, if the application only wanted to determine the image parameters,
  162940. * the data need not be decompressed. In that case, call jpeg_abort or
  162941. * jpeg_destroy to release any temporary space.)
  162942. * If an abbreviated (tables only) datastream is presented, the routine will
  162943. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  162944. * re-use the JPEG object to read the abbreviated image datastream(s).
  162945. * It is unnecessary (but OK) to call jpeg_abort in this case.
  162946. * The JPEG_SUSPENDED return code only occurs if the data source module
  162947. * requests suspension of the decompressor. In this case the application
  162948. * should load more source data and then re-call jpeg_read_header to resume
  162949. * processing.
  162950. * If a non-suspending data source is used and require_image is TRUE, then the
  162951. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  162952. *
  162953. * This routine is now just a front end to jpeg_consume_input, with some
  162954. * extra error checking.
  162955. */
  162956. GLOBAL(int)
  162957. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  162958. {
  162959. int retcode;
  162960. if (cinfo->global_state != DSTATE_START &&
  162961. cinfo->global_state != DSTATE_INHEADER)
  162962. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162963. retcode = jpeg_consume_input(cinfo);
  162964. switch (retcode) {
  162965. case JPEG_REACHED_SOS:
  162966. retcode = JPEG_HEADER_OK;
  162967. break;
  162968. case JPEG_REACHED_EOI:
  162969. if (require_image) /* Complain if application wanted an image */
  162970. ERREXIT(cinfo, JERR_NO_IMAGE);
  162971. /* Reset to start state; it would be safer to require the application to
  162972. * call jpeg_abort, but we can't change it now for compatibility reasons.
  162973. * A side effect is to free any temporary memory (there shouldn't be any).
  162974. */
  162975. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  162976. retcode = JPEG_HEADER_TABLES_ONLY;
  162977. break;
  162978. case JPEG_SUSPENDED:
  162979. /* no work */
  162980. break;
  162981. }
  162982. return retcode;
  162983. }
  162984. /*
  162985. * Consume data in advance of what the decompressor requires.
  162986. * This can be called at any time once the decompressor object has
  162987. * been created and a data source has been set up.
  162988. *
  162989. * This routine is essentially a state machine that handles a couple
  162990. * of critical state-transition actions, namely initial setup and
  162991. * transition from header scanning to ready-for-start_decompress.
  162992. * All the actual input is done via the input controller's consume_input
  162993. * method.
  162994. */
  162995. GLOBAL(int)
  162996. jpeg_consume_input (j_decompress_ptr cinfo)
  162997. {
  162998. int retcode = JPEG_SUSPENDED;
  162999. /* NB: every possible DSTATE value should be listed in this switch */
  163000. switch (cinfo->global_state) {
  163001. case DSTATE_START:
  163002. /* Start-of-datastream actions: reset appropriate modules */
  163003. (*cinfo->inputctl->reset_input_controller) (cinfo);
  163004. /* Initialize application's data source module */
  163005. (*cinfo->src->init_source) (cinfo);
  163006. cinfo->global_state = DSTATE_INHEADER;
  163007. /*FALLTHROUGH*/
  163008. case DSTATE_INHEADER:
  163009. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163010. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  163011. /* Set up default parameters based on header data */
  163012. default_decompress_parms(cinfo);
  163013. /* Set global state: ready for start_decompress */
  163014. cinfo->global_state = DSTATE_READY;
  163015. }
  163016. break;
  163017. case DSTATE_READY:
  163018. /* Can't advance past first SOS until start_decompress is called */
  163019. retcode = JPEG_REACHED_SOS;
  163020. break;
  163021. case DSTATE_PRELOAD:
  163022. case DSTATE_PRESCAN:
  163023. case DSTATE_SCANNING:
  163024. case DSTATE_RAW_OK:
  163025. case DSTATE_BUFIMAGE:
  163026. case DSTATE_BUFPOST:
  163027. case DSTATE_STOPPING:
  163028. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163029. break;
  163030. default:
  163031. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163032. }
  163033. return retcode;
  163034. }
  163035. /*
  163036. * Have we finished reading the input file?
  163037. */
  163038. GLOBAL(boolean)
  163039. jpeg_input_complete (j_decompress_ptr cinfo)
  163040. {
  163041. /* Check for valid jpeg object */
  163042. if (cinfo->global_state < DSTATE_START ||
  163043. cinfo->global_state > DSTATE_STOPPING)
  163044. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163045. return cinfo->inputctl->eoi_reached;
  163046. }
  163047. /*
  163048. * Is there more than one scan?
  163049. */
  163050. GLOBAL(boolean)
  163051. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  163052. {
  163053. /* Only valid after jpeg_read_header completes */
  163054. if (cinfo->global_state < DSTATE_READY ||
  163055. cinfo->global_state > DSTATE_STOPPING)
  163056. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163057. return cinfo->inputctl->has_multiple_scans;
  163058. }
  163059. /*
  163060. * Finish JPEG decompression.
  163061. *
  163062. * This will normally just verify the file trailer and release temp storage.
  163063. *
  163064. * Returns FALSE if suspended. The return value need be inspected only if
  163065. * a suspending data source is used.
  163066. */
  163067. GLOBAL(boolean)
  163068. jpeg_finish_decompress (j_decompress_ptr cinfo)
  163069. {
  163070. if ((cinfo->global_state == DSTATE_SCANNING ||
  163071. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  163072. /* Terminate final pass of non-buffered mode */
  163073. if (cinfo->output_scanline < cinfo->output_height)
  163074. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  163075. (*cinfo->master->finish_output_pass) (cinfo);
  163076. cinfo->global_state = DSTATE_STOPPING;
  163077. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  163078. /* Finishing after a buffered-image operation */
  163079. cinfo->global_state = DSTATE_STOPPING;
  163080. } else if (cinfo->global_state != DSTATE_STOPPING) {
  163081. /* STOPPING = repeat call after a suspension, anything else is error */
  163082. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163083. }
  163084. /* Read until EOI */
  163085. while (! cinfo->inputctl->eoi_reached) {
  163086. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163087. return FALSE; /* Suspend, come back later */
  163088. }
  163089. /* Do final cleanup */
  163090. (*cinfo->src->term_source) (cinfo);
  163091. /* We can use jpeg_abort to release memory and reset global_state */
  163092. jpeg_abort((j_common_ptr) cinfo);
  163093. return TRUE;
  163094. }
  163095. /********* End of inlined file: jdapimin.c *********/
  163096. /********* Start of inlined file: jdatasrc.c *********/
  163097. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  163098. /********* Start of inlined file: jerror.h *********/
  163099. /*
  163100. * To define the enum list of message codes, include this file without
  163101. * defining macro JMESSAGE. To create a message string table, include it
  163102. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  163103. */
  163104. #ifndef JMESSAGE
  163105. #ifndef JERROR_H
  163106. /* First time through, define the enum list */
  163107. #define JMAKE_ENUM_LIST
  163108. #else
  163109. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  163110. #define JMESSAGE(code,string)
  163111. #endif /* JERROR_H */
  163112. #endif /* JMESSAGE */
  163113. #ifdef JMAKE_ENUM_LIST
  163114. typedef enum {
  163115. #define JMESSAGE(code,string) code ,
  163116. #endif /* JMAKE_ENUM_LIST */
  163117. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  163118. /* For maintenance convenience, list is alphabetical by message code name */
  163119. JMESSAGE(JERR_ARITH_NOTIMPL,
  163120. "Sorry, there are legal restrictions on arithmetic coding")
  163121. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  163122. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  163123. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  163124. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  163125. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  163126. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  163127. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  163128. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  163129. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  163130. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  163131. JMESSAGE(JERR_BAD_LIB_VERSION,
  163132. "Wrong JPEG library version: library is %d, caller expects %d")
  163133. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  163134. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  163135. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  163136. JMESSAGE(JERR_BAD_PROGRESSION,
  163137. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  163138. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  163139. "Invalid progressive parameters at scan script entry %d")
  163140. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  163141. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  163142. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  163143. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  163144. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  163145. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  163146. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  163147. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  163148. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  163149. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  163150. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  163151. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  163152. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  163153. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  163154. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  163155. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  163156. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  163157. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  163158. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  163159. JMESSAGE(JERR_FILE_READ, "Input file read error")
  163160. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  163161. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  163162. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  163163. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  163164. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  163165. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  163166. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  163167. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  163168. "Cannot transcode due to multiple use of quantization table %d")
  163169. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  163170. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  163171. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  163172. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  163173. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  163174. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  163175. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  163176. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  163177. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  163178. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  163179. JMESSAGE(JERR_QUANT_COMPONENTS,
  163180. "Cannot quantize more than %d color components")
  163181. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  163182. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  163183. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  163184. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  163185. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  163186. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  163187. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  163188. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  163189. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  163190. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  163191. JMESSAGE(JERR_TFILE_WRITE,
  163192. "Write failed on temporary file --- out of disk space?")
  163193. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  163194. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  163195. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  163196. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  163197. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  163198. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  163199. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  163200. JMESSAGE(JMSG_VERSION, JVERSION)
  163201. JMESSAGE(JTRC_16BIT_TABLES,
  163202. "Caution: quantization tables are too coarse for baseline JPEG")
  163203. JMESSAGE(JTRC_ADOBE,
  163204. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  163205. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  163206. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  163207. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  163208. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  163209. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  163210. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  163211. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  163212. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  163213. JMESSAGE(JTRC_EOI, "End Of Image")
  163214. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  163215. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  163216. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  163217. "Warning: thumbnail image size does not match data length %u")
  163218. JMESSAGE(JTRC_JFIF_EXTENSION,
  163219. "JFIF extension marker: type 0x%02x, length %u")
  163220. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  163221. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  163222. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  163223. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  163224. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  163225. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  163226. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  163227. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  163228. JMESSAGE(JTRC_RST, "RST%d")
  163229. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  163230. "Smoothing not supported with nonstandard sampling ratios")
  163231. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  163232. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  163233. JMESSAGE(JTRC_SOI, "Start of Image")
  163234. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  163235. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  163236. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  163237. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  163238. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  163239. JMESSAGE(JTRC_THUMB_JPEG,
  163240. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  163241. JMESSAGE(JTRC_THUMB_PALETTE,
  163242. "JFIF extension marker: palette thumbnail image, length %u")
  163243. JMESSAGE(JTRC_THUMB_RGB,
  163244. "JFIF extension marker: RGB thumbnail image, length %u")
  163245. JMESSAGE(JTRC_UNKNOWN_IDS,
  163246. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  163247. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  163248. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  163249. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  163250. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  163251. "Inconsistent progression sequence for component %d coefficient %d")
  163252. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  163253. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  163254. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  163255. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  163256. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  163257. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  163258. JMESSAGE(JWRN_MUST_RESYNC,
  163259. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  163260. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  163261. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  163262. #ifdef JMAKE_ENUM_LIST
  163263. JMSG_LASTMSGCODE
  163264. } J_MESSAGE_CODE;
  163265. #undef JMAKE_ENUM_LIST
  163266. #endif /* JMAKE_ENUM_LIST */
  163267. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  163268. #undef JMESSAGE
  163269. #ifndef JERROR_H
  163270. #define JERROR_H
  163271. /* Macros to simplify using the error and trace message stuff */
  163272. /* The first parameter is either type of cinfo pointer */
  163273. /* Fatal errors (print message and exit) */
  163274. #define ERREXIT(cinfo,code) \
  163275. ((cinfo)->err->msg_code = (code), \
  163276. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163277. #define ERREXIT1(cinfo,code,p1) \
  163278. ((cinfo)->err->msg_code = (code), \
  163279. (cinfo)->err->msg_parm.i[0] = (p1), \
  163280. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163281. #define ERREXIT2(cinfo,code,p1,p2) \
  163282. ((cinfo)->err->msg_code = (code), \
  163283. (cinfo)->err->msg_parm.i[0] = (p1), \
  163284. (cinfo)->err->msg_parm.i[1] = (p2), \
  163285. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163286. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  163287. ((cinfo)->err->msg_code = (code), \
  163288. (cinfo)->err->msg_parm.i[0] = (p1), \
  163289. (cinfo)->err->msg_parm.i[1] = (p2), \
  163290. (cinfo)->err->msg_parm.i[2] = (p3), \
  163291. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163292. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  163293. ((cinfo)->err->msg_code = (code), \
  163294. (cinfo)->err->msg_parm.i[0] = (p1), \
  163295. (cinfo)->err->msg_parm.i[1] = (p2), \
  163296. (cinfo)->err->msg_parm.i[2] = (p3), \
  163297. (cinfo)->err->msg_parm.i[3] = (p4), \
  163298. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163299. #define ERREXITS(cinfo,code,str) \
  163300. ((cinfo)->err->msg_code = (code), \
  163301. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163302. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163303. #define MAKESTMT(stuff) do { stuff } while (0)
  163304. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  163305. #define WARNMS(cinfo,code) \
  163306. ((cinfo)->err->msg_code = (code), \
  163307. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163308. #define WARNMS1(cinfo,code,p1) \
  163309. ((cinfo)->err->msg_code = (code), \
  163310. (cinfo)->err->msg_parm.i[0] = (p1), \
  163311. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163312. #define WARNMS2(cinfo,code,p1,p2) \
  163313. ((cinfo)->err->msg_code = (code), \
  163314. (cinfo)->err->msg_parm.i[0] = (p1), \
  163315. (cinfo)->err->msg_parm.i[1] = (p2), \
  163316. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163317. /* Informational/debugging messages */
  163318. #define TRACEMS(cinfo,lvl,code) \
  163319. ((cinfo)->err->msg_code = (code), \
  163320. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163321. #define TRACEMS1(cinfo,lvl,code,p1) \
  163322. ((cinfo)->err->msg_code = (code), \
  163323. (cinfo)->err->msg_parm.i[0] = (p1), \
  163324. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163325. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  163326. ((cinfo)->err->msg_code = (code), \
  163327. (cinfo)->err->msg_parm.i[0] = (p1), \
  163328. (cinfo)->err->msg_parm.i[1] = (p2), \
  163329. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163330. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  163331. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163332. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  163333. (cinfo)->err->msg_code = (code); \
  163334. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163335. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  163336. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163337. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163338. (cinfo)->err->msg_code = (code); \
  163339. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163340. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  163341. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163342. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163343. _mp[4] = (p5); \
  163344. (cinfo)->err->msg_code = (code); \
  163345. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163346. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  163347. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163348. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163349. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  163350. (cinfo)->err->msg_code = (code); \
  163351. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163352. #define TRACEMSS(cinfo,lvl,code,str) \
  163353. ((cinfo)->err->msg_code = (code), \
  163354. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163355. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163356. #endif /* JERROR_H */
  163357. /********* End of inlined file: jerror.h *********/
  163358. /* Expanded data source object for stdio input */
  163359. typedef struct {
  163360. struct jpeg_source_mgr pub; /* public fields */
  163361. FILE * infile; /* source stream */
  163362. JOCTET * buffer; /* start of buffer */
  163363. boolean start_of_file; /* have we gotten any data yet? */
  163364. } my_source_mgr;
  163365. typedef my_source_mgr * my_src_ptr;
  163366. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  163367. /*
  163368. * Initialize source --- called by jpeg_read_header
  163369. * before any data is actually read.
  163370. */
  163371. METHODDEF(void)
  163372. init_source (j_decompress_ptr cinfo)
  163373. {
  163374. my_src_ptr src = (my_src_ptr) cinfo->src;
  163375. /* We reset the empty-input-file flag for each image,
  163376. * but we don't clear the input buffer.
  163377. * This is correct behavior for reading a series of images from one source.
  163378. */
  163379. src->start_of_file = TRUE;
  163380. }
  163381. /*
  163382. * Fill the input buffer --- called whenever buffer is emptied.
  163383. *
  163384. * In typical applications, this should read fresh data into the buffer
  163385. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  163386. * reset the pointer & count to the start of the buffer, and return TRUE
  163387. * indicating that the buffer has been reloaded. It is not necessary to
  163388. * fill the buffer entirely, only to obtain at least one more byte.
  163389. *
  163390. * There is no such thing as an EOF return. If the end of the file has been
  163391. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  163392. * the buffer. In most cases, generating a warning message and inserting a
  163393. * fake EOI marker is the best course of action --- this will allow the
  163394. * decompressor to output however much of the image is there. However,
  163395. * the resulting error message is misleading if the real problem is an empty
  163396. * input file, so we handle that case specially.
  163397. *
  163398. * In applications that need to be able to suspend compression due to input
  163399. * not being available yet, a FALSE return indicates that no more data can be
  163400. * obtained right now, but more may be forthcoming later. In this situation,
  163401. * the decompressor will return to its caller (with an indication of the
  163402. * number of scanlines it has read, if any). The application should resume
  163403. * decompression after it has loaded more data into the input buffer. Note
  163404. * that there are substantial restrictions on the use of suspension --- see
  163405. * the documentation.
  163406. *
  163407. * When suspending, the decompressor will back up to a convenient restart point
  163408. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  163409. * indicate where the restart point will be if the current call returns FALSE.
  163410. * Data beyond this point must be rescanned after resumption, so move it to
  163411. * the front of the buffer rather than discarding it.
  163412. */
  163413. METHODDEF(boolean)
  163414. fill_input_buffer (j_decompress_ptr cinfo)
  163415. {
  163416. my_src_ptr src = (my_src_ptr) cinfo->src;
  163417. size_t nbytes;
  163418. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  163419. if (nbytes <= 0) {
  163420. if (src->start_of_file) /* Treat empty input file as fatal error */
  163421. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  163422. WARNMS(cinfo, JWRN_JPEG_EOF);
  163423. /* Insert a fake EOI marker */
  163424. src->buffer[0] = (JOCTET) 0xFF;
  163425. src->buffer[1] = (JOCTET) JPEG_EOI;
  163426. nbytes = 2;
  163427. }
  163428. src->pub.next_input_byte = src->buffer;
  163429. src->pub.bytes_in_buffer = nbytes;
  163430. src->start_of_file = FALSE;
  163431. return TRUE;
  163432. }
  163433. /*
  163434. * Skip data --- used to skip over a potentially large amount of
  163435. * uninteresting data (such as an APPn marker).
  163436. *
  163437. * Writers of suspendable-input applications must note that skip_input_data
  163438. * is not granted the right to give a suspension return. If the skip extends
  163439. * beyond the data currently in the buffer, the buffer can be marked empty so
  163440. * that the next read will cause a fill_input_buffer call that can suspend.
  163441. * Arranging for additional bytes to be discarded before reloading the input
  163442. * buffer is the application writer's problem.
  163443. */
  163444. METHODDEF(void)
  163445. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  163446. {
  163447. my_src_ptr src = (my_src_ptr) cinfo->src;
  163448. /* Just a dumb implementation for now. Could use fseek() except
  163449. * it doesn't work on pipes. Not clear that being smart is worth
  163450. * any trouble anyway --- large skips are infrequent.
  163451. */
  163452. if (num_bytes > 0) {
  163453. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  163454. num_bytes -= (long) src->pub.bytes_in_buffer;
  163455. (void) fill_input_buffer(cinfo);
  163456. /* note we assume that fill_input_buffer will never return FALSE,
  163457. * so suspension need not be handled.
  163458. */
  163459. }
  163460. src->pub.next_input_byte += (size_t) num_bytes;
  163461. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  163462. }
  163463. }
  163464. /*
  163465. * An additional method that can be provided by data source modules is the
  163466. * resync_to_restart method for error recovery in the presence of RST markers.
  163467. * For the moment, this source module just uses the default resync method
  163468. * provided by the JPEG library. That method assumes that no backtracking
  163469. * is possible.
  163470. */
  163471. /*
  163472. * Terminate source --- called by jpeg_finish_decompress
  163473. * after all data has been read. Often a no-op.
  163474. *
  163475. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  163476. * application must deal with any cleanup that should happen even
  163477. * for error exit.
  163478. */
  163479. METHODDEF(void)
  163480. term_source (j_decompress_ptr cinfo)
  163481. {
  163482. /* no work necessary here */
  163483. }
  163484. /*
  163485. * Prepare for input from a stdio stream.
  163486. * The caller must have already opened the stream, and is responsible
  163487. * for closing it after finishing decompression.
  163488. */
  163489. GLOBAL(void)
  163490. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  163491. {
  163492. my_src_ptr src;
  163493. /* The source object and input buffer are made permanent so that a series
  163494. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  163495. * only before the first one. (If we discarded the buffer at the end of
  163496. * one image, we'd likely lose the start of the next one.)
  163497. * This makes it unsafe to use this manager and a different source
  163498. * manager serially with the same JPEG object. Caveat programmer.
  163499. */
  163500. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  163501. cinfo->src = (struct jpeg_source_mgr *)
  163502. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  163503. SIZEOF(my_source_mgr));
  163504. src = (my_src_ptr) cinfo->src;
  163505. src->buffer = (JOCTET *)
  163506. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  163507. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  163508. }
  163509. src = (my_src_ptr) cinfo->src;
  163510. src->pub.init_source = init_source;
  163511. src->pub.fill_input_buffer = fill_input_buffer;
  163512. src->pub.skip_input_data = skip_input_data;
  163513. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  163514. src->pub.term_source = term_source;
  163515. src->infile = infile;
  163516. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  163517. src->pub.next_input_byte = NULL; /* until buffer loaded */
  163518. }
  163519. /********* End of inlined file: jdatasrc.c *********/
  163520. /********* Start of inlined file: jdcoefct.c *********/
  163521. #define JPEG_INTERNALS
  163522. /* Block smoothing is only applicable for progressive JPEG, so: */
  163523. #ifndef D_PROGRESSIVE_SUPPORTED
  163524. #undef BLOCK_SMOOTHING_SUPPORTED
  163525. #endif
  163526. /* Private buffer controller object */
  163527. typedef struct {
  163528. struct jpeg_d_coef_controller pub; /* public fields */
  163529. /* These variables keep track of the current location of the input side. */
  163530. /* cinfo->input_iMCU_row is also used for this. */
  163531. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  163532. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  163533. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  163534. /* The output side's location is represented by cinfo->output_iMCU_row. */
  163535. /* In single-pass modes, it's sufficient to buffer just one MCU.
  163536. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  163537. * and let the entropy decoder write into that workspace each time.
  163538. * (On 80x86, the workspace is FAR even though it's not really very big;
  163539. * this is to keep the module interfaces unchanged when a large coefficient
  163540. * buffer is necessary.)
  163541. * In multi-pass modes, this array points to the current MCU's blocks
  163542. * within the virtual arrays; it is used only by the input side.
  163543. */
  163544. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  163545. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163546. /* In multi-pass modes, we need a virtual block array for each component. */
  163547. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  163548. #endif
  163549. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163550. /* When doing block smoothing, we latch coefficient Al values here */
  163551. int * coef_bits_latch;
  163552. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  163553. #endif
  163554. } my_coef_controller3;
  163555. typedef my_coef_controller3 * my_coef_ptr3;
  163556. /* Forward declarations */
  163557. METHODDEF(int) decompress_onepass
  163558. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  163559. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163560. METHODDEF(int) decompress_data
  163561. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  163562. #endif
  163563. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163564. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  163565. METHODDEF(int) decompress_smooth_data
  163566. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  163567. #endif
  163568. LOCAL(void)
  163569. start_iMCU_row3 (j_decompress_ptr cinfo)
  163570. /* Reset within-iMCU-row counters for a new row (input side) */
  163571. {
  163572. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163573. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  163574. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  163575. * But at the bottom of the image, process only what's left.
  163576. */
  163577. if (cinfo->comps_in_scan > 1) {
  163578. coef->MCU_rows_per_iMCU_row = 1;
  163579. } else {
  163580. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  163581. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  163582. else
  163583. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  163584. }
  163585. coef->MCU_ctr = 0;
  163586. coef->MCU_vert_offset = 0;
  163587. }
  163588. /*
  163589. * Initialize for an input processing pass.
  163590. */
  163591. METHODDEF(void)
  163592. start_input_pass (j_decompress_ptr cinfo)
  163593. {
  163594. cinfo->input_iMCU_row = 0;
  163595. start_iMCU_row3(cinfo);
  163596. }
  163597. /*
  163598. * Initialize for an output processing pass.
  163599. */
  163600. METHODDEF(void)
  163601. start_output_pass (j_decompress_ptr cinfo)
  163602. {
  163603. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163604. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163605. /* If multipass, check to see whether to use block smoothing on this pass */
  163606. if (coef->pub.coef_arrays != NULL) {
  163607. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  163608. coef->pub.decompress_data = decompress_smooth_data;
  163609. else
  163610. coef->pub.decompress_data = decompress_data;
  163611. }
  163612. #endif
  163613. cinfo->output_iMCU_row = 0;
  163614. }
  163615. /*
  163616. * Decompress and return some data in the single-pass case.
  163617. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  163618. * Input and output must run in lockstep since we have only a one-MCU buffer.
  163619. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  163620. *
  163621. * NB: output_buf contains a plane for each component in image,
  163622. * which we index according to the component's SOF position.
  163623. */
  163624. METHODDEF(int)
  163625. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  163626. {
  163627. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163628. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163629. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  163630. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163631. int blkn, ci, xindex, yindex, yoffset, useful_width;
  163632. JSAMPARRAY output_ptr;
  163633. JDIMENSION start_col, output_col;
  163634. jpeg_component_info *compptr;
  163635. inverse_DCT_method_ptr inverse_DCT;
  163636. /* Loop to process as much as one whole iMCU row */
  163637. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163638. yoffset++) {
  163639. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  163640. MCU_col_num++) {
  163641. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  163642. jzero_far((void FAR *) coef->MCU_buffer[0],
  163643. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  163644. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  163645. /* Suspension forced; update state counters and exit */
  163646. coef->MCU_vert_offset = yoffset;
  163647. coef->MCU_ctr = MCU_col_num;
  163648. return JPEG_SUSPENDED;
  163649. }
  163650. /* Determine where data should go in output_buf and do the IDCT thing.
  163651. * We skip dummy blocks at the right and bottom edges (but blkn gets
  163652. * incremented past them!). Note the inner loop relies on having
  163653. * allocated the MCU_buffer[] blocks sequentially.
  163654. */
  163655. blkn = 0; /* index of current DCT block within MCU */
  163656. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163657. compptr = cinfo->cur_comp_info[ci];
  163658. /* Don't bother to IDCT an uninteresting component. */
  163659. if (! compptr->component_needed) {
  163660. blkn += compptr->MCU_blocks;
  163661. continue;
  163662. }
  163663. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  163664. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  163665. : compptr->last_col_width;
  163666. output_ptr = output_buf[compptr->component_index] +
  163667. yoffset * compptr->DCT_scaled_size;
  163668. start_col = MCU_col_num * compptr->MCU_sample_width;
  163669. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163670. if (cinfo->input_iMCU_row < last_iMCU_row ||
  163671. yoffset+yindex < compptr->last_row_height) {
  163672. output_col = start_col;
  163673. for (xindex = 0; xindex < useful_width; xindex++) {
  163674. (*inverse_DCT) (cinfo, compptr,
  163675. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  163676. output_ptr, output_col);
  163677. output_col += compptr->DCT_scaled_size;
  163678. }
  163679. }
  163680. blkn += compptr->MCU_width;
  163681. output_ptr += compptr->DCT_scaled_size;
  163682. }
  163683. }
  163684. }
  163685. /* Completed an MCU row, but perhaps not an iMCU row */
  163686. coef->MCU_ctr = 0;
  163687. }
  163688. /* Completed the iMCU row, advance counters for next one */
  163689. cinfo->output_iMCU_row++;
  163690. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  163691. start_iMCU_row3(cinfo);
  163692. return JPEG_ROW_COMPLETED;
  163693. }
  163694. /* Completed the scan */
  163695. (*cinfo->inputctl->finish_input_pass) (cinfo);
  163696. return JPEG_SCAN_COMPLETED;
  163697. }
  163698. /*
  163699. * Dummy consume-input routine for single-pass operation.
  163700. */
  163701. METHODDEF(int)
  163702. dummy_consume_data (j_decompress_ptr cinfo)
  163703. {
  163704. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  163705. }
  163706. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163707. /*
  163708. * Consume input data and store it in the full-image coefficient buffer.
  163709. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  163710. * ie, v_samp_factor block rows for each component in the scan.
  163711. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  163712. */
  163713. METHODDEF(int)
  163714. consume_data (j_decompress_ptr cinfo)
  163715. {
  163716. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163717. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163718. int blkn, ci, xindex, yindex, yoffset;
  163719. JDIMENSION start_col;
  163720. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  163721. JBLOCKROW buffer_ptr;
  163722. jpeg_component_info *compptr;
  163723. /* Align the virtual buffers for the components used in this scan. */
  163724. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163725. compptr = cinfo->cur_comp_info[ci];
  163726. buffer[ci] = (*cinfo->mem->access_virt_barray)
  163727. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  163728. cinfo->input_iMCU_row * compptr->v_samp_factor,
  163729. (JDIMENSION) compptr->v_samp_factor, TRUE);
  163730. /* Note: entropy decoder expects buffer to be zeroed,
  163731. * but this is handled automatically by the memory manager
  163732. * because we requested a pre-zeroed array.
  163733. */
  163734. }
  163735. /* Loop to process one whole iMCU row */
  163736. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163737. yoffset++) {
  163738. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  163739. MCU_col_num++) {
  163740. /* Construct list of pointers to DCT blocks belonging to this MCU */
  163741. blkn = 0; /* index of current DCT block within MCU */
  163742. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163743. compptr = cinfo->cur_comp_info[ci];
  163744. start_col = MCU_col_num * compptr->MCU_width;
  163745. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163746. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  163747. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  163748. coef->MCU_buffer[blkn++] = buffer_ptr++;
  163749. }
  163750. }
  163751. }
  163752. /* Try to fetch the MCU. */
  163753. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  163754. /* Suspension forced; update state counters and exit */
  163755. coef->MCU_vert_offset = yoffset;
  163756. coef->MCU_ctr = MCU_col_num;
  163757. return JPEG_SUSPENDED;
  163758. }
  163759. }
  163760. /* Completed an MCU row, but perhaps not an iMCU row */
  163761. coef->MCU_ctr = 0;
  163762. }
  163763. /* Completed the iMCU row, advance counters for next one */
  163764. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  163765. start_iMCU_row3(cinfo);
  163766. return JPEG_ROW_COMPLETED;
  163767. }
  163768. /* Completed the scan */
  163769. (*cinfo->inputctl->finish_input_pass) (cinfo);
  163770. return JPEG_SCAN_COMPLETED;
  163771. }
  163772. /*
  163773. * Decompress and return some data in the multi-pass case.
  163774. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  163775. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  163776. *
  163777. * NB: output_buf contains a plane for each component in image.
  163778. */
  163779. METHODDEF(int)
  163780. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  163781. {
  163782. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163783. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163784. JDIMENSION block_num;
  163785. int ci, block_row, block_rows;
  163786. JBLOCKARRAY buffer;
  163787. JBLOCKROW buffer_ptr;
  163788. JSAMPARRAY output_ptr;
  163789. JDIMENSION output_col;
  163790. jpeg_component_info *compptr;
  163791. inverse_DCT_method_ptr inverse_DCT;
  163792. /* Force some input to be done if we are getting ahead of the input. */
  163793. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  163794. (cinfo->input_scan_number == cinfo->output_scan_number &&
  163795. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  163796. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  163797. return JPEG_SUSPENDED;
  163798. }
  163799. /* OK, output from the virtual arrays. */
  163800. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163801. ci++, compptr++) {
  163802. /* Don't bother to IDCT an uninteresting component. */
  163803. if (! compptr->component_needed)
  163804. continue;
  163805. /* Align the virtual buffer for this component. */
  163806. buffer = (*cinfo->mem->access_virt_barray)
  163807. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163808. cinfo->output_iMCU_row * compptr->v_samp_factor,
  163809. (JDIMENSION) compptr->v_samp_factor, FALSE);
  163810. /* Count non-dummy DCT block rows in this iMCU row. */
  163811. if (cinfo->output_iMCU_row < last_iMCU_row)
  163812. block_rows = compptr->v_samp_factor;
  163813. else {
  163814. /* NB: can't use last_row_height here; it is input-side-dependent! */
  163815. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163816. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  163817. }
  163818. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  163819. output_ptr = output_buf[ci];
  163820. /* Loop over all DCT blocks to be processed. */
  163821. for (block_row = 0; block_row < block_rows; block_row++) {
  163822. buffer_ptr = buffer[block_row];
  163823. output_col = 0;
  163824. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  163825. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  163826. output_ptr, output_col);
  163827. buffer_ptr++;
  163828. output_col += compptr->DCT_scaled_size;
  163829. }
  163830. output_ptr += compptr->DCT_scaled_size;
  163831. }
  163832. }
  163833. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  163834. return JPEG_ROW_COMPLETED;
  163835. return JPEG_SCAN_COMPLETED;
  163836. }
  163837. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163838. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163839. /*
  163840. * This code applies interblock smoothing as described by section K.8
  163841. * of the JPEG standard: the first 5 AC coefficients are estimated from
  163842. * the DC values of a DCT block and its 8 neighboring blocks.
  163843. * We apply smoothing only for progressive JPEG decoding, and only if
  163844. * the coefficients it can estimate are not yet known to full precision.
  163845. */
  163846. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  163847. #define Q01_POS 1
  163848. #define Q10_POS 8
  163849. #define Q20_POS 16
  163850. #define Q11_POS 9
  163851. #define Q02_POS 2
  163852. /*
  163853. * Determine whether block smoothing is applicable and safe.
  163854. * We also latch the current states of the coef_bits[] entries for the
  163855. * AC coefficients; otherwise, if the input side of the decompressor
  163856. * advances into a new scan, we might think the coefficients are known
  163857. * more accurately than they really are.
  163858. */
  163859. LOCAL(boolean)
  163860. smoothing_ok (j_decompress_ptr cinfo)
  163861. {
  163862. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163863. boolean smoothing_useful = FALSE;
  163864. int ci, coefi;
  163865. jpeg_component_info *compptr;
  163866. JQUANT_TBL * qtable;
  163867. int * coef_bits;
  163868. int * coef_bits_latch;
  163869. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  163870. return FALSE;
  163871. /* Allocate latch area if not already done */
  163872. if (coef->coef_bits_latch == NULL)
  163873. coef->coef_bits_latch = (int *)
  163874. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163875. cinfo->num_components *
  163876. (SAVED_COEFS * SIZEOF(int)));
  163877. coef_bits_latch = coef->coef_bits_latch;
  163878. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163879. ci++, compptr++) {
  163880. /* All components' quantization values must already be latched. */
  163881. if ((qtable = compptr->quant_table) == NULL)
  163882. return FALSE;
  163883. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  163884. if (qtable->quantval[0] == 0 ||
  163885. qtable->quantval[Q01_POS] == 0 ||
  163886. qtable->quantval[Q10_POS] == 0 ||
  163887. qtable->quantval[Q20_POS] == 0 ||
  163888. qtable->quantval[Q11_POS] == 0 ||
  163889. qtable->quantval[Q02_POS] == 0)
  163890. return FALSE;
  163891. /* DC values must be at least partly known for all components. */
  163892. coef_bits = cinfo->coef_bits[ci];
  163893. if (coef_bits[0] < 0)
  163894. return FALSE;
  163895. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  163896. for (coefi = 1; coefi <= 5; coefi++) {
  163897. coef_bits_latch[coefi] = coef_bits[coefi];
  163898. if (coef_bits[coefi] != 0)
  163899. smoothing_useful = TRUE;
  163900. }
  163901. coef_bits_latch += SAVED_COEFS;
  163902. }
  163903. return smoothing_useful;
  163904. }
  163905. /*
  163906. * Variant of decompress_data for use when doing block smoothing.
  163907. */
  163908. METHODDEF(int)
  163909. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  163910. {
  163911. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163912. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163913. JDIMENSION block_num, last_block_column;
  163914. int ci, block_row, block_rows, access_rows;
  163915. JBLOCKARRAY buffer;
  163916. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  163917. JSAMPARRAY output_ptr;
  163918. JDIMENSION output_col;
  163919. jpeg_component_info *compptr;
  163920. inverse_DCT_method_ptr inverse_DCT;
  163921. boolean first_row, last_row;
  163922. JBLOCK workspace;
  163923. int *coef_bits;
  163924. JQUANT_TBL *quanttbl;
  163925. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  163926. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  163927. int Al, pred;
  163928. /* Force some input to be done if we are getting ahead of the input. */
  163929. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  163930. ! cinfo->inputctl->eoi_reached) {
  163931. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  163932. /* If input is working on current scan, we ordinarily want it to
  163933. * have completed the current row. But if input scan is DC,
  163934. * we want it to keep one row ahead so that next block row's DC
  163935. * values are up to date.
  163936. */
  163937. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  163938. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  163939. break;
  163940. }
  163941. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  163942. return JPEG_SUSPENDED;
  163943. }
  163944. /* OK, output from the virtual arrays. */
  163945. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163946. ci++, compptr++) {
  163947. /* Don't bother to IDCT an uninteresting component. */
  163948. if (! compptr->component_needed)
  163949. continue;
  163950. /* Count non-dummy DCT block rows in this iMCU row. */
  163951. if (cinfo->output_iMCU_row < last_iMCU_row) {
  163952. block_rows = compptr->v_samp_factor;
  163953. access_rows = block_rows * 2; /* this and next iMCU row */
  163954. last_row = FALSE;
  163955. } else {
  163956. /* NB: can't use last_row_height here; it is input-side-dependent! */
  163957. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163958. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  163959. access_rows = block_rows; /* this iMCU row only */
  163960. last_row = TRUE;
  163961. }
  163962. /* Align the virtual buffer for this component. */
  163963. if (cinfo->output_iMCU_row > 0) {
  163964. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  163965. buffer = (*cinfo->mem->access_virt_barray)
  163966. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163967. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  163968. (JDIMENSION) access_rows, FALSE);
  163969. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  163970. first_row = FALSE;
  163971. } else {
  163972. buffer = (*cinfo->mem->access_virt_barray)
  163973. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163974. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  163975. first_row = TRUE;
  163976. }
  163977. /* Fetch component-dependent info */
  163978. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  163979. quanttbl = compptr->quant_table;
  163980. Q00 = quanttbl->quantval[0];
  163981. Q01 = quanttbl->quantval[Q01_POS];
  163982. Q10 = quanttbl->quantval[Q10_POS];
  163983. Q20 = quanttbl->quantval[Q20_POS];
  163984. Q11 = quanttbl->quantval[Q11_POS];
  163985. Q02 = quanttbl->quantval[Q02_POS];
  163986. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  163987. output_ptr = output_buf[ci];
  163988. /* Loop over all DCT blocks to be processed. */
  163989. for (block_row = 0; block_row < block_rows; block_row++) {
  163990. buffer_ptr = buffer[block_row];
  163991. if (first_row && block_row == 0)
  163992. prev_block_row = buffer_ptr;
  163993. else
  163994. prev_block_row = buffer[block_row-1];
  163995. if (last_row && block_row == block_rows-1)
  163996. next_block_row = buffer_ptr;
  163997. else
  163998. next_block_row = buffer[block_row+1];
  163999. /* We fetch the surrounding DC values using a sliding-register approach.
  164000. * Initialize all nine here so as to do the right thing on narrow pics.
  164001. */
  164002. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  164003. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  164004. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  164005. output_col = 0;
  164006. last_block_column = compptr->width_in_blocks - 1;
  164007. for (block_num = 0; block_num <= last_block_column; block_num++) {
  164008. /* Fetch current DCT block into workspace so we can modify it. */
  164009. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  164010. /* Update DC values */
  164011. if (block_num < last_block_column) {
  164012. DC3 = (int) prev_block_row[1][0];
  164013. DC6 = (int) buffer_ptr[1][0];
  164014. DC9 = (int) next_block_row[1][0];
  164015. }
  164016. /* Compute coefficient estimates per K.8.
  164017. * An estimate is applied only if coefficient is still zero,
  164018. * and is not known to be fully accurate.
  164019. */
  164020. /* AC01 */
  164021. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  164022. num = 36 * Q00 * (DC4 - DC6);
  164023. if (num >= 0) {
  164024. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  164025. if (Al > 0 && pred >= (1<<Al))
  164026. pred = (1<<Al)-1;
  164027. } else {
  164028. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  164029. if (Al > 0 && pred >= (1<<Al))
  164030. pred = (1<<Al)-1;
  164031. pred = -pred;
  164032. }
  164033. workspace[1] = (JCOEF) pred;
  164034. }
  164035. /* AC10 */
  164036. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  164037. num = 36 * Q00 * (DC2 - DC8);
  164038. if (num >= 0) {
  164039. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  164040. if (Al > 0 && pred >= (1<<Al))
  164041. pred = (1<<Al)-1;
  164042. } else {
  164043. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  164044. if (Al > 0 && pred >= (1<<Al))
  164045. pred = (1<<Al)-1;
  164046. pred = -pred;
  164047. }
  164048. workspace[8] = (JCOEF) pred;
  164049. }
  164050. /* AC20 */
  164051. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  164052. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  164053. if (num >= 0) {
  164054. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  164055. if (Al > 0 && pred >= (1<<Al))
  164056. pred = (1<<Al)-1;
  164057. } else {
  164058. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  164059. if (Al > 0 && pred >= (1<<Al))
  164060. pred = (1<<Al)-1;
  164061. pred = -pred;
  164062. }
  164063. workspace[16] = (JCOEF) pred;
  164064. }
  164065. /* AC11 */
  164066. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  164067. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  164068. if (num >= 0) {
  164069. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  164070. if (Al > 0 && pred >= (1<<Al))
  164071. pred = (1<<Al)-1;
  164072. } else {
  164073. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  164074. if (Al > 0 && pred >= (1<<Al))
  164075. pred = (1<<Al)-1;
  164076. pred = -pred;
  164077. }
  164078. workspace[9] = (JCOEF) pred;
  164079. }
  164080. /* AC02 */
  164081. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  164082. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  164083. if (num >= 0) {
  164084. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  164085. if (Al > 0 && pred >= (1<<Al))
  164086. pred = (1<<Al)-1;
  164087. } else {
  164088. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  164089. if (Al > 0 && pred >= (1<<Al))
  164090. pred = (1<<Al)-1;
  164091. pred = -pred;
  164092. }
  164093. workspace[2] = (JCOEF) pred;
  164094. }
  164095. /* OK, do the IDCT */
  164096. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  164097. output_ptr, output_col);
  164098. /* Advance for next column */
  164099. DC1 = DC2; DC2 = DC3;
  164100. DC4 = DC5; DC5 = DC6;
  164101. DC7 = DC8; DC8 = DC9;
  164102. buffer_ptr++, prev_block_row++, next_block_row++;
  164103. output_col += compptr->DCT_scaled_size;
  164104. }
  164105. output_ptr += compptr->DCT_scaled_size;
  164106. }
  164107. }
  164108. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164109. return JPEG_ROW_COMPLETED;
  164110. return JPEG_SCAN_COMPLETED;
  164111. }
  164112. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  164113. /*
  164114. * Initialize coefficient buffer controller.
  164115. */
  164116. GLOBAL(void)
  164117. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  164118. {
  164119. my_coef_ptr3 coef;
  164120. coef = (my_coef_ptr3)
  164121. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164122. SIZEOF(my_coef_controller3));
  164123. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  164124. coef->pub.start_input_pass = start_input_pass;
  164125. coef->pub.start_output_pass = start_output_pass;
  164126. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164127. coef->coef_bits_latch = NULL;
  164128. #endif
  164129. /* Create the coefficient buffer. */
  164130. if (need_full_buffer) {
  164131. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164132. /* Allocate a full-image virtual array for each component, */
  164133. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  164134. /* Note we ask for a pre-zeroed array. */
  164135. int ci, access_rows;
  164136. jpeg_component_info *compptr;
  164137. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164138. ci++, compptr++) {
  164139. access_rows = compptr->v_samp_factor;
  164140. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164141. /* If block smoothing could be used, need a bigger window */
  164142. if (cinfo->progressive_mode)
  164143. access_rows *= 3;
  164144. #endif
  164145. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  164146. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  164147. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  164148. (long) compptr->h_samp_factor),
  164149. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164150. (long) compptr->v_samp_factor),
  164151. (JDIMENSION) access_rows);
  164152. }
  164153. coef->pub.consume_data = consume_data;
  164154. coef->pub.decompress_data = decompress_data;
  164155. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  164156. #else
  164157. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164158. #endif
  164159. } else {
  164160. /* We only need a single-MCU buffer. */
  164161. JBLOCKROW buffer;
  164162. int i;
  164163. buffer = (JBLOCKROW)
  164164. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164165. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164166. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  164167. coef->MCU_buffer[i] = buffer + i;
  164168. }
  164169. coef->pub.consume_data = dummy_consume_data;
  164170. coef->pub.decompress_data = decompress_onepass;
  164171. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  164172. }
  164173. }
  164174. /********* End of inlined file: jdcoefct.c *********/
  164175. #undef FIX
  164176. /********* Start of inlined file: jdcolor.c *********/
  164177. #define JPEG_INTERNALS
  164178. /* Private subobject */
  164179. typedef struct {
  164180. struct jpeg_color_deconverter pub; /* public fields */
  164181. /* Private state for YCC->RGB conversion */
  164182. int * Cr_r_tab; /* => table for Cr to R conversion */
  164183. int * Cb_b_tab; /* => table for Cb to B conversion */
  164184. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  164185. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  164186. } my_color_deconverter2;
  164187. typedef my_color_deconverter2 * my_cconvert_ptr2;
  164188. /**************** YCbCr -> RGB conversion: most common case **************/
  164189. /*
  164190. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  164191. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  164192. * The conversion equations to be implemented are therefore
  164193. * R = Y + 1.40200 * Cr
  164194. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  164195. * B = Y + 1.77200 * Cb
  164196. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  164197. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  164198. *
  164199. * To avoid floating-point arithmetic, we represent the fractional constants
  164200. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  164201. * the products by 2^16, with appropriate rounding, to get the correct answer.
  164202. * Notice that Y, being an integral input, does not contribute any fraction
  164203. * so it need not participate in the rounding.
  164204. *
  164205. * For even more speed, we avoid doing any multiplications in the inner loop
  164206. * by precalculating the constants times Cb and Cr for all possible values.
  164207. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  164208. * for 12-bit samples it is still acceptable. It's not very reasonable for
  164209. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  164210. * colorspace anyway.
  164211. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  164212. * values for the G calculation are left scaled up, since we must add them
  164213. * together before rounding.
  164214. */
  164215. #define SCALEBITS 16 /* speediest right-shift on some machines */
  164216. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  164217. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  164218. /*
  164219. * Initialize tables for YCC->RGB colorspace conversion.
  164220. */
  164221. LOCAL(void)
  164222. build_ycc_rgb_table (j_decompress_ptr cinfo)
  164223. {
  164224. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164225. int i;
  164226. INT32 x;
  164227. SHIFT_TEMPS
  164228. cconvert->Cr_r_tab = (int *)
  164229. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164230. (MAXJSAMPLE+1) * SIZEOF(int));
  164231. cconvert->Cb_b_tab = (int *)
  164232. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164233. (MAXJSAMPLE+1) * SIZEOF(int));
  164234. cconvert->Cr_g_tab = (INT32 *)
  164235. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164236. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164237. cconvert->Cb_g_tab = (INT32 *)
  164238. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164239. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164240. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  164241. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  164242. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  164243. /* Cr=>R value is nearest int to 1.40200 * x */
  164244. cconvert->Cr_r_tab[i] = (int)
  164245. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  164246. /* Cb=>B value is nearest int to 1.77200 * x */
  164247. cconvert->Cb_b_tab[i] = (int)
  164248. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  164249. /* Cr=>G value is scaled-up -0.71414 * x */
  164250. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  164251. /* Cb=>G value is scaled-up -0.34414 * x */
  164252. /* We also add in ONE_HALF so that need not do it in inner loop */
  164253. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  164254. }
  164255. }
  164256. /*
  164257. * Convert some rows of samples to the output colorspace.
  164258. *
  164259. * Note that we change from noninterleaved, one-plane-per-component format
  164260. * to interleaved-pixel format. The output buffer is therefore three times
  164261. * as wide as the input buffer.
  164262. * A starting row offset is provided only for the input buffer. The caller
  164263. * can easily adjust the passed output_buf value to accommodate any row
  164264. * offset required on that side.
  164265. */
  164266. METHODDEF(void)
  164267. ycc_rgb_convert (j_decompress_ptr cinfo,
  164268. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164269. JSAMPARRAY output_buf, int num_rows)
  164270. {
  164271. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164272. register int y, cb, cr;
  164273. register JSAMPROW outptr;
  164274. register JSAMPROW inptr0, inptr1, inptr2;
  164275. register JDIMENSION col;
  164276. JDIMENSION num_cols = cinfo->output_width;
  164277. /* copy these pointers into registers if possible */
  164278. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164279. register int * Crrtab = cconvert->Cr_r_tab;
  164280. register int * Cbbtab = cconvert->Cb_b_tab;
  164281. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164282. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164283. SHIFT_TEMPS
  164284. while (--num_rows >= 0) {
  164285. inptr0 = input_buf[0][input_row];
  164286. inptr1 = input_buf[1][input_row];
  164287. inptr2 = input_buf[2][input_row];
  164288. input_row++;
  164289. outptr = *output_buf++;
  164290. for (col = 0; col < num_cols; col++) {
  164291. y = GETJSAMPLE(inptr0[col]);
  164292. cb = GETJSAMPLE(inptr1[col]);
  164293. cr = GETJSAMPLE(inptr2[col]);
  164294. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164295. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  164296. outptr[RGB_GREEN] = range_limit[y +
  164297. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164298. SCALEBITS))];
  164299. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  164300. outptr += RGB_PIXELSIZE;
  164301. }
  164302. }
  164303. }
  164304. /**************** Cases other than YCbCr -> RGB **************/
  164305. /*
  164306. * Color conversion for no colorspace change: just copy the data,
  164307. * converting from separate-planes to interleaved representation.
  164308. */
  164309. METHODDEF(void)
  164310. null_convert2 (j_decompress_ptr cinfo,
  164311. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164312. JSAMPARRAY output_buf, int num_rows)
  164313. {
  164314. register JSAMPROW inptr, outptr;
  164315. register JDIMENSION count;
  164316. register int num_components = cinfo->num_components;
  164317. JDIMENSION num_cols = cinfo->output_width;
  164318. int ci;
  164319. while (--num_rows >= 0) {
  164320. for (ci = 0; ci < num_components; ci++) {
  164321. inptr = input_buf[ci][input_row];
  164322. outptr = output_buf[0] + ci;
  164323. for (count = num_cols; count > 0; count--) {
  164324. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  164325. outptr += num_components;
  164326. }
  164327. }
  164328. input_row++;
  164329. output_buf++;
  164330. }
  164331. }
  164332. /*
  164333. * Color conversion for grayscale: just copy the data.
  164334. * This also works for YCbCr -> grayscale conversion, in which
  164335. * we just copy the Y (luminance) component and ignore chrominance.
  164336. */
  164337. METHODDEF(void)
  164338. grayscale_convert2 (j_decompress_ptr cinfo,
  164339. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164340. JSAMPARRAY output_buf, int num_rows)
  164341. {
  164342. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  164343. num_rows, cinfo->output_width);
  164344. }
  164345. /*
  164346. * Convert grayscale to RGB: just duplicate the graylevel three times.
  164347. * This is provided to support applications that don't want to cope
  164348. * with grayscale as a separate case.
  164349. */
  164350. METHODDEF(void)
  164351. gray_rgb_convert (j_decompress_ptr cinfo,
  164352. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164353. JSAMPARRAY output_buf, int num_rows)
  164354. {
  164355. register JSAMPROW inptr, outptr;
  164356. register JDIMENSION col;
  164357. JDIMENSION num_cols = cinfo->output_width;
  164358. while (--num_rows >= 0) {
  164359. inptr = input_buf[0][input_row++];
  164360. outptr = *output_buf++;
  164361. for (col = 0; col < num_cols; col++) {
  164362. /* We can dispense with GETJSAMPLE() here */
  164363. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  164364. outptr += RGB_PIXELSIZE;
  164365. }
  164366. }
  164367. }
  164368. /*
  164369. * Adobe-style YCCK->CMYK conversion.
  164370. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  164371. * conversion as above, while passing K (black) unchanged.
  164372. * We assume build_ycc_rgb_table has been called.
  164373. */
  164374. METHODDEF(void)
  164375. ycck_cmyk_convert (j_decompress_ptr cinfo,
  164376. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164377. JSAMPARRAY output_buf, int num_rows)
  164378. {
  164379. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164380. register int y, cb, cr;
  164381. register JSAMPROW outptr;
  164382. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  164383. register JDIMENSION col;
  164384. JDIMENSION num_cols = cinfo->output_width;
  164385. /* copy these pointers into registers if possible */
  164386. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164387. register int * Crrtab = cconvert->Cr_r_tab;
  164388. register int * Cbbtab = cconvert->Cb_b_tab;
  164389. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164390. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164391. SHIFT_TEMPS
  164392. while (--num_rows >= 0) {
  164393. inptr0 = input_buf[0][input_row];
  164394. inptr1 = input_buf[1][input_row];
  164395. inptr2 = input_buf[2][input_row];
  164396. inptr3 = input_buf[3][input_row];
  164397. input_row++;
  164398. outptr = *output_buf++;
  164399. for (col = 0; col < num_cols; col++) {
  164400. y = GETJSAMPLE(inptr0[col]);
  164401. cb = GETJSAMPLE(inptr1[col]);
  164402. cr = GETJSAMPLE(inptr2[col]);
  164403. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164404. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  164405. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  164406. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164407. SCALEBITS)))];
  164408. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  164409. /* K passes through unchanged */
  164410. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  164411. outptr += 4;
  164412. }
  164413. }
  164414. }
  164415. /*
  164416. * Empty method for start_pass.
  164417. */
  164418. METHODDEF(void)
  164419. start_pass_dcolor (j_decompress_ptr cinfo)
  164420. {
  164421. /* no work needed */
  164422. }
  164423. /*
  164424. * Module initialization routine for output colorspace conversion.
  164425. */
  164426. GLOBAL(void)
  164427. jinit_color_deconverter (j_decompress_ptr cinfo)
  164428. {
  164429. my_cconvert_ptr2 cconvert;
  164430. int ci;
  164431. cconvert = (my_cconvert_ptr2)
  164432. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164433. SIZEOF(my_color_deconverter2));
  164434. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  164435. cconvert->pub.start_pass = start_pass_dcolor;
  164436. /* Make sure num_components agrees with jpeg_color_space */
  164437. switch (cinfo->jpeg_color_space) {
  164438. case JCS_GRAYSCALE:
  164439. if (cinfo->num_components != 1)
  164440. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164441. break;
  164442. case JCS_RGB:
  164443. case JCS_YCbCr:
  164444. if (cinfo->num_components != 3)
  164445. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164446. break;
  164447. case JCS_CMYK:
  164448. case JCS_YCCK:
  164449. if (cinfo->num_components != 4)
  164450. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164451. break;
  164452. default: /* JCS_UNKNOWN can be anything */
  164453. if (cinfo->num_components < 1)
  164454. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164455. break;
  164456. }
  164457. /* Set out_color_components and conversion method based on requested space.
  164458. * Also clear the component_needed flags for any unused components,
  164459. * so that earlier pipeline stages can avoid useless computation.
  164460. */
  164461. switch (cinfo->out_color_space) {
  164462. case JCS_GRAYSCALE:
  164463. cinfo->out_color_components = 1;
  164464. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  164465. cinfo->jpeg_color_space == JCS_YCbCr) {
  164466. cconvert->pub.color_convert = grayscale_convert2;
  164467. /* For color->grayscale conversion, only the Y (0) component is needed */
  164468. for (ci = 1; ci < cinfo->num_components; ci++)
  164469. cinfo->comp_info[ci].component_needed = FALSE;
  164470. } else
  164471. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164472. break;
  164473. case JCS_RGB:
  164474. cinfo->out_color_components = RGB_PIXELSIZE;
  164475. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  164476. cconvert->pub.color_convert = ycc_rgb_convert;
  164477. build_ycc_rgb_table(cinfo);
  164478. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  164479. cconvert->pub.color_convert = gray_rgb_convert;
  164480. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  164481. cconvert->pub.color_convert = null_convert2;
  164482. } else
  164483. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164484. break;
  164485. case JCS_CMYK:
  164486. cinfo->out_color_components = 4;
  164487. if (cinfo->jpeg_color_space == JCS_YCCK) {
  164488. cconvert->pub.color_convert = ycck_cmyk_convert;
  164489. build_ycc_rgb_table(cinfo);
  164490. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  164491. cconvert->pub.color_convert = null_convert2;
  164492. } else
  164493. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164494. break;
  164495. default:
  164496. /* Permit null conversion to same output space */
  164497. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  164498. cinfo->out_color_components = cinfo->num_components;
  164499. cconvert->pub.color_convert = null_convert2;
  164500. } else /* unsupported non-null conversion */
  164501. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164502. break;
  164503. }
  164504. if (cinfo->quantize_colors)
  164505. cinfo->output_components = 1; /* single colormapped output component */
  164506. else
  164507. cinfo->output_components = cinfo->out_color_components;
  164508. }
  164509. /********* End of inlined file: jdcolor.c *********/
  164510. #undef FIX
  164511. /********* Start of inlined file: jddctmgr.c *********/
  164512. #define JPEG_INTERNALS
  164513. /*
  164514. * The decompressor input side (jdinput.c) saves away the appropriate
  164515. * quantization table for each component at the start of the first scan
  164516. * involving that component. (This is necessary in order to correctly
  164517. * decode files that reuse Q-table slots.)
  164518. * When we are ready to make an output pass, the saved Q-table is converted
  164519. * to a multiplier table that will actually be used by the IDCT routine.
  164520. * The multiplier table contents are IDCT-method-dependent. To support
  164521. * application changes in IDCT method between scans, we can remake the
  164522. * multiplier tables if necessary.
  164523. * In buffered-image mode, the first output pass may occur before any data
  164524. * has been seen for some components, and thus before their Q-tables have
  164525. * been saved away. To handle this case, multiplier tables are preset
  164526. * to zeroes; the result of the IDCT will be a neutral gray level.
  164527. */
  164528. /* Private subobject for this module */
  164529. typedef struct {
  164530. struct jpeg_inverse_dct pub; /* public fields */
  164531. /* This array contains the IDCT method code that each multiplier table
  164532. * is currently set up for, or -1 if it's not yet set up.
  164533. * The actual multiplier tables are pointed to by dct_table in the
  164534. * per-component comp_info structures.
  164535. */
  164536. int cur_method[MAX_COMPONENTS];
  164537. } my_idct_controller;
  164538. typedef my_idct_controller * my_idct_ptr;
  164539. /* Allocated multiplier tables: big enough for any supported variant */
  164540. typedef union {
  164541. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  164542. #ifdef DCT_IFAST_SUPPORTED
  164543. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  164544. #endif
  164545. #ifdef DCT_FLOAT_SUPPORTED
  164546. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  164547. #endif
  164548. } multiplier_table;
  164549. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  164550. * so be sure to compile that code if either ISLOW or SCALING is requested.
  164551. */
  164552. #ifdef DCT_ISLOW_SUPPORTED
  164553. #define PROVIDE_ISLOW_TABLES
  164554. #else
  164555. #ifdef IDCT_SCALING_SUPPORTED
  164556. #define PROVIDE_ISLOW_TABLES
  164557. #endif
  164558. #endif
  164559. /*
  164560. * Prepare for an output pass.
  164561. * Here we select the proper IDCT routine for each component and build
  164562. * a matching multiplier table.
  164563. */
  164564. METHODDEF(void)
  164565. start_pass (j_decompress_ptr cinfo)
  164566. {
  164567. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  164568. int ci, i;
  164569. jpeg_component_info *compptr;
  164570. int method = 0;
  164571. inverse_DCT_method_ptr method_ptr = NULL;
  164572. JQUANT_TBL * qtbl;
  164573. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164574. ci++, compptr++) {
  164575. /* Select the proper IDCT routine for this component's scaling */
  164576. switch (compptr->DCT_scaled_size) {
  164577. #ifdef IDCT_SCALING_SUPPORTED
  164578. case 1:
  164579. method_ptr = jpeg_idct_1x1;
  164580. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  164581. break;
  164582. case 2:
  164583. method_ptr = jpeg_idct_2x2;
  164584. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  164585. break;
  164586. case 4:
  164587. method_ptr = jpeg_idct_4x4;
  164588. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  164589. break;
  164590. #endif
  164591. case DCTSIZE:
  164592. switch (cinfo->dct_method) {
  164593. #ifdef DCT_ISLOW_SUPPORTED
  164594. case JDCT_ISLOW:
  164595. method_ptr = jpeg_idct_islow;
  164596. method = JDCT_ISLOW;
  164597. break;
  164598. #endif
  164599. #ifdef DCT_IFAST_SUPPORTED
  164600. case JDCT_IFAST:
  164601. method_ptr = jpeg_idct_ifast;
  164602. method = JDCT_IFAST;
  164603. break;
  164604. #endif
  164605. #ifdef DCT_FLOAT_SUPPORTED
  164606. case JDCT_FLOAT:
  164607. method_ptr = jpeg_idct_float;
  164608. method = JDCT_FLOAT;
  164609. break;
  164610. #endif
  164611. default:
  164612. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164613. break;
  164614. }
  164615. break;
  164616. default:
  164617. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  164618. break;
  164619. }
  164620. idct->pub.inverse_DCT[ci] = method_ptr;
  164621. /* Create multiplier table from quant table.
  164622. * However, we can skip this if the component is uninteresting
  164623. * or if we already built the table. Also, if no quant table
  164624. * has yet been saved for the component, we leave the
  164625. * multiplier table all-zero; we'll be reading zeroes from the
  164626. * coefficient controller's buffer anyway.
  164627. */
  164628. if (! compptr->component_needed || idct->cur_method[ci] == method)
  164629. continue;
  164630. qtbl = compptr->quant_table;
  164631. if (qtbl == NULL) /* happens if no data yet for component */
  164632. continue;
  164633. idct->cur_method[ci] = method;
  164634. switch (method) {
  164635. #ifdef PROVIDE_ISLOW_TABLES
  164636. case JDCT_ISLOW:
  164637. {
  164638. /* For LL&M IDCT method, multipliers are equal to raw quantization
  164639. * coefficients, but are stored as ints to ensure access efficiency.
  164640. */
  164641. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  164642. for (i = 0; i < DCTSIZE2; i++) {
  164643. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  164644. }
  164645. }
  164646. break;
  164647. #endif
  164648. #ifdef DCT_IFAST_SUPPORTED
  164649. case JDCT_IFAST:
  164650. {
  164651. /* For AA&N IDCT method, multipliers are equal to quantization
  164652. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  164653. * scalefactor[0] = 1
  164654. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  164655. * For integer operation, the multiplier table is to be scaled by
  164656. * IFAST_SCALE_BITS.
  164657. */
  164658. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  164659. #define CONST_BITS 14
  164660. static const INT16 aanscales[DCTSIZE2] = {
  164661. /* precomputed values scaled up by 14 bits */
  164662. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  164663. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  164664. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  164665. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  164666. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  164667. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  164668. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  164669. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  164670. };
  164671. SHIFT_TEMPS
  164672. for (i = 0; i < DCTSIZE2; i++) {
  164673. ifmtbl[i] = (IFAST_MULT_TYPE)
  164674. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  164675. (INT32) aanscales[i]),
  164676. CONST_BITS-IFAST_SCALE_BITS);
  164677. }
  164678. }
  164679. break;
  164680. #endif
  164681. #ifdef DCT_FLOAT_SUPPORTED
  164682. case JDCT_FLOAT:
  164683. {
  164684. /* For float AA&N IDCT method, multipliers are equal to quantization
  164685. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  164686. * scalefactor[0] = 1
  164687. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  164688. */
  164689. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  164690. int row, col;
  164691. static const double aanscalefactor[DCTSIZE] = {
  164692. 1.0, 1.387039845, 1.306562965, 1.175875602,
  164693. 1.0, 0.785694958, 0.541196100, 0.275899379
  164694. };
  164695. i = 0;
  164696. for (row = 0; row < DCTSIZE; row++) {
  164697. for (col = 0; col < DCTSIZE; col++) {
  164698. fmtbl[i] = (FLOAT_MULT_TYPE)
  164699. ((double) qtbl->quantval[i] *
  164700. aanscalefactor[row] * aanscalefactor[col]);
  164701. i++;
  164702. }
  164703. }
  164704. }
  164705. break;
  164706. #endif
  164707. default:
  164708. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164709. break;
  164710. }
  164711. }
  164712. }
  164713. /*
  164714. * Initialize IDCT manager.
  164715. */
  164716. GLOBAL(void)
  164717. jinit_inverse_dct (j_decompress_ptr cinfo)
  164718. {
  164719. my_idct_ptr idct;
  164720. int ci;
  164721. jpeg_component_info *compptr;
  164722. idct = (my_idct_ptr)
  164723. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164724. SIZEOF(my_idct_controller));
  164725. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  164726. idct->pub.start_pass = start_pass;
  164727. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164728. ci++, compptr++) {
  164729. /* Allocate and pre-zero a multiplier table for each component */
  164730. compptr->dct_table =
  164731. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164732. SIZEOF(multiplier_table));
  164733. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  164734. /* Mark multiplier table not yet set up for any method */
  164735. idct->cur_method[ci] = -1;
  164736. }
  164737. }
  164738. /********* End of inlined file: jddctmgr.c *********/
  164739. #undef CONST_BITS
  164740. #undef ASSIGN_STATE
  164741. /********* Start of inlined file: jdhuff.c *********/
  164742. #define JPEG_INTERNALS
  164743. /********* Start of inlined file: jdhuff.h *********/
  164744. /* Short forms of external names for systems with brain-damaged linkers. */
  164745. #ifndef __jdhuff_h__
  164746. #define __jdhuff_h__
  164747. #ifdef NEED_SHORT_EXTERNAL_NAMES
  164748. #define jpeg_make_d_derived_tbl jMkDDerived
  164749. #define jpeg_fill_bit_buffer jFilBitBuf
  164750. #define jpeg_huff_decode jHufDecode
  164751. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  164752. /* Derived data constructed for each Huffman table */
  164753. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  164754. typedef struct {
  164755. /* Basic tables: (element [0] of each array is unused) */
  164756. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  164757. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  164758. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  164759. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  164760. * the smallest code of length k; so given a code of length k, the
  164761. * corresponding symbol is huffval[code + valoffset[k]]
  164762. */
  164763. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  164764. JHUFF_TBL *pub;
  164765. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  164766. * the input data stream. If the next Huffman code is no more
  164767. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  164768. * the corresponding symbol directly from these tables.
  164769. */
  164770. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  164771. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  164772. } d_derived_tbl;
  164773. /* Expand a Huffman table definition into the derived format */
  164774. EXTERN(void) jpeg_make_d_derived_tbl
  164775. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  164776. d_derived_tbl ** pdtbl));
  164777. /*
  164778. * Fetching the next N bits from the input stream is a time-critical operation
  164779. * for the Huffman decoders. We implement it with a combination of inline
  164780. * macros and out-of-line subroutines. Note that N (the number of bits
  164781. * demanded at one time) never exceeds 15 for JPEG use.
  164782. *
  164783. * We read source bytes into get_buffer and dole out bits as needed.
  164784. * If get_buffer already contains enough bits, they are fetched in-line
  164785. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  164786. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  164787. * as full as possible (not just to the number of bits needed; this
  164788. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  164789. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  164790. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  164791. * at least the requested number of bits --- dummy zeroes are inserted if
  164792. * necessary.
  164793. */
  164794. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  164795. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  164796. /* If long is > 32 bits on your machine, and shifting/masking longs is
  164797. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  164798. * appropriately should be a win. Unfortunately we can't define the size
  164799. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  164800. * because not all machines measure sizeof in 8-bit bytes.
  164801. */
  164802. typedef struct { /* Bitreading state saved across MCUs */
  164803. bit_buf_type get_buffer; /* current bit-extraction buffer */
  164804. int bits_left; /* # of unused bits in it */
  164805. } bitread_perm_state;
  164806. typedef struct { /* Bitreading working state within an MCU */
  164807. /* Current data source location */
  164808. /* We need a copy, rather than munging the original, in case of suspension */
  164809. const JOCTET * next_input_byte; /* => next byte to read from source */
  164810. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  164811. /* Bit input buffer --- note these values are kept in register variables,
  164812. * not in this struct, inside the inner loops.
  164813. */
  164814. bit_buf_type get_buffer; /* current bit-extraction buffer */
  164815. int bits_left; /* # of unused bits in it */
  164816. /* Pointer needed by jpeg_fill_bit_buffer. */
  164817. j_decompress_ptr cinfo; /* back link to decompress master record */
  164818. } bitread_working_state;
  164819. /* Macros to declare and load/save bitread local variables. */
  164820. #define BITREAD_STATE_VARS \
  164821. register bit_buf_type get_buffer; \
  164822. register int bits_left; \
  164823. bitread_working_state br_state
  164824. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  164825. br_state.cinfo = cinfop; \
  164826. br_state.next_input_byte = cinfop->src->next_input_byte; \
  164827. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  164828. get_buffer = permstate.get_buffer; \
  164829. bits_left = permstate.bits_left;
  164830. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  164831. cinfop->src->next_input_byte = br_state.next_input_byte; \
  164832. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  164833. permstate.get_buffer = get_buffer; \
  164834. permstate.bits_left = bits_left
  164835. /*
  164836. * These macros provide the in-line portion of bit fetching.
  164837. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  164838. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  164839. * The variables get_buffer and bits_left are assumed to be locals,
  164840. * but the state struct might not be (jpeg_huff_decode needs this).
  164841. * CHECK_BIT_BUFFER(state,n,action);
  164842. * Ensure there are N bits in get_buffer; if suspend, take action.
  164843. * val = GET_BITS(n);
  164844. * Fetch next N bits.
  164845. * val = PEEK_BITS(n);
  164846. * Fetch next N bits without removing them from the buffer.
  164847. * DROP_BITS(n);
  164848. * Discard next N bits.
  164849. * The value N should be a simple variable, not an expression, because it
  164850. * is evaluated multiple times.
  164851. */
  164852. #define CHECK_BIT_BUFFER(state,nbits,action) \
  164853. { if (bits_left < (nbits)) { \
  164854. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  164855. { action; } \
  164856. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  164857. #define GET_BITS(nbits) \
  164858. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  164859. #define PEEK_BITS(nbits) \
  164860. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  164861. #define DROP_BITS(nbits) \
  164862. (bits_left -= (nbits))
  164863. /* Load up the bit buffer to a depth of at least nbits */
  164864. EXTERN(boolean) jpeg_fill_bit_buffer
  164865. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  164866. register int bits_left, int nbits));
  164867. /*
  164868. * Code for extracting next Huffman-coded symbol from input bit stream.
  164869. * Again, this is time-critical and we make the main paths be macros.
  164870. *
  164871. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  164872. * without looping. Usually, more than 95% of the Huffman codes will be 8
  164873. * or fewer bits long. The few overlength codes are handled with a loop,
  164874. * which need not be inline code.
  164875. *
  164876. * Notes about the HUFF_DECODE macro:
  164877. * 1. Near the end of the data segment, we may fail to get enough bits
  164878. * for a lookahead. In that case, we do it the hard way.
  164879. * 2. If the lookahead table contains no entry, the next code must be
  164880. * more than HUFF_LOOKAHEAD bits long.
  164881. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  164882. */
  164883. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  164884. { register int nb, look; \
  164885. if (bits_left < HUFF_LOOKAHEAD) { \
  164886. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  164887. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  164888. if (bits_left < HUFF_LOOKAHEAD) { \
  164889. nb = 1; goto slowlabel; \
  164890. } \
  164891. } \
  164892. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  164893. if ((nb = htbl->look_nbits[look]) != 0) { \
  164894. DROP_BITS(nb); \
  164895. result = htbl->look_sym[look]; \
  164896. } else { \
  164897. nb = HUFF_LOOKAHEAD+1; \
  164898. slowlabel: \
  164899. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  164900. { failaction; } \
  164901. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  164902. } \
  164903. }
  164904. /* Out-of-line case for Huffman code fetching */
  164905. EXTERN(int) jpeg_huff_decode
  164906. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  164907. register int bits_left, d_derived_tbl * htbl, int min_bits));
  164908. #endif
  164909. /********* End of inlined file: jdhuff.h *********/
  164910. /* Declarations shared with jdphuff.c */
  164911. /*
  164912. * Expanded entropy decoder object for Huffman decoding.
  164913. *
  164914. * The savable_state subrecord contains fields that change within an MCU,
  164915. * but must not be updated permanently until we complete the MCU.
  164916. */
  164917. typedef struct {
  164918. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  164919. } savable_state2;
  164920. /* This macro is to work around compilers with missing or broken
  164921. * structure assignment. You'll need to fix this code if you have
  164922. * such a compiler and you change MAX_COMPS_IN_SCAN.
  164923. */
  164924. #ifndef NO_STRUCT_ASSIGN
  164925. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  164926. #else
  164927. #if MAX_COMPS_IN_SCAN == 4
  164928. #define ASSIGN_STATE(dest,src) \
  164929. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  164930. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  164931. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  164932. (dest).last_dc_val[3] = (src).last_dc_val[3])
  164933. #endif
  164934. #endif
  164935. typedef struct {
  164936. struct jpeg_entropy_decoder pub; /* public fields */
  164937. /* These fields are loaded into local variables at start of each MCU.
  164938. * In case of suspension, we exit WITHOUT updating them.
  164939. */
  164940. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  164941. savable_state2 saved; /* Other state at start of MCU */
  164942. /* These fields are NOT loaded into local working state. */
  164943. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  164944. /* Pointers to derived tables (these workspaces have image lifespan) */
  164945. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  164946. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  164947. /* Precalculated info set up by start_pass for use in decode_mcu: */
  164948. /* Pointers to derived tables to be used for each block within an MCU */
  164949. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  164950. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  164951. /* Whether we care about the DC and AC coefficient values for each block */
  164952. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  164953. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  164954. } huff_entropy_decoder2;
  164955. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  164956. /*
  164957. * Initialize for a Huffman-compressed scan.
  164958. */
  164959. METHODDEF(void)
  164960. start_pass_huff_decoder (j_decompress_ptr cinfo)
  164961. {
  164962. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164963. int ci, blkn, dctbl, actbl;
  164964. jpeg_component_info * compptr;
  164965. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  164966. * This ought to be an error condition, but we make it a warning because
  164967. * there are some baseline files out there with all zeroes in these bytes.
  164968. */
  164969. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  164970. cinfo->Ah != 0 || cinfo->Al != 0)
  164971. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  164972. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164973. compptr = cinfo->cur_comp_info[ci];
  164974. dctbl = compptr->dc_tbl_no;
  164975. actbl = compptr->ac_tbl_no;
  164976. /* Compute derived values for Huffman tables */
  164977. /* We may do this more than once for a table, but it's not expensive */
  164978. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  164979. & entropy->dc_derived_tbls[dctbl]);
  164980. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  164981. & entropy->ac_derived_tbls[actbl]);
  164982. /* Initialize DC predictions to 0 */
  164983. entropy->saved.last_dc_val[ci] = 0;
  164984. }
  164985. /* Precalculate decoding info for each block in an MCU of this scan */
  164986. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164987. ci = cinfo->MCU_membership[blkn];
  164988. compptr = cinfo->cur_comp_info[ci];
  164989. /* Precalculate which table to use for each block */
  164990. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  164991. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  164992. /* Decide whether we really care about the coefficient values */
  164993. if (compptr->component_needed) {
  164994. entropy->dc_needed[blkn] = TRUE;
  164995. /* we don't need the ACs if producing a 1/8th-size image */
  164996. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  164997. } else {
  164998. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  164999. }
  165000. }
  165001. /* Initialize bitread state variables */
  165002. entropy->bitstate.bits_left = 0;
  165003. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  165004. entropy->pub.insufficient_data = FALSE;
  165005. /* Initialize restart counter */
  165006. entropy->restarts_to_go = cinfo->restart_interval;
  165007. }
  165008. /*
  165009. * Compute the derived values for a Huffman table.
  165010. * This routine also performs some validation checks on the table.
  165011. *
  165012. * Note this is also used by jdphuff.c.
  165013. */
  165014. GLOBAL(void)
  165015. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  165016. d_derived_tbl ** pdtbl)
  165017. {
  165018. JHUFF_TBL *htbl;
  165019. d_derived_tbl *dtbl;
  165020. int p, i, l, si, numsymbols;
  165021. int lookbits, ctr;
  165022. char huffsize[257];
  165023. unsigned int huffcode[257];
  165024. unsigned int code;
  165025. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  165026. * paralleling the order of the symbols themselves in htbl->huffval[].
  165027. */
  165028. /* Find the input Huffman table */
  165029. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  165030. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165031. htbl =
  165032. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  165033. if (htbl == NULL)
  165034. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165035. /* Allocate a workspace if we haven't already done so. */
  165036. if (*pdtbl == NULL)
  165037. *pdtbl = (d_derived_tbl *)
  165038. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165039. SIZEOF(d_derived_tbl));
  165040. dtbl = *pdtbl;
  165041. dtbl->pub = htbl; /* fill in back link */
  165042. /* Figure C.1: make table of Huffman code length for each symbol */
  165043. p = 0;
  165044. for (l = 1; l <= 16; l++) {
  165045. i = (int) htbl->bits[l];
  165046. if (i < 0 || p + i > 256) /* protect against table overrun */
  165047. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165048. while (i--)
  165049. huffsize[p++] = (char) l;
  165050. }
  165051. huffsize[p] = 0;
  165052. numsymbols = p;
  165053. /* Figure C.2: generate the codes themselves */
  165054. /* We also validate that the counts represent a legal Huffman code tree. */
  165055. code = 0;
  165056. si = huffsize[0];
  165057. p = 0;
  165058. while (huffsize[p]) {
  165059. while (((int) huffsize[p]) == si) {
  165060. huffcode[p++] = code;
  165061. code++;
  165062. }
  165063. /* code is now 1 more than the last code used for codelength si; but
  165064. * it must still fit in si bits, since no code is allowed to be all ones.
  165065. */
  165066. if (((INT32) code) >= (((INT32) 1) << si))
  165067. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165068. code <<= 1;
  165069. si++;
  165070. }
  165071. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  165072. p = 0;
  165073. for (l = 1; l <= 16; l++) {
  165074. if (htbl->bits[l]) {
  165075. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  165076. * minus the minimum code of length l
  165077. */
  165078. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  165079. p += htbl->bits[l];
  165080. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  165081. } else {
  165082. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  165083. }
  165084. }
  165085. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  165086. /* Compute lookahead tables to speed up decoding.
  165087. * First we set all the table entries to 0, indicating "too long";
  165088. * then we iterate through the Huffman codes that are short enough and
  165089. * fill in all the entries that correspond to bit sequences starting
  165090. * with that code.
  165091. */
  165092. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  165093. p = 0;
  165094. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  165095. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  165096. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  165097. /* Generate left-justified code followed by all possible bit sequences */
  165098. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  165099. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  165100. dtbl->look_nbits[lookbits] = l;
  165101. dtbl->look_sym[lookbits] = htbl->huffval[p];
  165102. lookbits++;
  165103. }
  165104. }
  165105. }
  165106. /* Validate symbols as being reasonable.
  165107. * For AC tables, we make no check, but accept all byte values 0..255.
  165108. * For DC tables, we require the symbols to be in range 0..15.
  165109. * (Tighter bounds could be applied depending on the data depth and mode,
  165110. * but this is sufficient to ensure safe decoding.)
  165111. */
  165112. if (isDC) {
  165113. for (i = 0; i < numsymbols; i++) {
  165114. int sym = htbl->huffval[i];
  165115. if (sym < 0 || sym > 15)
  165116. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165117. }
  165118. }
  165119. }
  165120. /*
  165121. * Out-of-line code for bit fetching (shared with jdphuff.c).
  165122. * See jdhuff.h for info about usage.
  165123. * Note: current values of get_buffer and bits_left are passed as parameters,
  165124. * but are returned in the corresponding fields of the state struct.
  165125. *
  165126. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  165127. * of get_buffer to be used. (On machines with wider words, an even larger
  165128. * buffer could be used.) However, on some machines 32-bit shifts are
  165129. * quite slow and take time proportional to the number of places shifted.
  165130. * (This is true with most PC compilers, for instance.) In this case it may
  165131. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  165132. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  165133. */
  165134. #ifdef SLOW_SHIFT_32
  165135. #define MIN_GET_BITS 15 /* minimum allowable value */
  165136. #else
  165137. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  165138. #endif
  165139. GLOBAL(boolean)
  165140. jpeg_fill_bit_buffer (bitread_working_state * state,
  165141. register bit_buf_type get_buffer, register int bits_left,
  165142. int nbits)
  165143. /* Load up the bit buffer to a depth of at least nbits */
  165144. {
  165145. /* Copy heavily used state fields into locals (hopefully registers) */
  165146. register const JOCTET * next_input_byte = state->next_input_byte;
  165147. register size_t bytes_in_buffer = state->bytes_in_buffer;
  165148. j_decompress_ptr cinfo = state->cinfo;
  165149. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  165150. /* (It is assumed that no request will be for more than that many bits.) */
  165151. /* We fail to do so only if we hit a marker or are forced to suspend. */
  165152. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  165153. while (bits_left < MIN_GET_BITS) {
  165154. register int c;
  165155. /* Attempt to read a byte */
  165156. if (bytes_in_buffer == 0) {
  165157. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165158. return FALSE;
  165159. next_input_byte = cinfo->src->next_input_byte;
  165160. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165161. }
  165162. bytes_in_buffer--;
  165163. c = GETJOCTET(*next_input_byte++);
  165164. /* If it's 0xFF, check and discard stuffed zero byte */
  165165. if (c == 0xFF) {
  165166. /* Loop here to discard any padding FF's on terminating marker,
  165167. * so that we can save a valid unread_marker value. NOTE: we will
  165168. * accept multiple FF's followed by a 0 as meaning a single FF data
  165169. * byte. This data pattern is not valid according to the standard.
  165170. */
  165171. do {
  165172. if (bytes_in_buffer == 0) {
  165173. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165174. return FALSE;
  165175. next_input_byte = cinfo->src->next_input_byte;
  165176. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165177. }
  165178. bytes_in_buffer--;
  165179. c = GETJOCTET(*next_input_byte++);
  165180. } while (c == 0xFF);
  165181. if (c == 0) {
  165182. /* Found FF/00, which represents an FF data byte */
  165183. c = 0xFF;
  165184. } else {
  165185. /* Oops, it's actually a marker indicating end of compressed data.
  165186. * Save the marker code for later use.
  165187. * Fine point: it might appear that we should save the marker into
  165188. * bitread working state, not straight into permanent state. But
  165189. * once we have hit a marker, we cannot need to suspend within the
  165190. * current MCU, because we will read no more bytes from the data
  165191. * source. So it is OK to update permanent state right away.
  165192. */
  165193. cinfo->unread_marker = c;
  165194. /* See if we need to insert some fake zero bits. */
  165195. goto no_more_bytes;
  165196. }
  165197. }
  165198. /* OK, load c into get_buffer */
  165199. get_buffer = (get_buffer << 8) | c;
  165200. bits_left += 8;
  165201. } /* end while */
  165202. } else {
  165203. no_more_bytes:
  165204. /* We get here if we've read the marker that terminates the compressed
  165205. * data segment. There should be enough bits in the buffer register
  165206. * to satisfy the request; if so, no problem.
  165207. */
  165208. if (nbits > bits_left) {
  165209. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  165210. * the data stream, so that we can produce some kind of image.
  165211. * We use a nonvolatile flag to ensure that only one warning message
  165212. * appears per data segment.
  165213. */
  165214. if (! cinfo->entropy->insufficient_data) {
  165215. WARNMS(cinfo, JWRN_HIT_MARKER);
  165216. cinfo->entropy->insufficient_data = TRUE;
  165217. }
  165218. /* Fill the buffer with zero bits */
  165219. get_buffer <<= MIN_GET_BITS - bits_left;
  165220. bits_left = MIN_GET_BITS;
  165221. }
  165222. }
  165223. /* Unload the local registers */
  165224. state->next_input_byte = next_input_byte;
  165225. state->bytes_in_buffer = bytes_in_buffer;
  165226. state->get_buffer = get_buffer;
  165227. state->bits_left = bits_left;
  165228. return TRUE;
  165229. }
  165230. /*
  165231. * Out-of-line code for Huffman code decoding.
  165232. * See jdhuff.h for info about usage.
  165233. */
  165234. GLOBAL(int)
  165235. jpeg_huff_decode (bitread_working_state * state,
  165236. register bit_buf_type get_buffer, register int bits_left,
  165237. d_derived_tbl * htbl, int min_bits)
  165238. {
  165239. register int l = min_bits;
  165240. register INT32 code;
  165241. /* HUFF_DECODE has determined that the code is at least min_bits */
  165242. /* bits long, so fetch that many bits in one swoop. */
  165243. CHECK_BIT_BUFFER(*state, l, return -1);
  165244. code = GET_BITS(l);
  165245. /* Collect the rest of the Huffman code one bit at a time. */
  165246. /* This is per Figure F.16 in the JPEG spec. */
  165247. while (code > htbl->maxcode[l]) {
  165248. code <<= 1;
  165249. CHECK_BIT_BUFFER(*state, 1, return -1);
  165250. code |= GET_BITS(1);
  165251. l++;
  165252. }
  165253. /* Unload the local registers */
  165254. state->get_buffer = get_buffer;
  165255. state->bits_left = bits_left;
  165256. /* With garbage input we may reach the sentinel value l = 17. */
  165257. if (l > 16) {
  165258. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  165259. return 0; /* fake a zero as the safest result */
  165260. }
  165261. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  165262. }
  165263. /*
  165264. * Check for a restart marker & resynchronize decoder.
  165265. * Returns FALSE if must suspend.
  165266. */
  165267. LOCAL(boolean)
  165268. process_restart (j_decompress_ptr cinfo)
  165269. {
  165270. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165271. int ci;
  165272. /* Throw away any unused bits remaining in bit buffer; */
  165273. /* include any full bytes in next_marker's count of discarded bytes */
  165274. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  165275. entropy->bitstate.bits_left = 0;
  165276. /* Advance past the RSTn marker */
  165277. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  165278. return FALSE;
  165279. /* Re-initialize DC predictions to 0 */
  165280. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  165281. entropy->saved.last_dc_val[ci] = 0;
  165282. /* Reset restart counter */
  165283. entropy->restarts_to_go = cinfo->restart_interval;
  165284. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  165285. * against a marker. In that case we will end up treating the next data
  165286. * segment as empty, and we can avoid producing bogus output pixels by
  165287. * leaving the flag set.
  165288. */
  165289. if (cinfo->unread_marker == 0)
  165290. entropy->pub.insufficient_data = FALSE;
  165291. return TRUE;
  165292. }
  165293. /*
  165294. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  165295. * The coefficients are reordered from zigzag order into natural array order,
  165296. * but are not dequantized.
  165297. *
  165298. * The i'th block of the MCU is stored into the block pointed to by
  165299. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  165300. * (Wholesale zeroing is usually a little faster than retail...)
  165301. *
  165302. * Returns FALSE if data source requested suspension. In that case no
  165303. * changes have been made to permanent state. (Exception: some output
  165304. * coefficients may already have been assigned. This is harmless for
  165305. * this module, since we'll just re-assign them on the next call.)
  165306. */
  165307. METHODDEF(boolean)
  165308. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  165309. {
  165310. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165311. int blkn;
  165312. BITREAD_STATE_VARS;
  165313. savable_state2 state;
  165314. /* Process restart marker if needed; may have to suspend */
  165315. if (cinfo->restart_interval) {
  165316. if (entropy->restarts_to_go == 0)
  165317. if (! process_restart(cinfo))
  165318. return FALSE;
  165319. }
  165320. /* If we've run out of data, just leave the MCU set to zeroes.
  165321. * This way, we return uniform gray for the remainder of the segment.
  165322. */
  165323. if (! entropy->pub.insufficient_data) {
  165324. /* Load up working state */
  165325. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  165326. ASSIGN_STATE(state, entropy->saved);
  165327. /* Outer loop handles each block in the MCU */
  165328. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165329. JBLOCKROW block = MCU_data[blkn];
  165330. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  165331. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  165332. register int s, k, r;
  165333. /* Decode a single block's worth of coefficients */
  165334. /* Section F.2.2.1: decode the DC coefficient difference */
  165335. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  165336. if (s) {
  165337. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165338. r = GET_BITS(s);
  165339. s = HUFF_EXTEND(r, s);
  165340. }
  165341. if (entropy->dc_needed[blkn]) {
  165342. /* Convert DC difference to actual value, update last_dc_val */
  165343. int ci = cinfo->MCU_membership[blkn];
  165344. s += state.last_dc_val[ci];
  165345. state.last_dc_val[ci] = s;
  165346. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  165347. (*block)[0] = (JCOEF) s;
  165348. }
  165349. if (entropy->ac_needed[blkn]) {
  165350. /* Section F.2.2.2: decode the AC coefficients */
  165351. /* Since zeroes are skipped, output area must be cleared beforehand */
  165352. for (k = 1; k < DCTSIZE2; k++) {
  165353. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  165354. r = s >> 4;
  165355. s &= 15;
  165356. if (s) {
  165357. k += r;
  165358. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165359. r = GET_BITS(s);
  165360. s = HUFF_EXTEND(r, s);
  165361. /* Output coefficient in natural (dezigzagged) order.
  165362. * Note: the extra entries in jpeg_natural_order[] will save us
  165363. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  165364. */
  165365. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  165366. } else {
  165367. if (r != 15)
  165368. break;
  165369. k += 15;
  165370. }
  165371. }
  165372. } else {
  165373. /* Section F.2.2.2: decode the AC coefficients */
  165374. /* In this path we just discard the values */
  165375. for (k = 1; k < DCTSIZE2; k++) {
  165376. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  165377. r = s >> 4;
  165378. s &= 15;
  165379. if (s) {
  165380. k += r;
  165381. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165382. DROP_BITS(s);
  165383. } else {
  165384. if (r != 15)
  165385. break;
  165386. k += 15;
  165387. }
  165388. }
  165389. }
  165390. }
  165391. /* Completed MCU, so update state */
  165392. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  165393. ASSIGN_STATE(entropy->saved, state);
  165394. }
  165395. /* Account for restart interval (no-op if not using restarts) */
  165396. entropy->restarts_to_go--;
  165397. return TRUE;
  165398. }
  165399. /*
  165400. * Module initialization routine for Huffman entropy decoding.
  165401. */
  165402. GLOBAL(void)
  165403. jinit_huff_decoder (j_decompress_ptr cinfo)
  165404. {
  165405. huff_entropy_ptr2 entropy;
  165406. int i;
  165407. entropy = (huff_entropy_ptr2)
  165408. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165409. SIZEOF(huff_entropy_decoder2));
  165410. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  165411. entropy->pub.start_pass = start_pass_huff_decoder;
  165412. entropy->pub.decode_mcu = decode_mcu;
  165413. /* Mark tables unallocated */
  165414. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165415. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  165416. }
  165417. }
  165418. /********* End of inlined file: jdhuff.c *********/
  165419. /********* Start of inlined file: jdinput.c *********/
  165420. #define JPEG_INTERNALS
  165421. /* Private state */
  165422. typedef struct {
  165423. struct jpeg_input_controller pub; /* public fields */
  165424. boolean inheaders; /* TRUE until first SOS is reached */
  165425. } my_input_controller;
  165426. typedef my_input_controller * my_inputctl_ptr;
  165427. /* Forward declarations */
  165428. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  165429. /*
  165430. * Routines to calculate various quantities related to the size of the image.
  165431. */
  165432. LOCAL(void)
  165433. initial_setup2 (j_decompress_ptr cinfo)
  165434. /* Called once, when first SOS marker is reached */
  165435. {
  165436. int ci;
  165437. jpeg_component_info *compptr;
  165438. /* Make sure image isn't bigger than I can handle */
  165439. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  165440. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  165441. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  165442. /* For now, precision must match compiled-in value... */
  165443. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  165444. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  165445. /* Check that number of components won't exceed internal array sizes */
  165446. if (cinfo->num_components > MAX_COMPONENTS)
  165447. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165448. MAX_COMPONENTS);
  165449. /* Compute maximum sampling factors; check factor validity */
  165450. cinfo->max_h_samp_factor = 1;
  165451. cinfo->max_v_samp_factor = 1;
  165452. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165453. ci++, compptr++) {
  165454. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  165455. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  165456. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  165457. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  165458. compptr->h_samp_factor);
  165459. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  165460. compptr->v_samp_factor);
  165461. }
  165462. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  165463. * In the full decompressor, this will be overridden by jdmaster.c;
  165464. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  165465. */
  165466. cinfo->min_DCT_scaled_size = DCTSIZE;
  165467. /* Compute dimensions of components */
  165468. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165469. ci++, compptr++) {
  165470. compptr->DCT_scaled_size = DCTSIZE;
  165471. /* Size in DCT blocks */
  165472. compptr->width_in_blocks = (JDIMENSION)
  165473. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165474. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  165475. compptr->height_in_blocks = (JDIMENSION)
  165476. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165477. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  165478. /* downsampled_width and downsampled_height will also be overridden by
  165479. * jdmaster.c if we are doing full decompression. The transcoder library
  165480. * doesn't use these values, but the calling application might.
  165481. */
  165482. /* Size in samples */
  165483. compptr->downsampled_width = (JDIMENSION)
  165484. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165485. (long) cinfo->max_h_samp_factor);
  165486. compptr->downsampled_height = (JDIMENSION)
  165487. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165488. (long) cinfo->max_v_samp_factor);
  165489. /* Mark component needed, until color conversion says otherwise */
  165490. compptr->component_needed = TRUE;
  165491. /* Mark no quantization table yet saved for component */
  165492. compptr->quant_table = NULL;
  165493. }
  165494. /* Compute number of fully interleaved MCU rows. */
  165495. cinfo->total_iMCU_rows = (JDIMENSION)
  165496. jdiv_round_up((long) cinfo->image_height,
  165497. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165498. /* Decide whether file contains multiple scans */
  165499. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  165500. cinfo->inputctl->has_multiple_scans = TRUE;
  165501. else
  165502. cinfo->inputctl->has_multiple_scans = FALSE;
  165503. }
  165504. LOCAL(void)
  165505. per_scan_setup2 (j_decompress_ptr cinfo)
  165506. /* Do computations that are needed before processing a JPEG scan */
  165507. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  165508. {
  165509. int ci, mcublks, tmp;
  165510. jpeg_component_info *compptr;
  165511. if (cinfo->comps_in_scan == 1) {
  165512. /* Noninterleaved (single-component) scan */
  165513. compptr = cinfo->cur_comp_info[0];
  165514. /* Overall image size in MCUs */
  165515. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165516. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165517. /* For noninterleaved scan, always one block per MCU */
  165518. compptr->MCU_width = 1;
  165519. compptr->MCU_height = 1;
  165520. compptr->MCU_blocks = 1;
  165521. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  165522. compptr->last_col_width = 1;
  165523. /* For noninterleaved scans, it is convenient to define last_row_height
  165524. * as the number of block rows present in the last iMCU row.
  165525. */
  165526. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165527. if (tmp == 0) tmp = compptr->v_samp_factor;
  165528. compptr->last_row_height = tmp;
  165529. /* Prepare array describing MCU composition */
  165530. cinfo->blocks_in_MCU = 1;
  165531. cinfo->MCU_membership[0] = 0;
  165532. } else {
  165533. /* Interleaved (multi-component) scan */
  165534. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165535. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165536. MAX_COMPS_IN_SCAN);
  165537. /* Overall image size in MCUs */
  165538. cinfo->MCUs_per_row = (JDIMENSION)
  165539. jdiv_round_up((long) cinfo->image_width,
  165540. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165541. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165542. jdiv_round_up((long) cinfo->image_height,
  165543. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165544. cinfo->blocks_in_MCU = 0;
  165545. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165546. compptr = cinfo->cur_comp_info[ci];
  165547. /* Sampling factors give # of blocks of component in each MCU */
  165548. compptr->MCU_width = compptr->h_samp_factor;
  165549. compptr->MCU_height = compptr->v_samp_factor;
  165550. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165551. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  165552. /* Figure number of non-dummy blocks in last MCU column & row */
  165553. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165554. if (tmp == 0) tmp = compptr->MCU_width;
  165555. compptr->last_col_width = tmp;
  165556. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165557. if (tmp == 0) tmp = compptr->MCU_height;
  165558. compptr->last_row_height = tmp;
  165559. /* Prepare array describing MCU composition */
  165560. mcublks = compptr->MCU_blocks;
  165561. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  165562. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165563. while (mcublks-- > 0) {
  165564. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165565. }
  165566. }
  165567. }
  165568. }
  165569. /*
  165570. * Save away a copy of the Q-table referenced by each component present
  165571. * in the current scan, unless already saved during a prior scan.
  165572. *
  165573. * In a multiple-scan JPEG file, the encoder could assign different components
  165574. * the same Q-table slot number, but change table definitions between scans
  165575. * so that each component uses a different Q-table. (The IJG encoder is not
  165576. * currently capable of doing this, but other encoders might.) Since we want
  165577. * to be able to dequantize all the components at the end of the file, this
  165578. * means that we have to save away the table actually used for each component.
  165579. * We do this by copying the table at the start of the first scan containing
  165580. * the component.
  165581. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  165582. * slot between scans of a component using that slot. If the encoder does so
  165583. * anyway, this decoder will simply use the Q-table values that were current
  165584. * at the start of the first scan for the component.
  165585. *
  165586. * The decompressor output side looks only at the saved quant tables,
  165587. * not at the current Q-table slots.
  165588. */
  165589. LOCAL(void)
  165590. latch_quant_tables (j_decompress_ptr cinfo)
  165591. {
  165592. int ci, qtblno;
  165593. jpeg_component_info *compptr;
  165594. JQUANT_TBL * qtbl;
  165595. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165596. compptr = cinfo->cur_comp_info[ci];
  165597. /* No work if we already saved Q-table for this component */
  165598. if (compptr->quant_table != NULL)
  165599. continue;
  165600. /* Make sure specified quantization table is present */
  165601. qtblno = compptr->quant_tbl_no;
  165602. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  165603. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  165604. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  165605. /* OK, save away the quantization table */
  165606. qtbl = (JQUANT_TBL *)
  165607. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165608. SIZEOF(JQUANT_TBL));
  165609. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  165610. compptr->quant_table = qtbl;
  165611. }
  165612. }
  165613. /*
  165614. * Initialize the input modules to read a scan of compressed data.
  165615. * The first call to this is done by jdmaster.c after initializing
  165616. * the entire decompressor (during jpeg_start_decompress).
  165617. * Subsequent calls come from consume_markers, below.
  165618. */
  165619. METHODDEF(void)
  165620. start_input_pass2 (j_decompress_ptr cinfo)
  165621. {
  165622. per_scan_setup2(cinfo);
  165623. latch_quant_tables(cinfo);
  165624. (*cinfo->entropy->start_pass) (cinfo);
  165625. (*cinfo->coef->start_input_pass) (cinfo);
  165626. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  165627. }
  165628. /*
  165629. * Finish up after inputting a compressed-data scan.
  165630. * This is called by the coefficient controller after it's read all
  165631. * the expected data of the scan.
  165632. */
  165633. METHODDEF(void)
  165634. finish_input_pass (j_decompress_ptr cinfo)
  165635. {
  165636. cinfo->inputctl->consume_input = consume_markers;
  165637. }
  165638. /*
  165639. * Read JPEG markers before, between, or after compressed-data scans.
  165640. * Change state as necessary when a new scan is reached.
  165641. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  165642. *
  165643. * The consume_input method pointer points either here or to the
  165644. * coefficient controller's consume_data routine, depending on whether
  165645. * we are reading a compressed data segment or inter-segment markers.
  165646. */
  165647. METHODDEF(int)
  165648. consume_markers (j_decompress_ptr cinfo)
  165649. {
  165650. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  165651. int val;
  165652. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  165653. return JPEG_REACHED_EOI;
  165654. val = (*cinfo->marker->read_markers) (cinfo);
  165655. switch (val) {
  165656. case JPEG_REACHED_SOS: /* Found SOS */
  165657. if (inputctl->inheaders) { /* 1st SOS */
  165658. initial_setup2(cinfo);
  165659. inputctl->inheaders = FALSE;
  165660. /* Note: start_input_pass must be called by jdmaster.c
  165661. * before any more input can be consumed. jdapimin.c is
  165662. * responsible for enforcing this sequencing.
  165663. */
  165664. } else { /* 2nd or later SOS marker */
  165665. if (! inputctl->pub.has_multiple_scans)
  165666. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  165667. start_input_pass2(cinfo);
  165668. }
  165669. break;
  165670. case JPEG_REACHED_EOI: /* Found EOI */
  165671. inputctl->pub.eoi_reached = TRUE;
  165672. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  165673. if (cinfo->marker->saw_SOF)
  165674. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  165675. } else {
  165676. /* Prevent infinite loop in coef ctlr's decompress_data routine
  165677. * if user set output_scan_number larger than number of scans.
  165678. */
  165679. if (cinfo->output_scan_number > cinfo->input_scan_number)
  165680. cinfo->output_scan_number = cinfo->input_scan_number;
  165681. }
  165682. break;
  165683. case JPEG_SUSPENDED:
  165684. break;
  165685. }
  165686. return val;
  165687. }
  165688. /*
  165689. * Reset state to begin a fresh datastream.
  165690. */
  165691. METHODDEF(void)
  165692. reset_input_controller (j_decompress_ptr cinfo)
  165693. {
  165694. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  165695. inputctl->pub.consume_input = consume_markers;
  165696. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  165697. inputctl->pub.eoi_reached = FALSE;
  165698. inputctl->inheaders = TRUE;
  165699. /* Reset other modules */
  165700. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  165701. (*cinfo->marker->reset_marker_reader) (cinfo);
  165702. /* Reset progression state -- would be cleaner if entropy decoder did this */
  165703. cinfo->coef_bits = NULL;
  165704. }
  165705. /*
  165706. * Initialize the input controller module.
  165707. * This is called only once, when the decompression object is created.
  165708. */
  165709. GLOBAL(void)
  165710. jinit_input_controller (j_decompress_ptr cinfo)
  165711. {
  165712. my_inputctl_ptr inputctl;
  165713. /* Create subobject in permanent pool */
  165714. inputctl = (my_inputctl_ptr)
  165715. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165716. SIZEOF(my_input_controller));
  165717. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  165718. /* Initialize method pointers */
  165719. inputctl->pub.consume_input = consume_markers;
  165720. inputctl->pub.reset_input_controller = reset_input_controller;
  165721. inputctl->pub.start_input_pass = start_input_pass2;
  165722. inputctl->pub.finish_input_pass = finish_input_pass;
  165723. /* Initialize state: can't use reset_input_controller since we don't
  165724. * want to try to reset other modules yet.
  165725. */
  165726. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  165727. inputctl->pub.eoi_reached = FALSE;
  165728. inputctl->inheaders = TRUE;
  165729. }
  165730. /********* End of inlined file: jdinput.c *********/
  165731. /********* Start of inlined file: jdmainct.c *********/
  165732. #define JPEG_INTERNALS
  165733. /*
  165734. * In the current system design, the main buffer need never be a full-image
  165735. * buffer; any full-height buffers will be found inside the coefficient or
  165736. * postprocessing controllers. Nonetheless, the main controller is not
  165737. * trivial. Its responsibility is to provide context rows for upsampling/
  165738. * rescaling, and doing this in an efficient fashion is a bit tricky.
  165739. *
  165740. * Postprocessor input data is counted in "row groups". A row group
  165741. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  165742. * sample rows of each component. (We require DCT_scaled_size values to be
  165743. * chosen such that these numbers are integers. In practice DCT_scaled_size
  165744. * values will likely be powers of two, so we actually have the stronger
  165745. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  165746. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  165747. * row group (times any additional scale factor that the upsampler is
  165748. * applying).
  165749. *
  165750. * The coefficient controller will deliver data to us one iMCU row at a time;
  165751. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  165752. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  165753. * to one row of MCUs when the image is fully interleaved.) Note that the
  165754. * number of sample rows varies across components, but the number of row
  165755. * groups does not. Some garbage sample rows may be included in the last iMCU
  165756. * row at the bottom of the image.
  165757. *
  165758. * Depending on the vertical scaling algorithm used, the upsampler may need
  165759. * access to the sample row(s) above and below its current input row group.
  165760. * The upsampler is required to set need_context_rows TRUE at global selection
  165761. * time if so. When need_context_rows is FALSE, this controller can simply
  165762. * obtain one iMCU row at a time from the coefficient controller and dole it
  165763. * out as row groups to the postprocessor.
  165764. *
  165765. * When need_context_rows is TRUE, this controller guarantees that the buffer
  165766. * passed to postprocessing contains at least one row group's worth of samples
  165767. * above and below the row group(s) being processed. Note that the context
  165768. * rows "above" the first passed row group appear at negative row offsets in
  165769. * the passed buffer. At the top and bottom of the image, the required
  165770. * context rows are manufactured by duplicating the first or last real sample
  165771. * row; this avoids having special cases in the upsampling inner loops.
  165772. *
  165773. * The amount of context is fixed at one row group just because that's a
  165774. * convenient number for this controller to work with. The existing
  165775. * upsamplers really only need one sample row of context. An upsampler
  165776. * supporting arbitrary output rescaling might wish for more than one row
  165777. * group of context when shrinking the image; tough, we don't handle that.
  165778. * (This is justified by the assumption that downsizing will be handled mostly
  165779. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  165780. * the upsample step needn't be much less than one.)
  165781. *
  165782. * To provide the desired context, we have to retain the last two row groups
  165783. * of one iMCU row while reading in the next iMCU row. (The last row group
  165784. * can't be processed until we have another row group for its below-context,
  165785. * and so we have to save the next-to-last group too for its above-context.)
  165786. * We could do this most simply by copying data around in our buffer, but
  165787. * that'd be very slow. We can avoid copying any data by creating a rather
  165788. * strange pointer structure. Here's how it works. We allocate a workspace
  165789. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  165790. * of row groups per iMCU row). We create two sets of redundant pointers to
  165791. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  165792. * pointer lists look like this:
  165793. * M+1 M-1
  165794. * master pointer --> 0 master pointer --> 0
  165795. * 1 1
  165796. * ... ...
  165797. * M-3 M-3
  165798. * M-2 M
  165799. * M-1 M+1
  165800. * M M-2
  165801. * M+1 M-1
  165802. * 0 0
  165803. * We read alternate iMCU rows using each master pointer; thus the last two
  165804. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  165805. * The pointer lists are set up so that the required context rows appear to
  165806. * be adjacent to the proper places when we pass the pointer lists to the
  165807. * upsampler.
  165808. *
  165809. * The above pictures describe the normal state of the pointer lists.
  165810. * At top and bottom of the image, we diddle the pointer lists to duplicate
  165811. * the first or last sample row as necessary (this is cheaper than copying
  165812. * sample rows around).
  165813. *
  165814. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  165815. * situation each iMCU row provides only one row group so the buffering logic
  165816. * must be different (eg, we must read two iMCU rows before we can emit the
  165817. * first row group). For now, we simply do not support providing context
  165818. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  165819. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  165820. * want it quick and dirty, so a context-free upsampler is sufficient.
  165821. */
  165822. /* Private buffer controller object */
  165823. typedef struct {
  165824. struct jpeg_d_main_controller pub; /* public fields */
  165825. /* Pointer to allocated workspace (M or M+2 row groups). */
  165826. JSAMPARRAY buffer[MAX_COMPONENTS];
  165827. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  165828. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  165829. /* Remaining fields are only used in the context case. */
  165830. /* These are the master pointers to the funny-order pointer lists. */
  165831. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  165832. int whichptr; /* indicates which pointer set is now in use */
  165833. int context_state; /* process_data state machine status */
  165834. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  165835. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  165836. } my_main_controller4;
  165837. typedef my_main_controller4 * my_main_ptr4;
  165838. /* context_state values: */
  165839. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  165840. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  165841. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  165842. /* Forward declarations */
  165843. METHODDEF(void) process_data_simple_main2
  165844. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  165845. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  165846. METHODDEF(void) process_data_context_main
  165847. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  165848. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  165849. #ifdef QUANT_2PASS_SUPPORTED
  165850. METHODDEF(void) process_data_crank_post
  165851. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  165852. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  165853. #endif
  165854. LOCAL(void)
  165855. alloc_funny_pointers (j_decompress_ptr cinfo)
  165856. /* Allocate space for the funny pointer lists.
  165857. * This is done only once, not once per pass.
  165858. */
  165859. {
  165860. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165861. int ci, rgroup;
  165862. int M = cinfo->min_DCT_scaled_size;
  165863. jpeg_component_info *compptr;
  165864. JSAMPARRAY xbuf;
  165865. /* Get top-level space for component array pointers.
  165866. * We alloc both arrays with one call to save a few cycles.
  165867. */
  165868. main_->xbuffer[0] = (JSAMPIMAGE)
  165869. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165870. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  165871. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  165872. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165873. ci++, compptr++) {
  165874. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165875. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165876. /* Get space for pointer lists --- M+4 row groups in each list.
  165877. * We alloc both pointer lists with one call to save a few cycles.
  165878. */
  165879. xbuf = (JSAMPARRAY)
  165880. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165881. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  165882. xbuf += rgroup; /* want one row group at negative offsets */
  165883. main_->xbuffer[0][ci] = xbuf;
  165884. xbuf += rgroup * (M + 4);
  165885. main_->xbuffer[1][ci] = xbuf;
  165886. }
  165887. }
  165888. LOCAL(void)
  165889. make_funny_pointers (j_decompress_ptr cinfo)
  165890. /* Create the funny pointer lists discussed in the comments above.
  165891. * The actual workspace is already allocated (in main->buffer),
  165892. * and the space for the pointer lists is allocated too.
  165893. * This routine just fills in the curiously ordered lists.
  165894. * This will be repeated at the beginning of each pass.
  165895. */
  165896. {
  165897. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165898. int ci, i, rgroup;
  165899. int M = cinfo->min_DCT_scaled_size;
  165900. jpeg_component_info *compptr;
  165901. JSAMPARRAY buf, xbuf0, xbuf1;
  165902. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165903. ci++, compptr++) {
  165904. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165905. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165906. xbuf0 = main_->xbuffer[0][ci];
  165907. xbuf1 = main_->xbuffer[1][ci];
  165908. /* First copy the workspace pointers as-is */
  165909. buf = main_->buffer[ci];
  165910. for (i = 0; i < rgroup * (M + 2); i++) {
  165911. xbuf0[i] = xbuf1[i] = buf[i];
  165912. }
  165913. /* In the second list, put the last four row groups in swapped order */
  165914. for (i = 0; i < rgroup * 2; i++) {
  165915. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  165916. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  165917. }
  165918. /* The wraparound pointers at top and bottom will be filled later
  165919. * (see set_wraparound_pointers, below). Initially we want the "above"
  165920. * pointers to duplicate the first actual data line. This only needs
  165921. * to happen in xbuffer[0].
  165922. */
  165923. for (i = 0; i < rgroup; i++) {
  165924. xbuf0[i - rgroup] = xbuf0[0];
  165925. }
  165926. }
  165927. }
  165928. LOCAL(void)
  165929. set_wraparound_pointers (j_decompress_ptr cinfo)
  165930. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  165931. * This changes the pointer list state from top-of-image to the normal state.
  165932. */
  165933. {
  165934. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165935. int ci, i, rgroup;
  165936. int M = cinfo->min_DCT_scaled_size;
  165937. jpeg_component_info *compptr;
  165938. JSAMPARRAY xbuf0, xbuf1;
  165939. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165940. ci++, compptr++) {
  165941. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165942. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165943. xbuf0 = main_->xbuffer[0][ci];
  165944. xbuf1 = main_->xbuffer[1][ci];
  165945. for (i = 0; i < rgroup; i++) {
  165946. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  165947. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  165948. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  165949. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  165950. }
  165951. }
  165952. }
  165953. LOCAL(void)
  165954. set_bottom_pointers (j_decompress_ptr cinfo)
  165955. /* Change the pointer lists to duplicate the last sample row at the bottom
  165956. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  165957. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  165958. */
  165959. {
  165960. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165961. int ci, i, rgroup, iMCUheight, rows_left;
  165962. jpeg_component_info *compptr;
  165963. JSAMPARRAY xbuf;
  165964. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165965. ci++, compptr++) {
  165966. /* Count sample rows in one iMCU row and in one row group */
  165967. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  165968. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  165969. /* Count nondummy sample rows remaining for this component */
  165970. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  165971. if (rows_left == 0) rows_left = iMCUheight;
  165972. /* Count nondummy row groups. Should get same answer for each component,
  165973. * so we need only do it once.
  165974. */
  165975. if (ci == 0) {
  165976. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  165977. }
  165978. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  165979. * last partial rowgroup and ensures at least one full rowgroup of context.
  165980. */
  165981. xbuf = main_->xbuffer[main_->whichptr][ci];
  165982. for (i = 0; i < rgroup * 2; i++) {
  165983. xbuf[rows_left + i] = xbuf[rows_left-1];
  165984. }
  165985. }
  165986. }
  165987. /*
  165988. * Initialize for a processing pass.
  165989. */
  165990. METHODDEF(void)
  165991. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  165992. {
  165993. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165994. switch (pass_mode) {
  165995. case JBUF_PASS_THRU:
  165996. if (cinfo->upsample->need_context_rows) {
  165997. main_->pub.process_data = process_data_context_main;
  165998. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  165999. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  166000. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166001. main_->iMCU_row_ctr = 0;
  166002. } else {
  166003. /* Simple case with no context needed */
  166004. main_->pub.process_data = process_data_simple_main2;
  166005. }
  166006. main_->buffer_full = FALSE; /* Mark buffer empty */
  166007. main_->rowgroup_ctr = 0;
  166008. break;
  166009. #ifdef QUANT_2PASS_SUPPORTED
  166010. case JBUF_CRANK_DEST:
  166011. /* For last pass of 2-pass quantization, just crank the postprocessor */
  166012. main_->pub.process_data = process_data_crank_post;
  166013. break;
  166014. #endif
  166015. default:
  166016. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166017. break;
  166018. }
  166019. }
  166020. /*
  166021. * Process some data.
  166022. * This handles the simple case where no context is required.
  166023. */
  166024. METHODDEF(void)
  166025. process_data_simple_main2 (j_decompress_ptr cinfo,
  166026. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166027. JDIMENSION out_rows_avail)
  166028. {
  166029. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166030. JDIMENSION rowgroups_avail;
  166031. /* Read input data if we haven't filled the main buffer yet */
  166032. if (! main_->buffer_full) {
  166033. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  166034. return; /* suspension forced, can do nothing more */
  166035. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166036. }
  166037. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  166038. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  166039. /* Note: at the bottom of the image, we may pass extra garbage row groups
  166040. * to the postprocessor. The postprocessor has to check for bottom
  166041. * of image anyway (at row resolution), so no point in us doing it too.
  166042. */
  166043. /* Feed the postprocessor */
  166044. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  166045. &main_->rowgroup_ctr, rowgroups_avail,
  166046. output_buf, out_row_ctr, out_rows_avail);
  166047. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  166048. if (main_->rowgroup_ctr >= rowgroups_avail) {
  166049. main_->buffer_full = FALSE;
  166050. main_->rowgroup_ctr = 0;
  166051. }
  166052. }
  166053. /*
  166054. * Process some data.
  166055. * This handles the case where context rows must be provided.
  166056. */
  166057. METHODDEF(void)
  166058. process_data_context_main (j_decompress_ptr cinfo,
  166059. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166060. JDIMENSION out_rows_avail)
  166061. {
  166062. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166063. /* Read input data if we haven't filled the main buffer yet */
  166064. if (! main_->buffer_full) {
  166065. if (! (*cinfo->coef->decompress_data) (cinfo,
  166066. main_->xbuffer[main_->whichptr]))
  166067. return; /* suspension forced, can do nothing more */
  166068. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166069. main_->iMCU_row_ctr++; /* count rows received */
  166070. }
  166071. /* Postprocessor typically will not swallow all the input data it is handed
  166072. * in one call (due to filling the output buffer first). Must be prepared
  166073. * to exit and restart. This switch lets us keep track of how far we got.
  166074. * Note that each case falls through to the next on successful completion.
  166075. */
  166076. switch (main_->context_state) {
  166077. case CTX_POSTPONED_ROW:
  166078. /* Call postprocessor using previously set pointers for postponed row */
  166079. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166080. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166081. output_buf, out_row_ctr, out_rows_avail);
  166082. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166083. return; /* Need to suspend */
  166084. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166085. if (*out_row_ctr >= out_rows_avail)
  166086. return; /* Postprocessor exactly filled output buf */
  166087. /*FALLTHROUGH*/
  166088. case CTX_PREPARE_FOR_IMCU:
  166089. /* Prepare to process first M-1 row groups of this iMCU row */
  166090. main_->rowgroup_ctr = 0;
  166091. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  166092. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  166093. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  166094. */
  166095. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  166096. set_bottom_pointers(cinfo);
  166097. main_->context_state = CTX_PROCESS_IMCU;
  166098. /*FALLTHROUGH*/
  166099. case CTX_PROCESS_IMCU:
  166100. /* Call postprocessor using previously set pointers */
  166101. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166102. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166103. output_buf, out_row_ctr, out_rows_avail);
  166104. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166105. return; /* Need to suspend */
  166106. /* After the first iMCU, change wraparound pointers to normal state */
  166107. if (main_->iMCU_row_ctr == 1)
  166108. set_wraparound_pointers(cinfo);
  166109. /* Prepare to load new iMCU row using other xbuffer list */
  166110. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  166111. main_->buffer_full = FALSE;
  166112. /* Still need to process last row group of this iMCU row, */
  166113. /* which is saved at index M+1 of the other xbuffer */
  166114. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  166115. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  166116. main_->context_state = CTX_POSTPONED_ROW;
  166117. }
  166118. }
  166119. /*
  166120. * Process some data.
  166121. * Final pass of two-pass quantization: just call the postprocessor.
  166122. * Source data will be the postprocessor controller's internal buffer.
  166123. */
  166124. #ifdef QUANT_2PASS_SUPPORTED
  166125. METHODDEF(void)
  166126. process_data_crank_post (j_decompress_ptr cinfo,
  166127. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166128. JDIMENSION out_rows_avail)
  166129. {
  166130. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  166131. (JDIMENSION *) NULL, (JDIMENSION) 0,
  166132. output_buf, out_row_ctr, out_rows_avail);
  166133. }
  166134. #endif /* QUANT_2PASS_SUPPORTED */
  166135. /*
  166136. * Initialize main buffer controller.
  166137. */
  166138. GLOBAL(void)
  166139. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  166140. {
  166141. my_main_ptr4 main_;
  166142. int ci, rgroup, ngroups;
  166143. jpeg_component_info *compptr;
  166144. main_ = (my_main_ptr4)
  166145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166146. SIZEOF(my_main_controller4));
  166147. cinfo->main = (struct jpeg_d_main_controller *) main_;
  166148. main_->pub.start_pass = start_pass_main2;
  166149. if (need_full_buffer) /* shouldn't happen */
  166150. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166151. /* Allocate the workspace.
  166152. * ngroups is the number of row groups we need.
  166153. */
  166154. if (cinfo->upsample->need_context_rows) {
  166155. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  166156. ERREXIT(cinfo, JERR_NOTIMPL);
  166157. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  166158. ngroups = cinfo->min_DCT_scaled_size + 2;
  166159. } else {
  166160. ngroups = cinfo->min_DCT_scaled_size;
  166161. }
  166162. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166163. ci++, compptr++) {
  166164. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166165. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166166. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  166167. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166168. compptr->width_in_blocks * compptr->DCT_scaled_size,
  166169. (JDIMENSION) (rgroup * ngroups));
  166170. }
  166171. }
  166172. /********* End of inlined file: jdmainct.c *********/
  166173. /********* Start of inlined file: jdmarker.c *********/
  166174. #define JPEG_INTERNALS
  166175. /* Private state */
  166176. typedef struct {
  166177. struct jpeg_marker_reader pub; /* public fields */
  166178. /* Application-overridable marker processing methods */
  166179. jpeg_marker_parser_method process_COM;
  166180. jpeg_marker_parser_method process_APPn[16];
  166181. /* Limit on marker data length to save for each marker type */
  166182. unsigned int length_limit_COM;
  166183. unsigned int length_limit_APPn[16];
  166184. /* Status of COM/APPn marker saving */
  166185. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  166186. unsigned int bytes_read; /* data bytes read so far in marker */
  166187. /* Note: cur_marker is not linked into marker_list until it's all read. */
  166188. } my_marker_reader;
  166189. typedef my_marker_reader * my_marker_ptr2;
  166190. /*
  166191. * Macros for fetching data from the data source module.
  166192. *
  166193. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  166194. * the current restart point; we update them only when we have reached a
  166195. * suitable place to restart if a suspension occurs.
  166196. */
  166197. /* Declare and initialize local copies of input pointer/count */
  166198. #define INPUT_VARS(cinfo) \
  166199. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  166200. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  166201. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  166202. /* Unload the local copies --- do this only at a restart boundary */
  166203. #define INPUT_SYNC(cinfo) \
  166204. ( datasrc->next_input_byte = next_input_byte, \
  166205. datasrc->bytes_in_buffer = bytes_in_buffer )
  166206. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  166207. #define INPUT_RELOAD(cinfo) \
  166208. ( next_input_byte = datasrc->next_input_byte, \
  166209. bytes_in_buffer = datasrc->bytes_in_buffer )
  166210. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  166211. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  166212. * but we must reload the local copies after a successful fill.
  166213. */
  166214. #define MAKE_BYTE_AVAIL(cinfo,action) \
  166215. if (bytes_in_buffer == 0) { \
  166216. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  166217. { action; } \
  166218. INPUT_RELOAD(cinfo); \
  166219. }
  166220. /* Read a byte into variable V.
  166221. * If must suspend, take the specified action (typically "return FALSE").
  166222. */
  166223. #define INPUT_BYTE(cinfo,V,action) \
  166224. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166225. bytes_in_buffer--; \
  166226. V = GETJOCTET(*next_input_byte++); )
  166227. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  166228. * V should be declared unsigned int or perhaps INT32.
  166229. */
  166230. #define INPUT_2BYTES(cinfo,V,action) \
  166231. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166232. bytes_in_buffer--; \
  166233. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  166234. MAKE_BYTE_AVAIL(cinfo,action); \
  166235. bytes_in_buffer--; \
  166236. V += GETJOCTET(*next_input_byte++); )
  166237. /*
  166238. * Routines to process JPEG markers.
  166239. *
  166240. * Entry condition: JPEG marker itself has been read and its code saved
  166241. * in cinfo->unread_marker; input restart point is just after the marker.
  166242. *
  166243. * Exit: if return TRUE, have read and processed any parameters, and have
  166244. * updated the restart point to point after the parameters.
  166245. * If return FALSE, was forced to suspend before reaching end of
  166246. * marker parameters; restart point has not been moved. Same routine
  166247. * will be called again after application supplies more input data.
  166248. *
  166249. * This approach to suspension assumes that all of a marker's parameters
  166250. * can fit into a single input bufferload. This should hold for "normal"
  166251. * markers. Some COM/APPn markers might have large parameter segments
  166252. * that might not fit. If we are simply dropping such a marker, we use
  166253. * skip_input_data to get past it, and thereby put the problem on the
  166254. * source manager's shoulders. If we are saving the marker's contents
  166255. * into memory, we use a slightly different convention: when forced to
  166256. * suspend, the marker processor updates the restart point to the end of
  166257. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  166258. * On resumption, cinfo->unread_marker still contains the marker code,
  166259. * but the data source will point to the next chunk of marker data.
  166260. * The marker processor must retain internal state to deal with this.
  166261. *
  166262. * Note that we don't bother to avoid duplicate trace messages if a
  166263. * suspension occurs within marker parameters. Other side effects
  166264. * require more care.
  166265. */
  166266. LOCAL(boolean)
  166267. get_soi (j_decompress_ptr cinfo)
  166268. /* Process an SOI marker */
  166269. {
  166270. int i;
  166271. TRACEMS(cinfo, 1, JTRC_SOI);
  166272. if (cinfo->marker->saw_SOI)
  166273. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  166274. /* Reset all parameters that are defined to be reset by SOI */
  166275. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  166276. cinfo->arith_dc_L[i] = 0;
  166277. cinfo->arith_dc_U[i] = 1;
  166278. cinfo->arith_ac_K[i] = 5;
  166279. }
  166280. cinfo->restart_interval = 0;
  166281. /* Set initial assumptions for colorspace etc */
  166282. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166283. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  166284. cinfo->saw_JFIF_marker = FALSE;
  166285. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  166286. cinfo->JFIF_minor_version = 1;
  166287. cinfo->density_unit = 0;
  166288. cinfo->X_density = 1;
  166289. cinfo->Y_density = 1;
  166290. cinfo->saw_Adobe_marker = FALSE;
  166291. cinfo->Adobe_transform = 0;
  166292. cinfo->marker->saw_SOI = TRUE;
  166293. return TRUE;
  166294. }
  166295. LOCAL(boolean)
  166296. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  166297. /* Process a SOFn marker */
  166298. {
  166299. INT32 length;
  166300. int c, ci;
  166301. jpeg_component_info * compptr;
  166302. INPUT_VARS(cinfo);
  166303. cinfo->progressive_mode = is_prog;
  166304. cinfo->arith_code = is_arith;
  166305. INPUT_2BYTES(cinfo, length, return FALSE);
  166306. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  166307. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  166308. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  166309. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  166310. length -= 8;
  166311. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  166312. (int) cinfo->image_width, (int) cinfo->image_height,
  166313. cinfo->num_components);
  166314. if (cinfo->marker->saw_SOF)
  166315. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  166316. /* We don't support files in which the image height is initially specified */
  166317. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  166318. /* might as well have a general sanity check. */
  166319. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  166320. || cinfo->num_components <= 0)
  166321. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  166322. if (length != (cinfo->num_components * 3))
  166323. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166324. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  166325. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  166326. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166327. cinfo->num_components * SIZEOF(jpeg_component_info));
  166328. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166329. ci++, compptr++) {
  166330. compptr->component_index = ci;
  166331. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  166332. INPUT_BYTE(cinfo, c, return FALSE);
  166333. compptr->h_samp_factor = (c >> 4) & 15;
  166334. compptr->v_samp_factor = (c ) & 15;
  166335. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  166336. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  166337. compptr->component_id, compptr->h_samp_factor,
  166338. compptr->v_samp_factor, compptr->quant_tbl_no);
  166339. }
  166340. cinfo->marker->saw_SOF = TRUE;
  166341. INPUT_SYNC(cinfo);
  166342. return TRUE;
  166343. }
  166344. LOCAL(boolean)
  166345. get_sos (j_decompress_ptr cinfo)
  166346. /* Process a SOS marker */
  166347. {
  166348. INT32 length;
  166349. int i, ci, n, c, cc;
  166350. jpeg_component_info * compptr;
  166351. INPUT_VARS(cinfo);
  166352. if (! cinfo->marker->saw_SOF)
  166353. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  166354. INPUT_2BYTES(cinfo, length, return FALSE);
  166355. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  166356. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  166357. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  166358. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166359. cinfo->comps_in_scan = n;
  166360. /* Collect the component-spec parameters */
  166361. for (i = 0; i < n; i++) {
  166362. INPUT_BYTE(cinfo, cc, return FALSE);
  166363. INPUT_BYTE(cinfo, c, return FALSE);
  166364. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166365. ci++, compptr++) {
  166366. if (cc == compptr->component_id)
  166367. goto id_found;
  166368. }
  166369. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  166370. id_found:
  166371. cinfo->cur_comp_info[i] = compptr;
  166372. compptr->dc_tbl_no = (c >> 4) & 15;
  166373. compptr->ac_tbl_no = (c ) & 15;
  166374. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  166375. compptr->dc_tbl_no, compptr->ac_tbl_no);
  166376. }
  166377. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  166378. INPUT_BYTE(cinfo, c, return FALSE);
  166379. cinfo->Ss = c;
  166380. INPUT_BYTE(cinfo, c, return FALSE);
  166381. cinfo->Se = c;
  166382. INPUT_BYTE(cinfo, c, return FALSE);
  166383. cinfo->Ah = (c >> 4) & 15;
  166384. cinfo->Al = (c ) & 15;
  166385. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  166386. cinfo->Ah, cinfo->Al);
  166387. /* Prepare to scan data & restart markers */
  166388. cinfo->marker->next_restart_num = 0;
  166389. /* Count another SOS marker */
  166390. cinfo->input_scan_number++;
  166391. INPUT_SYNC(cinfo);
  166392. return TRUE;
  166393. }
  166394. #ifdef D_ARITH_CODING_SUPPORTED
  166395. LOCAL(boolean)
  166396. get_dac (j_decompress_ptr cinfo)
  166397. /* Process a DAC marker */
  166398. {
  166399. INT32 length;
  166400. int index, val;
  166401. INPUT_VARS(cinfo);
  166402. INPUT_2BYTES(cinfo, length, return FALSE);
  166403. length -= 2;
  166404. while (length > 0) {
  166405. INPUT_BYTE(cinfo, index, return FALSE);
  166406. INPUT_BYTE(cinfo, val, return FALSE);
  166407. length -= 2;
  166408. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  166409. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  166410. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  166411. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  166412. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  166413. } else { /* define DC table */
  166414. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  166415. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  166416. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  166417. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  166418. }
  166419. }
  166420. if (length != 0)
  166421. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166422. INPUT_SYNC(cinfo);
  166423. return TRUE;
  166424. }
  166425. #else /* ! D_ARITH_CODING_SUPPORTED */
  166426. #define get_dac(cinfo) skip_variable(cinfo)
  166427. #endif /* D_ARITH_CODING_SUPPORTED */
  166428. LOCAL(boolean)
  166429. get_dht (j_decompress_ptr cinfo)
  166430. /* Process a DHT marker */
  166431. {
  166432. INT32 length;
  166433. UINT8 bits[17];
  166434. UINT8 huffval[256];
  166435. int i, index, count;
  166436. JHUFF_TBL **htblptr;
  166437. INPUT_VARS(cinfo);
  166438. INPUT_2BYTES(cinfo, length, return FALSE);
  166439. length -= 2;
  166440. while (length > 16) {
  166441. INPUT_BYTE(cinfo, index, return FALSE);
  166442. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  166443. bits[0] = 0;
  166444. count = 0;
  166445. for (i = 1; i <= 16; i++) {
  166446. INPUT_BYTE(cinfo, bits[i], return FALSE);
  166447. count += bits[i];
  166448. }
  166449. length -= 1 + 16;
  166450. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  166451. bits[1], bits[2], bits[3], bits[4],
  166452. bits[5], bits[6], bits[7], bits[8]);
  166453. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  166454. bits[9], bits[10], bits[11], bits[12],
  166455. bits[13], bits[14], bits[15], bits[16]);
  166456. /* Here we just do minimal validation of the counts to avoid walking
  166457. * off the end of our table space. jdhuff.c will check more carefully.
  166458. */
  166459. if (count > 256 || ((INT32) count) > length)
  166460. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166461. for (i = 0; i < count; i++)
  166462. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  166463. length -= count;
  166464. if (index & 0x10) { /* AC table definition */
  166465. index -= 0x10;
  166466. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  166467. } else { /* DC table definition */
  166468. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  166469. }
  166470. if (index < 0 || index >= NUM_HUFF_TBLS)
  166471. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  166472. if (*htblptr == NULL)
  166473. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166474. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  166475. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  166476. }
  166477. if (length != 0)
  166478. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166479. INPUT_SYNC(cinfo);
  166480. return TRUE;
  166481. }
  166482. LOCAL(boolean)
  166483. get_dqt (j_decompress_ptr cinfo)
  166484. /* Process a DQT marker */
  166485. {
  166486. INT32 length;
  166487. int n, i, prec;
  166488. unsigned int tmp;
  166489. JQUANT_TBL *quant_ptr;
  166490. INPUT_VARS(cinfo);
  166491. INPUT_2BYTES(cinfo, length, return FALSE);
  166492. length -= 2;
  166493. while (length > 0) {
  166494. INPUT_BYTE(cinfo, n, return FALSE);
  166495. prec = n >> 4;
  166496. n &= 0x0F;
  166497. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  166498. if (n >= NUM_QUANT_TBLS)
  166499. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  166500. if (cinfo->quant_tbl_ptrs[n] == NULL)
  166501. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  166502. quant_ptr = cinfo->quant_tbl_ptrs[n];
  166503. for (i = 0; i < DCTSIZE2; i++) {
  166504. if (prec)
  166505. INPUT_2BYTES(cinfo, tmp, return FALSE);
  166506. else
  166507. INPUT_BYTE(cinfo, tmp, return FALSE);
  166508. /* We convert the zigzag-order table to natural array order. */
  166509. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  166510. }
  166511. if (cinfo->err->trace_level >= 2) {
  166512. for (i = 0; i < DCTSIZE2; i += 8) {
  166513. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  166514. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  166515. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  166516. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  166517. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  166518. }
  166519. }
  166520. length -= DCTSIZE2+1;
  166521. if (prec) length -= DCTSIZE2;
  166522. }
  166523. if (length != 0)
  166524. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166525. INPUT_SYNC(cinfo);
  166526. return TRUE;
  166527. }
  166528. LOCAL(boolean)
  166529. get_dri (j_decompress_ptr cinfo)
  166530. /* Process a DRI marker */
  166531. {
  166532. INT32 length;
  166533. unsigned int tmp;
  166534. INPUT_VARS(cinfo);
  166535. INPUT_2BYTES(cinfo, length, return FALSE);
  166536. if (length != 4)
  166537. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166538. INPUT_2BYTES(cinfo, tmp, return FALSE);
  166539. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  166540. cinfo->restart_interval = tmp;
  166541. INPUT_SYNC(cinfo);
  166542. return TRUE;
  166543. }
  166544. /*
  166545. * Routines for processing APPn and COM markers.
  166546. * These are either saved in memory or discarded, per application request.
  166547. * APP0 and APP14 are specially checked to see if they are
  166548. * JFIF and Adobe markers, respectively.
  166549. */
  166550. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  166551. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  166552. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  166553. LOCAL(void)
  166554. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  166555. unsigned int datalen, INT32 remaining)
  166556. /* Examine first few bytes from an APP0.
  166557. * Take appropriate action if it is a JFIF marker.
  166558. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  166559. */
  166560. {
  166561. INT32 totallen = (INT32) datalen + remaining;
  166562. if (datalen >= APP0_DATA_LEN &&
  166563. GETJOCTET(data[0]) == 0x4A &&
  166564. GETJOCTET(data[1]) == 0x46 &&
  166565. GETJOCTET(data[2]) == 0x49 &&
  166566. GETJOCTET(data[3]) == 0x46 &&
  166567. GETJOCTET(data[4]) == 0) {
  166568. /* Found JFIF APP0 marker: save info */
  166569. cinfo->saw_JFIF_marker = TRUE;
  166570. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  166571. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  166572. cinfo->density_unit = GETJOCTET(data[7]);
  166573. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  166574. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  166575. /* Check version.
  166576. * Major version must be 1, anything else signals an incompatible change.
  166577. * (We used to treat this as an error, but now it's a nonfatal warning,
  166578. * because some bozo at Hijaak couldn't read the spec.)
  166579. * Minor version should be 0..2, but process anyway if newer.
  166580. */
  166581. if (cinfo->JFIF_major_version != 1)
  166582. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  166583. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  166584. /* Generate trace messages */
  166585. TRACEMS5(cinfo, 1, JTRC_JFIF,
  166586. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  166587. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  166588. /* Validate thumbnail dimensions and issue appropriate messages */
  166589. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  166590. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  166591. GETJOCTET(data[12]), GETJOCTET(data[13]));
  166592. totallen -= APP0_DATA_LEN;
  166593. if (totallen !=
  166594. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  166595. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  166596. } else if (datalen >= 6 &&
  166597. GETJOCTET(data[0]) == 0x4A &&
  166598. GETJOCTET(data[1]) == 0x46 &&
  166599. GETJOCTET(data[2]) == 0x58 &&
  166600. GETJOCTET(data[3]) == 0x58 &&
  166601. GETJOCTET(data[4]) == 0) {
  166602. /* Found JFIF "JFXX" extension APP0 marker */
  166603. /* The library doesn't actually do anything with these,
  166604. * but we try to produce a helpful trace message.
  166605. */
  166606. switch (GETJOCTET(data[5])) {
  166607. case 0x10:
  166608. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  166609. break;
  166610. case 0x11:
  166611. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  166612. break;
  166613. case 0x13:
  166614. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  166615. break;
  166616. default:
  166617. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  166618. GETJOCTET(data[5]), (int) totallen);
  166619. break;
  166620. }
  166621. } else {
  166622. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  166623. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  166624. }
  166625. }
  166626. LOCAL(void)
  166627. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  166628. unsigned int datalen, INT32 remaining)
  166629. /* Examine first few bytes from an APP14.
  166630. * Take appropriate action if it is an Adobe marker.
  166631. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  166632. */
  166633. {
  166634. unsigned int version, flags0, flags1, transform;
  166635. if (datalen >= APP14_DATA_LEN &&
  166636. GETJOCTET(data[0]) == 0x41 &&
  166637. GETJOCTET(data[1]) == 0x64 &&
  166638. GETJOCTET(data[2]) == 0x6F &&
  166639. GETJOCTET(data[3]) == 0x62 &&
  166640. GETJOCTET(data[4]) == 0x65) {
  166641. /* Found Adobe APP14 marker */
  166642. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  166643. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  166644. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  166645. transform = GETJOCTET(data[11]);
  166646. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  166647. cinfo->saw_Adobe_marker = TRUE;
  166648. cinfo->Adobe_transform = (UINT8) transform;
  166649. } else {
  166650. /* Start of APP14 does not match "Adobe", or too short */
  166651. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  166652. }
  166653. }
  166654. METHODDEF(boolean)
  166655. get_interesting_appn (j_decompress_ptr cinfo)
  166656. /* Process an APP0 or APP14 marker without saving it */
  166657. {
  166658. INT32 length;
  166659. JOCTET b[APPN_DATA_LEN];
  166660. unsigned int i, numtoread;
  166661. INPUT_VARS(cinfo);
  166662. INPUT_2BYTES(cinfo, length, return FALSE);
  166663. length -= 2;
  166664. /* get the interesting part of the marker data */
  166665. if (length >= APPN_DATA_LEN)
  166666. numtoread = APPN_DATA_LEN;
  166667. else if (length > 0)
  166668. numtoread = (unsigned int) length;
  166669. else
  166670. numtoread = 0;
  166671. for (i = 0; i < numtoread; i++)
  166672. INPUT_BYTE(cinfo, b[i], return FALSE);
  166673. length -= numtoread;
  166674. /* process it */
  166675. switch (cinfo->unread_marker) {
  166676. case M_APP0:
  166677. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  166678. break;
  166679. case M_APP14:
  166680. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  166681. break;
  166682. default:
  166683. /* can't get here unless jpeg_save_markers chooses wrong processor */
  166684. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  166685. break;
  166686. }
  166687. /* skip any remaining data -- could be lots */
  166688. INPUT_SYNC(cinfo);
  166689. if (length > 0)
  166690. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  166691. return TRUE;
  166692. }
  166693. #ifdef SAVE_MARKERS_SUPPORTED
  166694. METHODDEF(boolean)
  166695. save_marker (j_decompress_ptr cinfo)
  166696. /* Save an APPn or COM marker into the marker list */
  166697. {
  166698. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166699. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  166700. unsigned int bytes_read, data_length;
  166701. JOCTET FAR * data;
  166702. INT32 length = 0;
  166703. INPUT_VARS(cinfo);
  166704. if (cur_marker == NULL) {
  166705. /* begin reading a marker */
  166706. INPUT_2BYTES(cinfo, length, return FALSE);
  166707. length -= 2;
  166708. if (length >= 0) { /* watch out for bogus length word */
  166709. /* figure out how much we want to save */
  166710. unsigned int limit;
  166711. if (cinfo->unread_marker == (int) M_COM)
  166712. limit = marker->length_limit_COM;
  166713. else
  166714. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  166715. if ((unsigned int) length < limit)
  166716. limit = (unsigned int) length;
  166717. /* allocate and initialize the marker item */
  166718. cur_marker = (jpeg_saved_marker_ptr)
  166719. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166720. SIZEOF(struct jpeg_marker_struct) + limit);
  166721. cur_marker->next = NULL;
  166722. cur_marker->marker = (UINT8) cinfo->unread_marker;
  166723. cur_marker->original_length = (unsigned int) length;
  166724. cur_marker->data_length = limit;
  166725. /* data area is just beyond the jpeg_marker_struct */
  166726. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  166727. marker->cur_marker = cur_marker;
  166728. marker->bytes_read = 0;
  166729. bytes_read = 0;
  166730. data_length = limit;
  166731. } else {
  166732. /* deal with bogus length word */
  166733. bytes_read = data_length = 0;
  166734. data = NULL;
  166735. }
  166736. } else {
  166737. /* resume reading a marker */
  166738. bytes_read = marker->bytes_read;
  166739. data_length = cur_marker->data_length;
  166740. data = cur_marker->data + bytes_read;
  166741. }
  166742. while (bytes_read < data_length) {
  166743. INPUT_SYNC(cinfo); /* move the restart point to here */
  166744. marker->bytes_read = bytes_read;
  166745. /* If there's not at least one byte in buffer, suspend */
  166746. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  166747. /* Copy bytes with reasonable rapidity */
  166748. while (bytes_read < data_length && bytes_in_buffer > 0) {
  166749. *data++ = *next_input_byte++;
  166750. bytes_in_buffer--;
  166751. bytes_read++;
  166752. }
  166753. }
  166754. /* Done reading what we want to read */
  166755. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  166756. /* Add new marker to end of list */
  166757. if (cinfo->marker_list == NULL) {
  166758. cinfo->marker_list = cur_marker;
  166759. } else {
  166760. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  166761. while (prev->next != NULL)
  166762. prev = prev->next;
  166763. prev->next = cur_marker;
  166764. }
  166765. /* Reset pointer & calc remaining data length */
  166766. data = cur_marker->data;
  166767. length = cur_marker->original_length - data_length;
  166768. }
  166769. /* Reset to initial state for next marker */
  166770. marker->cur_marker = NULL;
  166771. /* Process the marker if interesting; else just make a generic trace msg */
  166772. switch (cinfo->unread_marker) {
  166773. case M_APP0:
  166774. examine_app0(cinfo, data, data_length, length);
  166775. break;
  166776. case M_APP14:
  166777. examine_app14(cinfo, data, data_length, length);
  166778. break;
  166779. default:
  166780. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  166781. (int) (data_length + length));
  166782. break;
  166783. }
  166784. /* skip any remaining data -- could be lots */
  166785. INPUT_SYNC(cinfo); /* do before skip_input_data */
  166786. if (length > 0)
  166787. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  166788. return TRUE;
  166789. }
  166790. #endif /* SAVE_MARKERS_SUPPORTED */
  166791. METHODDEF(boolean)
  166792. skip_variable (j_decompress_ptr cinfo)
  166793. /* Skip over an unknown or uninteresting variable-length marker */
  166794. {
  166795. INT32 length;
  166796. INPUT_VARS(cinfo);
  166797. INPUT_2BYTES(cinfo, length, return FALSE);
  166798. length -= 2;
  166799. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  166800. INPUT_SYNC(cinfo); /* do before skip_input_data */
  166801. if (length > 0)
  166802. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  166803. return TRUE;
  166804. }
  166805. /*
  166806. * Find the next JPEG marker, save it in cinfo->unread_marker.
  166807. * Returns FALSE if had to suspend before reaching a marker;
  166808. * in that case cinfo->unread_marker is unchanged.
  166809. *
  166810. * Note that the result might not be a valid marker code,
  166811. * but it will never be 0 or FF.
  166812. */
  166813. LOCAL(boolean)
  166814. next_marker (j_decompress_ptr cinfo)
  166815. {
  166816. int c;
  166817. INPUT_VARS(cinfo);
  166818. for (;;) {
  166819. INPUT_BYTE(cinfo, c, return FALSE);
  166820. /* Skip any non-FF bytes.
  166821. * This may look a bit inefficient, but it will not occur in a valid file.
  166822. * We sync after each discarded byte so that a suspending data source
  166823. * can discard the byte from its buffer.
  166824. */
  166825. while (c != 0xFF) {
  166826. cinfo->marker->discarded_bytes++;
  166827. INPUT_SYNC(cinfo);
  166828. INPUT_BYTE(cinfo, c, return FALSE);
  166829. }
  166830. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  166831. * pad bytes, so don't count them in discarded_bytes. We assume there
  166832. * will not be so many consecutive FF bytes as to overflow a suspending
  166833. * data source's input buffer.
  166834. */
  166835. do {
  166836. INPUT_BYTE(cinfo, c, return FALSE);
  166837. } while (c == 0xFF);
  166838. if (c != 0)
  166839. break; /* found a valid marker, exit loop */
  166840. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  166841. * Discard it and loop back to try again.
  166842. */
  166843. cinfo->marker->discarded_bytes += 2;
  166844. INPUT_SYNC(cinfo);
  166845. }
  166846. if (cinfo->marker->discarded_bytes != 0) {
  166847. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  166848. cinfo->marker->discarded_bytes = 0;
  166849. }
  166850. cinfo->unread_marker = c;
  166851. INPUT_SYNC(cinfo);
  166852. return TRUE;
  166853. }
  166854. LOCAL(boolean)
  166855. first_marker (j_decompress_ptr cinfo)
  166856. /* Like next_marker, but used to obtain the initial SOI marker. */
  166857. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  166858. * we might well scan an entire input file before realizing it ain't JPEG.
  166859. * If an application wants to process non-JFIF files, it must seek to the
  166860. * SOI before calling the JPEG library.
  166861. */
  166862. {
  166863. int c, c2;
  166864. INPUT_VARS(cinfo);
  166865. INPUT_BYTE(cinfo, c, return FALSE);
  166866. INPUT_BYTE(cinfo, c2, return FALSE);
  166867. if (c != 0xFF || c2 != (int) M_SOI)
  166868. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  166869. cinfo->unread_marker = c2;
  166870. INPUT_SYNC(cinfo);
  166871. return TRUE;
  166872. }
  166873. /*
  166874. * Read markers until SOS or EOI.
  166875. *
  166876. * Returns same codes as are defined for jpeg_consume_input:
  166877. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  166878. */
  166879. METHODDEF(int)
  166880. read_markers (j_decompress_ptr cinfo)
  166881. {
  166882. /* Outer loop repeats once for each marker. */
  166883. for (;;) {
  166884. /* Collect the marker proper, unless we already did. */
  166885. /* NB: first_marker() enforces the requirement that SOI appear first. */
  166886. if (cinfo->unread_marker == 0) {
  166887. if (! cinfo->marker->saw_SOI) {
  166888. if (! first_marker(cinfo))
  166889. return JPEG_SUSPENDED;
  166890. } else {
  166891. if (! next_marker(cinfo))
  166892. return JPEG_SUSPENDED;
  166893. }
  166894. }
  166895. /* At this point cinfo->unread_marker contains the marker code and the
  166896. * input point is just past the marker proper, but before any parameters.
  166897. * A suspension will cause us to return with this state still true.
  166898. */
  166899. switch (cinfo->unread_marker) {
  166900. case M_SOI:
  166901. if (! get_soi(cinfo))
  166902. return JPEG_SUSPENDED;
  166903. break;
  166904. case M_SOF0: /* Baseline */
  166905. case M_SOF1: /* Extended sequential, Huffman */
  166906. if (! get_sof(cinfo, FALSE, FALSE))
  166907. return JPEG_SUSPENDED;
  166908. break;
  166909. case M_SOF2: /* Progressive, Huffman */
  166910. if (! get_sof(cinfo, TRUE, FALSE))
  166911. return JPEG_SUSPENDED;
  166912. break;
  166913. case M_SOF9: /* Extended sequential, arithmetic */
  166914. if (! get_sof(cinfo, FALSE, TRUE))
  166915. return JPEG_SUSPENDED;
  166916. break;
  166917. case M_SOF10: /* Progressive, arithmetic */
  166918. if (! get_sof(cinfo, TRUE, TRUE))
  166919. return JPEG_SUSPENDED;
  166920. break;
  166921. /* Currently unsupported SOFn types */
  166922. case M_SOF3: /* Lossless, Huffman */
  166923. case M_SOF5: /* Differential sequential, Huffman */
  166924. case M_SOF6: /* Differential progressive, Huffman */
  166925. case M_SOF7: /* Differential lossless, Huffman */
  166926. case M_JPG: /* Reserved for JPEG extensions */
  166927. case M_SOF11: /* Lossless, arithmetic */
  166928. case M_SOF13: /* Differential sequential, arithmetic */
  166929. case M_SOF14: /* Differential progressive, arithmetic */
  166930. case M_SOF15: /* Differential lossless, arithmetic */
  166931. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  166932. break;
  166933. case M_SOS:
  166934. if (! get_sos(cinfo))
  166935. return JPEG_SUSPENDED;
  166936. cinfo->unread_marker = 0; /* processed the marker */
  166937. return JPEG_REACHED_SOS;
  166938. case M_EOI:
  166939. TRACEMS(cinfo, 1, JTRC_EOI);
  166940. cinfo->unread_marker = 0; /* processed the marker */
  166941. return JPEG_REACHED_EOI;
  166942. case M_DAC:
  166943. if (! get_dac(cinfo))
  166944. return JPEG_SUSPENDED;
  166945. break;
  166946. case M_DHT:
  166947. if (! get_dht(cinfo))
  166948. return JPEG_SUSPENDED;
  166949. break;
  166950. case M_DQT:
  166951. if (! get_dqt(cinfo))
  166952. return JPEG_SUSPENDED;
  166953. break;
  166954. case M_DRI:
  166955. if (! get_dri(cinfo))
  166956. return JPEG_SUSPENDED;
  166957. break;
  166958. case M_APP0:
  166959. case M_APP1:
  166960. case M_APP2:
  166961. case M_APP3:
  166962. case M_APP4:
  166963. case M_APP5:
  166964. case M_APP6:
  166965. case M_APP7:
  166966. case M_APP8:
  166967. case M_APP9:
  166968. case M_APP10:
  166969. case M_APP11:
  166970. case M_APP12:
  166971. case M_APP13:
  166972. case M_APP14:
  166973. case M_APP15:
  166974. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  166975. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  166976. return JPEG_SUSPENDED;
  166977. break;
  166978. case M_COM:
  166979. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  166980. return JPEG_SUSPENDED;
  166981. break;
  166982. case M_RST0: /* these are all parameterless */
  166983. case M_RST1:
  166984. case M_RST2:
  166985. case M_RST3:
  166986. case M_RST4:
  166987. case M_RST5:
  166988. case M_RST6:
  166989. case M_RST7:
  166990. case M_TEM:
  166991. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  166992. break;
  166993. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  166994. if (! skip_variable(cinfo))
  166995. return JPEG_SUSPENDED;
  166996. break;
  166997. default: /* must be DHP, EXP, JPGn, or RESn */
  166998. /* For now, we treat the reserved markers as fatal errors since they are
  166999. * likely to be used to signal incompatible JPEG Part 3 extensions.
  167000. * Once the JPEG 3 version-number marker is well defined, this code
  167001. * ought to change!
  167002. */
  167003. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167004. break;
  167005. }
  167006. /* Successfully processed marker, so reset state variable */
  167007. cinfo->unread_marker = 0;
  167008. } /* end loop */
  167009. }
  167010. /*
  167011. * Read a restart marker, which is expected to appear next in the datastream;
  167012. * if the marker is not there, take appropriate recovery action.
  167013. * Returns FALSE if suspension is required.
  167014. *
  167015. * This is called by the entropy decoder after it has read an appropriate
  167016. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  167017. * has already read a marker from the data source. Under normal conditions
  167018. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  167019. * it holds a marker which the decoder will be unable to read past.
  167020. */
  167021. METHODDEF(boolean)
  167022. read_restart_marker (j_decompress_ptr cinfo)
  167023. {
  167024. /* Obtain a marker unless we already did. */
  167025. /* Note that next_marker will complain if it skips any data. */
  167026. if (cinfo->unread_marker == 0) {
  167027. if (! next_marker(cinfo))
  167028. return FALSE;
  167029. }
  167030. if (cinfo->unread_marker ==
  167031. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  167032. /* Normal case --- swallow the marker and let entropy decoder continue */
  167033. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  167034. cinfo->unread_marker = 0;
  167035. } else {
  167036. /* Uh-oh, the restart markers have been messed up. */
  167037. /* Let the data source manager determine how to resync. */
  167038. if (! (*cinfo->src->resync_to_restart) (cinfo,
  167039. cinfo->marker->next_restart_num))
  167040. return FALSE;
  167041. }
  167042. /* Update next-restart state */
  167043. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  167044. return TRUE;
  167045. }
  167046. /*
  167047. * This is the default resync_to_restart method for data source managers
  167048. * to use if they don't have any better approach. Some data source managers
  167049. * may be able to back up, or may have additional knowledge about the data
  167050. * which permits a more intelligent recovery strategy; such managers would
  167051. * presumably supply their own resync method.
  167052. *
  167053. * read_restart_marker calls resync_to_restart if it finds a marker other than
  167054. * the restart marker it was expecting. (This code is *not* used unless
  167055. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  167056. * the marker code actually found (might be anything, except 0 or FF).
  167057. * The desired restart marker number (0..7) is passed as a parameter.
  167058. * This routine is supposed to apply whatever error recovery strategy seems
  167059. * appropriate in order to position the input stream to the next data segment.
  167060. * Note that cinfo->unread_marker is treated as a marker appearing before
  167061. * the current data-source input point; usually it should be reset to zero
  167062. * before returning.
  167063. * Returns FALSE if suspension is required.
  167064. *
  167065. * This implementation is substantially constrained by wanting to treat the
  167066. * input as a data stream; this means we can't back up. Therefore, we have
  167067. * only the following actions to work with:
  167068. * 1. Simply discard the marker and let the entropy decoder resume at next
  167069. * byte of file.
  167070. * 2. Read forward until we find another marker, discarding intervening
  167071. * data. (In theory we could look ahead within the current bufferload,
  167072. * without having to discard data if we don't find the desired marker.
  167073. * This idea is not implemented here, in part because it makes behavior
  167074. * dependent on buffer size and chance buffer-boundary positions.)
  167075. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  167076. * This will cause the entropy decoder to process an empty data segment,
  167077. * inserting dummy zeroes, and then we will reprocess the marker.
  167078. *
  167079. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  167080. * appropriate if the found marker is a future restart marker (indicating
  167081. * that we have missed the desired restart marker, probably because it got
  167082. * corrupted).
  167083. * We apply #2 or #3 if the found marker is a restart marker no more than
  167084. * two counts behind or ahead of the expected one. We also apply #2 if the
  167085. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  167086. * If the found marker is a restart marker more than 2 counts away, we do #1
  167087. * (too much risk that the marker is erroneous; with luck we will be able to
  167088. * resync at some future point).
  167089. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  167090. * overrunning the end of a scan. An implementation limited to single-scan
  167091. * files might find it better to apply #2 for markers other than EOI, since
  167092. * any other marker would have to be bogus data in that case.
  167093. */
  167094. GLOBAL(boolean)
  167095. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  167096. {
  167097. int marker = cinfo->unread_marker;
  167098. int action = 1;
  167099. /* Always put up a warning. */
  167100. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  167101. /* Outer loop handles repeated decision after scanning forward. */
  167102. for (;;) {
  167103. if (marker < (int) M_SOF0)
  167104. action = 2; /* invalid marker */
  167105. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  167106. action = 3; /* valid non-restart marker */
  167107. else {
  167108. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  167109. marker == ((int) M_RST0 + ((desired+2) & 7)))
  167110. action = 3; /* one of the next two expected restarts */
  167111. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  167112. marker == ((int) M_RST0 + ((desired-2) & 7)))
  167113. action = 2; /* a prior restart, so advance */
  167114. else
  167115. action = 1; /* desired restart or too far away */
  167116. }
  167117. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  167118. switch (action) {
  167119. case 1:
  167120. /* Discard marker and let entropy decoder resume processing. */
  167121. cinfo->unread_marker = 0;
  167122. return TRUE;
  167123. case 2:
  167124. /* Scan to the next marker, and repeat the decision loop. */
  167125. if (! next_marker(cinfo))
  167126. return FALSE;
  167127. marker = cinfo->unread_marker;
  167128. break;
  167129. case 3:
  167130. /* Return without advancing past this marker. */
  167131. /* Entropy decoder will be forced to process an empty segment. */
  167132. return TRUE;
  167133. }
  167134. } /* end loop */
  167135. }
  167136. /*
  167137. * Reset marker processing state to begin a fresh datastream.
  167138. */
  167139. METHODDEF(void)
  167140. reset_marker_reader (j_decompress_ptr cinfo)
  167141. {
  167142. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167143. cinfo->comp_info = NULL; /* until allocated by get_sof */
  167144. cinfo->input_scan_number = 0; /* no SOS seen yet */
  167145. cinfo->unread_marker = 0; /* no pending marker */
  167146. marker->pub.saw_SOI = FALSE; /* set internal state too */
  167147. marker->pub.saw_SOF = FALSE;
  167148. marker->pub.discarded_bytes = 0;
  167149. marker->cur_marker = NULL;
  167150. }
  167151. /*
  167152. * Initialize the marker reader module.
  167153. * This is called only once, when the decompression object is created.
  167154. */
  167155. GLOBAL(void)
  167156. jinit_marker_reader (j_decompress_ptr cinfo)
  167157. {
  167158. my_marker_ptr2 marker;
  167159. int i;
  167160. /* Create subobject in permanent pool */
  167161. marker = (my_marker_ptr2)
  167162. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167163. SIZEOF(my_marker_reader));
  167164. cinfo->marker = (struct jpeg_marker_reader *) marker;
  167165. /* Initialize public method pointers */
  167166. marker->pub.reset_marker_reader = reset_marker_reader;
  167167. marker->pub.read_markers = read_markers;
  167168. marker->pub.read_restart_marker = read_restart_marker;
  167169. /* Initialize COM/APPn processing.
  167170. * By default, we examine and then discard APP0 and APP14,
  167171. * but simply discard COM and all other APPn.
  167172. */
  167173. marker->process_COM = skip_variable;
  167174. marker->length_limit_COM = 0;
  167175. for (i = 0; i < 16; i++) {
  167176. marker->process_APPn[i] = skip_variable;
  167177. marker->length_limit_APPn[i] = 0;
  167178. }
  167179. marker->process_APPn[0] = get_interesting_appn;
  167180. marker->process_APPn[14] = get_interesting_appn;
  167181. /* Reset marker processing state */
  167182. reset_marker_reader(cinfo);
  167183. }
  167184. /*
  167185. * Control saving of COM and APPn markers into marker_list.
  167186. */
  167187. #ifdef SAVE_MARKERS_SUPPORTED
  167188. GLOBAL(void)
  167189. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  167190. unsigned int length_limit)
  167191. {
  167192. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167193. long maxlength;
  167194. jpeg_marker_parser_method processor;
  167195. /* Length limit mustn't be larger than what we can allocate
  167196. * (should only be a concern in a 16-bit environment).
  167197. */
  167198. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  167199. if (((long) length_limit) > maxlength)
  167200. length_limit = (unsigned int) maxlength;
  167201. /* Choose processor routine to use.
  167202. * APP0/APP14 have special requirements.
  167203. */
  167204. if (length_limit) {
  167205. processor = save_marker;
  167206. /* If saving APP0/APP14, save at least enough for our internal use. */
  167207. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  167208. length_limit = APP0_DATA_LEN;
  167209. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  167210. length_limit = APP14_DATA_LEN;
  167211. } else {
  167212. processor = skip_variable;
  167213. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  167214. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  167215. processor = get_interesting_appn;
  167216. }
  167217. if (marker_code == (int) M_COM) {
  167218. marker->process_COM = processor;
  167219. marker->length_limit_COM = length_limit;
  167220. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  167221. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  167222. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  167223. } else
  167224. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167225. }
  167226. #endif /* SAVE_MARKERS_SUPPORTED */
  167227. /*
  167228. * Install a special processing method for COM or APPn markers.
  167229. */
  167230. GLOBAL(void)
  167231. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  167232. jpeg_marker_parser_method routine)
  167233. {
  167234. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167235. if (marker_code == (int) M_COM)
  167236. marker->process_COM = routine;
  167237. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  167238. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  167239. else
  167240. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167241. }
  167242. /********* End of inlined file: jdmarker.c *********/
  167243. /********* Start of inlined file: jdmaster.c *********/
  167244. #define JPEG_INTERNALS
  167245. /* Private state */
  167246. typedef struct {
  167247. struct jpeg_decomp_master pub; /* public fields */
  167248. int pass_number; /* # of passes completed */
  167249. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  167250. /* Saved references to initialized quantizer modules,
  167251. * in case we need to switch modes.
  167252. */
  167253. struct jpeg_color_quantizer * quantizer_1pass;
  167254. struct jpeg_color_quantizer * quantizer_2pass;
  167255. } my_decomp_master;
  167256. typedef my_decomp_master * my_master_ptr6;
  167257. /*
  167258. * Determine whether merged upsample/color conversion should be used.
  167259. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  167260. */
  167261. LOCAL(boolean)
  167262. use_merged_upsample (j_decompress_ptr cinfo)
  167263. {
  167264. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167265. /* Merging is the equivalent of plain box-filter upsampling */
  167266. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  167267. return FALSE;
  167268. /* jdmerge.c only supports YCC=>RGB color conversion */
  167269. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  167270. cinfo->out_color_space != JCS_RGB ||
  167271. cinfo->out_color_components != RGB_PIXELSIZE)
  167272. return FALSE;
  167273. /* and it only handles 2h1v or 2h2v sampling ratios */
  167274. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  167275. cinfo->comp_info[1].h_samp_factor != 1 ||
  167276. cinfo->comp_info[2].h_samp_factor != 1 ||
  167277. cinfo->comp_info[0].v_samp_factor > 2 ||
  167278. cinfo->comp_info[1].v_samp_factor != 1 ||
  167279. cinfo->comp_info[2].v_samp_factor != 1)
  167280. return FALSE;
  167281. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  167282. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167283. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167284. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  167285. return FALSE;
  167286. /* ??? also need to test for upsample-time rescaling, when & if supported */
  167287. return TRUE; /* by golly, it'll work... */
  167288. #else
  167289. return FALSE;
  167290. #endif
  167291. }
  167292. /*
  167293. * Compute output image dimensions and related values.
  167294. * NOTE: this is exported for possible use by application.
  167295. * Hence it mustn't do anything that can't be done twice.
  167296. * Also note that it may be called before the master module is initialized!
  167297. */
  167298. GLOBAL(void)
  167299. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  167300. /* Do computations that are needed before master selection phase */
  167301. {
  167302. #ifdef IDCT_SCALING_SUPPORTED
  167303. int ci;
  167304. jpeg_component_info *compptr;
  167305. #endif
  167306. /* Prevent application from calling me at wrong times */
  167307. if (cinfo->global_state != DSTATE_READY)
  167308. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167309. #ifdef IDCT_SCALING_SUPPORTED
  167310. /* Compute actual output image dimensions and DCT scaling choices. */
  167311. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  167312. /* Provide 1/8 scaling */
  167313. cinfo->output_width = (JDIMENSION)
  167314. jdiv_round_up((long) cinfo->image_width, 8L);
  167315. cinfo->output_height = (JDIMENSION)
  167316. jdiv_round_up((long) cinfo->image_height, 8L);
  167317. cinfo->min_DCT_scaled_size = 1;
  167318. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  167319. /* Provide 1/4 scaling */
  167320. cinfo->output_width = (JDIMENSION)
  167321. jdiv_round_up((long) cinfo->image_width, 4L);
  167322. cinfo->output_height = (JDIMENSION)
  167323. jdiv_round_up((long) cinfo->image_height, 4L);
  167324. cinfo->min_DCT_scaled_size = 2;
  167325. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  167326. /* Provide 1/2 scaling */
  167327. cinfo->output_width = (JDIMENSION)
  167328. jdiv_round_up((long) cinfo->image_width, 2L);
  167329. cinfo->output_height = (JDIMENSION)
  167330. jdiv_round_up((long) cinfo->image_height, 2L);
  167331. cinfo->min_DCT_scaled_size = 4;
  167332. } else {
  167333. /* Provide 1/1 scaling */
  167334. cinfo->output_width = cinfo->image_width;
  167335. cinfo->output_height = cinfo->image_height;
  167336. cinfo->min_DCT_scaled_size = DCTSIZE;
  167337. }
  167338. /* In selecting the actual DCT scaling for each component, we try to
  167339. * scale up the chroma components via IDCT scaling rather than upsampling.
  167340. * This saves time if the upsampler gets to use 1:1 scaling.
  167341. * Note this code assumes that the supported DCT scalings are powers of 2.
  167342. */
  167343. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167344. ci++, compptr++) {
  167345. int ssize = cinfo->min_DCT_scaled_size;
  167346. while (ssize < DCTSIZE &&
  167347. (compptr->h_samp_factor * ssize * 2 <=
  167348. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  167349. (compptr->v_samp_factor * ssize * 2 <=
  167350. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  167351. ssize = ssize * 2;
  167352. }
  167353. compptr->DCT_scaled_size = ssize;
  167354. }
  167355. /* Recompute downsampled dimensions of components;
  167356. * application needs to know these if using raw downsampled data.
  167357. */
  167358. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167359. ci++, compptr++) {
  167360. /* Size in samples, after IDCT scaling */
  167361. compptr->downsampled_width = (JDIMENSION)
  167362. jdiv_round_up((long) cinfo->image_width *
  167363. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  167364. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  167365. compptr->downsampled_height = (JDIMENSION)
  167366. jdiv_round_up((long) cinfo->image_height *
  167367. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  167368. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  167369. }
  167370. #else /* !IDCT_SCALING_SUPPORTED */
  167371. /* Hardwire it to "no scaling" */
  167372. cinfo->output_width = cinfo->image_width;
  167373. cinfo->output_height = cinfo->image_height;
  167374. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  167375. * and has computed unscaled downsampled_width and downsampled_height.
  167376. */
  167377. #endif /* IDCT_SCALING_SUPPORTED */
  167378. /* Report number of components in selected colorspace. */
  167379. /* Probably this should be in the color conversion module... */
  167380. switch (cinfo->out_color_space) {
  167381. case JCS_GRAYSCALE:
  167382. cinfo->out_color_components = 1;
  167383. break;
  167384. case JCS_RGB:
  167385. #if RGB_PIXELSIZE != 3
  167386. cinfo->out_color_components = RGB_PIXELSIZE;
  167387. break;
  167388. #endif /* else share code with YCbCr */
  167389. case JCS_YCbCr:
  167390. cinfo->out_color_components = 3;
  167391. break;
  167392. case JCS_CMYK:
  167393. case JCS_YCCK:
  167394. cinfo->out_color_components = 4;
  167395. break;
  167396. default: /* else must be same colorspace as in file */
  167397. cinfo->out_color_components = cinfo->num_components;
  167398. break;
  167399. }
  167400. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  167401. cinfo->out_color_components);
  167402. /* See if upsampler will want to emit more than one row at a time */
  167403. if (use_merged_upsample(cinfo))
  167404. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  167405. else
  167406. cinfo->rec_outbuf_height = 1;
  167407. }
  167408. /*
  167409. * Several decompression processes need to range-limit values to the range
  167410. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  167411. * due to noise introduced by quantization, roundoff error, etc. These
  167412. * processes are inner loops and need to be as fast as possible. On most
  167413. * machines, particularly CPUs with pipelines or instruction prefetch,
  167414. * a (subscript-check-less) C table lookup
  167415. * x = sample_range_limit[x];
  167416. * is faster than explicit tests
  167417. * if (x < 0) x = 0;
  167418. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  167419. * These processes all use a common table prepared by the routine below.
  167420. *
  167421. * For most steps we can mathematically guarantee that the initial value
  167422. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  167423. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  167424. * limiting step (just after the IDCT), a wildly out-of-range value is
  167425. * possible if the input data is corrupt. To avoid any chance of indexing
  167426. * off the end of memory and getting a bad-pointer trap, we perform the
  167427. * post-IDCT limiting thus:
  167428. * x = range_limit[x & MASK];
  167429. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  167430. * samples. Under normal circumstances this is more than enough range and
  167431. * a correct output will be generated; with bogus input data the mask will
  167432. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  167433. * For the post-IDCT step, we want to convert the data from signed to unsigned
  167434. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  167435. * So the post-IDCT limiting table ends up looking like this:
  167436. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  167437. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  167438. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  167439. * 0,1,...,CENTERJSAMPLE-1
  167440. * Negative inputs select values from the upper half of the table after
  167441. * masking.
  167442. *
  167443. * We can save some space by overlapping the start of the post-IDCT table
  167444. * with the simpler range limiting table. The post-IDCT table begins at
  167445. * sample_range_limit + CENTERJSAMPLE.
  167446. *
  167447. * Note that the table is allocated in near data space on PCs; it's small
  167448. * enough and used often enough to justify this.
  167449. */
  167450. LOCAL(void)
  167451. prepare_range_limit_table (j_decompress_ptr cinfo)
  167452. /* Allocate and fill in the sample_range_limit table */
  167453. {
  167454. JSAMPLE * table;
  167455. int i;
  167456. table = (JSAMPLE *)
  167457. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167458. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  167459. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  167460. cinfo->sample_range_limit = table;
  167461. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  167462. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  167463. /* Main part of "simple" table: limit[x] = x */
  167464. for (i = 0; i <= MAXJSAMPLE; i++)
  167465. table[i] = (JSAMPLE) i;
  167466. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  167467. /* End of simple table, rest of first half of post-IDCT table */
  167468. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  167469. table[i] = MAXJSAMPLE;
  167470. /* Second half of post-IDCT table */
  167471. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  167472. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  167473. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  167474. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  167475. }
  167476. /*
  167477. * Master selection of decompression modules.
  167478. * This is done once at jpeg_start_decompress time. We determine
  167479. * which modules will be used and give them appropriate initialization calls.
  167480. * We also initialize the decompressor input side to begin consuming data.
  167481. *
  167482. * Since jpeg_read_header has finished, we know what is in the SOF
  167483. * and (first) SOS markers. We also have all the application parameter
  167484. * settings.
  167485. */
  167486. LOCAL(void)
  167487. master_selection (j_decompress_ptr cinfo)
  167488. {
  167489. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167490. boolean use_c_buffer;
  167491. long samplesperrow;
  167492. JDIMENSION jd_samplesperrow;
  167493. /* Initialize dimensions and other stuff */
  167494. jpeg_calc_output_dimensions(cinfo);
  167495. prepare_range_limit_table(cinfo);
  167496. /* Width of an output scanline must be representable as JDIMENSION. */
  167497. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  167498. jd_samplesperrow = (JDIMENSION) samplesperrow;
  167499. if ((long) jd_samplesperrow != samplesperrow)
  167500. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  167501. /* Initialize my private state */
  167502. master->pass_number = 0;
  167503. master->using_merged_upsample = use_merged_upsample(cinfo);
  167504. /* Color quantizer selection */
  167505. master->quantizer_1pass = NULL;
  167506. master->quantizer_2pass = NULL;
  167507. /* No mode changes if not using buffered-image mode. */
  167508. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  167509. cinfo->enable_1pass_quant = FALSE;
  167510. cinfo->enable_external_quant = FALSE;
  167511. cinfo->enable_2pass_quant = FALSE;
  167512. }
  167513. if (cinfo->quantize_colors) {
  167514. if (cinfo->raw_data_out)
  167515. ERREXIT(cinfo, JERR_NOTIMPL);
  167516. /* 2-pass quantizer only works in 3-component color space. */
  167517. if (cinfo->out_color_components != 3) {
  167518. cinfo->enable_1pass_quant = TRUE;
  167519. cinfo->enable_external_quant = FALSE;
  167520. cinfo->enable_2pass_quant = FALSE;
  167521. cinfo->colormap = NULL;
  167522. } else if (cinfo->colormap != NULL) {
  167523. cinfo->enable_external_quant = TRUE;
  167524. } else if (cinfo->two_pass_quantize) {
  167525. cinfo->enable_2pass_quant = TRUE;
  167526. } else {
  167527. cinfo->enable_1pass_quant = TRUE;
  167528. }
  167529. if (cinfo->enable_1pass_quant) {
  167530. #ifdef QUANT_1PASS_SUPPORTED
  167531. jinit_1pass_quantizer(cinfo);
  167532. master->quantizer_1pass = cinfo->cquantize;
  167533. #else
  167534. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167535. #endif
  167536. }
  167537. /* We use the 2-pass code to map to external colormaps. */
  167538. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  167539. #ifdef QUANT_2PASS_SUPPORTED
  167540. jinit_2pass_quantizer(cinfo);
  167541. master->quantizer_2pass = cinfo->cquantize;
  167542. #else
  167543. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167544. #endif
  167545. }
  167546. /* If both quantizers are initialized, the 2-pass one is left active;
  167547. * this is necessary for starting with quantization to an external map.
  167548. */
  167549. }
  167550. /* Post-processing: in particular, color conversion first */
  167551. if (! cinfo->raw_data_out) {
  167552. if (master->using_merged_upsample) {
  167553. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167554. jinit_merged_upsampler(cinfo); /* does color conversion too */
  167555. #else
  167556. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167557. #endif
  167558. } else {
  167559. jinit_color_deconverter(cinfo);
  167560. jinit_upsampler(cinfo);
  167561. }
  167562. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  167563. }
  167564. /* Inverse DCT */
  167565. jinit_inverse_dct(cinfo);
  167566. /* Entropy decoding: either Huffman or arithmetic coding. */
  167567. if (cinfo->arith_code) {
  167568. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167569. } else {
  167570. if (cinfo->progressive_mode) {
  167571. #ifdef D_PROGRESSIVE_SUPPORTED
  167572. jinit_phuff_decoder(cinfo);
  167573. #else
  167574. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167575. #endif
  167576. } else
  167577. jinit_huff_decoder(cinfo);
  167578. }
  167579. /* Initialize principal buffer controllers. */
  167580. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  167581. jinit_d_coef_controller(cinfo, use_c_buffer);
  167582. if (! cinfo->raw_data_out)
  167583. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  167584. /* We can now tell the memory manager to allocate virtual arrays. */
  167585. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167586. /* Initialize input side of decompressor to consume first scan. */
  167587. (*cinfo->inputctl->start_input_pass) (cinfo);
  167588. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167589. /* If jpeg_start_decompress will read the whole file, initialize
  167590. * progress monitoring appropriately. The input step is counted
  167591. * as one pass.
  167592. */
  167593. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  167594. cinfo->inputctl->has_multiple_scans) {
  167595. int nscans;
  167596. /* Estimate number of scans to set pass_limit. */
  167597. if (cinfo->progressive_mode) {
  167598. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  167599. nscans = 2 + 3 * cinfo->num_components;
  167600. } else {
  167601. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  167602. nscans = cinfo->num_components;
  167603. }
  167604. cinfo->progress->pass_counter = 0L;
  167605. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  167606. cinfo->progress->completed_passes = 0;
  167607. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  167608. /* Count the input pass as done */
  167609. master->pass_number++;
  167610. }
  167611. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167612. }
  167613. /*
  167614. * Per-pass setup.
  167615. * This is called at the beginning of each output pass. We determine which
  167616. * modules will be active during this pass and give them appropriate
  167617. * start_pass calls. We also set is_dummy_pass to indicate whether this
  167618. * is a "real" output pass or a dummy pass for color quantization.
  167619. * (In the latter case, jdapistd.c will crank the pass to completion.)
  167620. */
  167621. METHODDEF(void)
  167622. prepare_for_output_pass (j_decompress_ptr cinfo)
  167623. {
  167624. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167625. if (master->pub.is_dummy_pass) {
  167626. #ifdef QUANT_2PASS_SUPPORTED
  167627. /* Final pass of 2-pass quantization */
  167628. master->pub.is_dummy_pass = FALSE;
  167629. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  167630. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  167631. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  167632. #else
  167633. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167634. #endif /* QUANT_2PASS_SUPPORTED */
  167635. } else {
  167636. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  167637. /* Select new quantization method */
  167638. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  167639. cinfo->cquantize = master->quantizer_2pass;
  167640. master->pub.is_dummy_pass = TRUE;
  167641. } else if (cinfo->enable_1pass_quant) {
  167642. cinfo->cquantize = master->quantizer_1pass;
  167643. } else {
  167644. ERREXIT(cinfo, JERR_MODE_CHANGE);
  167645. }
  167646. }
  167647. (*cinfo->idct->start_pass) (cinfo);
  167648. (*cinfo->coef->start_output_pass) (cinfo);
  167649. if (! cinfo->raw_data_out) {
  167650. if (! master->using_merged_upsample)
  167651. (*cinfo->cconvert->start_pass) (cinfo);
  167652. (*cinfo->upsample->start_pass) (cinfo);
  167653. if (cinfo->quantize_colors)
  167654. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  167655. (*cinfo->post->start_pass) (cinfo,
  167656. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  167657. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  167658. }
  167659. }
  167660. /* Set up progress monitor's pass info if present */
  167661. if (cinfo->progress != NULL) {
  167662. cinfo->progress->completed_passes = master->pass_number;
  167663. cinfo->progress->total_passes = master->pass_number +
  167664. (master->pub.is_dummy_pass ? 2 : 1);
  167665. /* In buffered-image mode, we assume one more output pass if EOI not
  167666. * yet reached, but no more passes if EOI has been reached.
  167667. */
  167668. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  167669. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  167670. }
  167671. }
  167672. }
  167673. /*
  167674. * Finish up at end of an output pass.
  167675. */
  167676. METHODDEF(void)
  167677. finish_output_pass (j_decompress_ptr cinfo)
  167678. {
  167679. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167680. if (cinfo->quantize_colors)
  167681. (*cinfo->cquantize->finish_pass) (cinfo);
  167682. master->pass_number++;
  167683. }
  167684. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167685. /*
  167686. * Switch to a new external colormap between output passes.
  167687. */
  167688. GLOBAL(void)
  167689. jpeg_new_colormap (j_decompress_ptr cinfo)
  167690. {
  167691. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167692. /* Prevent application from calling me at wrong times */
  167693. if (cinfo->global_state != DSTATE_BUFIMAGE)
  167694. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167695. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  167696. cinfo->colormap != NULL) {
  167697. /* Select 2-pass quantizer for external colormap use */
  167698. cinfo->cquantize = master->quantizer_2pass;
  167699. /* Notify quantizer of colormap change */
  167700. (*cinfo->cquantize->new_color_map) (cinfo);
  167701. master->pub.is_dummy_pass = FALSE; /* just in case */
  167702. } else
  167703. ERREXIT(cinfo, JERR_MODE_CHANGE);
  167704. }
  167705. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167706. /*
  167707. * Initialize master decompression control and select active modules.
  167708. * This is performed at the start of jpeg_start_decompress.
  167709. */
  167710. GLOBAL(void)
  167711. jinit_master_decompress (j_decompress_ptr cinfo)
  167712. {
  167713. my_master_ptr6 master;
  167714. master = (my_master_ptr6)
  167715. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167716. SIZEOF(my_decomp_master));
  167717. cinfo->master = (struct jpeg_decomp_master *) master;
  167718. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  167719. master->pub.finish_output_pass = finish_output_pass;
  167720. master->pub.is_dummy_pass = FALSE;
  167721. master_selection(cinfo);
  167722. }
  167723. /********* End of inlined file: jdmaster.c *********/
  167724. #undef FIX
  167725. /********* Start of inlined file: jdmerge.c *********/
  167726. #define JPEG_INTERNALS
  167727. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167728. /* Private subobject */
  167729. typedef struct {
  167730. struct jpeg_upsampler pub; /* public fields */
  167731. /* Pointer to routine to do actual upsampling/conversion of one row group */
  167732. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  167733. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  167734. JSAMPARRAY output_buf));
  167735. /* Private state for YCC->RGB conversion */
  167736. int * Cr_r_tab; /* => table for Cr to R conversion */
  167737. int * Cb_b_tab; /* => table for Cb to B conversion */
  167738. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  167739. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  167740. /* For 2:1 vertical sampling, we produce two output rows at a time.
  167741. * We need a "spare" row buffer to hold the second output row if the
  167742. * application provides just a one-row buffer; we also use the spare
  167743. * to discard the dummy last row if the image height is odd.
  167744. */
  167745. JSAMPROW spare_row;
  167746. boolean spare_full; /* T if spare buffer is occupied */
  167747. JDIMENSION out_row_width; /* samples per output row */
  167748. JDIMENSION rows_to_go; /* counts rows remaining in image */
  167749. } my_upsampler;
  167750. typedef my_upsampler * my_upsample_ptr;
  167751. #define SCALEBITS 16 /* speediest right-shift on some machines */
  167752. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  167753. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  167754. /*
  167755. * Initialize tables for YCC->RGB colorspace conversion.
  167756. * This is taken directly from jdcolor.c; see that file for more info.
  167757. */
  167758. LOCAL(void)
  167759. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  167760. {
  167761. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167762. int i;
  167763. INT32 x;
  167764. SHIFT_TEMPS
  167765. upsample->Cr_r_tab = (int *)
  167766. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167767. (MAXJSAMPLE+1) * SIZEOF(int));
  167768. upsample->Cb_b_tab = (int *)
  167769. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167770. (MAXJSAMPLE+1) * SIZEOF(int));
  167771. upsample->Cr_g_tab = (INT32 *)
  167772. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167773. (MAXJSAMPLE+1) * SIZEOF(INT32));
  167774. upsample->Cb_g_tab = (INT32 *)
  167775. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167776. (MAXJSAMPLE+1) * SIZEOF(INT32));
  167777. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  167778. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  167779. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  167780. /* Cr=>R value is nearest int to 1.40200 * x */
  167781. upsample->Cr_r_tab[i] = (int)
  167782. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  167783. /* Cb=>B value is nearest int to 1.77200 * x */
  167784. upsample->Cb_b_tab[i] = (int)
  167785. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  167786. /* Cr=>G value is scaled-up -0.71414 * x */
  167787. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  167788. /* Cb=>G value is scaled-up -0.34414 * x */
  167789. /* We also add in ONE_HALF so that need not do it in inner loop */
  167790. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  167791. }
  167792. }
  167793. /*
  167794. * Initialize for an upsampling pass.
  167795. */
  167796. METHODDEF(void)
  167797. start_pass_merged_upsample (j_decompress_ptr cinfo)
  167798. {
  167799. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167800. /* Mark the spare buffer empty */
  167801. upsample->spare_full = FALSE;
  167802. /* Initialize total-height counter for detecting bottom of image */
  167803. upsample->rows_to_go = cinfo->output_height;
  167804. }
  167805. /*
  167806. * Control routine to do upsampling (and color conversion).
  167807. *
  167808. * The control routine just handles the row buffering considerations.
  167809. */
  167810. METHODDEF(void)
  167811. merged_2v_upsample (j_decompress_ptr cinfo,
  167812. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167813. JDIMENSION in_row_groups_avail,
  167814. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167815. JDIMENSION out_rows_avail)
  167816. /* 2:1 vertical sampling case: may need a spare row. */
  167817. {
  167818. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167819. JSAMPROW work_ptrs[2];
  167820. JDIMENSION num_rows; /* number of rows returned to caller */
  167821. if (upsample->spare_full) {
  167822. /* If we have a spare row saved from a previous cycle, just return it. */
  167823. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  167824. 1, upsample->out_row_width);
  167825. num_rows = 1;
  167826. upsample->spare_full = FALSE;
  167827. } else {
  167828. /* Figure number of rows to return to caller. */
  167829. num_rows = 2;
  167830. /* Not more than the distance to the end of the image. */
  167831. if (num_rows > upsample->rows_to_go)
  167832. num_rows = upsample->rows_to_go;
  167833. /* And not more than what the client can accept: */
  167834. out_rows_avail -= *out_row_ctr;
  167835. if (num_rows > out_rows_avail)
  167836. num_rows = out_rows_avail;
  167837. /* Create output pointer array for upsampler. */
  167838. work_ptrs[0] = output_buf[*out_row_ctr];
  167839. if (num_rows > 1) {
  167840. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  167841. } else {
  167842. work_ptrs[1] = upsample->spare_row;
  167843. upsample->spare_full = TRUE;
  167844. }
  167845. /* Now do the upsampling. */
  167846. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  167847. }
  167848. /* Adjust counts */
  167849. *out_row_ctr += num_rows;
  167850. upsample->rows_to_go -= num_rows;
  167851. /* When the buffer is emptied, declare this input row group consumed */
  167852. if (! upsample->spare_full)
  167853. (*in_row_group_ctr)++;
  167854. }
  167855. METHODDEF(void)
  167856. merged_1v_upsample (j_decompress_ptr cinfo,
  167857. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167858. JDIMENSION in_row_groups_avail,
  167859. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167860. JDIMENSION out_rows_avail)
  167861. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  167862. {
  167863. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167864. /* Just do the upsampling. */
  167865. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  167866. output_buf + *out_row_ctr);
  167867. /* Adjust counts */
  167868. (*out_row_ctr)++;
  167869. (*in_row_group_ctr)++;
  167870. }
  167871. /*
  167872. * These are the routines invoked by the control routines to do
  167873. * the actual upsampling/conversion. One row group is processed per call.
  167874. *
  167875. * Note: since we may be writing directly into application-supplied buffers,
  167876. * we have to be honest about the output width; we can't assume the buffer
  167877. * has been rounded up to an even width.
  167878. */
  167879. /*
  167880. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  167881. */
  167882. METHODDEF(void)
  167883. h2v1_merged_upsample (j_decompress_ptr cinfo,
  167884. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  167885. JSAMPARRAY output_buf)
  167886. {
  167887. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167888. register int y, cred, cgreen, cblue;
  167889. int cb, cr;
  167890. register JSAMPROW outptr;
  167891. JSAMPROW inptr0, inptr1, inptr2;
  167892. JDIMENSION col;
  167893. /* copy these pointers into registers if possible */
  167894. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  167895. int * Crrtab = upsample->Cr_r_tab;
  167896. int * Cbbtab = upsample->Cb_b_tab;
  167897. INT32 * Crgtab = upsample->Cr_g_tab;
  167898. INT32 * Cbgtab = upsample->Cb_g_tab;
  167899. SHIFT_TEMPS
  167900. inptr0 = input_buf[0][in_row_group_ctr];
  167901. inptr1 = input_buf[1][in_row_group_ctr];
  167902. inptr2 = input_buf[2][in_row_group_ctr];
  167903. outptr = output_buf[0];
  167904. /* Loop for each pair of output pixels */
  167905. for (col = cinfo->output_width >> 1; col > 0; col--) {
  167906. /* Do the chroma part of the calculation */
  167907. cb = GETJSAMPLE(*inptr1++);
  167908. cr = GETJSAMPLE(*inptr2++);
  167909. cred = Crrtab[cr];
  167910. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167911. cblue = Cbbtab[cb];
  167912. /* Fetch 2 Y values and emit 2 pixels */
  167913. y = GETJSAMPLE(*inptr0++);
  167914. outptr[RGB_RED] = range_limit[y + cred];
  167915. outptr[RGB_GREEN] = range_limit[y + cgreen];
  167916. outptr[RGB_BLUE] = range_limit[y + cblue];
  167917. outptr += RGB_PIXELSIZE;
  167918. y = GETJSAMPLE(*inptr0++);
  167919. outptr[RGB_RED] = range_limit[y + cred];
  167920. outptr[RGB_GREEN] = range_limit[y + cgreen];
  167921. outptr[RGB_BLUE] = range_limit[y + cblue];
  167922. outptr += RGB_PIXELSIZE;
  167923. }
  167924. /* If image width is odd, do the last output column separately */
  167925. if (cinfo->output_width & 1) {
  167926. cb = GETJSAMPLE(*inptr1);
  167927. cr = GETJSAMPLE(*inptr2);
  167928. cred = Crrtab[cr];
  167929. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167930. cblue = Cbbtab[cb];
  167931. y = GETJSAMPLE(*inptr0);
  167932. outptr[RGB_RED] = range_limit[y + cred];
  167933. outptr[RGB_GREEN] = range_limit[y + cgreen];
  167934. outptr[RGB_BLUE] = range_limit[y + cblue];
  167935. }
  167936. }
  167937. /*
  167938. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  167939. */
  167940. METHODDEF(void)
  167941. h2v2_merged_upsample (j_decompress_ptr cinfo,
  167942. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  167943. JSAMPARRAY output_buf)
  167944. {
  167945. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167946. register int y, cred, cgreen, cblue;
  167947. int cb, cr;
  167948. register JSAMPROW outptr0, outptr1;
  167949. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  167950. JDIMENSION col;
  167951. /* copy these pointers into registers if possible */
  167952. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  167953. int * Crrtab = upsample->Cr_r_tab;
  167954. int * Cbbtab = upsample->Cb_b_tab;
  167955. INT32 * Crgtab = upsample->Cr_g_tab;
  167956. INT32 * Cbgtab = upsample->Cb_g_tab;
  167957. SHIFT_TEMPS
  167958. inptr00 = input_buf[0][in_row_group_ctr*2];
  167959. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  167960. inptr1 = input_buf[1][in_row_group_ctr];
  167961. inptr2 = input_buf[2][in_row_group_ctr];
  167962. outptr0 = output_buf[0];
  167963. outptr1 = output_buf[1];
  167964. /* Loop for each group of output pixels */
  167965. for (col = cinfo->output_width >> 1; col > 0; col--) {
  167966. /* Do the chroma part of the calculation */
  167967. cb = GETJSAMPLE(*inptr1++);
  167968. cr = GETJSAMPLE(*inptr2++);
  167969. cred = Crrtab[cr];
  167970. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167971. cblue = Cbbtab[cb];
  167972. /* Fetch 4 Y values and emit 4 pixels */
  167973. y = GETJSAMPLE(*inptr00++);
  167974. outptr0[RGB_RED] = range_limit[y + cred];
  167975. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  167976. outptr0[RGB_BLUE] = range_limit[y + cblue];
  167977. outptr0 += RGB_PIXELSIZE;
  167978. y = GETJSAMPLE(*inptr00++);
  167979. outptr0[RGB_RED] = range_limit[y + cred];
  167980. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  167981. outptr0[RGB_BLUE] = range_limit[y + cblue];
  167982. outptr0 += RGB_PIXELSIZE;
  167983. y = GETJSAMPLE(*inptr01++);
  167984. outptr1[RGB_RED] = range_limit[y + cred];
  167985. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167986. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167987. outptr1 += RGB_PIXELSIZE;
  167988. y = GETJSAMPLE(*inptr01++);
  167989. outptr1[RGB_RED] = range_limit[y + cred];
  167990. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167991. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167992. outptr1 += RGB_PIXELSIZE;
  167993. }
  167994. /* If image width is odd, do the last output column separately */
  167995. if (cinfo->output_width & 1) {
  167996. cb = GETJSAMPLE(*inptr1);
  167997. cr = GETJSAMPLE(*inptr2);
  167998. cred = Crrtab[cr];
  167999. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168000. cblue = Cbbtab[cb];
  168001. y = GETJSAMPLE(*inptr00);
  168002. outptr0[RGB_RED] = range_limit[y + cred];
  168003. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168004. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168005. y = GETJSAMPLE(*inptr01);
  168006. outptr1[RGB_RED] = range_limit[y + cred];
  168007. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168008. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168009. }
  168010. }
  168011. /*
  168012. * Module initialization routine for merged upsampling/color conversion.
  168013. *
  168014. * NB: this is called under the conditions determined by use_merged_upsample()
  168015. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  168016. * of this module; no safety checks are made here.
  168017. */
  168018. GLOBAL(void)
  168019. jinit_merged_upsampler (j_decompress_ptr cinfo)
  168020. {
  168021. my_upsample_ptr upsample;
  168022. upsample = (my_upsample_ptr)
  168023. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168024. SIZEOF(my_upsampler));
  168025. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168026. upsample->pub.start_pass = start_pass_merged_upsample;
  168027. upsample->pub.need_context_rows = FALSE;
  168028. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  168029. if (cinfo->max_v_samp_factor == 2) {
  168030. upsample->pub.upsample = merged_2v_upsample;
  168031. upsample->upmethod = h2v2_merged_upsample;
  168032. /* Allocate a spare row buffer */
  168033. upsample->spare_row = (JSAMPROW)
  168034. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168035. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  168036. } else {
  168037. upsample->pub.upsample = merged_1v_upsample;
  168038. upsample->upmethod = h2v1_merged_upsample;
  168039. /* No spare row needed */
  168040. upsample->spare_row = NULL;
  168041. }
  168042. build_ycc_rgb_table2(cinfo);
  168043. }
  168044. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  168045. /********* End of inlined file: jdmerge.c *********/
  168046. #undef ASSIGN_STATE
  168047. /********* Start of inlined file: jdphuff.c *********/
  168048. #define JPEG_INTERNALS
  168049. #ifdef D_PROGRESSIVE_SUPPORTED
  168050. /*
  168051. * Expanded entropy decoder object for progressive Huffman decoding.
  168052. *
  168053. * The savable_state subrecord contains fields that change within an MCU,
  168054. * but must not be updated permanently until we complete the MCU.
  168055. */
  168056. typedef struct {
  168057. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  168058. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168059. } savable_state3;
  168060. /* This macro is to work around compilers with missing or broken
  168061. * structure assignment. You'll need to fix this code if you have
  168062. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168063. */
  168064. #ifndef NO_STRUCT_ASSIGN
  168065. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  168066. #else
  168067. #if MAX_COMPS_IN_SCAN == 4
  168068. #define ASSIGN_STATE(dest,src) \
  168069. ((dest).EOBRUN = (src).EOBRUN, \
  168070. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  168071. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  168072. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  168073. (dest).last_dc_val[3] = (src).last_dc_val[3])
  168074. #endif
  168075. #endif
  168076. typedef struct {
  168077. struct jpeg_entropy_decoder pub; /* public fields */
  168078. /* These fields are loaded into local variables at start of each MCU.
  168079. * In case of suspension, we exit WITHOUT updating them.
  168080. */
  168081. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  168082. savable_state3 saved; /* Other state at start of MCU */
  168083. /* These fields are NOT loaded into local working state. */
  168084. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  168085. /* Pointers to derived tables (these workspaces have image lifespan) */
  168086. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  168087. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  168088. } phuff_entropy_decoder;
  168089. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  168090. /* Forward declarations */
  168091. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  168092. JBLOCKROW *MCU_data));
  168093. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  168094. JBLOCKROW *MCU_data));
  168095. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  168096. JBLOCKROW *MCU_data));
  168097. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  168098. JBLOCKROW *MCU_data));
  168099. /*
  168100. * Initialize for a Huffman-compressed scan.
  168101. */
  168102. METHODDEF(void)
  168103. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  168104. {
  168105. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168106. boolean is_DC_band, bad;
  168107. int ci, coefi, tbl;
  168108. int *coef_bit_ptr;
  168109. jpeg_component_info * compptr;
  168110. is_DC_band = (cinfo->Ss == 0);
  168111. /* Validate scan parameters */
  168112. bad = FALSE;
  168113. if (is_DC_band) {
  168114. if (cinfo->Se != 0)
  168115. bad = TRUE;
  168116. } else {
  168117. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  168118. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  168119. bad = TRUE;
  168120. /* AC scans may have only one component */
  168121. if (cinfo->comps_in_scan != 1)
  168122. bad = TRUE;
  168123. }
  168124. if (cinfo->Ah != 0) {
  168125. /* Successive approximation refinement scan: must have Al = Ah-1. */
  168126. if (cinfo->Al != cinfo->Ah-1)
  168127. bad = TRUE;
  168128. }
  168129. if (cinfo->Al > 13) /* need not check for < 0 */
  168130. bad = TRUE;
  168131. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  168132. * but the spec doesn't say so, and we try to be liberal about what we
  168133. * accept. Note: large Al values could result in out-of-range DC
  168134. * coefficients during early scans, leading to bizarre displays due to
  168135. * overflows in the IDCT math. But we won't crash.
  168136. */
  168137. if (bad)
  168138. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  168139. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  168140. /* Update progression status, and verify that scan order is legal.
  168141. * Note that inter-scan inconsistencies are treated as warnings
  168142. * not fatal errors ... not clear if this is right way to behave.
  168143. */
  168144. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168145. int cindex = cinfo->cur_comp_info[ci]->component_index;
  168146. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  168147. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  168148. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  168149. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  168150. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  168151. if (cinfo->Ah != expected)
  168152. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  168153. coef_bit_ptr[coefi] = cinfo->Al;
  168154. }
  168155. }
  168156. /* Select MCU decoding routine */
  168157. if (cinfo->Ah == 0) {
  168158. if (is_DC_band)
  168159. entropy->pub.decode_mcu = decode_mcu_DC_first;
  168160. else
  168161. entropy->pub.decode_mcu = decode_mcu_AC_first;
  168162. } else {
  168163. if (is_DC_band)
  168164. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  168165. else
  168166. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  168167. }
  168168. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168169. compptr = cinfo->cur_comp_info[ci];
  168170. /* Make sure requested tables are present, and compute derived tables.
  168171. * We may build same derived table more than once, but it's not expensive.
  168172. */
  168173. if (is_DC_band) {
  168174. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  168175. tbl = compptr->dc_tbl_no;
  168176. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  168177. & entropy->derived_tbls[tbl]);
  168178. }
  168179. } else {
  168180. tbl = compptr->ac_tbl_no;
  168181. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  168182. & entropy->derived_tbls[tbl]);
  168183. /* remember the single active table */
  168184. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  168185. }
  168186. /* Initialize DC predictions to 0 */
  168187. entropy->saved.last_dc_val[ci] = 0;
  168188. }
  168189. /* Initialize bitread state variables */
  168190. entropy->bitstate.bits_left = 0;
  168191. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  168192. entropy->pub.insufficient_data = FALSE;
  168193. /* Initialize private state variables */
  168194. entropy->saved.EOBRUN = 0;
  168195. /* Initialize restart counter */
  168196. entropy->restarts_to_go = cinfo->restart_interval;
  168197. }
  168198. /*
  168199. * Check for a restart marker & resynchronize decoder.
  168200. * Returns FALSE if must suspend.
  168201. */
  168202. LOCAL(boolean)
  168203. process_restartp (j_decompress_ptr cinfo)
  168204. {
  168205. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168206. int ci;
  168207. /* Throw away any unused bits remaining in bit buffer; */
  168208. /* include any full bytes in next_marker's count of discarded bytes */
  168209. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  168210. entropy->bitstate.bits_left = 0;
  168211. /* Advance past the RSTn marker */
  168212. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  168213. return FALSE;
  168214. /* Re-initialize DC predictions to 0 */
  168215. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  168216. entropy->saved.last_dc_val[ci] = 0;
  168217. /* Re-init EOB run count, too */
  168218. entropy->saved.EOBRUN = 0;
  168219. /* Reset restart counter */
  168220. entropy->restarts_to_go = cinfo->restart_interval;
  168221. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  168222. * against a marker. In that case we will end up treating the next data
  168223. * segment as empty, and we can avoid producing bogus output pixels by
  168224. * leaving the flag set.
  168225. */
  168226. if (cinfo->unread_marker == 0)
  168227. entropy->pub.insufficient_data = FALSE;
  168228. return TRUE;
  168229. }
  168230. /*
  168231. * Huffman MCU decoding.
  168232. * Each of these routines decodes and returns one MCU's worth of
  168233. * Huffman-compressed coefficients.
  168234. * The coefficients are reordered from zigzag order into natural array order,
  168235. * but are not dequantized.
  168236. *
  168237. * The i'th block of the MCU is stored into the block pointed to by
  168238. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  168239. *
  168240. * We return FALSE if data source requested suspension. In that case no
  168241. * changes have been made to permanent state. (Exception: some output
  168242. * coefficients may already have been assigned. This is harmless for
  168243. * spectral selection, since we'll just re-assign them on the next call.
  168244. * Successive approximation AC refinement has to be more careful, however.)
  168245. */
  168246. /*
  168247. * MCU decoding for DC initial scan (either spectral selection,
  168248. * or first pass of successive approximation).
  168249. */
  168250. METHODDEF(boolean)
  168251. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168252. {
  168253. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168254. int Al = cinfo->Al;
  168255. register int s, r;
  168256. int blkn, ci;
  168257. JBLOCKROW block;
  168258. BITREAD_STATE_VARS;
  168259. savable_state3 state;
  168260. d_derived_tbl * tbl;
  168261. jpeg_component_info * compptr;
  168262. /* Process restart marker if needed; may have to suspend */
  168263. if (cinfo->restart_interval) {
  168264. if (entropy->restarts_to_go == 0)
  168265. if (! process_restartp(cinfo))
  168266. return FALSE;
  168267. }
  168268. /* If we've run out of data, just leave the MCU set to zeroes.
  168269. * This way, we return uniform gray for the remainder of the segment.
  168270. */
  168271. if (! entropy->pub.insufficient_data) {
  168272. /* Load up working state */
  168273. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168274. ASSIGN_STATE(state, entropy->saved);
  168275. /* Outer loop handles each block in the MCU */
  168276. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168277. block = MCU_data[blkn];
  168278. ci = cinfo->MCU_membership[blkn];
  168279. compptr = cinfo->cur_comp_info[ci];
  168280. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  168281. /* Decode a single block's worth of coefficients */
  168282. /* Section F.2.2.1: decode the DC coefficient difference */
  168283. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  168284. if (s) {
  168285. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168286. r = GET_BITS(s);
  168287. s = HUFF_EXTEND(r, s);
  168288. }
  168289. /* Convert DC difference to actual value, update last_dc_val */
  168290. s += state.last_dc_val[ci];
  168291. state.last_dc_val[ci] = s;
  168292. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  168293. (*block)[0] = (JCOEF) (s << Al);
  168294. }
  168295. /* Completed MCU, so update state */
  168296. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168297. ASSIGN_STATE(entropy->saved, state);
  168298. }
  168299. /* Account for restart interval (no-op if not using restarts) */
  168300. entropy->restarts_to_go--;
  168301. return TRUE;
  168302. }
  168303. /*
  168304. * MCU decoding for AC initial scan (either spectral selection,
  168305. * or first pass of successive approximation).
  168306. */
  168307. METHODDEF(boolean)
  168308. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168309. {
  168310. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168311. int Se = cinfo->Se;
  168312. int Al = cinfo->Al;
  168313. register int s, k, r;
  168314. unsigned int EOBRUN;
  168315. JBLOCKROW block;
  168316. BITREAD_STATE_VARS;
  168317. d_derived_tbl * tbl;
  168318. /* Process restart marker if needed; may have to suspend */
  168319. if (cinfo->restart_interval) {
  168320. if (entropy->restarts_to_go == 0)
  168321. if (! process_restartp(cinfo))
  168322. return FALSE;
  168323. }
  168324. /* If we've run out of data, just leave the MCU set to zeroes.
  168325. * This way, we return uniform gray for the remainder of the segment.
  168326. */
  168327. if (! entropy->pub.insufficient_data) {
  168328. /* Load up working state.
  168329. * We can avoid loading/saving bitread state if in an EOB run.
  168330. */
  168331. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168332. /* There is always only one block per MCU */
  168333. if (EOBRUN > 0) /* if it's a band of zeroes... */
  168334. EOBRUN--; /* ...process it now (we do nothing) */
  168335. else {
  168336. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168337. block = MCU_data[0];
  168338. tbl = entropy->ac_derived_tbl;
  168339. for (k = cinfo->Ss; k <= Se; k++) {
  168340. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  168341. r = s >> 4;
  168342. s &= 15;
  168343. if (s) {
  168344. k += r;
  168345. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168346. r = GET_BITS(s);
  168347. s = HUFF_EXTEND(r, s);
  168348. /* Scale and output coefficient in natural (dezigzagged) order */
  168349. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  168350. } else {
  168351. if (r == 15) { /* ZRL */
  168352. k += 15; /* skip 15 zeroes in band */
  168353. } else { /* EOBr, run length is 2^r + appended bits */
  168354. EOBRUN = 1 << r;
  168355. if (r) { /* EOBr, r > 0 */
  168356. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  168357. r = GET_BITS(r);
  168358. EOBRUN += r;
  168359. }
  168360. EOBRUN--; /* this band is processed at this moment */
  168361. break; /* force end-of-band */
  168362. }
  168363. }
  168364. }
  168365. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168366. }
  168367. /* Completed MCU, so update state */
  168368. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  168369. }
  168370. /* Account for restart interval (no-op if not using restarts) */
  168371. entropy->restarts_to_go--;
  168372. return TRUE;
  168373. }
  168374. /*
  168375. * MCU decoding for DC successive approximation refinement scan.
  168376. * Note: we assume such scans can be multi-component, although the spec
  168377. * is not very clear on the point.
  168378. */
  168379. METHODDEF(boolean)
  168380. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168381. {
  168382. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168383. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  168384. int blkn;
  168385. JBLOCKROW block;
  168386. BITREAD_STATE_VARS;
  168387. /* Process restart marker if needed; may have to suspend */
  168388. if (cinfo->restart_interval) {
  168389. if (entropy->restarts_to_go == 0)
  168390. if (! process_restartp(cinfo))
  168391. return FALSE;
  168392. }
  168393. /* Not worth the cycles to check insufficient_data here,
  168394. * since we will not change the data anyway if we read zeroes.
  168395. */
  168396. /* Load up working state */
  168397. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168398. /* Outer loop handles each block in the MCU */
  168399. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168400. block = MCU_data[blkn];
  168401. /* Encoded data is simply the next bit of the two's-complement DC value */
  168402. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  168403. if (GET_BITS(1))
  168404. (*block)[0] |= p1;
  168405. /* Note: since we use |=, repeating the assignment later is safe */
  168406. }
  168407. /* Completed MCU, so update state */
  168408. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168409. /* Account for restart interval (no-op if not using restarts) */
  168410. entropy->restarts_to_go--;
  168411. return TRUE;
  168412. }
  168413. /*
  168414. * MCU decoding for AC successive approximation refinement scan.
  168415. */
  168416. METHODDEF(boolean)
  168417. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168418. {
  168419. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168420. int Se = cinfo->Se;
  168421. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  168422. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  168423. register int s, k, r;
  168424. unsigned int EOBRUN;
  168425. JBLOCKROW block;
  168426. JCOEFPTR thiscoef;
  168427. BITREAD_STATE_VARS;
  168428. d_derived_tbl * tbl;
  168429. int num_newnz;
  168430. int newnz_pos[DCTSIZE2];
  168431. /* Process restart marker if needed; may have to suspend */
  168432. if (cinfo->restart_interval) {
  168433. if (entropy->restarts_to_go == 0)
  168434. if (! process_restartp(cinfo))
  168435. return FALSE;
  168436. }
  168437. /* If we've run out of data, don't modify the MCU.
  168438. */
  168439. if (! entropy->pub.insufficient_data) {
  168440. /* Load up working state */
  168441. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168442. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168443. /* There is always only one block per MCU */
  168444. block = MCU_data[0];
  168445. tbl = entropy->ac_derived_tbl;
  168446. /* If we are forced to suspend, we must undo the assignments to any newly
  168447. * nonzero coefficients in the block, because otherwise we'd get confused
  168448. * next time about which coefficients were already nonzero.
  168449. * But we need not undo addition of bits to already-nonzero coefficients;
  168450. * instead, we can test the current bit to see if we already did it.
  168451. */
  168452. num_newnz = 0;
  168453. /* initialize coefficient loop counter to start of band */
  168454. k = cinfo->Ss;
  168455. if (EOBRUN == 0) {
  168456. for (; k <= Se; k++) {
  168457. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  168458. r = s >> 4;
  168459. s &= 15;
  168460. if (s) {
  168461. if (s != 1) /* size of new coef should always be 1 */
  168462. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  168463. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168464. if (GET_BITS(1))
  168465. s = p1; /* newly nonzero coef is positive */
  168466. else
  168467. s = m1; /* newly nonzero coef is negative */
  168468. } else {
  168469. if (r != 15) {
  168470. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  168471. if (r) {
  168472. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  168473. r = GET_BITS(r);
  168474. EOBRUN += r;
  168475. }
  168476. break; /* rest of block is handled by EOB logic */
  168477. }
  168478. /* note s = 0 for processing ZRL */
  168479. }
  168480. /* Advance over already-nonzero coefs and r still-zero coefs,
  168481. * appending correction bits to the nonzeroes. A correction bit is 1
  168482. * if the absolute value of the coefficient must be increased.
  168483. */
  168484. do {
  168485. thiscoef = *block + jpeg_natural_order[k];
  168486. if (*thiscoef != 0) {
  168487. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168488. if (GET_BITS(1)) {
  168489. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  168490. if (*thiscoef >= 0)
  168491. *thiscoef += p1;
  168492. else
  168493. *thiscoef += m1;
  168494. }
  168495. }
  168496. } else {
  168497. if (--r < 0)
  168498. break; /* reached target zero coefficient */
  168499. }
  168500. k++;
  168501. } while (k <= Se);
  168502. if (s) {
  168503. int pos = jpeg_natural_order[k];
  168504. /* Output newly nonzero coefficient */
  168505. (*block)[pos] = (JCOEF) s;
  168506. /* Remember its position in case we have to suspend */
  168507. newnz_pos[num_newnz++] = pos;
  168508. }
  168509. }
  168510. }
  168511. if (EOBRUN > 0) {
  168512. /* Scan any remaining coefficient positions after the end-of-band
  168513. * (the last newly nonzero coefficient, if any). Append a correction
  168514. * bit to each already-nonzero coefficient. A correction bit is 1
  168515. * if the absolute value of the coefficient must be increased.
  168516. */
  168517. for (; k <= Se; k++) {
  168518. thiscoef = *block + jpeg_natural_order[k];
  168519. if (*thiscoef != 0) {
  168520. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168521. if (GET_BITS(1)) {
  168522. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  168523. if (*thiscoef >= 0)
  168524. *thiscoef += p1;
  168525. else
  168526. *thiscoef += m1;
  168527. }
  168528. }
  168529. }
  168530. }
  168531. /* Count one block completed in EOB run */
  168532. EOBRUN--;
  168533. }
  168534. /* Completed MCU, so update state */
  168535. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168536. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  168537. }
  168538. /* Account for restart interval (no-op if not using restarts) */
  168539. entropy->restarts_to_go--;
  168540. return TRUE;
  168541. undoit:
  168542. /* Re-zero any output coefficients that we made newly nonzero */
  168543. while (num_newnz > 0)
  168544. (*block)[newnz_pos[--num_newnz]] = 0;
  168545. return FALSE;
  168546. }
  168547. /*
  168548. * Module initialization routine for progressive Huffman entropy decoding.
  168549. */
  168550. GLOBAL(void)
  168551. jinit_phuff_decoder (j_decompress_ptr cinfo)
  168552. {
  168553. phuff_entropy_ptr2 entropy;
  168554. int *coef_bit_ptr;
  168555. int ci, i;
  168556. entropy = (phuff_entropy_ptr2)
  168557. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168558. SIZEOF(phuff_entropy_decoder));
  168559. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  168560. entropy->pub.start_pass = start_pass_phuff_decoder;
  168561. /* Mark derived tables unallocated */
  168562. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  168563. entropy->derived_tbls[i] = NULL;
  168564. }
  168565. /* Create progression status table */
  168566. cinfo->coef_bits = (int (*)[DCTSIZE2])
  168567. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168568. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  168569. coef_bit_ptr = & cinfo->coef_bits[0][0];
  168570. for (ci = 0; ci < cinfo->num_components; ci++)
  168571. for (i = 0; i < DCTSIZE2; i++)
  168572. *coef_bit_ptr++ = -1;
  168573. }
  168574. #endif /* D_PROGRESSIVE_SUPPORTED */
  168575. /********* End of inlined file: jdphuff.c *********/
  168576. /********* Start of inlined file: jdpostct.c *********/
  168577. #define JPEG_INTERNALS
  168578. /* Private buffer controller object */
  168579. typedef struct {
  168580. struct jpeg_d_post_controller pub; /* public fields */
  168581. /* Color quantization source buffer: this holds output data from
  168582. * the upsample/color conversion step to be passed to the quantizer.
  168583. * For two-pass color quantization, we need a full-image buffer;
  168584. * for one-pass operation, a strip buffer is sufficient.
  168585. */
  168586. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  168587. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  168588. JDIMENSION strip_height; /* buffer size in rows */
  168589. /* for two-pass mode only: */
  168590. JDIMENSION starting_row; /* row # of first row in current strip */
  168591. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  168592. } my_post_controller;
  168593. typedef my_post_controller * my_post_ptr;
  168594. /* Forward declarations */
  168595. METHODDEF(void) post_process_1pass
  168596. JPP((j_decompress_ptr cinfo,
  168597. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168598. JDIMENSION in_row_groups_avail,
  168599. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168600. JDIMENSION out_rows_avail));
  168601. #ifdef QUANT_2PASS_SUPPORTED
  168602. METHODDEF(void) post_process_prepass
  168603. JPP((j_decompress_ptr cinfo,
  168604. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168605. JDIMENSION in_row_groups_avail,
  168606. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168607. JDIMENSION out_rows_avail));
  168608. METHODDEF(void) post_process_2pass
  168609. JPP((j_decompress_ptr cinfo,
  168610. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168611. JDIMENSION in_row_groups_avail,
  168612. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168613. JDIMENSION out_rows_avail));
  168614. #endif
  168615. /*
  168616. * Initialize for a processing pass.
  168617. */
  168618. METHODDEF(void)
  168619. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  168620. {
  168621. my_post_ptr post = (my_post_ptr) cinfo->post;
  168622. switch (pass_mode) {
  168623. case JBUF_PASS_THRU:
  168624. if (cinfo->quantize_colors) {
  168625. /* Single-pass processing with color quantization. */
  168626. post->pub.post_process_data = post_process_1pass;
  168627. /* We could be doing buffered-image output before starting a 2-pass
  168628. * color quantization; in that case, jinit_d_post_controller did not
  168629. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  168630. */
  168631. if (post->buffer == NULL) {
  168632. post->buffer = (*cinfo->mem->access_virt_sarray)
  168633. ((j_common_ptr) cinfo, post->whole_image,
  168634. (JDIMENSION) 0, post->strip_height, TRUE);
  168635. }
  168636. } else {
  168637. /* For single-pass processing without color quantization,
  168638. * I have no work to do; just call the upsampler directly.
  168639. */
  168640. post->pub.post_process_data = cinfo->upsample->upsample;
  168641. }
  168642. break;
  168643. #ifdef QUANT_2PASS_SUPPORTED
  168644. case JBUF_SAVE_AND_PASS:
  168645. /* First pass of 2-pass quantization */
  168646. if (post->whole_image == NULL)
  168647. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168648. post->pub.post_process_data = post_process_prepass;
  168649. break;
  168650. case JBUF_CRANK_DEST:
  168651. /* Second pass of 2-pass quantization */
  168652. if (post->whole_image == NULL)
  168653. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168654. post->pub.post_process_data = post_process_2pass;
  168655. break;
  168656. #endif /* QUANT_2PASS_SUPPORTED */
  168657. default:
  168658. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168659. break;
  168660. }
  168661. post->starting_row = post->next_row = 0;
  168662. }
  168663. /*
  168664. * Process some data in the one-pass (strip buffer) case.
  168665. * This is used for color precision reduction as well as one-pass quantization.
  168666. */
  168667. METHODDEF(void)
  168668. post_process_1pass (j_decompress_ptr cinfo,
  168669. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168670. JDIMENSION in_row_groups_avail,
  168671. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168672. JDIMENSION out_rows_avail)
  168673. {
  168674. my_post_ptr post = (my_post_ptr) cinfo->post;
  168675. JDIMENSION num_rows, max_rows;
  168676. /* Fill the buffer, but not more than what we can dump out in one go. */
  168677. /* Note we rely on the upsampler to detect bottom of image. */
  168678. max_rows = out_rows_avail - *out_row_ctr;
  168679. if (max_rows > post->strip_height)
  168680. max_rows = post->strip_height;
  168681. num_rows = 0;
  168682. (*cinfo->upsample->upsample) (cinfo,
  168683. input_buf, in_row_group_ctr, in_row_groups_avail,
  168684. post->buffer, &num_rows, max_rows);
  168685. /* Quantize and emit data. */
  168686. (*cinfo->cquantize->color_quantize) (cinfo,
  168687. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  168688. *out_row_ctr += num_rows;
  168689. }
  168690. #ifdef QUANT_2PASS_SUPPORTED
  168691. /*
  168692. * Process some data in the first pass of 2-pass quantization.
  168693. */
  168694. METHODDEF(void)
  168695. post_process_prepass (j_decompress_ptr cinfo,
  168696. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168697. JDIMENSION in_row_groups_avail,
  168698. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168699. JDIMENSION out_rows_avail)
  168700. {
  168701. my_post_ptr post = (my_post_ptr) cinfo->post;
  168702. JDIMENSION old_next_row, num_rows;
  168703. /* Reposition virtual buffer if at start of strip. */
  168704. if (post->next_row == 0) {
  168705. post->buffer = (*cinfo->mem->access_virt_sarray)
  168706. ((j_common_ptr) cinfo, post->whole_image,
  168707. post->starting_row, post->strip_height, TRUE);
  168708. }
  168709. /* Upsample some data (up to a strip height's worth). */
  168710. old_next_row = post->next_row;
  168711. (*cinfo->upsample->upsample) (cinfo,
  168712. input_buf, in_row_group_ctr, in_row_groups_avail,
  168713. post->buffer, &post->next_row, post->strip_height);
  168714. /* Allow quantizer to scan new data. No data is emitted, */
  168715. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  168716. if (post->next_row > old_next_row) {
  168717. num_rows = post->next_row - old_next_row;
  168718. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  168719. (JSAMPARRAY) NULL, (int) num_rows);
  168720. *out_row_ctr += num_rows;
  168721. }
  168722. /* Advance if we filled the strip. */
  168723. if (post->next_row >= post->strip_height) {
  168724. post->starting_row += post->strip_height;
  168725. post->next_row = 0;
  168726. }
  168727. }
  168728. /*
  168729. * Process some data in the second pass of 2-pass quantization.
  168730. */
  168731. METHODDEF(void)
  168732. post_process_2pass (j_decompress_ptr cinfo,
  168733. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168734. JDIMENSION in_row_groups_avail,
  168735. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168736. JDIMENSION out_rows_avail)
  168737. {
  168738. my_post_ptr post = (my_post_ptr) cinfo->post;
  168739. JDIMENSION num_rows, max_rows;
  168740. /* Reposition virtual buffer if at start of strip. */
  168741. if (post->next_row == 0) {
  168742. post->buffer = (*cinfo->mem->access_virt_sarray)
  168743. ((j_common_ptr) cinfo, post->whole_image,
  168744. post->starting_row, post->strip_height, FALSE);
  168745. }
  168746. /* Determine number of rows to emit. */
  168747. num_rows = post->strip_height - post->next_row; /* available in strip */
  168748. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  168749. if (num_rows > max_rows)
  168750. num_rows = max_rows;
  168751. /* We have to check bottom of image here, can't depend on upsampler. */
  168752. max_rows = cinfo->output_height - post->starting_row;
  168753. if (num_rows > max_rows)
  168754. num_rows = max_rows;
  168755. /* Quantize and emit data. */
  168756. (*cinfo->cquantize->color_quantize) (cinfo,
  168757. post->buffer + post->next_row, output_buf + *out_row_ctr,
  168758. (int) num_rows);
  168759. *out_row_ctr += num_rows;
  168760. /* Advance if we filled the strip. */
  168761. post->next_row += num_rows;
  168762. if (post->next_row >= post->strip_height) {
  168763. post->starting_row += post->strip_height;
  168764. post->next_row = 0;
  168765. }
  168766. }
  168767. #endif /* QUANT_2PASS_SUPPORTED */
  168768. /*
  168769. * Initialize postprocessing controller.
  168770. */
  168771. GLOBAL(void)
  168772. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168773. {
  168774. my_post_ptr post;
  168775. post = (my_post_ptr)
  168776. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168777. SIZEOF(my_post_controller));
  168778. cinfo->post = (struct jpeg_d_post_controller *) post;
  168779. post->pub.start_pass = start_pass_dpost;
  168780. post->whole_image = NULL; /* flag for no virtual arrays */
  168781. post->buffer = NULL; /* flag for no strip buffer */
  168782. /* Create the quantization buffer, if needed */
  168783. if (cinfo->quantize_colors) {
  168784. /* The buffer strip height is max_v_samp_factor, which is typically
  168785. * an efficient number of rows for upsampling to return.
  168786. * (In the presence of output rescaling, we might want to be smarter?)
  168787. */
  168788. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  168789. if (need_full_buffer) {
  168790. /* Two-pass color quantization: need full-image storage. */
  168791. /* We round up the number of rows to a multiple of the strip height. */
  168792. #ifdef QUANT_2PASS_SUPPORTED
  168793. post->whole_image = (*cinfo->mem->request_virt_sarray)
  168794. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  168795. cinfo->output_width * cinfo->out_color_components,
  168796. (JDIMENSION) jround_up((long) cinfo->output_height,
  168797. (long) post->strip_height),
  168798. post->strip_height);
  168799. #else
  168800. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168801. #endif /* QUANT_2PASS_SUPPORTED */
  168802. } else {
  168803. /* One-pass color quantization: just make a strip buffer. */
  168804. post->buffer = (*cinfo->mem->alloc_sarray)
  168805. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168806. cinfo->output_width * cinfo->out_color_components,
  168807. post->strip_height);
  168808. }
  168809. }
  168810. }
  168811. /********* End of inlined file: jdpostct.c *********/
  168812. #undef FIX
  168813. /********* Start of inlined file: jdsample.c *********/
  168814. #define JPEG_INTERNALS
  168815. /* Pointer to routine to upsample a single component */
  168816. typedef JMETHOD(void, upsample1_ptr,
  168817. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168818. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  168819. /* Private subobject */
  168820. typedef struct {
  168821. struct jpeg_upsampler pub; /* public fields */
  168822. /* Color conversion buffer. When using separate upsampling and color
  168823. * conversion steps, this buffer holds one upsampled row group until it
  168824. * has been color converted and output.
  168825. * Note: we do not allocate any storage for component(s) which are full-size,
  168826. * ie do not need rescaling. The corresponding entry of color_buf[] is
  168827. * simply set to point to the input data array, thereby avoiding copying.
  168828. */
  168829. JSAMPARRAY color_buf[MAX_COMPONENTS];
  168830. /* Per-component upsampling method pointers */
  168831. upsample1_ptr methods[MAX_COMPONENTS];
  168832. int next_row_out; /* counts rows emitted from color_buf */
  168833. JDIMENSION rows_to_go; /* counts rows remaining in image */
  168834. /* Height of an input row group for each component. */
  168835. int rowgroup_height[MAX_COMPONENTS];
  168836. /* These arrays save pixel expansion factors so that int_expand need not
  168837. * recompute them each time. They are unused for other upsampling methods.
  168838. */
  168839. UINT8 h_expand[MAX_COMPONENTS];
  168840. UINT8 v_expand[MAX_COMPONENTS];
  168841. } my_upsampler2;
  168842. typedef my_upsampler2 * my_upsample_ptr2;
  168843. /*
  168844. * Initialize for an upsampling pass.
  168845. */
  168846. METHODDEF(void)
  168847. start_pass_upsample (j_decompress_ptr cinfo)
  168848. {
  168849. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  168850. /* Mark the conversion buffer empty */
  168851. upsample->next_row_out = cinfo->max_v_samp_factor;
  168852. /* Initialize total-height counter for detecting bottom of image */
  168853. upsample->rows_to_go = cinfo->output_height;
  168854. }
  168855. /*
  168856. * Control routine to do upsampling (and color conversion).
  168857. *
  168858. * In this version we upsample each component independently.
  168859. * We upsample one row group into the conversion buffer, then apply
  168860. * color conversion a row at a time.
  168861. */
  168862. METHODDEF(void)
  168863. sep_upsample (j_decompress_ptr cinfo,
  168864. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168865. JDIMENSION in_row_groups_avail,
  168866. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168867. JDIMENSION out_rows_avail)
  168868. {
  168869. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  168870. int ci;
  168871. jpeg_component_info * compptr;
  168872. JDIMENSION num_rows;
  168873. /* Fill the conversion buffer, if it's empty */
  168874. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  168875. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168876. ci++, compptr++) {
  168877. /* Invoke per-component upsample method. Notice we pass a POINTER
  168878. * to color_buf[ci], so that fullsize_upsample can change it.
  168879. */
  168880. (*upsample->methods[ci]) (cinfo, compptr,
  168881. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  168882. upsample->color_buf + ci);
  168883. }
  168884. upsample->next_row_out = 0;
  168885. }
  168886. /* Color-convert and emit rows */
  168887. /* How many we have in the buffer: */
  168888. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  168889. /* Not more than the distance to the end of the image. Need this test
  168890. * in case the image height is not a multiple of max_v_samp_factor:
  168891. */
  168892. if (num_rows > upsample->rows_to_go)
  168893. num_rows = upsample->rows_to_go;
  168894. /* And not more than what the client can accept: */
  168895. out_rows_avail -= *out_row_ctr;
  168896. if (num_rows > out_rows_avail)
  168897. num_rows = out_rows_avail;
  168898. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  168899. (JDIMENSION) upsample->next_row_out,
  168900. output_buf + *out_row_ctr,
  168901. (int) num_rows);
  168902. /* Adjust counts */
  168903. *out_row_ctr += num_rows;
  168904. upsample->rows_to_go -= num_rows;
  168905. upsample->next_row_out += num_rows;
  168906. /* When the buffer is emptied, declare this input row group consumed */
  168907. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  168908. (*in_row_group_ctr)++;
  168909. }
  168910. /*
  168911. * These are the routines invoked by sep_upsample to upsample pixel values
  168912. * of a single component. One row group is processed per call.
  168913. */
  168914. /*
  168915. * For full-size components, we just make color_buf[ci] point at the
  168916. * input buffer, and thus avoid copying any data. Note that this is
  168917. * safe only because sep_upsample doesn't declare the input row group
  168918. * "consumed" until we are done color converting and emitting it.
  168919. */
  168920. METHODDEF(void)
  168921. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168922. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168923. {
  168924. *output_data_ptr = input_data;
  168925. }
  168926. /*
  168927. * This is a no-op version used for "uninteresting" components.
  168928. * These components will not be referenced by color conversion.
  168929. */
  168930. METHODDEF(void)
  168931. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168932. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168933. {
  168934. *output_data_ptr = NULL; /* safety check */
  168935. }
  168936. /*
  168937. * This version handles any integral sampling ratios.
  168938. * This is not used for typical JPEG files, so it need not be fast.
  168939. * Nor, for that matter, is it particularly accurate: the algorithm is
  168940. * simple replication of the input pixel onto the corresponding output
  168941. * pixels. The hi-falutin sampling literature refers to this as a
  168942. * "box filter". A box filter tends to introduce visible artifacts,
  168943. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  168944. * you would be well advised to improve this code.
  168945. */
  168946. METHODDEF(void)
  168947. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168948. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168949. {
  168950. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  168951. JSAMPARRAY output_data = *output_data_ptr;
  168952. register JSAMPROW inptr, outptr;
  168953. register JSAMPLE invalue;
  168954. register int h;
  168955. JSAMPROW outend;
  168956. int h_expand, v_expand;
  168957. int inrow, outrow;
  168958. h_expand = upsample->h_expand[compptr->component_index];
  168959. v_expand = upsample->v_expand[compptr->component_index];
  168960. inrow = outrow = 0;
  168961. while (outrow < cinfo->max_v_samp_factor) {
  168962. /* Generate one output row with proper horizontal expansion */
  168963. inptr = input_data[inrow];
  168964. outptr = output_data[outrow];
  168965. outend = outptr + cinfo->output_width;
  168966. while (outptr < outend) {
  168967. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168968. for (h = h_expand; h > 0; h--) {
  168969. *outptr++ = invalue;
  168970. }
  168971. }
  168972. /* Generate any additional output rows by duplicating the first one */
  168973. if (v_expand > 1) {
  168974. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  168975. v_expand-1, cinfo->output_width);
  168976. }
  168977. inrow++;
  168978. outrow += v_expand;
  168979. }
  168980. }
  168981. /*
  168982. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  168983. * It's still a box filter.
  168984. */
  168985. METHODDEF(void)
  168986. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168987. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168988. {
  168989. JSAMPARRAY output_data = *output_data_ptr;
  168990. register JSAMPROW inptr, outptr;
  168991. register JSAMPLE invalue;
  168992. JSAMPROW outend;
  168993. int inrow;
  168994. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  168995. inptr = input_data[inrow];
  168996. outptr = output_data[inrow];
  168997. outend = outptr + cinfo->output_width;
  168998. while (outptr < outend) {
  168999. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169000. *outptr++ = invalue;
  169001. *outptr++ = invalue;
  169002. }
  169003. }
  169004. }
  169005. /*
  169006. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  169007. * It's still a box filter.
  169008. */
  169009. METHODDEF(void)
  169010. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169011. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169012. {
  169013. JSAMPARRAY output_data = *output_data_ptr;
  169014. register JSAMPROW inptr, outptr;
  169015. register JSAMPLE invalue;
  169016. JSAMPROW outend;
  169017. int inrow, outrow;
  169018. inrow = outrow = 0;
  169019. while (outrow < cinfo->max_v_samp_factor) {
  169020. inptr = input_data[inrow];
  169021. outptr = output_data[outrow];
  169022. outend = outptr + cinfo->output_width;
  169023. while (outptr < outend) {
  169024. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169025. *outptr++ = invalue;
  169026. *outptr++ = invalue;
  169027. }
  169028. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169029. 1, cinfo->output_width);
  169030. inrow++;
  169031. outrow += 2;
  169032. }
  169033. }
  169034. /*
  169035. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  169036. *
  169037. * The upsampling algorithm is linear interpolation between pixel centers,
  169038. * also known as a "triangle filter". This is a good compromise between
  169039. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  169040. * of the way between input pixel centers.
  169041. *
  169042. * A note about the "bias" calculations: when rounding fractional values to
  169043. * integer, we do not want to always round 0.5 up to the next integer.
  169044. * If we did that, we'd introduce a noticeable bias towards larger values.
  169045. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  169046. * alternate pixel locations (a simple ordered dither pattern).
  169047. */
  169048. METHODDEF(void)
  169049. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169050. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169051. {
  169052. JSAMPARRAY output_data = *output_data_ptr;
  169053. register JSAMPROW inptr, outptr;
  169054. register int invalue;
  169055. register JDIMENSION colctr;
  169056. int inrow;
  169057. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169058. inptr = input_data[inrow];
  169059. outptr = output_data[inrow];
  169060. /* Special case for first column */
  169061. invalue = GETJSAMPLE(*inptr++);
  169062. *outptr++ = (JSAMPLE) invalue;
  169063. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  169064. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169065. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  169066. invalue = GETJSAMPLE(*inptr++) * 3;
  169067. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  169068. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  169069. }
  169070. /* Special case for last column */
  169071. invalue = GETJSAMPLE(*inptr);
  169072. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  169073. *outptr++ = (JSAMPLE) invalue;
  169074. }
  169075. }
  169076. /*
  169077. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  169078. * Again a triangle filter; see comments for h2v1 case, above.
  169079. *
  169080. * It is OK for us to reference the adjacent input rows because we demanded
  169081. * context from the main buffer controller (see initialization code).
  169082. */
  169083. METHODDEF(void)
  169084. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169085. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169086. {
  169087. JSAMPARRAY output_data = *output_data_ptr;
  169088. register JSAMPROW inptr0, inptr1, outptr;
  169089. #if BITS_IN_JSAMPLE == 8
  169090. register int thiscolsum, lastcolsum, nextcolsum;
  169091. #else
  169092. register INT32 thiscolsum, lastcolsum, nextcolsum;
  169093. #endif
  169094. register JDIMENSION colctr;
  169095. int inrow, outrow, v;
  169096. inrow = outrow = 0;
  169097. while (outrow < cinfo->max_v_samp_factor) {
  169098. for (v = 0; v < 2; v++) {
  169099. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  169100. inptr0 = input_data[inrow];
  169101. if (v == 0) /* next nearest is row above */
  169102. inptr1 = input_data[inrow-1];
  169103. else /* next nearest is row below */
  169104. inptr1 = input_data[inrow+1];
  169105. outptr = output_data[outrow++];
  169106. /* Special case for first column */
  169107. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169108. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169109. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  169110. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169111. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169112. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169113. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  169114. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  169115. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169116. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169117. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169118. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169119. }
  169120. /* Special case for last column */
  169121. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169122. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  169123. }
  169124. inrow++;
  169125. }
  169126. }
  169127. /*
  169128. * Module initialization routine for upsampling.
  169129. */
  169130. GLOBAL(void)
  169131. jinit_upsampler (j_decompress_ptr cinfo)
  169132. {
  169133. my_upsample_ptr2 upsample;
  169134. int ci;
  169135. jpeg_component_info * compptr;
  169136. boolean need_buffer, do_fancy;
  169137. int h_in_group, v_in_group, h_out_group, v_out_group;
  169138. upsample = (my_upsample_ptr2)
  169139. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169140. SIZEOF(my_upsampler2));
  169141. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  169142. upsample->pub.start_pass = start_pass_upsample;
  169143. upsample->pub.upsample = sep_upsample;
  169144. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  169145. if (cinfo->CCIR601_sampling) /* this isn't supported */
  169146. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  169147. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  169148. * so don't ask for it.
  169149. */
  169150. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  169151. /* Verify we can handle the sampling factors, select per-component methods,
  169152. * and create storage as needed.
  169153. */
  169154. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169155. ci++, compptr++) {
  169156. /* Compute size of an "input group" after IDCT scaling. This many samples
  169157. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  169158. */
  169159. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  169160. cinfo->min_DCT_scaled_size;
  169161. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169162. cinfo->min_DCT_scaled_size;
  169163. h_out_group = cinfo->max_h_samp_factor;
  169164. v_out_group = cinfo->max_v_samp_factor;
  169165. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  169166. need_buffer = TRUE;
  169167. if (! compptr->component_needed) {
  169168. /* Don't bother to upsample an uninteresting component. */
  169169. upsample->methods[ci] = noop_upsample;
  169170. need_buffer = FALSE;
  169171. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  169172. /* Fullsize components can be processed without any work. */
  169173. upsample->methods[ci] = fullsize_upsample;
  169174. need_buffer = FALSE;
  169175. } else if (h_in_group * 2 == h_out_group &&
  169176. v_in_group == v_out_group) {
  169177. /* Special cases for 2h1v upsampling */
  169178. if (do_fancy && compptr->downsampled_width > 2)
  169179. upsample->methods[ci] = h2v1_fancy_upsample;
  169180. else
  169181. upsample->methods[ci] = h2v1_upsample;
  169182. } else if (h_in_group * 2 == h_out_group &&
  169183. v_in_group * 2 == v_out_group) {
  169184. /* Special cases for 2h2v upsampling */
  169185. if (do_fancy && compptr->downsampled_width > 2) {
  169186. upsample->methods[ci] = h2v2_fancy_upsample;
  169187. upsample->pub.need_context_rows = TRUE;
  169188. } else
  169189. upsample->methods[ci] = h2v2_upsample;
  169190. } else if ((h_out_group % h_in_group) == 0 &&
  169191. (v_out_group % v_in_group) == 0) {
  169192. /* Generic integral-factors upsampling method */
  169193. upsample->methods[ci] = int_upsample;
  169194. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  169195. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  169196. } else
  169197. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  169198. if (need_buffer) {
  169199. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  169200. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169201. (JDIMENSION) jround_up((long) cinfo->output_width,
  169202. (long) cinfo->max_h_samp_factor),
  169203. (JDIMENSION) cinfo->max_v_samp_factor);
  169204. }
  169205. }
  169206. }
  169207. /********* End of inlined file: jdsample.c *********/
  169208. /********* Start of inlined file: jdtrans.c *********/
  169209. #define JPEG_INTERNALS
  169210. /* Forward declarations */
  169211. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  169212. /*
  169213. * Read the coefficient arrays from a JPEG file.
  169214. * jpeg_read_header must be completed before calling this.
  169215. *
  169216. * The entire image is read into a set of virtual coefficient-block arrays,
  169217. * one per component. The return value is a pointer to the array of
  169218. * virtual-array descriptors. These can be manipulated directly via the
  169219. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  169220. * To release the memory occupied by the virtual arrays, call
  169221. * jpeg_finish_decompress() when done with the data.
  169222. *
  169223. * An alternative usage is to simply obtain access to the coefficient arrays
  169224. * during a buffered-image-mode decompression operation. This is allowed
  169225. * after any jpeg_finish_output() call. The arrays can be accessed until
  169226. * jpeg_finish_decompress() is called. (Note that any call to the library
  169227. * may reposition the arrays, so don't rely on access_virt_barray() results
  169228. * to stay valid across library calls.)
  169229. *
  169230. * Returns NULL if suspended. This case need be checked only if
  169231. * a suspending data source is used.
  169232. */
  169233. GLOBAL(jvirt_barray_ptr *)
  169234. jpeg_read_coefficients (j_decompress_ptr cinfo)
  169235. {
  169236. if (cinfo->global_state == DSTATE_READY) {
  169237. /* First call: initialize active modules */
  169238. transdecode_master_selection(cinfo);
  169239. cinfo->global_state = DSTATE_RDCOEFS;
  169240. }
  169241. if (cinfo->global_state == DSTATE_RDCOEFS) {
  169242. /* Absorb whole file into the coef buffer */
  169243. for (;;) {
  169244. int retcode;
  169245. /* Call progress monitor hook if present */
  169246. if (cinfo->progress != NULL)
  169247. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  169248. /* Absorb some more input */
  169249. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  169250. if (retcode == JPEG_SUSPENDED)
  169251. return NULL;
  169252. if (retcode == JPEG_REACHED_EOI)
  169253. break;
  169254. /* Advance progress counter if appropriate */
  169255. if (cinfo->progress != NULL &&
  169256. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  169257. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  169258. /* startup underestimated number of scans; ratchet up one scan */
  169259. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  169260. }
  169261. }
  169262. }
  169263. /* Set state so that jpeg_finish_decompress does the right thing */
  169264. cinfo->global_state = DSTATE_STOPPING;
  169265. }
  169266. /* At this point we should be in state DSTATE_STOPPING if being used
  169267. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  169268. * to the coefficients during a full buffered-image-mode decompression.
  169269. */
  169270. if ((cinfo->global_state == DSTATE_STOPPING ||
  169271. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  169272. return cinfo->coef->coef_arrays;
  169273. }
  169274. /* Oops, improper usage */
  169275. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169276. return NULL; /* keep compiler happy */
  169277. }
  169278. /*
  169279. * Master selection of decompression modules for transcoding.
  169280. * This substitutes for jdmaster.c's initialization of the full decompressor.
  169281. */
  169282. LOCAL(void)
  169283. transdecode_master_selection (j_decompress_ptr cinfo)
  169284. {
  169285. /* This is effectively a buffered-image operation. */
  169286. cinfo->buffered_image = TRUE;
  169287. /* Entropy decoding: either Huffman or arithmetic coding. */
  169288. if (cinfo->arith_code) {
  169289. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  169290. } else {
  169291. if (cinfo->progressive_mode) {
  169292. #ifdef D_PROGRESSIVE_SUPPORTED
  169293. jinit_phuff_decoder(cinfo);
  169294. #else
  169295. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169296. #endif
  169297. } else
  169298. jinit_huff_decoder(cinfo);
  169299. }
  169300. /* Always get a full-image coefficient buffer. */
  169301. jinit_d_coef_controller(cinfo, TRUE);
  169302. /* We can now tell the memory manager to allocate virtual arrays. */
  169303. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  169304. /* Initialize input side of decompressor to consume first scan. */
  169305. (*cinfo->inputctl->start_input_pass) (cinfo);
  169306. /* Initialize progress monitoring. */
  169307. if (cinfo->progress != NULL) {
  169308. int nscans;
  169309. /* Estimate number of scans to set pass_limit. */
  169310. if (cinfo->progressive_mode) {
  169311. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169312. nscans = 2 + 3 * cinfo->num_components;
  169313. } else if (cinfo->inputctl->has_multiple_scans) {
  169314. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169315. nscans = cinfo->num_components;
  169316. } else {
  169317. nscans = 1;
  169318. }
  169319. cinfo->progress->pass_counter = 0L;
  169320. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169321. cinfo->progress->completed_passes = 0;
  169322. cinfo->progress->total_passes = 1;
  169323. }
  169324. }
  169325. /********* End of inlined file: jdtrans.c *********/
  169326. /********* Start of inlined file: jfdctflt.c *********/
  169327. #define JPEG_INTERNALS
  169328. #ifdef DCT_FLOAT_SUPPORTED
  169329. /*
  169330. * This module is specialized to the case DCTSIZE = 8.
  169331. */
  169332. #if DCTSIZE != 8
  169333. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169334. #endif
  169335. /*
  169336. * Perform the forward DCT on one block of samples.
  169337. */
  169338. GLOBAL(void)
  169339. jpeg_fdct_float (FAST_FLOAT * data)
  169340. {
  169341. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169342. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  169343. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  169344. FAST_FLOAT *dataptr;
  169345. int ctr;
  169346. /* Pass 1: process rows. */
  169347. dataptr = data;
  169348. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169349. tmp0 = dataptr[0] + dataptr[7];
  169350. tmp7 = dataptr[0] - dataptr[7];
  169351. tmp1 = dataptr[1] + dataptr[6];
  169352. tmp6 = dataptr[1] - dataptr[6];
  169353. tmp2 = dataptr[2] + dataptr[5];
  169354. tmp5 = dataptr[2] - dataptr[5];
  169355. tmp3 = dataptr[3] + dataptr[4];
  169356. tmp4 = dataptr[3] - dataptr[4];
  169357. /* Even part */
  169358. tmp10 = tmp0 + tmp3; /* phase 2 */
  169359. tmp13 = tmp0 - tmp3;
  169360. tmp11 = tmp1 + tmp2;
  169361. tmp12 = tmp1 - tmp2;
  169362. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  169363. dataptr[4] = tmp10 - tmp11;
  169364. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  169365. dataptr[2] = tmp13 + z1; /* phase 5 */
  169366. dataptr[6] = tmp13 - z1;
  169367. /* Odd part */
  169368. tmp10 = tmp4 + tmp5; /* phase 2 */
  169369. tmp11 = tmp5 + tmp6;
  169370. tmp12 = tmp6 + tmp7;
  169371. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169372. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  169373. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  169374. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  169375. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  169376. z11 = tmp7 + z3; /* phase 5 */
  169377. z13 = tmp7 - z3;
  169378. dataptr[5] = z13 + z2; /* phase 6 */
  169379. dataptr[3] = z13 - z2;
  169380. dataptr[1] = z11 + z4;
  169381. dataptr[7] = z11 - z4;
  169382. dataptr += DCTSIZE; /* advance pointer to next row */
  169383. }
  169384. /* Pass 2: process columns. */
  169385. dataptr = data;
  169386. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169387. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  169388. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  169389. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  169390. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  169391. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  169392. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  169393. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  169394. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  169395. /* Even part */
  169396. tmp10 = tmp0 + tmp3; /* phase 2 */
  169397. tmp13 = tmp0 - tmp3;
  169398. tmp11 = tmp1 + tmp2;
  169399. tmp12 = tmp1 - tmp2;
  169400. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  169401. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  169402. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  169403. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  169404. dataptr[DCTSIZE*6] = tmp13 - z1;
  169405. /* Odd part */
  169406. tmp10 = tmp4 + tmp5; /* phase 2 */
  169407. tmp11 = tmp5 + tmp6;
  169408. tmp12 = tmp6 + tmp7;
  169409. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169410. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  169411. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  169412. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  169413. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  169414. z11 = tmp7 + z3; /* phase 5 */
  169415. z13 = tmp7 - z3;
  169416. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  169417. dataptr[DCTSIZE*3] = z13 - z2;
  169418. dataptr[DCTSIZE*1] = z11 + z4;
  169419. dataptr[DCTSIZE*7] = z11 - z4;
  169420. dataptr++; /* advance pointer to next column */
  169421. }
  169422. }
  169423. #endif /* DCT_FLOAT_SUPPORTED */
  169424. /********* End of inlined file: jfdctflt.c *********/
  169425. /********* Start of inlined file: jfdctint.c *********/
  169426. #define JPEG_INTERNALS
  169427. #ifdef DCT_ISLOW_SUPPORTED
  169428. /*
  169429. * This module is specialized to the case DCTSIZE = 8.
  169430. */
  169431. #if DCTSIZE != 8
  169432. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169433. #endif
  169434. /*
  169435. * The poop on this scaling stuff is as follows:
  169436. *
  169437. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  169438. * larger than the true DCT outputs. The final outputs are therefore
  169439. * a factor of N larger than desired; since N=8 this can be cured by
  169440. * a simple right shift at the end of the algorithm. The advantage of
  169441. * this arrangement is that we save two multiplications per 1-D DCT,
  169442. * because the y0 and y4 outputs need not be divided by sqrt(N).
  169443. * In the IJG code, this factor of 8 is removed by the quantization step
  169444. * (in jcdctmgr.c), NOT in this module.
  169445. *
  169446. * We have to do addition and subtraction of the integer inputs, which
  169447. * is no problem, and multiplication by fractional constants, which is
  169448. * a problem to do in integer arithmetic. We multiply all the constants
  169449. * by CONST_SCALE and convert them to integer constants (thus retaining
  169450. * CONST_BITS bits of precision in the constants). After doing a
  169451. * multiplication we have to divide the product by CONST_SCALE, with proper
  169452. * rounding, to produce the correct output. This division can be done
  169453. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  169454. * as long as possible so that partial sums can be added together with
  169455. * full fractional precision.
  169456. *
  169457. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  169458. * they are represented to better-than-integral precision. These outputs
  169459. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  169460. * with the recommended scaling. (For 12-bit sample data, the intermediate
  169461. * array is INT32 anyway.)
  169462. *
  169463. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  169464. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  169465. * shows that the values given below are the most effective.
  169466. */
  169467. #if BITS_IN_JSAMPLE == 8
  169468. #define CONST_BITS 13
  169469. #define PASS1_BITS 2
  169470. #else
  169471. #define CONST_BITS 13
  169472. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169473. #endif
  169474. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169475. * causing a lot of useless floating-point operations at run time.
  169476. * To get around this we use the following pre-calculated constants.
  169477. * If you change CONST_BITS you may want to add appropriate values.
  169478. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169479. */
  169480. #if CONST_BITS == 13
  169481. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  169482. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  169483. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  169484. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169485. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169486. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  169487. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  169488. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169489. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  169490. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  169491. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169492. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  169493. #else
  169494. #define FIX_0_298631336 FIX(0.298631336)
  169495. #define FIX_0_390180644 FIX(0.390180644)
  169496. #define FIX_0_541196100 FIX(0.541196100)
  169497. #define FIX_0_765366865 FIX(0.765366865)
  169498. #define FIX_0_899976223 FIX(0.899976223)
  169499. #define FIX_1_175875602 FIX(1.175875602)
  169500. #define FIX_1_501321110 FIX(1.501321110)
  169501. #define FIX_1_847759065 FIX(1.847759065)
  169502. #define FIX_1_961570560 FIX(1.961570560)
  169503. #define FIX_2_053119869 FIX(2.053119869)
  169504. #define FIX_2_562915447 FIX(2.562915447)
  169505. #define FIX_3_072711026 FIX(3.072711026)
  169506. #endif
  169507. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  169508. * For 8-bit samples with the recommended scaling, all the variable
  169509. * and constant values involved are no more than 16 bits wide, so a
  169510. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  169511. * For 12-bit samples, a full 32-bit multiplication will be needed.
  169512. */
  169513. #if BITS_IN_JSAMPLE == 8
  169514. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  169515. #else
  169516. #define MULTIPLY(var,const) ((var) * (const))
  169517. #endif
  169518. /*
  169519. * Perform the forward DCT on one block of samples.
  169520. */
  169521. GLOBAL(void)
  169522. jpeg_fdct_islow (DCTELEM * data)
  169523. {
  169524. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169525. INT32 tmp10, tmp11, tmp12, tmp13;
  169526. INT32 z1, z2, z3, z4, z5;
  169527. DCTELEM *dataptr;
  169528. int ctr;
  169529. SHIFT_TEMPS
  169530. /* Pass 1: process rows. */
  169531. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  169532. /* furthermore, we scale the results by 2**PASS1_BITS. */
  169533. dataptr = data;
  169534. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169535. tmp0 = dataptr[0] + dataptr[7];
  169536. tmp7 = dataptr[0] - dataptr[7];
  169537. tmp1 = dataptr[1] + dataptr[6];
  169538. tmp6 = dataptr[1] - dataptr[6];
  169539. tmp2 = dataptr[2] + dataptr[5];
  169540. tmp5 = dataptr[2] - dataptr[5];
  169541. tmp3 = dataptr[3] + dataptr[4];
  169542. tmp4 = dataptr[3] - dataptr[4];
  169543. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  169544. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  169545. */
  169546. tmp10 = tmp0 + tmp3;
  169547. tmp13 = tmp0 - tmp3;
  169548. tmp11 = tmp1 + tmp2;
  169549. tmp12 = tmp1 - tmp2;
  169550. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  169551. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  169552. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  169553. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  169554. CONST_BITS-PASS1_BITS);
  169555. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  169556. CONST_BITS-PASS1_BITS);
  169557. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  169558. * cK represents cos(K*pi/16).
  169559. * i0..i3 in the paper are tmp4..tmp7 here.
  169560. */
  169561. z1 = tmp4 + tmp7;
  169562. z2 = tmp5 + tmp6;
  169563. z3 = tmp4 + tmp6;
  169564. z4 = tmp5 + tmp7;
  169565. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169566. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169567. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169568. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169569. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169570. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169571. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169572. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169573. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169574. z3 += z5;
  169575. z4 += z5;
  169576. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  169577. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  169578. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  169579. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  169580. dataptr += DCTSIZE; /* advance pointer to next row */
  169581. }
  169582. /* Pass 2: process columns.
  169583. * We remove the PASS1_BITS scaling, but leave the results scaled up
  169584. * by an overall factor of 8.
  169585. */
  169586. dataptr = data;
  169587. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169588. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  169589. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  169590. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  169591. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  169592. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  169593. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  169594. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  169595. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  169596. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  169597. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  169598. */
  169599. tmp10 = tmp0 + tmp3;
  169600. tmp13 = tmp0 - tmp3;
  169601. tmp11 = tmp1 + tmp2;
  169602. tmp12 = tmp1 - tmp2;
  169603. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  169604. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  169605. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  169606. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  169607. CONST_BITS+PASS1_BITS);
  169608. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  169609. CONST_BITS+PASS1_BITS);
  169610. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  169611. * cK represents cos(K*pi/16).
  169612. * i0..i3 in the paper are tmp4..tmp7 here.
  169613. */
  169614. z1 = tmp4 + tmp7;
  169615. z2 = tmp5 + tmp6;
  169616. z3 = tmp4 + tmp6;
  169617. z4 = tmp5 + tmp7;
  169618. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169619. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169620. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169621. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169622. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169623. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169624. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169625. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169626. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169627. z3 += z5;
  169628. z4 += z5;
  169629. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  169630. CONST_BITS+PASS1_BITS);
  169631. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  169632. CONST_BITS+PASS1_BITS);
  169633. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  169634. CONST_BITS+PASS1_BITS);
  169635. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  169636. CONST_BITS+PASS1_BITS);
  169637. dataptr++; /* advance pointer to next column */
  169638. }
  169639. }
  169640. #endif /* DCT_ISLOW_SUPPORTED */
  169641. /********* End of inlined file: jfdctint.c *********/
  169642. #undef CONST_BITS
  169643. #undef MULTIPLY
  169644. #undef FIX_0_541196100
  169645. /********* Start of inlined file: jfdctfst.c *********/
  169646. #define JPEG_INTERNALS
  169647. #ifdef DCT_IFAST_SUPPORTED
  169648. /*
  169649. * This module is specialized to the case DCTSIZE = 8.
  169650. */
  169651. #if DCTSIZE != 8
  169652. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169653. #endif
  169654. /* Scaling decisions are generally the same as in the LL&M algorithm;
  169655. * see jfdctint.c for more details. However, we choose to descale
  169656. * (right shift) multiplication products as soon as they are formed,
  169657. * rather than carrying additional fractional bits into subsequent additions.
  169658. * This compromises accuracy slightly, but it lets us save a few shifts.
  169659. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  169660. * everywhere except in the multiplications proper; this saves a good deal
  169661. * of work on 16-bit-int machines.
  169662. *
  169663. * Again to save a few shifts, the intermediate results between pass 1 and
  169664. * pass 2 are not upscaled, but are represented only to integral precision.
  169665. *
  169666. * A final compromise is to represent the multiplicative constants to only
  169667. * 8 fractional bits, rather than 13. This saves some shifting work on some
  169668. * machines, and may also reduce the cost of multiplication (since there
  169669. * are fewer one-bits in the constants).
  169670. */
  169671. #define CONST_BITS 8
  169672. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169673. * causing a lot of useless floating-point operations at run time.
  169674. * To get around this we use the following pre-calculated constants.
  169675. * If you change CONST_BITS you may want to add appropriate values.
  169676. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169677. */
  169678. #if CONST_BITS == 8
  169679. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  169680. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  169681. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  169682. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  169683. #else
  169684. #define FIX_0_382683433 FIX(0.382683433)
  169685. #define FIX_0_541196100 FIX(0.541196100)
  169686. #define FIX_0_707106781 FIX(0.707106781)
  169687. #define FIX_1_306562965 FIX(1.306562965)
  169688. #endif
  169689. /* We can gain a little more speed, with a further compromise in accuracy,
  169690. * by omitting the addition in a descaling shift. This yields an incorrectly
  169691. * rounded result half the time...
  169692. */
  169693. #ifndef USE_ACCURATE_ROUNDING
  169694. #undef DESCALE
  169695. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  169696. #endif
  169697. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  169698. * descale to yield a DCTELEM result.
  169699. */
  169700. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  169701. /*
  169702. * Perform the forward DCT on one block of samples.
  169703. */
  169704. GLOBAL(void)
  169705. jpeg_fdct_ifast (DCTELEM * data)
  169706. {
  169707. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169708. DCTELEM tmp10, tmp11, tmp12, tmp13;
  169709. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  169710. DCTELEM *dataptr;
  169711. int ctr;
  169712. SHIFT_TEMPS
  169713. /* Pass 1: process rows. */
  169714. dataptr = data;
  169715. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169716. tmp0 = dataptr[0] + dataptr[7];
  169717. tmp7 = dataptr[0] - dataptr[7];
  169718. tmp1 = dataptr[1] + dataptr[6];
  169719. tmp6 = dataptr[1] - dataptr[6];
  169720. tmp2 = dataptr[2] + dataptr[5];
  169721. tmp5 = dataptr[2] - dataptr[5];
  169722. tmp3 = dataptr[3] + dataptr[4];
  169723. tmp4 = dataptr[3] - dataptr[4];
  169724. /* Even part */
  169725. tmp10 = tmp0 + tmp3; /* phase 2 */
  169726. tmp13 = tmp0 - tmp3;
  169727. tmp11 = tmp1 + tmp2;
  169728. tmp12 = tmp1 - tmp2;
  169729. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  169730. dataptr[4] = tmp10 - tmp11;
  169731. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  169732. dataptr[2] = tmp13 + z1; /* phase 5 */
  169733. dataptr[6] = tmp13 - z1;
  169734. /* Odd part */
  169735. tmp10 = tmp4 + tmp5; /* phase 2 */
  169736. tmp11 = tmp5 + tmp6;
  169737. tmp12 = tmp6 + tmp7;
  169738. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169739. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  169740. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  169741. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  169742. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  169743. z11 = tmp7 + z3; /* phase 5 */
  169744. z13 = tmp7 - z3;
  169745. dataptr[5] = z13 + z2; /* phase 6 */
  169746. dataptr[3] = z13 - z2;
  169747. dataptr[1] = z11 + z4;
  169748. dataptr[7] = z11 - z4;
  169749. dataptr += DCTSIZE; /* advance pointer to next row */
  169750. }
  169751. /* Pass 2: process columns. */
  169752. dataptr = data;
  169753. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169754. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  169755. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  169756. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  169757. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  169758. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  169759. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  169760. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  169761. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  169762. /* Even part */
  169763. tmp10 = tmp0 + tmp3; /* phase 2 */
  169764. tmp13 = tmp0 - tmp3;
  169765. tmp11 = tmp1 + tmp2;
  169766. tmp12 = tmp1 - tmp2;
  169767. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  169768. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  169769. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  169770. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  169771. dataptr[DCTSIZE*6] = tmp13 - z1;
  169772. /* Odd part */
  169773. tmp10 = tmp4 + tmp5; /* phase 2 */
  169774. tmp11 = tmp5 + tmp6;
  169775. tmp12 = tmp6 + tmp7;
  169776. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169777. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  169778. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  169779. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  169780. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  169781. z11 = tmp7 + z3; /* phase 5 */
  169782. z13 = tmp7 - z3;
  169783. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  169784. dataptr[DCTSIZE*3] = z13 - z2;
  169785. dataptr[DCTSIZE*1] = z11 + z4;
  169786. dataptr[DCTSIZE*7] = z11 - z4;
  169787. dataptr++; /* advance pointer to next column */
  169788. }
  169789. }
  169790. #endif /* DCT_IFAST_SUPPORTED */
  169791. /********* End of inlined file: jfdctfst.c *********/
  169792. #undef FIX_0_541196100
  169793. /********* Start of inlined file: jidctflt.c *********/
  169794. #define JPEG_INTERNALS
  169795. #ifdef DCT_FLOAT_SUPPORTED
  169796. /*
  169797. * This module is specialized to the case DCTSIZE = 8.
  169798. */
  169799. #if DCTSIZE != 8
  169800. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169801. #endif
  169802. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169803. * entry; produce a float result.
  169804. */
  169805. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  169806. /*
  169807. * Perform dequantization and inverse DCT on one block of coefficients.
  169808. */
  169809. GLOBAL(void)
  169810. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169811. JCOEFPTR coef_block,
  169812. JSAMPARRAY output_buf, JDIMENSION output_col)
  169813. {
  169814. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169815. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  169816. FAST_FLOAT z5, z10, z11, z12, z13;
  169817. JCOEFPTR inptr;
  169818. FLOAT_MULT_TYPE * quantptr;
  169819. FAST_FLOAT * wsptr;
  169820. JSAMPROW outptr;
  169821. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169822. int ctr;
  169823. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  169824. SHIFT_TEMPS
  169825. /* Pass 1: process columns from input, store into work array. */
  169826. inptr = coef_block;
  169827. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169828. wsptr = workspace;
  169829. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169830. /* Due to quantization, we will usually find that many of the input
  169831. * coefficients are zero, especially the AC terms. We can exploit this
  169832. * by short-circuiting the IDCT calculation for any column in which all
  169833. * the AC terms are zero. In that case each output is equal to the
  169834. * DC coefficient (with scale factor as needed).
  169835. * With typical images and quantization tables, half or more of the
  169836. * column DCT calculations can be simplified this way.
  169837. */
  169838. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169839. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169840. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169841. inptr[DCTSIZE*7] == 0) {
  169842. /* AC terms all zero */
  169843. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169844. wsptr[DCTSIZE*0] = dcval;
  169845. wsptr[DCTSIZE*1] = dcval;
  169846. wsptr[DCTSIZE*2] = dcval;
  169847. wsptr[DCTSIZE*3] = dcval;
  169848. wsptr[DCTSIZE*4] = dcval;
  169849. wsptr[DCTSIZE*5] = dcval;
  169850. wsptr[DCTSIZE*6] = dcval;
  169851. wsptr[DCTSIZE*7] = dcval;
  169852. inptr++; /* advance pointers to next column */
  169853. quantptr++;
  169854. wsptr++;
  169855. continue;
  169856. }
  169857. /* Even part */
  169858. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169859. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169860. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169861. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169862. tmp10 = tmp0 + tmp2; /* phase 3 */
  169863. tmp11 = tmp0 - tmp2;
  169864. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  169865. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  169866. tmp0 = tmp10 + tmp13; /* phase 2 */
  169867. tmp3 = tmp10 - tmp13;
  169868. tmp1 = tmp11 + tmp12;
  169869. tmp2 = tmp11 - tmp12;
  169870. /* Odd part */
  169871. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169872. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169873. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169874. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169875. z13 = tmp6 + tmp5; /* phase 6 */
  169876. z10 = tmp6 - tmp5;
  169877. z11 = tmp4 + tmp7;
  169878. z12 = tmp4 - tmp7;
  169879. tmp7 = z11 + z13; /* phase 5 */
  169880. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  169881. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  169882. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  169883. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  169884. tmp6 = tmp12 - tmp7; /* phase 2 */
  169885. tmp5 = tmp11 - tmp6;
  169886. tmp4 = tmp10 + tmp5;
  169887. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  169888. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  169889. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  169890. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  169891. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  169892. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  169893. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  169894. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  169895. inptr++; /* advance pointers to next column */
  169896. quantptr++;
  169897. wsptr++;
  169898. }
  169899. /* Pass 2: process rows from work array, store into output array. */
  169900. /* Note that we must descale the results by a factor of 8 == 2**3. */
  169901. wsptr = workspace;
  169902. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169903. outptr = output_buf[ctr] + output_col;
  169904. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169905. * However, the column calculation has created many nonzero AC terms, so
  169906. * the simplification applies less often (typically 5% to 10% of the time).
  169907. * And testing floats for zero is relatively expensive, so we don't bother.
  169908. */
  169909. /* Even part */
  169910. tmp10 = wsptr[0] + wsptr[4];
  169911. tmp11 = wsptr[0] - wsptr[4];
  169912. tmp13 = wsptr[2] + wsptr[6];
  169913. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  169914. tmp0 = tmp10 + tmp13;
  169915. tmp3 = tmp10 - tmp13;
  169916. tmp1 = tmp11 + tmp12;
  169917. tmp2 = tmp11 - tmp12;
  169918. /* Odd part */
  169919. z13 = wsptr[5] + wsptr[3];
  169920. z10 = wsptr[5] - wsptr[3];
  169921. z11 = wsptr[1] + wsptr[7];
  169922. z12 = wsptr[1] - wsptr[7];
  169923. tmp7 = z11 + z13;
  169924. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  169925. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  169926. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  169927. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  169928. tmp6 = tmp12 - tmp7;
  169929. tmp5 = tmp11 - tmp6;
  169930. tmp4 = tmp10 + tmp5;
  169931. /* Final output stage: scale down by a factor of 8 and range-limit */
  169932. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  169933. & RANGE_MASK];
  169934. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  169935. & RANGE_MASK];
  169936. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  169937. & RANGE_MASK];
  169938. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  169939. & RANGE_MASK];
  169940. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  169941. & RANGE_MASK];
  169942. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  169943. & RANGE_MASK];
  169944. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  169945. & RANGE_MASK];
  169946. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  169947. & RANGE_MASK];
  169948. wsptr += DCTSIZE; /* advance pointer to next row */
  169949. }
  169950. }
  169951. #endif /* DCT_FLOAT_SUPPORTED */
  169952. /********* End of inlined file: jidctflt.c *********/
  169953. #undef CONST_BITS
  169954. #undef FIX_1_847759065
  169955. #undef MULTIPLY
  169956. #undef DEQUANTIZE
  169957. #undef DESCALE
  169958. /********* Start of inlined file: jidctfst.c *********/
  169959. #define JPEG_INTERNALS
  169960. #ifdef DCT_IFAST_SUPPORTED
  169961. /*
  169962. * This module is specialized to the case DCTSIZE = 8.
  169963. */
  169964. #if DCTSIZE != 8
  169965. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169966. #endif
  169967. /* Scaling decisions are generally the same as in the LL&M algorithm;
  169968. * see jidctint.c for more details. However, we choose to descale
  169969. * (right shift) multiplication products as soon as they are formed,
  169970. * rather than carrying additional fractional bits into subsequent additions.
  169971. * This compromises accuracy slightly, but it lets us save a few shifts.
  169972. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  169973. * everywhere except in the multiplications proper; this saves a good deal
  169974. * of work on 16-bit-int machines.
  169975. *
  169976. * The dequantized coefficients are not integers because the AA&N scaling
  169977. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  169978. * so that the first and second IDCT rounds have the same input scaling.
  169979. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  169980. * avoid a descaling shift; this compromises accuracy rather drastically
  169981. * for small quantization table entries, but it saves a lot of shifts.
  169982. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  169983. * so we use a much larger scaling factor to preserve accuracy.
  169984. *
  169985. * A final compromise is to represent the multiplicative constants to only
  169986. * 8 fractional bits, rather than 13. This saves some shifting work on some
  169987. * machines, and may also reduce the cost of multiplication (since there
  169988. * are fewer one-bits in the constants).
  169989. */
  169990. #if BITS_IN_JSAMPLE == 8
  169991. #define CONST_BITS 8
  169992. #define PASS1_BITS 2
  169993. #else
  169994. #define CONST_BITS 8
  169995. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169996. #endif
  169997. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169998. * causing a lot of useless floating-point operations at run time.
  169999. * To get around this we use the following pre-calculated constants.
  170000. * If you change CONST_BITS you may want to add appropriate values.
  170001. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170002. */
  170003. #if CONST_BITS == 8
  170004. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  170005. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  170006. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  170007. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  170008. #else
  170009. #define FIX_1_082392200 FIX(1.082392200)
  170010. #define FIX_1_414213562 FIX(1.414213562)
  170011. #define FIX_1_847759065 FIX(1.847759065)
  170012. #define FIX_2_613125930 FIX(2.613125930)
  170013. #endif
  170014. /* We can gain a little more speed, with a further compromise in accuracy,
  170015. * by omitting the addition in a descaling shift. This yields an incorrectly
  170016. * rounded result half the time...
  170017. */
  170018. #ifndef USE_ACCURATE_ROUNDING
  170019. #undef DESCALE
  170020. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170021. #endif
  170022. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170023. * descale to yield a DCTELEM result.
  170024. */
  170025. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170026. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170027. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  170028. * multiplication will do. For 12-bit data, the multiplier table is
  170029. * declared INT32, so a 32-bit multiply will be used.
  170030. */
  170031. #if BITS_IN_JSAMPLE == 8
  170032. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  170033. #else
  170034. #define DEQUANTIZE(coef,quantval) \
  170035. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  170036. #endif
  170037. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  170038. * We assume that int right shift is unsigned if INT32 right shift is.
  170039. */
  170040. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  170041. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  170042. #if BITS_IN_JSAMPLE == 8
  170043. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  170044. #else
  170045. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  170046. #endif
  170047. #define IRIGHT_SHIFT(x,shft) \
  170048. ((ishift_temp = (x)) < 0 ? \
  170049. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  170050. (ishift_temp >> (shft)))
  170051. #else
  170052. #define ISHIFT_TEMPS
  170053. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  170054. #endif
  170055. #ifdef USE_ACCURATE_ROUNDING
  170056. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  170057. #else
  170058. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  170059. #endif
  170060. /*
  170061. * Perform dequantization and inverse DCT on one block of coefficients.
  170062. */
  170063. GLOBAL(void)
  170064. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170065. JCOEFPTR coef_block,
  170066. JSAMPARRAY output_buf, JDIMENSION output_col)
  170067. {
  170068. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170069. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170070. DCTELEM z5, z10, z11, z12, z13;
  170071. JCOEFPTR inptr;
  170072. IFAST_MULT_TYPE * quantptr;
  170073. int * wsptr;
  170074. JSAMPROW outptr;
  170075. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170076. int ctr;
  170077. int workspace[DCTSIZE2]; /* buffers data between passes */
  170078. SHIFT_TEMPS /* for DESCALE */
  170079. ISHIFT_TEMPS /* for IDESCALE */
  170080. /* Pass 1: process columns from input, store into work array. */
  170081. inptr = coef_block;
  170082. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  170083. wsptr = workspace;
  170084. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170085. /* Due to quantization, we will usually find that many of the input
  170086. * coefficients are zero, especially the AC terms. We can exploit this
  170087. * by short-circuiting the IDCT calculation for any column in which all
  170088. * the AC terms are zero. In that case each output is equal to the
  170089. * DC coefficient (with scale factor as needed).
  170090. * With typical images and quantization tables, half or more of the
  170091. * column DCT calculations can be simplified this way.
  170092. */
  170093. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170094. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170095. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170096. inptr[DCTSIZE*7] == 0) {
  170097. /* AC terms all zero */
  170098. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170099. wsptr[DCTSIZE*0] = dcval;
  170100. wsptr[DCTSIZE*1] = dcval;
  170101. wsptr[DCTSIZE*2] = dcval;
  170102. wsptr[DCTSIZE*3] = dcval;
  170103. wsptr[DCTSIZE*4] = dcval;
  170104. wsptr[DCTSIZE*5] = dcval;
  170105. wsptr[DCTSIZE*6] = dcval;
  170106. wsptr[DCTSIZE*7] = dcval;
  170107. inptr++; /* advance pointers to next column */
  170108. quantptr++;
  170109. wsptr++;
  170110. continue;
  170111. }
  170112. /* Even part */
  170113. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170114. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170115. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170116. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170117. tmp10 = tmp0 + tmp2; /* phase 3 */
  170118. tmp11 = tmp0 - tmp2;
  170119. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170120. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  170121. tmp0 = tmp10 + tmp13; /* phase 2 */
  170122. tmp3 = tmp10 - tmp13;
  170123. tmp1 = tmp11 + tmp12;
  170124. tmp2 = tmp11 - tmp12;
  170125. /* Odd part */
  170126. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170127. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170128. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170129. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170130. z13 = tmp6 + tmp5; /* phase 6 */
  170131. z10 = tmp6 - tmp5;
  170132. z11 = tmp4 + tmp7;
  170133. z12 = tmp4 - tmp7;
  170134. tmp7 = z11 + z13; /* phase 5 */
  170135. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170136. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170137. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170138. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170139. tmp6 = tmp12 - tmp7; /* phase 2 */
  170140. tmp5 = tmp11 - tmp6;
  170141. tmp4 = tmp10 + tmp5;
  170142. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  170143. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  170144. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  170145. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  170146. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  170147. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  170148. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  170149. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  170150. inptr++; /* advance pointers to next column */
  170151. quantptr++;
  170152. wsptr++;
  170153. }
  170154. /* Pass 2: process rows from work array, store into output array. */
  170155. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170156. /* and also undo the PASS1_BITS scaling. */
  170157. wsptr = workspace;
  170158. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170159. outptr = output_buf[ctr] + output_col;
  170160. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170161. * However, the column calculation has created many nonzero AC terms, so
  170162. * the simplification applies less often (typically 5% to 10% of the time).
  170163. * On machines with very fast multiplication, it's possible that the
  170164. * test takes more time than it's worth. In that case this section
  170165. * may be commented out.
  170166. */
  170167. #ifndef NO_ZERO_ROW_TEST
  170168. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170169. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170170. /* AC terms all zero */
  170171. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  170172. & RANGE_MASK];
  170173. outptr[0] = dcval;
  170174. outptr[1] = dcval;
  170175. outptr[2] = dcval;
  170176. outptr[3] = dcval;
  170177. outptr[4] = dcval;
  170178. outptr[5] = dcval;
  170179. outptr[6] = dcval;
  170180. outptr[7] = dcval;
  170181. wsptr += DCTSIZE; /* advance pointer to next row */
  170182. continue;
  170183. }
  170184. #endif
  170185. /* Even part */
  170186. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  170187. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  170188. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  170189. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  170190. - tmp13;
  170191. tmp0 = tmp10 + tmp13;
  170192. tmp3 = tmp10 - tmp13;
  170193. tmp1 = tmp11 + tmp12;
  170194. tmp2 = tmp11 - tmp12;
  170195. /* Odd part */
  170196. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  170197. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  170198. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  170199. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  170200. tmp7 = z11 + z13; /* phase 5 */
  170201. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170202. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170203. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170204. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170205. tmp6 = tmp12 - tmp7; /* phase 2 */
  170206. tmp5 = tmp11 - tmp6;
  170207. tmp4 = tmp10 + tmp5;
  170208. /* Final output stage: scale down by a factor of 8 and range-limit */
  170209. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  170210. & RANGE_MASK];
  170211. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  170212. & RANGE_MASK];
  170213. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  170214. & RANGE_MASK];
  170215. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  170216. & RANGE_MASK];
  170217. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  170218. & RANGE_MASK];
  170219. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  170220. & RANGE_MASK];
  170221. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  170222. & RANGE_MASK];
  170223. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  170224. & RANGE_MASK];
  170225. wsptr += DCTSIZE; /* advance pointer to next row */
  170226. }
  170227. }
  170228. #endif /* DCT_IFAST_SUPPORTED */
  170229. /********* End of inlined file: jidctfst.c *********/
  170230. #undef CONST_BITS
  170231. #undef FIX_1_847759065
  170232. #undef MULTIPLY
  170233. #undef DEQUANTIZE
  170234. /********* Start of inlined file: jidctint.c *********/
  170235. #define JPEG_INTERNALS
  170236. #ifdef DCT_ISLOW_SUPPORTED
  170237. /*
  170238. * This module is specialized to the case DCTSIZE = 8.
  170239. */
  170240. #if DCTSIZE != 8
  170241. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170242. #endif
  170243. /*
  170244. * The poop on this scaling stuff is as follows:
  170245. *
  170246. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  170247. * larger than the true IDCT outputs. The final outputs are therefore
  170248. * a factor of N larger than desired; since N=8 this can be cured by
  170249. * a simple right shift at the end of the algorithm. The advantage of
  170250. * this arrangement is that we save two multiplications per 1-D IDCT,
  170251. * because the y0 and y4 inputs need not be divided by sqrt(N).
  170252. *
  170253. * We have to do addition and subtraction of the integer inputs, which
  170254. * is no problem, and multiplication by fractional constants, which is
  170255. * a problem to do in integer arithmetic. We multiply all the constants
  170256. * by CONST_SCALE and convert them to integer constants (thus retaining
  170257. * CONST_BITS bits of precision in the constants). After doing a
  170258. * multiplication we have to divide the product by CONST_SCALE, with proper
  170259. * rounding, to produce the correct output. This division can be done
  170260. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170261. * as long as possible so that partial sums can be added together with
  170262. * full fractional precision.
  170263. *
  170264. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170265. * they are represented to better-than-integral precision. These outputs
  170266. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170267. * with the recommended scaling. (To scale up 12-bit sample data further, an
  170268. * intermediate INT32 array would be needed.)
  170269. *
  170270. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170271. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170272. * shows that the values given below are the most effective.
  170273. */
  170274. #if BITS_IN_JSAMPLE == 8
  170275. #define CONST_BITS 13
  170276. #define PASS1_BITS 2
  170277. #else
  170278. #define CONST_BITS 13
  170279. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170280. #endif
  170281. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170282. * causing a lot of useless floating-point operations at run time.
  170283. * To get around this we use the following pre-calculated constants.
  170284. * If you change CONST_BITS you may want to add appropriate values.
  170285. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170286. */
  170287. #if CONST_BITS == 13
  170288. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170289. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170290. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170291. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170292. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170293. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170294. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170295. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170296. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170297. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170298. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170299. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170300. #else
  170301. #define FIX_0_298631336 FIX(0.298631336)
  170302. #define FIX_0_390180644 FIX(0.390180644)
  170303. #define FIX_0_541196100 FIX(0.541196100)
  170304. #define FIX_0_765366865 FIX(0.765366865)
  170305. #define FIX_0_899976223 FIX(0.899976223)
  170306. #define FIX_1_175875602 FIX(1.175875602)
  170307. #define FIX_1_501321110 FIX(1.501321110)
  170308. #define FIX_1_847759065 FIX(1.847759065)
  170309. #define FIX_1_961570560 FIX(1.961570560)
  170310. #define FIX_2_053119869 FIX(2.053119869)
  170311. #define FIX_2_562915447 FIX(2.562915447)
  170312. #define FIX_3_072711026 FIX(3.072711026)
  170313. #endif
  170314. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170315. * For 8-bit samples with the recommended scaling, all the variable
  170316. * and constant values involved are no more than 16 bits wide, so a
  170317. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170318. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170319. */
  170320. #if BITS_IN_JSAMPLE == 8
  170321. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170322. #else
  170323. #define MULTIPLY(var,const) ((var) * (const))
  170324. #endif
  170325. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170326. * entry; produce an int result. In this module, both inputs and result
  170327. * are 16 bits or less, so either int or short multiply will work.
  170328. */
  170329. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  170330. /*
  170331. * Perform dequantization and inverse DCT on one block of coefficients.
  170332. */
  170333. GLOBAL(void)
  170334. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170335. JCOEFPTR coef_block,
  170336. JSAMPARRAY output_buf, JDIMENSION output_col)
  170337. {
  170338. INT32 tmp0, tmp1, tmp2, tmp3;
  170339. INT32 tmp10, tmp11, tmp12, tmp13;
  170340. INT32 z1, z2, z3, z4, z5;
  170341. JCOEFPTR inptr;
  170342. ISLOW_MULT_TYPE * quantptr;
  170343. int * wsptr;
  170344. JSAMPROW outptr;
  170345. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170346. int ctr;
  170347. int workspace[DCTSIZE2]; /* buffers data between passes */
  170348. SHIFT_TEMPS
  170349. /* Pass 1: process columns from input, store into work array. */
  170350. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  170351. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170352. inptr = coef_block;
  170353. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170354. wsptr = workspace;
  170355. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170356. /* Due to quantization, we will usually find that many of the input
  170357. * coefficients are zero, especially the AC terms. We can exploit this
  170358. * by short-circuiting the IDCT calculation for any column in which all
  170359. * the AC terms are zero. In that case each output is equal to the
  170360. * DC coefficient (with scale factor as needed).
  170361. * With typical images and quantization tables, half or more of the
  170362. * column DCT calculations can be simplified this way.
  170363. */
  170364. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170365. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170366. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170367. inptr[DCTSIZE*7] == 0) {
  170368. /* AC terms all zero */
  170369. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  170370. wsptr[DCTSIZE*0] = dcval;
  170371. wsptr[DCTSIZE*1] = dcval;
  170372. wsptr[DCTSIZE*2] = dcval;
  170373. wsptr[DCTSIZE*3] = dcval;
  170374. wsptr[DCTSIZE*4] = dcval;
  170375. wsptr[DCTSIZE*5] = dcval;
  170376. wsptr[DCTSIZE*6] = dcval;
  170377. wsptr[DCTSIZE*7] = dcval;
  170378. inptr++; /* advance pointers to next column */
  170379. quantptr++;
  170380. wsptr++;
  170381. continue;
  170382. }
  170383. /* Even part: reverse the even part of the forward DCT. */
  170384. /* The rotator is sqrt(2)*c(-6). */
  170385. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170386. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170387. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  170388. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  170389. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  170390. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170391. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170392. tmp0 = (z2 + z3) << CONST_BITS;
  170393. tmp1 = (z2 - z3) << CONST_BITS;
  170394. tmp10 = tmp0 + tmp3;
  170395. tmp13 = tmp0 - tmp3;
  170396. tmp11 = tmp1 + tmp2;
  170397. tmp12 = tmp1 - tmp2;
  170398. /* Odd part per figure 8; the matrix is unitary and hence its
  170399. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  170400. */
  170401. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170402. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170403. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170404. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170405. z1 = tmp0 + tmp3;
  170406. z2 = tmp1 + tmp2;
  170407. z3 = tmp0 + tmp2;
  170408. z4 = tmp1 + tmp3;
  170409. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170410. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170411. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170412. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170413. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170414. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170415. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170416. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170417. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170418. z3 += z5;
  170419. z4 += z5;
  170420. tmp0 += z1 + z3;
  170421. tmp1 += z2 + z4;
  170422. tmp2 += z2 + z3;
  170423. tmp3 += z1 + z4;
  170424. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  170425. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  170426. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  170427. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  170428. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  170429. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  170430. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  170431. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  170432. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  170433. inptr++; /* advance pointers to next column */
  170434. quantptr++;
  170435. wsptr++;
  170436. }
  170437. /* Pass 2: process rows from work array, store into output array. */
  170438. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170439. /* and also undo the PASS1_BITS scaling. */
  170440. wsptr = workspace;
  170441. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170442. outptr = output_buf[ctr] + output_col;
  170443. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170444. * However, the column calculation has created many nonzero AC terms, so
  170445. * the simplification applies less often (typically 5% to 10% of the time).
  170446. * On machines with very fast multiplication, it's possible that the
  170447. * test takes more time than it's worth. In that case this section
  170448. * may be commented out.
  170449. */
  170450. #ifndef NO_ZERO_ROW_TEST
  170451. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170452. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170453. /* AC terms all zero */
  170454. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  170455. & RANGE_MASK];
  170456. outptr[0] = dcval;
  170457. outptr[1] = dcval;
  170458. outptr[2] = dcval;
  170459. outptr[3] = dcval;
  170460. outptr[4] = dcval;
  170461. outptr[5] = dcval;
  170462. outptr[6] = dcval;
  170463. outptr[7] = dcval;
  170464. wsptr += DCTSIZE; /* advance pointer to next row */
  170465. continue;
  170466. }
  170467. #endif
  170468. /* Even part: reverse the even part of the forward DCT. */
  170469. /* The rotator is sqrt(2)*c(-6). */
  170470. z2 = (INT32) wsptr[2];
  170471. z3 = (INT32) wsptr[6];
  170472. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  170473. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  170474. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  170475. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  170476. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  170477. tmp10 = tmp0 + tmp3;
  170478. tmp13 = tmp0 - tmp3;
  170479. tmp11 = tmp1 + tmp2;
  170480. tmp12 = tmp1 - tmp2;
  170481. /* Odd part per figure 8; the matrix is unitary and hence its
  170482. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  170483. */
  170484. tmp0 = (INT32) wsptr[7];
  170485. tmp1 = (INT32) wsptr[5];
  170486. tmp2 = (INT32) wsptr[3];
  170487. tmp3 = (INT32) wsptr[1];
  170488. z1 = tmp0 + tmp3;
  170489. z2 = tmp1 + tmp2;
  170490. z3 = tmp0 + tmp2;
  170491. z4 = tmp1 + tmp3;
  170492. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170493. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170494. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170495. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170496. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170497. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170498. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170499. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170500. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170501. z3 += z5;
  170502. z4 += z5;
  170503. tmp0 += z1 + z3;
  170504. tmp1 += z2 + z4;
  170505. tmp2 += z2 + z3;
  170506. tmp3 += z1 + z4;
  170507. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  170508. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  170509. CONST_BITS+PASS1_BITS+3)
  170510. & RANGE_MASK];
  170511. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  170512. CONST_BITS+PASS1_BITS+3)
  170513. & RANGE_MASK];
  170514. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  170515. CONST_BITS+PASS1_BITS+3)
  170516. & RANGE_MASK];
  170517. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  170518. CONST_BITS+PASS1_BITS+3)
  170519. & RANGE_MASK];
  170520. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  170521. CONST_BITS+PASS1_BITS+3)
  170522. & RANGE_MASK];
  170523. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  170524. CONST_BITS+PASS1_BITS+3)
  170525. & RANGE_MASK];
  170526. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  170527. CONST_BITS+PASS1_BITS+3)
  170528. & RANGE_MASK];
  170529. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  170530. CONST_BITS+PASS1_BITS+3)
  170531. & RANGE_MASK];
  170532. wsptr += DCTSIZE; /* advance pointer to next row */
  170533. }
  170534. }
  170535. #endif /* DCT_ISLOW_SUPPORTED */
  170536. /********* End of inlined file: jidctint.c *********/
  170537. /********* Start of inlined file: jidctred.c *********/
  170538. #define JPEG_INTERNALS
  170539. #ifdef IDCT_SCALING_SUPPORTED
  170540. /*
  170541. * This module is specialized to the case DCTSIZE = 8.
  170542. */
  170543. #if DCTSIZE != 8
  170544. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170545. #endif
  170546. /* Scaling is the same as in jidctint.c. */
  170547. #if BITS_IN_JSAMPLE == 8
  170548. #define CONST_BITS 13
  170549. #define PASS1_BITS 2
  170550. #else
  170551. #define CONST_BITS 13
  170552. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170553. #endif
  170554. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170555. * causing a lot of useless floating-point operations at run time.
  170556. * To get around this we use the following pre-calculated constants.
  170557. * If you change CONST_BITS you may want to add appropriate values.
  170558. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170559. */
  170560. #if CONST_BITS == 13
  170561. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  170562. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  170563. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  170564. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  170565. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170566. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  170567. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170568. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  170569. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  170570. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  170571. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170572. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  170573. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170574. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  170575. #else
  170576. #define FIX_0_211164243 FIX(0.211164243)
  170577. #define FIX_0_509795579 FIX(0.509795579)
  170578. #define FIX_0_601344887 FIX(0.601344887)
  170579. #define FIX_0_720959822 FIX(0.720959822)
  170580. #define FIX_0_765366865 FIX(0.765366865)
  170581. #define FIX_0_850430095 FIX(0.850430095)
  170582. #define FIX_0_899976223 FIX(0.899976223)
  170583. #define FIX_1_061594337 FIX(1.061594337)
  170584. #define FIX_1_272758580 FIX(1.272758580)
  170585. #define FIX_1_451774981 FIX(1.451774981)
  170586. #define FIX_1_847759065 FIX(1.847759065)
  170587. #define FIX_2_172734803 FIX(2.172734803)
  170588. #define FIX_2_562915447 FIX(2.562915447)
  170589. #define FIX_3_624509785 FIX(3.624509785)
  170590. #endif
  170591. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170592. * For 8-bit samples with the recommended scaling, all the variable
  170593. * and constant values involved are no more than 16 bits wide, so a
  170594. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170595. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170596. */
  170597. #if BITS_IN_JSAMPLE == 8
  170598. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170599. #else
  170600. #define MULTIPLY(var,const) ((var) * (const))
  170601. #endif
  170602. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170603. * entry; produce an int result. In this module, both inputs and result
  170604. * are 16 bits or less, so either int or short multiply will work.
  170605. */
  170606. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  170607. /*
  170608. * Perform dequantization and inverse DCT on one block of coefficients,
  170609. * producing a reduced-size 4x4 output block.
  170610. */
  170611. GLOBAL(void)
  170612. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170613. JCOEFPTR coef_block,
  170614. JSAMPARRAY output_buf, JDIMENSION output_col)
  170615. {
  170616. INT32 tmp0, tmp2, tmp10, tmp12;
  170617. INT32 z1, z2, z3, z4;
  170618. JCOEFPTR inptr;
  170619. ISLOW_MULT_TYPE * quantptr;
  170620. int * wsptr;
  170621. JSAMPROW outptr;
  170622. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170623. int ctr;
  170624. int workspace[DCTSIZE*4]; /* buffers data between passes */
  170625. SHIFT_TEMPS
  170626. /* Pass 1: process columns from input, store into work array. */
  170627. inptr = coef_block;
  170628. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170629. wsptr = workspace;
  170630. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  170631. /* Don't bother to process column 4, because second pass won't use it */
  170632. if (ctr == DCTSIZE-4)
  170633. continue;
  170634. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170635. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  170636. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  170637. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  170638. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  170639. wsptr[DCTSIZE*0] = dcval;
  170640. wsptr[DCTSIZE*1] = dcval;
  170641. wsptr[DCTSIZE*2] = dcval;
  170642. wsptr[DCTSIZE*3] = dcval;
  170643. continue;
  170644. }
  170645. /* Even part */
  170646. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170647. tmp0 <<= (CONST_BITS+1);
  170648. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170649. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170650. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  170651. tmp10 = tmp0 + tmp2;
  170652. tmp12 = tmp0 - tmp2;
  170653. /* Odd part */
  170654. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170655. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170656. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170657. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170658. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  170659. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  170660. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  170661. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  170662. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  170663. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  170664. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  170665. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  170666. /* Final output stage */
  170667. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  170668. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  170669. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  170670. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  170671. }
  170672. /* Pass 2: process 4 rows from work array, store into output array. */
  170673. wsptr = workspace;
  170674. for (ctr = 0; ctr < 4; ctr++) {
  170675. outptr = output_buf[ctr] + output_col;
  170676. /* It's not clear whether a zero row test is worthwhile here ... */
  170677. #ifndef NO_ZERO_ROW_TEST
  170678. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  170679. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170680. /* AC terms all zero */
  170681. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  170682. & RANGE_MASK];
  170683. outptr[0] = dcval;
  170684. outptr[1] = dcval;
  170685. outptr[2] = dcval;
  170686. outptr[3] = dcval;
  170687. wsptr += DCTSIZE; /* advance pointer to next row */
  170688. continue;
  170689. }
  170690. #endif
  170691. /* Even part */
  170692. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  170693. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  170694. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  170695. tmp10 = tmp0 + tmp2;
  170696. tmp12 = tmp0 - tmp2;
  170697. /* Odd part */
  170698. z1 = (INT32) wsptr[7];
  170699. z2 = (INT32) wsptr[5];
  170700. z3 = (INT32) wsptr[3];
  170701. z4 = (INT32) wsptr[1];
  170702. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  170703. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  170704. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  170705. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  170706. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  170707. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  170708. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  170709. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  170710. /* Final output stage */
  170711. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  170712. CONST_BITS+PASS1_BITS+3+1)
  170713. & RANGE_MASK];
  170714. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  170715. CONST_BITS+PASS1_BITS+3+1)
  170716. & RANGE_MASK];
  170717. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  170718. CONST_BITS+PASS1_BITS+3+1)
  170719. & RANGE_MASK];
  170720. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  170721. CONST_BITS+PASS1_BITS+3+1)
  170722. & RANGE_MASK];
  170723. wsptr += DCTSIZE; /* advance pointer to next row */
  170724. }
  170725. }
  170726. /*
  170727. * Perform dequantization and inverse DCT on one block of coefficients,
  170728. * producing a reduced-size 2x2 output block.
  170729. */
  170730. GLOBAL(void)
  170731. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170732. JCOEFPTR coef_block,
  170733. JSAMPARRAY output_buf, JDIMENSION output_col)
  170734. {
  170735. INT32 tmp0, tmp10, z1;
  170736. JCOEFPTR inptr;
  170737. ISLOW_MULT_TYPE * quantptr;
  170738. int * wsptr;
  170739. JSAMPROW outptr;
  170740. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170741. int ctr;
  170742. int workspace[DCTSIZE*2]; /* buffers data between passes */
  170743. SHIFT_TEMPS
  170744. /* Pass 1: process columns from input, store into work array. */
  170745. inptr = coef_block;
  170746. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170747. wsptr = workspace;
  170748. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  170749. /* Don't bother to process columns 2,4,6 */
  170750. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  170751. continue;
  170752. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  170753. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  170754. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  170755. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  170756. wsptr[DCTSIZE*0] = dcval;
  170757. wsptr[DCTSIZE*1] = dcval;
  170758. continue;
  170759. }
  170760. /* Even part */
  170761. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170762. tmp10 = z1 << (CONST_BITS+2);
  170763. /* Odd part */
  170764. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170765. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  170766. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170767. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  170768. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170769. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  170770. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170771. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  170772. /* Final output stage */
  170773. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  170774. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  170775. }
  170776. /* Pass 2: process 2 rows from work array, store into output array. */
  170777. wsptr = workspace;
  170778. for (ctr = 0; ctr < 2; ctr++) {
  170779. outptr = output_buf[ctr] + output_col;
  170780. /* It's not clear whether a zero row test is worthwhile here ... */
  170781. #ifndef NO_ZERO_ROW_TEST
  170782. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  170783. /* AC terms all zero */
  170784. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  170785. & RANGE_MASK];
  170786. outptr[0] = dcval;
  170787. outptr[1] = dcval;
  170788. wsptr += DCTSIZE; /* advance pointer to next row */
  170789. continue;
  170790. }
  170791. #endif
  170792. /* Even part */
  170793. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  170794. /* Odd part */
  170795. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  170796. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  170797. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  170798. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  170799. /* Final output stage */
  170800. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  170801. CONST_BITS+PASS1_BITS+3+2)
  170802. & RANGE_MASK];
  170803. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  170804. CONST_BITS+PASS1_BITS+3+2)
  170805. & RANGE_MASK];
  170806. wsptr += DCTSIZE; /* advance pointer to next row */
  170807. }
  170808. }
  170809. /*
  170810. * Perform dequantization and inverse DCT on one block of coefficients,
  170811. * producing a reduced-size 1x1 output block.
  170812. */
  170813. GLOBAL(void)
  170814. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170815. JCOEFPTR coef_block,
  170816. JSAMPARRAY output_buf, JDIMENSION output_col)
  170817. {
  170818. int dcval;
  170819. ISLOW_MULT_TYPE * quantptr;
  170820. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170821. SHIFT_TEMPS
  170822. /* We hardly need an inverse DCT routine for this: just take the
  170823. * average pixel value, which is one-eighth of the DC coefficient.
  170824. */
  170825. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170826. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  170827. dcval = (int) DESCALE((INT32) dcval, 3);
  170828. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  170829. }
  170830. #endif /* IDCT_SCALING_SUPPORTED */
  170831. /********* End of inlined file: jidctred.c *********/
  170832. /********* Start of inlined file: jmemmgr.c *********/
  170833. #define JPEG_INTERNALS
  170834. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  170835. /********* Start of inlined file: jmemsys.h *********/
  170836. #ifndef __jmemsys_h__
  170837. #define __jmemsys_h__
  170838. /* Short forms of external names for systems with brain-damaged linkers. */
  170839. #ifdef NEED_SHORT_EXTERNAL_NAMES
  170840. #define jpeg_get_small jGetSmall
  170841. #define jpeg_free_small jFreeSmall
  170842. #define jpeg_get_large jGetLarge
  170843. #define jpeg_free_large jFreeLarge
  170844. #define jpeg_mem_available jMemAvail
  170845. #define jpeg_open_backing_store jOpenBackStore
  170846. #define jpeg_mem_init jMemInit
  170847. #define jpeg_mem_term jMemTerm
  170848. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  170849. /*
  170850. * These two functions are used to allocate and release small chunks of
  170851. * memory. (Typically the total amount requested through jpeg_get_small is
  170852. * no more than 20K or so; this will be requested in chunks of a few K each.)
  170853. * Behavior should be the same as for the standard library functions malloc
  170854. * and free; in particular, jpeg_get_small must return NULL on failure.
  170855. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  170856. * size of the object being freed, just in case it's needed.
  170857. * On an 80x86 machine using small-data memory model, these manage near heap.
  170858. */
  170859. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  170860. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  170861. size_t sizeofobject));
  170862. /*
  170863. * These two functions are used to allocate and release large chunks of
  170864. * memory (up to the total free space designated by jpeg_mem_available).
  170865. * The interface is the same as above, except that on an 80x86 machine,
  170866. * far pointers are used. On most other machines these are identical to
  170867. * the jpeg_get/free_small routines; but we keep them separate anyway,
  170868. * in case a different allocation strategy is desirable for large chunks.
  170869. */
  170870. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  170871. size_t sizeofobject));
  170872. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  170873. size_t sizeofobject));
  170874. /*
  170875. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  170876. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  170877. * matter, but that case should never come into play). This macro is needed
  170878. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  170879. * On those machines, we expect that jconfig.h will provide a proper value.
  170880. * On machines with 32-bit flat address spaces, any large constant may be used.
  170881. *
  170882. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  170883. * size_t and will be a multiple of sizeof(align_type).
  170884. */
  170885. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  170886. #define MAX_ALLOC_CHUNK 1000000000L
  170887. #endif
  170888. /*
  170889. * This routine computes the total space still available for allocation by
  170890. * jpeg_get_large. If more space than this is needed, backing store will be
  170891. * used. NOTE: any memory already allocated must not be counted.
  170892. *
  170893. * There is a minimum space requirement, corresponding to the minimum
  170894. * feasible buffer sizes; jmemmgr.c will request that much space even if
  170895. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  170896. * all working storage in memory, is also passed in case it is useful.
  170897. * Finally, the total space already allocated is passed. If no better
  170898. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  170899. * is often a suitable calculation.
  170900. *
  170901. * It is OK for jpeg_mem_available to underestimate the space available
  170902. * (that'll just lead to more backing-store access than is really necessary).
  170903. * However, an overestimate will lead to failure. Hence it's wise to subtract
  170904. * a slop factor from the true available space. 5% should be enough.
  170905. *
  170906. * On machines with lots of virtual memory, any large constant may be returned.
  170907. * Conversely, zero may be returned to always use the minimum amount of memory.
  170908. */
  170909. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  170910. long min_bytes_needed,
  170911. long max_bytes_needed,
  170912. long already_allocated));
  170913. /*
  170914. * This structure holds whatever state is needed to access a single
  170915. * backing-store object. The read/write/close method pointers are called
  170916. * by jmemmgr.c to manipulate the backing-store object; all other fields
  170917. * are private to the system-dependent backing store routines.
  170918. */
  170919. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  170920. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  170921. typedef unsigned short XMSH; /* type of extended-memory handles */
  170922. typedef unsigned short EMSH; /* type of expanded-memory handles */
  170923. typedef union {
  170924. short file_handle; /* DOS file handle if it's a temp file */
  170925. XMSH xms_handle; /* handle if it's a chunk of XMS */
  170926. EMSH ems_handle; /* handle if it's a chunk of EMS */
  170927. } handle_union;
  170928. #endif /* USE_MSDOS_MEMMGR */
  170929. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  170930. #include <Files.h>
  170931. #endif /* USE_MAC_MEMMGR */
  170932. //typedef struct backing_store_struct * backing_store_ptr;
  170933. typedef struct backing_store_struct {
  170934. /* Methods for reading/writing/closing this backing-store object */
  170935. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  170936. struct backing_store_struct *info,
  170937. void FAR * buffer_address,
  170938. long file_offset, long byte_count));
  170939. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  170940. struct backing_store_struct *info,
  170941. void FAR * buffer_address,
  170942. long file_offset, long byte_count));
  170943. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  170944. struct backing_store_struct *info));
  170945. /* Private fields for system-dependent backing-store management */
  170946. #ifdef USE_MSDOS_MEMMGR
  170947. /* For the MS-DOS manager (jmemdos.c), we need: */
  170948. handle_union handle; /* reference to backing-store storage object */
  170949. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  170950. #else
  170951. #ifdef USE_MAC_MEMMGR
  170952. /* For the Mac manager (jmemmac.c), we need: */
  170953. short temp_file; /* file reference number to temp file */
  170954. FSSpec tempSpec; /* the FSSpec for the temp file */
  170955. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  170956. #else
  170957. /* For a typical implementation with temp files, we need: */
  170958. FILE * temp_file; /* stdio reference to temp file */
  170959. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  170960. #endif
  170961. #endif
  170962. } backing_store_info;
  170963. /*
  170964. * Initial opening of a backing-store object. This must fill in the
  170965. * read/write/close pointers in the object. The read/write routines
  170966. * may take an error exit if the specified maximum file size is exceeded.
  170967. * (If jpeg_mem_available always returns a large value, this routine can
  170968. * just take an error exit.)
  170969. */
  170970. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  170971. struct backing_store_struct *info,
  170972. long total_bytes_needed));
  170973. /*
  170974. * These routines take care of any system-dependent initialization and
  170975. * cleanup required. jpeg_mem_init will be called before anything is
  170976. * allocated (and, therefore, nothing in cinfo is of use except the error
  170977. * manager pointer). It should return a suitable default value for
  170978. * max_memory_to_use; this may subsequently be overridden by the surrounding
  170979. * application. (Note that max_memory_to_use is only important if
  170980. * jpeg_mem_available chooses to consult it ... no one else will.)
  170981. * jpeg_mem_term may assume that all requested memory has been freed and that
  170982. * all opened backing-store objects have been closed.
  170983. */
  170984. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  170985. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  170986. #endif
  170987. /********* End of inlined file: jmemsys.h *********/
  170988. /* import the system-dependent declarations */
  170989. #ifndef NO_GETENV
  170990. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  170991. extern char * getenv JPP((const char * name));
  170992. #endif
  170993. #endif
  170994. /*
  170995. * Some important notes:
  170996. * The allocation routines provided here must never return NULL.
  170997. * They should exit to error_exit if unsuccessful.
  170998. *
  170999. * It's not a good idea to try to merge the sarray and barray routines,
  171000. * even though they are textually almost the same, because samples are
  171001. * usually stored as bytes while coefficients are shorts or ints. Thus,
  171002. * in machines where byte pointers have a different representation from
  171003. * word pointers, the resulting machine code could not be the same.
  171004. */
  171005. /*
  171006. * Many machines require storage alignment: longs must start on 4-byte
  171007. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  171008. * always returns pointers that are multiples of the worst-case alignment
  171009. * requirement, and we had better do so too.
  171010. * There isn't any really portable way to determine the worst-case alignment
  171011. * requirement. This module assumes that the alignment requirement is
  171012. * multiples of sizeof(ALIGN_TYPE).
  171013. * By default, we define ALIGN_TYPE as double. This is necessary on some
  171014. * workstations (where doubles really do need 8-byte alignment) and will work
  171015. * fine on nearly everything. If your machine has lesser alignment needs,
  171016. * you can save a few bytes by making ALIGN_TYPE smaller.
  171017. * The only place I know of where this will NOT work is certain Macintosh
  171018. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  171019. * Doing 10-byte alignment is counterproductive because longwords won't be
  171020. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  171021. * such a compiler.
  171022. */
  171023. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  171024. #define ALIGN_TYPE double
  171025. #endif
  171026. /*
  171027. * We allocate objects from "pools", where each pool is gotten with a single
  171028. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  171029. * overhead within a pool, except for alignment padding. Each pool has a
  171030. * header with a link to the next pool of the same class.
  171031. * Small and large pool headers are identical except that the latter's
  171032. * link pointer must be FAR on 80x86 machines.
  171033. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  171034. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  171035. * of the alignment requirement of ALIGN_TYPE.
  171036. */
  171037. typedef union small_pool_struct * small_pool_ptr;
  171038. typedef union small_pool_struct {
  171039. struct {
  171040. small_pool_ptr next; /* next in list of pools */
  171041. size_t bytes_used; /* how many bytes already used within pool */
  171042. size_t bytes_left; /* bytes still available in this pool */
  171043. } hdr;
  171044. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171045. } small_pool_hdr;
  171046. typedef union large_pool_struct FAR * large_pool_ptr;
  171047. typedef union large_pool_struct {
  171048. struct {
  171049. large_pool_ptr next; /* next in list of pools */
  171050. size_t bytes_used; /* how many bytes already used within pool */
  171051. size_t bytes_left; /* bytes still available in this pool */
  171052. } hdr;
  171053. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171054. } large_pool_hdr;
  171055. /*
  171056. * Here is the full definition of a memory manager object.
  171057. */
  171058. typedef struct {
  171059. struct jpeg_memory_mgr pub; /* public fields */
  171060. /* Each pool identifier (lifetime class) names a linked list of pools. */
  171061. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  171062. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  171063. /* Since we only have one lifetime class of virtual arrays, only one
  171064. * linked list is necessary (for each datatype). Note that the virtual
  171065. * array control blocks being linked together are actually stored somewhere
  171066. * in the small-pool list.
  171067. */
  171068. jvirt_sarray_ptr virt_sarray_list;
  171069. jvirt_barray_ptr virt_barray_list;
  171070. /* This counts total space obtained from jpeg_get_small/large */
  171071. long total_space_allocated;
  171072. /* alloc_sarray and alloc_barray set this value for use by virtual
  171073. * array routines.
  171074. */
  171075. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  171076. } my_memory_mgr;
  171077. typedef my_memory_mgr * my_mem_ptr;
  171078. /*
  171079. * The control blocks for virtual arrays.
  171080. * Note that these blocks are allocated in the "small" pool area.
  171081. * System-dependent info for the associated backing store (if any) is hidden
  171082. * inside the backing_store_info struct.
  171083. */
  171084. struct jvirt_sarray_control {
  171085. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  171086. JDIMENSION rows_in_array; /* total virtual array height */
  171087. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  171088. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  171089. JDIMENSION rows_in_mem; /* height of memory buffer */
  171090. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171091. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171092. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171093. boolean pre_zero; /* pre-zero mode requested? */
  171094. boolean dirty; /* do current buffer contents need written? */
  171095. boolean b_s_open; /* is backing-store data valid? */
  171096. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  171097. backing_store_info b_s_info; /* System-dependent control info */
  171098. };
  171099. struct jvirt_barray_control {
  171100. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  171101. JDIMENSION rows_in_array; /* total virtual array height */
  171102. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  171103. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  171104. JDIMENSION rows_in_mem; /* height of memory buffer */
  171105. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171106. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171107. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171108. boolean pre_zero; /* pre-zero mode requested? */
  171109. boolean dirty; /* do current buffer contents need written? */
  171110. boolean b_s_open; /* is backing-store data valid? */
  171111. jvirt_barray_ptr next; /* link to next virtual barray control block */
  171112. backing_store_info b_s_info; /* System-dependent control info */
  171113. };
  171114. #ifdef MEM_STATS /* optional extra stuff for statistics */
  171115. LOCAL(void)
  171116. print_mem_stats (j_common_ptr cinfo, int pool_id)
  171117. {
  171118. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171119. small_pool_ptr shdr_ptr;
  171120. large_pool_ptr lhdr_ptr;
  171121. /* Since this is only a debugging stub, we can cheat a little by using
  171122. * fprintf directly rather than going through the trace message code.
  171123. * This is helpful because message parm array can't handle longs.
  171124. */
  171125. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  171126. pool_id, mem->total_space_allocated);
  171127. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  171128. lhdr_ptr = lhdr_ptr->hdr.next) {
  171129. fprintf(stderr, " Large chunk used %ld\n",
  171130. (long) lhdr_ptr->hdr.bytes_used);
  171131. }
  171132. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  171133. shdr_ptr = shdr_ptr->hdr.next) {
  171134. fprintf(stderr, " Small chunk used %ld free %ld\n",
  171135. (long) shdr_ptr->hdr.bytes_used,
  171136. (long) shdr_ptr->hdr.bytes_left);
  171137. }
  171138. }
  171139. #endif /* MEM_STATS */
  171140. LOCAL(void)
  171141. out_of_memory (j_common_ptr cinfo, int which)
  171142. /* Report an out-of-memory error and stop execution */
  171143. /* If we compiled MEM_STATS support, report alloc requests before dying */
  171144. {
  171145. #ifdef MEM_STATS
  171146. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  171147. #endif
  171148. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  171149. }
  171150. /*
  171151. * Allocation of "small" objects.
  171152. *
  171153. * For these, we use pooled storage. When a new pool must be created,
  171154. * we try to get enough space for the current request plus a "slop" factor,
  171155. * where the slop will be the amount of leftover space in the new pool.
  171156. * The speed vs. space tradeoff is largely determined by the slop values.
  171157. * A different slop value is provided for each pool class (lifetime),
  171158. * and we also distinguish the first pool of a class from later ones.
  171159. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  171160. * machines, but may be too small if longs are 64 bits or more.
  171161. */
  171162. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  171163. {
  171164. 1600, /* first PERMANENT pool */
  171165. 16000 /* first IMAGE pool */
  171166. };
  171167. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  171168. {
  171169. 0, /* additional PERMANENT pools */
  171170. 5000 /* additional IMAGE pools */
  171171. };
  171172. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  171173. METHODDEF(void *)
  171174. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171175. /* Allocate a "small" object */
  171176. {
  171177. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171178. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  171179. char * data_ptr;
  171180. size_t odd_bytes, min_request, slop;
  171181. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171182. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  171183. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  171184. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171185. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171186. if (odd_bytes > 0)
  171187. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171188. /* See if space is available in any existing pool */
  171189. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171190. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171191. prev_hdr_ptr = NULL;
  171192. hdr_ptr = mem->small_list[pool_id];
  171193. while (hdr_ptr != NULL) {
  171194. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  171195. break; /* found pool with enough space */
  171196. prev_hdr_ptr = hdr_ptr;
  171197. hdr_ptr = hdr_ptr->hdr.next;
  171198. }
  171199. /* Time to make a new pool? */
  171200. if (hdr_ptr == NULL) {
  171201. /* min_request is what we need now, slop is what will be leftover */
  171202. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  171203. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171204. slop = first_pool_slop[pool_id];
  171205. else
  171206. slop = extra_pool_slop[pool_id];
  171207. /* Don't ask for more than MAX_ALLOC_CHUNK */
  171208. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  171209. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  171210. /* Try to get space, if fail reduce slop and try again */
  171211. for (;;) {
  171212. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  171213. if (hdr_ptr != NULL)
  171214. break;
  171215. slop /= 2;
  171216. if (slop < MIN_SLOP) /* give up when it gets real small */
  171217. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  171218. }
  171219. mem->total_space_allocated += min_request + slop;
  171220. /* Success, initialize the new pool header and add to end of list */
  171221. hdr_ptr->hdr.next = NULL;
  171222. hdr_ptr->hdr.bytes_used = 0;
  171223. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  171224. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171225. mem->small_list[pool_id] = hdr_ptr;
  171226. else
  171227. prev_hdr_ptr->hdr.next = hdr_ptr;
  171228. }
  171229. /* OK, allocate the object from the current pool */
  171230. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  171231. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  171232. hdr_ptr->hdr.bytes_used += sizeofobject;
  171233. hdr_ptr->hdr.bytes_left -= sizeofobject;
  171234. return (void *) data_ptr;
  171235. }
  171236. /*
  171237. * Allocation of "large" objects.
  171238. *
  171239. * The external semantics of these are the same as "small" objects,
  171240. * except that FAR pointers are used on 80x86. However the pool
  171241. * management heuristics are quite different. We assume that each
  171242. * request is large enough that it may as well be passed directly to
  171243. * jpeg_get_large; the pool management just links everything together
  171244. * so that we can free it all on demand.
  171245. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  171246. * structures. The routines that create these structures (see below)
  171247. * deliberately bunch rows together to ensure a large request size.
  171248. */
  171249. METHODDEF(void FAR *)
  171250. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171251. /* Allocate a "large" object */
  171252. {
  171253. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171254. large_pool_ptr hdr_ptr;
  171255. size_t odd_bytes;
  171256. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171257. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  171258. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  171259. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171260. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171261. if (odd_bytes > 0)
  171262. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171263. /* Always make a new pool */
  171264. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171265. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171266. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  171267. SIZEOF(large_pool_hdr));
  171268. if (hdr_ptr == NULL)
  171269. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  171270. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  171271. /* Success, initialize the new pool header and add to list */
  171272. hdr_ptr->hdr.next = mem->large_list[pool_id];
  171273. /* We maintain space counts in each pool header for statistical purposes,
  171274. * even though they are not needed for allocation.
  171275. */
  171276. hdr_ptr->hdr.bytes_used = sizeofobject;
  171277. hdr_ptr->hdr.bytes_left = 0;
  171278. mem->large_list[pool_id] = hdr_ptr;
  171279. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  171280. }
  171281. /*
  171282. * Creation of 2-D sample arrays.
  171283. * The pointers are in near heap, the samples themselves in FAR heap.
  171284. *
  171285. * To minimize allocation overhead and to allow I/O of large contiguous
  171286. * blocks, we allocate the sample rows in groups of as many rows as possible
  171287. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  171288. * NB: the virtual array control routines, later in this file, know about
  171289. * this chunking of rows. The rowsperchunk value is left in the mem manager
  171290. * object so that it can be saved away if this sarray is the workspace for
  171291. * a virtual array.
  171292. */
  171293. METHODDEF(JSAMPARRAY)
  171294. alloc_sarray (j_common_ptr cinfo, int pool_id,
  171295. JDIMENSION samplesperrow, JDIMENSION numrows)
  171296. /* Allocate a 2-D sample array */
  171297. {
  171298. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171299. JSAMPARRAY result;
  171300. JSAMPROW workspace;
  171301. JDIMENSION rowsperchunk, currow, i;
  171302. long ltemp;
  171303. /* Calculate max # of rows allowed in one allocation chunk */
  171304. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171305. ((long) samplesperrow * SIZEOF(JSAMPLE));
  171306. if (ltemp <= 0)
  171307. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171308. if (ltemp < (long) numrows)
  171309. rowsperchunk = (JDIMENSION) ltemp;
  171310. else
  171311. rowsperchunk = numrows;
  171312. mem->last_rowsperchunk = rowsperchunk;
  171313. /* Get space for row pointers (small object) */
  171314. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  171315. (size_t) (numrows * SIZEOF(JSAMPROW)));
  171316. /* Get the rows themselves (large objects) */
  171317. currow = 0;
  171318. while (currow < numrows) {
  171319. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171320. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  171321. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  171322. * SIZEOF(JSAMPLE)));
  171323. for (i = rowsperchunk; i > 0; i--) {
  171324. result[currow++] = workspace;
  171325. workspace += samplesperrow;
  171326. }
  171327. }
  171328. return result;
  171329. }
  171330. /*
  171331. * Creation of 2-D coefficient-block arrays.
  171332. * This is essentially the same as the code for sample arrays, above.
  171333. */
  171334. METHODDEF(JBLOCKARRAY)
  171335. alloc_barray (j_common_ptr cinfo, int pool_id,
  171336. JDIMENSION blocksperrow, JDIMENSION numrows)
  171337. /* Allocate a 2-D coefficient-block array */
  171338. {
  171339. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171340. JBLOCKARRAY result;
  171341. JBLOCKROW workspace;
  171342. JDIMENSION rowsperchunk, currow, i;
  171343. long ltemp;
  171344. /* Calculate max # of rows allowed in one allocation chunk */
  171345. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171346. ((long) blocksperrow * SIZEOF(JBLOCK));
  171347. if (ltemp <= 0)
  171348. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171349. if (ltemp < (long) numrows)
  171350. rowsperchunk = (JDIMENSION) ltemp;
  171351. else
  171352. rowsperchunk = numrows;
  171353. mem->last_rowsperchunk = rowsperchunk;
  171354. /* Get space for row pointers (small object) */
  171355. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  171356. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  171357. /* Get the rows themselves (large objects) */
  171358. currow = 0;
  171359. while (currow < numrows) {
  171360. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171361. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  171362. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  171363. * SIZEOF(JBLOCK)));
  171364. for (i = rowsperchunk; i > 0; i--) {
  171365. result[currow++] = workspace;
  171366. workspace += blocksperrow;
  171367. }
  171368. }
  171369. return result;
  171370. }
  171371. /*
  171372. * About virtual array management:
  171373. *
  171374. * The above "normal" array routines are only used to allocate strip buffers
  171375. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  171376. * are handled as "virtual" arrays. The array is still accessed a strip at a
  171377. * time, but the memory manager must save the whole array for repeated
  171378. * accesses. The intended implementation is that there is a strip buffer in
  171379. * memory (as high as is possible given the desired memory limit), plus a
  171380. * backing file that holds the rest of the array.
  171381. *
  171382. * The request_virt_array routines are told the total size of the image and
  171383. * the maximum number of rows that will be accessed at once. The in-memory
  171384. * buffer must be at least as large as the maxaccess value.
  171385. *
  171386. * The request routines create control blocks but not the in-memory buffers.
  171387. * That is postponed until realize_virt_arrays is called. At that time the
  171388. * total amount of space needed is known (approximately, anyway), so free
  171389. * memory can be divided up fairly.
  171390. *
  171391. * The access_virt_array routines are responsible for making a specific strip
  171392. * area accessible (after reading or writing the backing file, if necessary).
  171393. * Note that the access routines are told whether the caller intends to modify
  171394. * the accessed strip; during a read-only pass this saves having to rewrite
  171395. * data to disk. The access routines are also responsible for pre-zeroing
  171396. * any newly accessed rows, if pre-zeroing was requested.
  171397. *
  171398. * In current usage, the access requests are usually for nonoverlapping
  171399. * strips; that is, successive access start_row numbers differ by exactly
  171400. * num_rows = maxaccess. This means we can get good performance with simple
  171401. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  171402. * of the access height; then there will never be accesses across bufferload
  171403. * boundaries. The code will still work with overlapping access requests,
  171404. * but it doesn't handle bufferload overlaps very efficiently.
  171405. */
  171406. METHODDEF(jvirt_sarray_ptr)
  171407. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  171408. JDIMENSION samplesperrow, JDIMENSION numrows,
  171409. JDIMENSION maxaccess)
  171410. /* Request a virtual 2-D sample array */
  171411. {
  171412. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171413. jvirt_sarray_ptr result;
  171414. /* Only IMAGE-lifetime virtual arrays are currently supported */
  171415. if (pool_id != JPOOL_IMAGE)
  171416. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171417. /* get control block */
  171418. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  171419. SIZEOF(struct jvirt_sarray_control));
  171420. result->mem_buffer = NULL; /* marks array not yet realized */
  171421. result->rows_in_array = numrows;
  171422. result->samplesperrow = samplesperrow;
  171423. result->maxaccess = maxaccess;
  171424. result->pre_zero = pre_zero;
  171425. result->b_s_open = FALSE; /* no associated backing-store object */
  171426. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  171427. mem->virt_sarray_list = result;
  171428. return result;
  171429. }
  171430. METHODDEF(jvirt_barray_ptr)
  171431. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  171432. JDIMENSION blocksperrow, JDIMENSION numrows,
  171433. JDIMENSION maxaccess)
  171434. /* Request a virtual 2-D coefficient-block array */
  171435. {
  171436. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171437. jvirt_barray_ptr result;
  171438. /* Only IMAGE-lifetime virtual arrays are currently supported */
  171439. if (pool_id != JPOOL_IMAGE)
  171440. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171441. /* get control block */
  171442. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  171443. SIZEOF(struct jvirt_barray_control));
  171444. result->mem_buffer = NULL; /* marks array not yet realized */
  171445. result->rows_in_array = numrows;
  171446. result->blocksperrow = blocksperrow;
  171447. result->maxaccess = maxaccess;
  171448. result->pre_zero = pre_zero;
  171449. result->b_s_open = FALSE; /* no associated backing-store object */
  171450. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  171451. mem->virt_barray_list = result;
  171452. return result;
  171453. }
  171454. METHODDEF(void)
  171455. realize_virt_arrays (j_common_ptr cinfo)
  171456. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  171457. {
  171458. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171459. long space_per_minheight, maximum_space, avail_mem;
  171460. long minheights, max_minheights;
  171461. jvirt_sarray_ptr sptr;
  171462. jvirt_barray_ptr bptr;
  171463. /* Compute the minimum space needed (maxaccess rows in each buffer)
  171464. * and the maximum space needed (full image height in each buffer).
  171465. * These may be of use to the system-dependent jpeg_mem_available routine.
  171466. */
  171467. space_per_minheight = 0;
  171468. maximum_space = 0;
  171469. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  171470. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  171471. space_per_minheight += (long) sptr->maxaccess *
  171472. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  171473. maximum_space += (long) sptr->rows_in_array *
  171474. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  171475. }
  171476. }
  171477. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  171478. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  171479. space_per_minheight += (long) bptr->maxaccess *
  171480. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  171481. maximum_space += (long) bptr->rows_in_array *
  171482. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  171483. }
  171484. }
  171485. if (space_per_minheight <= 0)
  171486. return; /* no unrealized arrays, no work */
  171487. /* Determine amount of memory to actually use; this is system-dependent. */
  171488. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  171489. mem->total_space_allocated);
  171490. /* If the maximum space needed is available, make all the buffers full
  171491. * height; otherwise parcel it out with the same number of minheights
  171492. * in each buffer.
  171493. */
  171494. if (avail_mem >= maximum_space)
  171495. max_minheights = 1000000000L;
  171496. else {
  171497. max_minheights = avail_mem / space_per_minheight;
  171498. /* If there doesn't seem to be enough space, try to get the minimum
  171499. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  171500. */
  171501. if (max_minheights <= 0)
  171502. max_minheights = 1;
  171503. }
  171504. /* Allocate the in-memory buffers and initialize backing store as needed. */
  171505. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  171506. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  171507. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  171508. if (minheights <= max_minheights) {
  171509. /* This buffer fits in memory */
  171510. sptr->rows_in_mem = sptr->rows_in_array;
  171511. } else {
  171512. /* It doesn't fit in memory, create backing store. */
  171513. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  171514. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  171515. (long) sptr->rows_in_array *
  171516. (long) sptr->samplesperrow *
  171517. (long) SIZEOF(JSAMPLE));
  171518. sptr->b_s_open = TRUE;
  171519. }
  171520. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  171521. sptr->samplesperrow, sptr->rows_in_mem);
  171522. sptr->rowsperchunk = mem->last_rowsperchunk;
  171523. sptr->cur_start_row = 0;
  171524. sptr->first_undef_row = 0;
  171525. sptr->dirty = FALSE;
  171526. }
  171527. }
  171528. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  171529. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  171530. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  171531. if (minheights <= max_minheights) {
  171532. /* This buffer fits in memory */
  171533. bptr->rows_in_mem = bptr->rows_in_array;
  171534. } else {
  171535. /* It doesn't fit in memory, create backing store. */
  171536. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  171537. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  171538. (long) bptr->rows_in_array *
  171539. (long) bptr->blocksperrow *
  171540. (long) SIZEOF(JBLOCK));
  171541. bptr->b_s_open = TRUE;
  171542. }
  171543. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  171544. bptr->blocksperrow, bptr->rows_in_mem);
  171545. bptr->rowsperchunk = mem->last_rowsperchunk;
  171546. bptr->cur_start_row = 0;
  171547. bptr->first_undef_row = 0;
  171548. bptr->dirty = FALSE;
  171549. }
  171550. }
  171551. }
  171552. LOCAL(void)
  171553. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  171554. /* Do backing store read or write of a virtual sample array */
  171555. {
  171556. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  171557. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  171558. file_offset = ptr->cur_start_row * bytesperrow;
  171559. /* Loop to read or write each allocation chunk in mem_buffer */
  171560. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  171561. /* One chunk, but check for short chunk at end of buffer */
  171562. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  171563. /* Transfer no more than is currently defined */
  171564. thisrow = (long) ptr->cur_start_row + i;
  171565. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  171566. /* Transfer no more than fits in file */
  171567. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  171568. if (rows <= 0) /* this chunk might be past end of file! */
  171569. break;
  171570. byte_count = rows * bytesperrow;
  171571. if (writing)
  171572. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  171573. (void FAR *) ptr->mem_buffer[i],
  171574. file_offset, byte_count);
  171575. else
  171576. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  171577. (void FAR *) ptr->mem_buffer[i],
  171578. file_offset, byte_count);
  171579. file_offset += byte_count;
  171580. }
  171581. }
  171582. LOCAL(void)
  171583. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  171584. /* Do backing store read or write of a virtual coefficient-block array */
  171585. {
  171586. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  171587. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  171588. file_offset = ptr->cur_start_row * bytesperrow;
  171589. /* Loop to read or write each allocation chunk in mem_buffer */
  171590. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  171591. /* One chunk, but check for short chunk at end of buffer */
  171592. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  171593. /* Transfer no more than is currently defined */
  171594. thisrow = (long) ptr->cur_start_row + i;
  171595. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  171596. /* Transfer no more than fits in file */
  171597. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  171598. if (rows <= 0) /* this chunk might be past end of file! */
  171599. break;
  171600. byte_count = rows * bytesperrow;
  171601. if (writing)
  171602. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  171603. (void FAR *) ptr->mem_buffer[i],
  171604. file_offset, byte_count);
  171605. else
  171606. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  171607. (void FAR *) ptr->mem_buffer[i],
  171608. file_offset, byte_count);
  171609. file_offset += byte_count;
  171610. }
  171611. }
  171612. METHODDEF(JSAMPARRAY)
  171613. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  171614. JDIMENSION start_row, JDIMENSION num_rows,
  171615. boolean writable)
  171616. /* Access the part of a virtual sample array starting at start_row */
  171617. /* and extending for num_rows rows. writable is true if */
  171618. /* caller intends to modify the accessed area. */
  171619. {
  171620. JDIMENSION end_row = start_row + num_rows;
  171621. JDIMENSION undef_row;
  171622. /* debugging check */
  171623. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  171624. ptr->mem_buffer == NULL)
  171625. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171626. /* Make the desired part of the virtual array accessible */
  171627. if (start_row < ptr->cur_start_row ||
  171628. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  171629. if (! ptr->b_s_open)
  171630. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  171631. /* Flush old buffer contents if necessary */
  171632. if (ptr->dirty) {
  171633. do_sarray_io(cinfo, ptr, TRUE);
  171634. ptr->dirty = FALSE;
  171635. }
  171636. /* Decide what part of virtual array to access.
  171637. * Algorithm: if target address > current window, assume forward scan,
  171638. * load starting at target address. If target address < current window,
  171639. * assume backward scan, load so that target area is top of window.
  171640. * Note that when switching from forward write to forward read, will have
  171641. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  171642. */
  171643. if (start_row > ptr->cur_start_row) {
  171644. ptr->cur_start_row = start_row;
  171645. } else {
  171646. /* use long arithmetic here to avoid overflow & unsigned problems */
  171647. long ltemp;
  171648. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  171649. if (ltemp < 0)
  171650. ltemp = 0; /* don't fall off front end of file */
  171651. ptr->cur_start_row = (JDIMENSION) ltemp;
  171652. }
  171653. /* Read in the selected part of the array.
  171654. * During the initial write pass, we will do no actual read
  171655. * because the selected part is all undefined.
  171656. */
  171657. do_sarray_io(cinfo, ptr, FALSE);
  171658. }
  171659. /* Ensure the accessed part of the array is defined; prezero if needed.
  171660. * To improve locality of access, we only prezero the part of the array
  171661. * that the caller is about to access, not the entire in-memory array.
  171662. */
  171663. if (ptr->first_undef_row < end_row) {
  171664. if (ptr->first_undef_row < start_row) {
  171665. if (writable) /* writer skipped over a section of array */
  171666. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171667. undef_row = start_row; /* but reader is allowed to read ahead */
  171668. } else {
  171669. undef_row = ptr->first_undef_row;
  171670. }
  171671. if (writable)
  171672. ptr->first_undef_row = end_row;
  171673. if (ptr->pre_zero) {
  171674. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  171675. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  171676. end_row -= ptr->cur_start_row;
  171677. while (undef_row < end_row) {
  171678. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  171679. undef_row++;
  171680. }
  171681. } else {
  171682. if (! writable) /* reader looking at undefined data */
  171683. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171684. }
  171685. }
  171686. /* Flag the buffer dirty if caller will write in it */
  171687. if (writable)
  171688. ptr->dirty = TRUE;
  171689. /* Return address of proper part of the buffer */
  171690. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  171691. }
  171692. METHODDEF(JBLOCKARRAY)
  171693. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  171694. JDIMENSION start_row, JDIMENSION num_rows,
  171695. boolean writable)
  171696. /* Access the part of a virtual block array starting at start_row */
  171697. /* and extending for num_rows rows. writable is true if */
  171698. /* caller intends to modify the accessed area. */
  171699. {
  171700. JDIMENSION end_row = start_row + num_rows;
  171701. JDIMENSION undef_row;
  171702. /* debugging check */
  171703. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  171704. ptr->mem_buffer == NULL)
  171705. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171706. /* Make the desired part of the virtual array accessible */
  171707. if (start_row < ptr->cur_start_row ||
  171708. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  171709. if (! ptr->b_s_open)
  171710. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  171711. /* Flush old buffer contents if necessary */
  171712. if (ptr->dirty) {
  171713. do_barray_io(cinfo, ptr, TRUE);
  171714. ptr->dirty = FALSE;
  171715. }
  171716. /* Decide what part of virtual array to access.
  171717. * Algorithm: if target address > current window, assume forward scan,
  171718. * load starting at target address. If target address < current window,
  171719. * assume backward scan, load so that target area is top of window.
  171720. * Note that when switching from forward write to forward read, will have
  171721. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  171722. */
  171723. if (start_row > ptr->cur_start_row) {
  171724. ptr->cur_start_row = start_row;
  171725. } else {
  171726. /* use long arithmetic here to avoid overflow & unsigned problems */
  171727. long ltemp;
  171728. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  171729. if (ltemp < 0)
  171730. ltemp = 0; /* don't fall off front end of file */
  171731. ptr->cur_start_row = (JDIMENSION) ltemp;
  171732. }
  171733. /* Read in the selected part of the array.
  171734. * During the initial write pass, we will do no actual read
  171735. * because the selected part is all undefined.
  171736. */
  171737. do_barray_io(cinfo, ptr, FALSE);
  171738. }
  171739. /* Ensure the accessed part of the array is defined; prezero if needed.
  171740. * To improve locality of access, we only prezero the part of the array
  171741. * that the caller is about to access, not the entire in-memory array.
  171742. */
  171743. if (ptr->first_undef_row < end_row) {
  171744. if (ptr->first_undef_row < start_row) {
  171745. if (writable) /* writer skipped over a section of array */
  171746. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171747. undef_row = start_row; /* but reader is allowed to read ahead */
  171748. } else {
  171749. undef_row = ptr->first_undef_row;
  171750. }
  171751. if (writable)
  171752. ptr->first_undef_row = end_row;
  171753. if (ptr->pre_zero) {
  171754. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  171755. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  171756. end_row -= ptr->cur_start_row;
  171757. while (undef_row < end_row) {
  171758. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  171759. undef_row++;
  171760. }
  171761. } else {
  171762. if (! writable) /* reader looking at undefined data */
  171763. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171764. }
  171765. }
  171766. /* Flag the buffer dirty if caller will write in it */
  171767. if (writable)
  171768. ptr->dirty = TRUE;
  171769. /* Return address of proper part of the buffer */
  171770. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  171771. }
  171772. /*
  171773. * Release all objects belonging to a specified pool.
  171774. */
  171775. METHODDEF(void)
  171776. free_pool (j_common_ptr cinfo, int pool_id)
  171777. {
  171778. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171779. small_pool_ptr shdr_ptr;
  171780. large_pool_ptr lhdr_ptr;
  171781. size_t space_freed;
  171782. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171783. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171784. #ifdef MEM_STATS
  171785. if (cinfo->err->trace_level > 1)
  171786. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  171787. #endif
  171788. /* If freeing IMAGE pool, close any virtual arrays first */
  171789. if (pool_id == JPOOL_IMAGE) {
  171790. jvirt_sarray_ptr sptr;
  171791. jvirt_barray_ptr bptr;
  171792. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  171793. if (sptr->b_s_open) { /* there may be no backing store */
  171794. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  171795. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  171796. }
  171797. }
  171798. mem->virt_sarray_list = NULL;
  171799. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  171800. if (bptr->b_s_open) { /* there may be no backing store */
  171801. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  171802. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  171803. }
  171804. }
  171805. mem->virt_barray_list = NULL;
  171806. }
  171807. /* Release large objects */
  171808. lhdr_ptr = mem->large_list[pool_id];
  171809. mem->large_list[pool_id] = NULL;
  171810. while (lhdr_ptr != NULL) {
  171811. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  171812. space_freed = lhdr_ptr->hdr.bytes_used +
  171813. lhdr_ptr->hdr.bytes_left +
  171814. SIZEOF(large_pool_hdr);
  171815. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  171816. mem->total_space_allocated -= space_freed;
  171817. lhdr_ptr = next_lhdr_ptr;
  171818. }
  171819. /* Release small objects */
  171820. shdr_ptr = mem->small_list[pool_id];
  171821. mem->small_list[pool_id] = NULL;
  171822. while (shdr_ptr != NULL) {
  171823. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  171824. space_freed = shdr_ptr->hdr.bytes_used +
  171825. shdr_ptr->hdr.bytes_left +
  171826. SIZEOF(small_pool_hdr);
  171827. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  171828. mem->total_space_allocated -= space_freed;
  171829. shdr_ptr = next_shdr_ptr;
  171830. }
  171831. }
  171832. /*
  171833. * Close up shop entirely.
  171834. * Note that this cannot be called unless cinfo->mem is non-NULL.
  171835. */
  171836. METHODDEF(void)
  171837. self_destruct (j_common_ptr cinfo)
  171838. {
  171839. int pool;
  171840. /* Close all backing store, release all memory.
  171841. * Releasing pools in reverse order might help avoid fragmentation
  171842. * with some (brain-damaged) malloc libraries.
  171843. */
  171844. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  171845. free_pool(cinfo, pool);
  171846. }
  171847. /* Release the memory manager control block too. */
  171848. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  171849. cinfo->mem = NULL; /* ensures I will be called only once */
  171850. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  171851. }
  171852. /*
  171853. * Memory manager initialization.
  171854. * When this is called, only the error manager pointer is valid in cinfo!
  171855. */
  171856. GLOBAL(void)
  171857. jinit_memory_mgr (j_common_ptr cinfo)
  171858. {
  171859. my_mem_ptr mem;
  171860. long max_to_use;
  171861. int pool;
  171862. size_t test_mac;
  171863. cinfo->mem = NULL; /* for safety if init fails */
  171864. /* Check for configuration errors.
  171865. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  171866. * doesn't reflect any real hardware alignment requirement.
  171867. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  171868. * in common if and only if X is a power of 2, ie has only one one-bit.
  171869. * Some compilers may give an "unreachable code" warning here; ignore it.
  171870. */
  171871. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  171872. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  171873. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  171874. * a multiple of SIZEOF(ALIGN_TYPE).
  171875. * Again, an "unreachable code" warning may be ignored here.
  171876. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  171877. */
  171878. test_mac = (size_t) MAX_ALLOC_CHUNK;
  171879. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  171880. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  171881. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  171882. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  171883. /* Attempt to allocate memory manager's control block */
  171884. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  171885. if (mem == NULL) {
  171886. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  171887. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  171888. }
  171889. /* OK, fill in the method pointers */
  171890. mem->pub.alloc_small = alloc_small;
  171891. mem->pub.alloc_large = alloc_large;
  171892. mem->pub.alloc_sarray = alloc_sarray;
  171893. mem->pub.alloc_barray = alloc_barray;
  171894. mem->pub.request_virt_sarray = request_virt_sarray;
  171895. mem->pub.request_virt_barray = request_virt_barray;
  171896. mem->pub.realize_virt_arrays = realize_virt_arrays;
  171897. mem->pub.access_virt_sarray = access_virt_sarray;
  171898. mem->pub.access_virt_barray = access_virt_barray;
  171899. mem->pub.free_pool = free_pool;
  171900. mem->pub.self_destruct = self_destruct;
  171901. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  171902. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  171903. /* Initialize working state */
  171904. mem->pub.max_memory_to_use = max_to_use;
  171905. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  171906. mem->small_list[pool] = NULL;
  171907. mem->large_list[pool] = NULL;
  171908. }
  171909. mem->virt_sarray_list = NULL;
  171910. mem->virt_barray_list = NULL;
  171911. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  171912. /* Declare ourselves open for business */
  171913. cinfo->mem = & mem->pub;
  171914. /* Check for an environment variable JPEGMEM; if found, override the
  171915. * default max_memory setting from jpeg_mem_init. Note that the
  171916. * surrounding application may again override this value.
  171917. * If your system doesn't support getenv(), define NO_GETENV to disable
  171918. * this feature.
  171919. */
  171920. #ifndef NO_GETENV
  171921. { char * memenv;
  171922. if ((memenv = getenv("JPEGMEM")) != NULL) {
  171923. char ch = 'x';
  171924. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  171925. if (ch == 'm' || ch == 'M')
  171926. max_to_use *= 1000L;
  171927. mem->pub.max_memory_to_use = max_to_use * 1000L;
  171928. }
  171929. }
  171930. }
  171931. #endif
  171932. }
  171933. /********* End of inlined file: jmemmgr.c *********/
  171934. /********* Start of inlined file: jmemnobs.c *********/
  171935. #define JPEG_INTERNALS
  171936. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  171937. extern void * malloc JPP((size_t size));
  171938. extern void free JPP((void *ptr));
  171939. #endif
  171940. /*
  171941. * Memory allocation and freeing are controlled by the regular library
  171942. * routines malloc() and free().
  171943. */
  171944. GLOBAL(void *)
  171945. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  171946. {
  171947. return (void *) malloc(sizeofobject);
  171948. }
  171949. GLOBAL(void)
  171950. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  171951. {
  171952. free(object);
  171953. }
  171954. /*
  171955. * "Large" objects are treated the same as "small" ones.
  171956. * NB: although we include FAR keywords in the routine declarations,
  171957. * this file won't actually work in 80x86 small/medium model; at least,
  171958. * you probably won't be able to process useful-size images in only 64KB.
  171959. */
  171960. GLOBAL(void FAR *)
  171961. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  171962. {
  171963. return (void FAR *) malloc(sizeofobject);
  171964. }
  171965. GLOBAL(void)
  171966. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  171967. {
  171968. free(object);
  171969. }
  171970. /*
  171971. * This routine computes the total memory space available for allocation.
  171972. * Here we always say, "we got all you want bud!"
  171973. */
  171974. GLOBAL(long)
  171975. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  171976. long max_bytes_needed, long already_allocated)
  171977. {
  171978. return max_bytes_needed;
  171979. }
  171980. /*
  171981. * Backing store (temporary file) management.
  171982. * Since jpeg_mem_available always promised the moon,
  171983. * this should never be called and we can just error out.
  171984. */
  171985. GLOBAL(void)
  171986. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  171987. long total_bytes_needed)
  171988. {
  171989. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  171990. }
  171991. /*
  171992. * These routines take care of any system-dependent initialization and
  171993. * cleanup required. Here, there isn't any.
  171994. */
  171995. GLOBAL(long)
  171996. jpeg_mem_init (j_common_ptr cinfo)
  171997. {
  171998. return 0; /* just set max_memory_to_use to 0 */
  171999. }
  172000. GLOBAL(void)
  172001. jpeg_mem_term (j_common_ptr cinfo)
  172002. {
  172003. /* no work */
  172004. }
  172005. /********* End of inlined file: jmemnobs.c *********/
  172006. /********* Start of inlined file: jquant1.c *********/
  172007. #define JPEG_INTERNALS
  172008. #ifdef QUANT_1PASS_SUPPORTED
  172009. /*
  172010. * The main purpose of 1-pass quantization is to provide a fast, if not very
  172011. * high quality, colormapped output capability. A 2-pass quantizer usually
  172012. * gives better visual quality; however, for quantized grayscale output this
  172013. * quantizer is perfectly adequate. Dithering is highly recommended with this
  172014. * quantizer, though you can turn it off if you really want to.
  172015. *
  172016. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  172017. * image. We use a map consisting of all combinations of Ncolors[i] color
  172018. * values for the i'th component. The Ncolors[] values are chosen so that
  172019. * their product, the total number of colors, is no more than that requested.
  172020. * (In most cases, the product will be somewhat less.)
  172021. *
  172022. * Since the colormap is orthogonal, the representative value for each color
  172023. * component can be determined without considering the other components;
  172024. * then these indexes can be combined into a colormap index by a standard
  172025. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  172026. * can be precalculated and stored in the lookup table colorindex[].
  172027. * colorindex[i][j] maps pixel value j in component i to the nearest
  172028. * representative value (grid plane) for that component; this index is
  172029. * multiplied by the array stride for component i, so that the
  172030. * index of the colormap entry closest to a given pixel value is just
  172031. * sum( colorindex[component-number][pixel-component-value] )
  172032. * Aside from being fast, this scheme allows for variable spacing between
  172033. * representative values with no additional lookup cost.
  172034. *
  172035. * If gamma correction has been applied in color conversion, it might be wise
  172036. * to adjust the color grid spacing so that the representative colors are
  172037. * equidistant in linear space. At this writing, gamma correction is not
  172038. * implemented by jdcolor, so nothing is done here.
  172039. */
  172040. /* Declarations for ordered dithering.
  172041. *
  172042. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  172043. * dithering is described in many references, for instance Dale Schumacher's
  172044. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  172045. * In place of Schumacher's comparisons against a "threshold" value, we add a
  172046. * "dither" value to the input pixel and then round the result to the nearest
  172047. * output value. The dither value is equivalent to (0.5 - threshold) times
  172048. * the distance between output values. For ordered dithering, we assume that
  172049. * the output colors are equally spaced; if not, results will probably be
  172050. * worse, since the dither may be too much or too little at a given point.
  172051. *
  172052. * The normal calculation would be to form pixel value + dither, range-limit
  172053. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  172054. * We can skip the separate range-limiting step by extending the colorindex
  172055. * table in both directions.
  172056. */
  172057. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  172058. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  172059. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  172060. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  172061. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  172062. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  172063. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  172064. /* Bayer's order-4 dither array. Generated by the code given in
  172065. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  172066. * The values in this array must range from 0 to ODITHER_CELLS-1.
  172067. */
  172068. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  172069. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  172070. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  172071. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  172072. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  172073. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  172074. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  172075. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  172076. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  172077. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  172078. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  172079. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  172080. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  172081. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  172082. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  172083. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  172084. };
  172085. /* Declarations for Floyd-Steinberg dithering.
  172086. *
  172087. * Errors are accumulated into the array fserrors[], at a resolution of
  172088. * 1/16th of a pixel count. The error at a given pixel is propagated
  172089. * to its not-yet-processed neighbors using the standard F-S fractions,
  172090. * ... (here) 7/16
  172091. * 3/16 5/16 1/16
  172092. * We work left-to-right on even rows, right-to-left on odd rows.
  172093. *
  172094. * We can get away with a single array (holding one row's worth of errors)
  172095. * by using it to store the current row's errors at pixel columns not yet
  172096. * processed, but the next row's errors at columns already processed. We
  172097. * need only a few extra variables to hold the errors immediately around the
  172098. * current column. (If we are lucky, those variables are in registers, but
  172099. * even if not, they're probably cheaper to access than array elements are.)
  172100. *
  172101. * The fserrors[] array is indexed [component#][position].
  172102. * We provide (#columns + 2) entries per component; the extra entry at each
  172103. * end saves us from special-casing the first and last pixels.
  172104. *
  172105. * Note: on a wide image, we might not have enough room in a PC's near data
  172106. * segment to hold the error array; so it is allocated with alloc_large.
  172107. */
  172108. #if BITS_IN_JSAMPLE == 8
  172109. typedef INT16 FSERROR; /* 16 bits should be enough */
  172110. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  172111. #else
  172112. typedef INT32 FSERROR; /* may need more than 16 bits */
  172113. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  172114. #endif
  172115. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  172116. /* Private subobject */
  172117. #define MAX_Q_COMPS 4 /* max components I can handle */
  172118. typedef struct {
  172119. struct jpeg_color_quantizer pub; /* public fields */
  172120. /* Initially allocated colormap is saved here */
  172121. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  172122. int sv_actual; /* number of entries in use */
  172123. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  172124. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  172125. * premultiplied as described above. Since colormap indexes must fit into
  172126. * JSAMPLEs, the entries of this array will too.
  172127. */
  172128. boolean is_padded; /* is the colorindex padded for odither? */
  172129. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  172130. /* Variables for ordered dithering */
  172131. int row_index; /* cur row's vertical index in dither matrix */
  172132. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  172133. /* Variables for Floyd-Steinberg dithering */
  172134. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  172135. boolean on_odd_row; /* flag to remember which row we are on */
  172136. } my_cquantizer;
  172137. typedef my_cquantizer * my_cquantize_ptr;
  172138. /*
  172139. * Policy-making subroutines for create_colormap and create_colorindex.
  172140. * These routines determine the colormap to be used. The rest of the module
  172141. * only assumes that the colormap is orthogonal.
  172142. *
  172143. * * select_ncolors decides how to divvy up the available colors
  172144. * among the components.
  172145. * * output_value defines the set of representative values for a component.
  172146. * * largest_input_value defines the mapping from input values to
  172147. * representative values for a component.
  172148. * Note that the latter two routines may impose different policies for
  172149. * different components, though this is not currently done.
  172150. */
  172151. LOCAL(int)
  172152. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  172153. /* Determine allocation of desired colors to components, */
  172154. /* and fill in Ncolors[] array to indicate choice. */
  172155. /* Return value is total number of colors (product of Ncolors[] values). */
  172156. {
  172157. int nc = cinfo->out_color_components; /* number of color components */
  172158. int max_colors = cinfo->desired_number_of_colors;
  172159. int total_colors, iroot, i, j;
  172160. boolean changed;
  172161. long temp;
  172162. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  172163. /* We can allocate at least the nc'th root of max_colors per component. */
  172164. /* Compute floor(nc'th root of max_colors). */
  172165. iroot = 1;
  172166. do {
  172167. iroot++;
  172168. temp = iroot; /* set temp = iroot ** nc */
  172169. for (i = 1; i < nc; i++)
  172170. temp *= iroot;
  172171. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  172172. iroot--; /* now iroot = floor(root) */
  172173. /* Must have at least 2 color values per component */
  172174. if (iroot < 2)
  172175. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  172176. /* Initialize to iroot color values for each component */
  172177. total_colors = 1;
  172178. for (i = 0; i < nc; i++) {
  172179. Ncolors[i] = iroot;
  172180. total_colors *= iroot;
  172181. }
  172182. /* We may be able to increment the count for one or more components without
  172183. * exceeding max_colors, though we know not all can be incremented.
  172184. * Sometimes, the first component can be incremented more than once!
  172185. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  172186. * In RGB colorspace, try to increment G first, then R, then B.
  172187. */
  172188. do {
  172189. changed = FALSE;
  172190. for (i = 0; i < nc; i++) {
  172191. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  172192. /* calculate new total_colors if Ncolors[j] is incremented */
  172193. temp = total_colors / Ncolors[j];
  172194. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  172195. if (temp > (long) max_colors)
  172196. break; /* won't fit, done with this pass */
  172197. Ncolors[j]++; /* OK, apply the increment */
  172198. total_colors = (int) temp;
  172199. changed = TRUE;
  172200. }
  172201. } while (changed);
  172202. return total_colors;
  172203. }
  172204. LOCAL(int)
  172205. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172206. /* Return j'th output value, where j will range from 0 to maxj */
  172207. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  172208. {
  172209. /* We always provide values 0 and MAXJSAMPLE for each component;
  172210. * any additional values are equally spaced between these limits.
  172211. * (Forcing the upper and lower values to the limits ensures that
  172212. * dithering can't produce a color outside the selected gamut.)
  172213. */
  172214. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  172215. }
  172216. LOCAL(int)
  172217. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172218. /* Return largest input value that should map to j'th output value */
  172219. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  172220. {
  172221. /* Breakpoints are halfway between values returned by output_value */
  172222. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  172223. }
  172224. /*
  172225. * Create the colormap.
  172226. */
  172227. LOCAL(void)
  172228. create_colormap (j_decompress_ptr cinfo)
  172229. {
  172230. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172231. JSAMPARRAY colormap; /* Created colormap */
  172232. int total_colors; /* Number of distinct output colors */
  172233. int i,j,k, nci, blksize, blkdist, ptr, val;
  172234. /* Select number of colors for each component */
  172235. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  172236. /* Report selected color counts */
  172237. if (cinfo->out_color_components == 3)
  172238. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  172239. total_colors, cquantize->Ncolors[0],
  172240. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  172241. else
  172242. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  172243. /* Allocate and fill in the colormap. */
  172244. /* The colors are ordered in the map in standard row-major order, */
  172245. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  172246. colormap = (*cinfo->mem->alloc_sarray)
  172247. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172248. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  172249. /* blksize is number of adjacent repeated entries for a component */
  172250. /* blkdist is distance between groups of identical entries for a component */
  172251. blkdist = total_colors;
  172252. for (i = 0; i < cinfo->out_color_components; i++) {
  172253. /* fill in colormap entries for i'th color component */
  172254. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172255. blksize = blkdist / nci;
  172256. for (j = 0; j < nci; j++) {
  172257. /* Compute j'th output value (out of nci) for component */
  172258. val = output_value(cinfo, i, j, nci-1);
  172259. /* Fill in all colormap entries that have this value of this component */
  172260. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  172261. /* fill in blksize entries beginning at ptr */
  172262. for (k = 0; k < blksize; k++)
  172263. colormap[i][ptr+k] = (JSAMPLE) val;
  172264. }
  172265. }
  172266. blkdist = blksize; /* blksize of this color is blkdist of next */
  172267. }
  172268. /* Save the colormap in private storage,
  172269. * where it will survive color quantization mode changes.
  172270. */
  172271. cquantize->sv_colormap = colormap;
  172272. cquantize->sv_actual = total_colors;
  172273. }
  172274. /*
  172275. * Create the color index table.
  172276. */
  172277. LOCAL(void)
  172278. create_colorindex (j_decompress_ptr cinfo)
  172279. {
  172280. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172281. JSAMPROW indexptr;
  172282. int i,j,k, nci, blksize, val, pad;
  172283. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  172284. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  172285. * This is not necessary in the other dithering modes. However, we
  172286. * flag whether it was done in case user changes dithering mode.
  172287. */
  172288. if (cinfo->dither_mode == JDITHER_ORDERED) {
  172289. pad = MAXJSAMPLE*2;
  172290. cquantize->is_padded = TRUE;
  172291. } else {
  172292. pad = 0;
  172293. cquantize->is_padded = FALSE;
  172294. }
  172295. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  172296. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172297. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  172298. (JDIMENSION) cinfo->out_color_components);
  172299. /* blksize is number of adjacent repeated entries for a component */
  172300. blksize = cquantize->sv_actual;
  172301. for (i = 0; i < cinfo->out_color_components; i++) {
  172302. /* fill in colorindex entries for i'th color component */
  172303. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172304. blksize = blksize / nci;
  172305. /* adjust colorindex pointers to provide padding at negative indexes. */
  172306. if (pad)
  172307. cquantize->colorindex[i] += MAXJSAMPLE;
  172308. /* in loop, val = index of current output value, */
  172309. /* and k = largest j that maps to current val */
  172310. indexptr = cquantize->colorindex[i];
  172311. val = 0;
  172312. k = largest_input_value(cinfo, i, 0, nci-1);
  172313. for (j = 0; j <= MAXJSAMPLE; j++) {
  172314. while (j > k) /* advance val if past boundary */
  172315. k = largest_input_value(cinfo, i, ++val, nci-1);
  172316. /* premultiply so that no multiplication needed in main processing */
  172317. indexptr[j] = (JSAMPLE) (val * blksize);
  172318. }
  172319. /* Pad at both ends if necessary */
  172320. if (pad)
  172321. for (j = 1; j <= MAXJSAMPLE; j++) {
  172322. indexptr[-j] = indexptr[0];
  172323. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  172324. }
  172325. }
  172326. }
  172327. /*
  172328. * Create an ordered-dither array for a component having ncolors
  172329. * distinct output values.
  172330. */
  172331. LOCAL(ODITHER_MATRIX_PTR)
  172332. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  172333. {
  172334. ODITHER_MATRIX_PTR odither;
  172335. int j,k;
  172336. INT32 num,den;
  172337. odither = (ODITHER_MATRIX_PTR)
  172338. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172339. SIZEOF(ODITHER_MATRIX));
  172340. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  172341. * Hence the dither value for the matrix cell with fill order f
  172342. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  172343. * On 16-bit-int machine, be careful to avoid overflow.
  172344. */
  172345. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  172346. for (j = 0; j < ODITHER_SIZE; j++) {
  172347. for (k = 0; k < ODITHER_SIZE; k++) {
  172348. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  172349. * MAXJSAMPLE;
  172350. /* Ensure round towards zero despite C's lack of consistency
  172351. * about rounding negative values in integer division...
  172352. */
  172353. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  172354. }
  172355. }
  172356. return odither;
  172357. }
  172358. /*
  172359. * Create the ordered-dither tables.
  172360. * Components having the same number of representative colors may
  172361. * share a dither table.
  172362. */
  172363. LOCAL(void)
  172364. create_odither_tables (j_decompress_ptr cinfo)
  172365. {
  172366. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172367. ODITHER_MATRIX_PTR odither;
  172368. int i, j, nci;
  172369. for (i = 0; i < cinfo->out_color_components; i++) {
  172370. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172371. odither = NULL; /* search for matching prior component */
  172372. for (j = 0; j < i; j++) {
  172373. if (nci == cquantize->Ncolors[j]) {
  172374. odither = cquantize->odither[j];
  172375. break;
  172376. }
  172377. }
  172378. if (odither == NULL) /* need a new table? */
  172379. odither = make_odither_array(cinfo, nci);
  172380. cquantize->odither[i] = odither;
  172381. }
  172382. }
  172383. /*
  172384. * Map some rows of pixels to the output colormapped representation.
  172385. */
  172386. METHODDEF(void)
  172387. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172388. JSAMPARRAY output_buf, int num_rows)
  172389. /* General case, no dithering */
  172390. {
  172391. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172392. JSAMPARRAY colorindex = cquantize->colorindex;
  172393. register int pixcode, ci;
  172394. register JSAMPROW ptrin, ptrout;
  172395. int row;
  172396. JDIMENSION col;
  172397. JDIMENSION width = cinfo->output_width;
  172398. register int nc = cinfo->out_color_components;
  172399. for (row = 0; row < num_rows; row++) {
  172400. ptrin = input_buf[row];
  172401. ptrout = output_buf[row];
  172402. for (col = width; col > 0; col--) {
  172403. pixcode = 0;
  172404. for (ci = 0; ci < nc; ci++) {
  172405. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  172406. }
  172407. *ptrout++ = (JSAMPLE) pixcode;
  172408. }
  172409. }
  172410. }
  172411. METHODDEF(void)
  172412. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172413. JSAMPARRAY output_buf, int num_rows)
  172414. /* Fast path for out_color_components==3, no dithering */
  172415. {
  172416. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172417. register int pixcode;
  172418. register JSAMPROW ptrin, ptrout;
  172419. JSAMPROW colorindex0 = cquantize->colorindex[0];
  172420. JSAMPROW colorindex1 = cquantize->colorindex[1];
  172421. JSAMPROW colorindex2 = cquantize->colorindex[2];
  172422. int row;
  172423. JDIMENSION col;
  172424. JDIMENSION width = cinfo->output_width;
  172425. for (row = 0; row < num_rows; row++) {
  172426. ptrin = input_buf[row];
  172427. ptrout = output_buf[row];
  172428. for (col = width; col > 0; col--) {
  172429. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  172430. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  172431. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  172432. *ptrout++ = (JSAMPLE) pixcode;
  172433. }
  172434. }
  172435. }
  172436. METHODDEF(void)
  172437. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172438. JSAMPARRAY output_buf, int num_rows)
  172439. /* General case, with ordered dithering */
  172440. {
  172441. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172442. register JSAMPROW input_ptr;
  172443. register JSAMPROW output_ptr;
  172444. JSAMPROW colorindex_ci;
  172445. int * dither; /* points to active row of dither matrix */
  172446. int row_index, col_index; /* current indexes into dither matrix */
  172447. int nc = cinfo->out_color_components;
  172448. int ci;
  172449. int row;
  172450. JDIMENSION col;
  172451. JDIMENSION width = cinfo->output_width;
  172452. for (row = 0; row < num_rows; row++) {
  172453. /* Initialize output values to 0 so can process components separately */
  172454. jzero_far((void FAR *) output_buf[row],
  172455. (size_t) (width * SIZEOF(JSAMPLE)));
  172456. row_index = cquantize->row_index;
  172457. for (ci = 0; ci < nc; ci++) {
  172458. input_ptr = input_buf[row] + ci;
  172459. output_ptr = output_buf[row];
  172460. colorindex_ci = cquantize->colorindex[ci];
  172461. dither = cquantize->odither[ci][row_index];
  172462. col_index = 0;
  172463. for (col = width; col > 0; col--) {
  172464. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  172465. * select output value, accumulate into output code for this pixel.
  172466. * Range-limiting need not be done explicitly, as we have extended
  172467. * the colorindex table to produce the right answers for out-of-range
  172468. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  172469. * required amount of padding.
  172470. */
  172471. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  172472. input_ptr += nc;
  172473. output_ptr++;
  172474. col_index = (col_index + 1) & ODITHER_MASK;
  172475. }
  172476. }
  172477. /* Advance row index for next row */
  172478. row_index = (row_index + 1) & ODITHER_MASK;
  172479. cquantize->row_index = row_index;
  172480. }
  172481. }
  172482. METHODDEF(void)
  172483. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172484. JSAMPARRAY output_buf, int num_rows)
  172485. /* Fast path for out_color_components==3, with ordered dithering */
  172486. {
  172487. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172488. register int pixcode;
  172489. register JSAMPROW input_ptr;
  172490. register JSAMPROW output_ptr;
  172491. JSAMPROW colorindex0 = cquantize->colorindex[0];
  172492. JSAMPROW colorindex1 = cquantize->colorindex[1];
  172493. JSAMPROW colorindex2 = cquantize->colorindex[2];
  172494. int * dither0; /* points to active row of dither matrix */
  172495. int * dither1;
  172496. int * dither2;
  172497. int row_index, col_index; /* current indexes into dither matrix */
  172498. int row;
  172499. JDIMENSION col;
  172500. JDIMENSION width = cinfo->output_width;
  172501. for (row = 0; row < num_rows; row++) {
  172502. row_index = cquantize->row_index;
  172503. input_ptr = input_buf[row];
  172504. output_ptr = output_buf[row];
  172505. dither0 = cquantize->odither[0][row_index];
  172506. dither1 = cquantize->odither[1][row_index];
  172507. dither2 = cquantize->odither[2][row_index];
  172508. col_index = 0;
  172509. for (col = width; col > 0; col--) {
  172510. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  172511. dither0[col_index]]);
  172512. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  172513. dither1[col_index]]);
  172514. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  172515. dither2[col_index]]);
  172516. *output_ptr++ = (JSAMPLE) pixcode;
  172517. col_index = (col_index + 1) & ODITHER_MASK;
  172518. }
  172519. row_index = (row_index + 1) & ODITHER_MASK;
  172520. cquantize->row_index = row_index;
  172521. }
  172522. }
  172523. METHODDEF(void)
  172524. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172525. JSAMPARRAY output_buf, int num_rows)
  172526. /* General case, with Floyd-Steinberg dithering */
  172527. {
  172528. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172529. register LOCFSERROR cur; /* current error or pixel value */
  172530. LOCFSERROR belowerr; /* error for pixel below cur */
  172531. LOCFSERROR bpreverr; /* error for below/prev col */
  172532. LOCFSERROR bnexterr; /* error for below/next col */
  172533. LOCFSERROR delta;
  172534. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  172535. register JSAMPROW input_ptr;
  172536. register JSAMPROW output_ptr;
  172537. JSAMPROW colorindex_ci;
  172538. JSAMPROW colormap_ci;
  172539. int pixcode;
  172540. int nc = cinfo->out_color_components;
  172541. int dir; /* 1 for left-to-right, -1 for right-to-left */
  172542. int dirnc; /* dir * nc */
  172543. int ci;
  172544. int row;
  172545. JDIMENSION col;
  172546. JDIMENSION width = cinfo->output_width;
  172547. JSAMPLE *range_limit = cinfo->sample_range_limit;
  172548. SHIFT_TEMPS
  172549. for (row = 0; row < num_rows; row++) {
  172550. /* Initialize output values to 0 so can process components separately */
  172551. jzero_far((void FAR *) output_buf[row],
  172552. (size_t) (width * SIZEOF(JSAMPLE)));
  172553. for (ci = 0; ci < nc; ci++) {
  172554. input_ptr = input_buf[row] + ci;
  172555. output_ptr = output_buf[row];
  172556. if (cquantize->on_odd_row) {
  172557. /* work right to left in this row */
  172558. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  172559. output_ptr += width-1;
  172560. dir = -1;
  172561. dirnc = -nc;
  172562. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  172563. } else {
  172564. /* work left to right in this row */
  172565. dir = 1;
  172566. dirnc = nc;
  172567. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  172568. }
  172569. colorindex_ci = cquantize->colorindex[ci];
  172570. colormap_ci = cquantize->sv_colormap[ci];
  172571. /* Preset error values: no error propagated to first pixel from left */
  172572. cur = 0;
  172573. /* and no error propagated to row below yet */
  172574. belowerr = bpreverr = 0;
  172575. for (col = width; col > 0; col--) {
  172576. /* cur holds the error propagated from the previous pixel on the
  172577. * current line. Add the error propagated from the previous line
  172578. * to form the complete error correction term for this pixel, and
  172579. * round the error term (which is expressed * 16) to an integer.
  172580. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  172581. * for either sign of the error value.
  172582. * Note: errorptr points to *previous* column's array entry.
  172583. */
  172584. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  172585. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  172586. * The maximum error is +- MAXJSAMPLE; this sets the required size
  172587. * of the range_limit array.
  172588. */
  172589. cur += GETJSAMPLE(*input_ptr);
  172590. cur = GETJSAMPLE(range_limit[cur]);
  172591. /* Select output value, accumulate into output code for this pixel */
  172592. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  172593. *output_ptr += (JSAMPLE) pixcode;
  172594. /* Compute actual representation error at this pixel */
  172595. /* Note: we can do this even though we don't have the final */
  172596. /* pixel code, because the colormap is orthogonal. */
  172597. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  172598. /* Compute error fractions to be propagated to adjacent pixels.
  172599. * Add these into the running sums, and simultaneously shift the
  172600. * next-line error sums left by 1 column.
  172601. */
  172602. bnexterr = cur;
  172603. delta = cur * 2;
  172604. cur += delta; /* form error * 3 */
  172605. errorptr[0] = (FSERROR) (bpreverr + cur);
  172606. cur += delta; /* form error * 5 */
  172607. bpreverr = belowerr + cur;
  172608. belowerr = bnexterr;
  172609. cur += delta; /* form error * 7 */
  172610. /* At this point cur contains the 7/16 error value to be propagated
  172611. * to the next pixel on the current line, and all the errors for the
  172612. * next line have been shifted over. We are therefore ready to move on.
  172613. */
  172614. input_ptr += dirnc; /* advance input ptr to next column */
  172615. output_ptr += dir; /* advance output ptr to next column */
  172616. errorptr += dir; /* advance errorptr to current column */
  172617. }
  172618. /* Post-loop cleanup: we must unload the final error value into the
  172619. * final fserrors[] entry. Note we need not unload belowerr because
  172620. * it is for the dummy column before or after the actual array.
  172621. */
  172622. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  172623. }
  172624. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  172625. }
  172626. }
  172627. /*
  172628. * Allocate workspace for Floyd-Steinberg errors.
  172629. */
  172630. LOCAL(void)
  172631. alloc_fs_workspace (j_decompress_ptr cinfo)
  172632. {
  172633. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172634. size_t arraysize;
  172635. int i;
  172636. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  172637. for (i = 0; i < cinfo->out_color_components; i++) {
  172638. cquantize->fserrors[i] = (FSERRPTR)
  172639. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  172640. }
  172641. }
  172642. /*
  172643. * Initialize for one-pass color quantization.
  172644. */
  172645. METHODDEF(void)
  172646. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  172647. {
  172648. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172649. size_t arraysize;
  172650. int i;
  172651. /* Install my colormap. */
  172652. cinfo->colormap = cquantize->sv_colormap;
  172653. cinfo->actual_number_of_colors = cquantize->sv_actual;
  172654. /* Initialize for desired dithering mode. */
  172655. switch (cinfo->dither_mode) {
  172656. case JDITHER_NONE:
  172657. if (cinfo->out_color_components == 3)
  172658. cquantize->pub.color_quantize = color_quantize3;
  172659. else
  172660. cquantize->pub.color_quantize = color_quantize;
  172661. break;
  172662. case JDITHER_ORDERED:
  172663. if (cinfo->out_color_components == 3)
  172664. cquantize->pub.color_quantize = quantize3_ord_dither;
  172665. else
  172666. cquantize->pub.color_quantize = quantize_ord_dither;
  172667. cquantize->row_index = 0; /* initialize state for ordered dither */
  172668. /* If user changed to ordered dither from another mode,
  172669. * we must recreate the color index table with padding.
  172670. * This will cost extra space, but probably isn't very likely.
  172671. */
  172672. if (! cquantize->is_padded)
  172673. create_colorindex(cinfo);
  172674. /* Create ordered-dither tables if we didn't already. */
  172675. if (cquantize->odither[0] == NULL)
  172676. create_odither_tables(cinfo);
  172677. break;
  172678. case JDITHER_FS:
  172679. cquantize->pub.color_quantize = quantize_fs_dither;
  172680. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  172681. /* Allocate Floyd-Steinberg workspace if didn't already. */
  172682. if (cquantize->fserrors[0] == NULL)
  172683. alloc_fs_workspace(cinfo);
  172684. /* Initialize the propagated errors to zero. */
  172685. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  172686. for (i = 0; i < cinfo->out_color_components; i++)
  172687. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  172688. break;
  172689. default:
  172690. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172691. break;
  172692. }
  172693. }
  172694. /*
  172695. * Finish up at the end of the pass.
  172696. */
  172697. METHODDEF(void)
  172698. finish_pass_1_quant (j_decompress_ptr cinfo)
  172699. {
  172700. /* no work in 1-pass case */
  172701. }
  172702. /*
  172703. * Switch to a new external colormap between output passes.
  172704. * Shouldn't get to this module!
  172705. */
  172706. METHODDEF(void)
  172707. new_color_map_1_quant (j_decompress_ptr cinfo)
  172708. {
  172709. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172710. }
  172711. /*
  172712. * Module initialization routine for 1-pass color quantization.
  172713. */
  172714. GLOBAL(void)
  172715. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  172716. {
  172717. my_cquantize_ptr cquantize;
  172718. cquantize = (my_cquantize_ptr)
  172719. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172720. SIZEOF(my_cquantizer));
  172721. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  172722. cquantize->pub.start_pass = start_pass_1_quant;
  172723. cquantize->pub.finish_pass = finish_pass_1_quant;
  172724. cquantize->pub.new_color_map = new_color_map_1_quant;
  172725. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  172726. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  172727. /* Make sure my internal arrays won't overflow */
  172728. if (cinfo->out_color_components > MAX_Q_COMPS)
  172729. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  172730. /* Make sure colormap indexes can be represented by JSAMPLEs */
  172731. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  172732. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  172733. /* Create the colormap and color index table. */
  172734. create_colormap(cinfo);
  172735. create_colorindex(cinfo);
  172736. /* Allocate Floyd-Steinberg workspace now if requested.
  172737. * We do this now since it is FAR storage and may affect the memory
  172738. * manager's space calculations. If the user changes to FS dither
  172739. * mode in a later pass, we will allocate the space then, and will
  172740. * possibly overrun the max_memory_to_use setting.
  172741. */
  172742. if (cinfo->dither_mode == JDITHER_FS)
  172743. alloc_fs_workspace(cinfo);
  172744. }
  172745. #endif /* QUANT_1PASS_SUPPORTED */
  172746. /********* End of inlined file: jquant1.c *********/
  172747. /********* Start of inlined file: jquant2.c *********/
  172748. #define JPEG_INTERNALS
  172749. #ifdef QUANT_2PASS_SUPPORTED
  172750. /*
  172751. * This module implements the well-known Heckbert paradigm for color
  172752. * quantization. Most of the ideas used here can be traced back to
  172753. * Heckbert's seminal paper
  172754. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  172755. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  172756. *
  172757. * In the first pass over the image, we accumulate a histogram showing the
  172758. * usage count of each possible color. To keep the histogram to a reasonable
  172759. * size, we reduce the precision of the input; typical practice is to retain
  172760. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  172761. * in the same histogram cell.
  172762. *
  172763. * Next, the color-selection step begins with a box representing the whole
  172764. * color space, and repeatedly splits the "largest" remaining box until we
  172765. * have as many boxes as desired colors. Then the mean color in each
  172766. * remaining box becomes one of the possible output colors.
  172767. *
  172768. * The second pass over the image maps each input pixel to the closest output
  172769. * color (optionally after applying a Floyd-Steinberg dithering correction).
  172770. * This mapping is logically trivial, but making it go fast enough requires
  172771. * considerable care.
  172772. *
  172773. * Heckbert-style quantizers vary a good deal in their policies for choosing
  172774. * the "largest" box and deciding where to cut it. The particular policies
  172775. * used here have proved out well in experimental comparisons, but better ones
  172776. * may yet be found.
  172777. *
  172778. * In earlier versions of the IJG code, this module quantized in YCbCr color
  172779. * space, processing the raw upsampled data without a color conversion step.
  172780. * This allowed the color conversion math to be done only once per colormap
  172781. * entry, not once per pixel. However, that optimization precluded other
  172782. * useful optimizations (such as merging color conversion with upsampling)
  172783. * and it also interfered with desired capabilities such as quantizing to an
  172784. * externally-supplied colormap. We have therefore abandoned that approach.
  172785. * The present code works in the post-conversion color space, typically RGB.
  172786. *
  172787. * To improve the visual quality of the results, we actually work in scaled
  172788. * RGB space, giving G distances more weight than R, and R in turn more than
  172789. * B. To do everything in integer math, we must use integer scale factors.
  172790. * The 2/3/1 scale factors used here correspond loosely to the relative
  172791. * weights of the colors in the NTSC grayscale equation.
  172792. * If you want to use this code to quantize a non-RGB color space, you'll
  172793. * probably need to change these scale factors.
  172794. */
  172795. #define R_SCALE 2 /* scale R distances by this much */
  172796. #define G_SCALE 3 /* scale G distances by this much */
  172797. #define B_SCALE 1 /* and B by this much */
  172798. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  172799. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  172800. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  172801. * you'll get compile errors until you extend this logic. In that case
  172802. * you'll probably want to tweak the histogram sizes too.
  172803. */
  172804. #if RGB_RED == 0
  172805. #define C0_SCALE R_SCALE
  172806. #endif
  172807. #if RGB_BLUE == 0
  172808. #define C0_SCALE B_SCALE
  172809. #endif
  172810. #if RGB_GREEN == 1
  172811. #define C1_SCALE G_SCALE
  172812. #endif
  172813. #if RGB_RED == 2
  172814. #define C2_SCALE R_SCALE
  172815. #endif
  172816. #if RGB_BLUE == 2
  172817. #define C2_SCALE B_SCALE
  172818. #endif
  172819. /*
  172820. * First we have the histogram data structure and routines for creating it.
  172821. *
  172822. * The number of bits of precision can be adjusted by changing these symbols.
  172823. * We recommend keeping 6 bits for G and 5 each for R and B.
  172824. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  172825. * better results; if you are short of memory, 5 bits all around will save
  172826. * some space but degrade the results.
  172827. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  172828. * (preferably unsigned long) for each cell. In practice this is overkill;
  172829. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  172830. * and clamping those that do overflow to the maximum value will give close-
  172831. * enough results. This reduces the recommended histogram size from 256Kb
  172832. * to 128Kb, which is a useful savings on PC-class machines.
  172833. * (In the second pass the histogram space is re-used for pixel mapping data;
  172834. * in that capacity, each cell must be able to store zero to the number of
  172835. * desired colors. 16 bits/cell is plenty for that too.)
  172836. * Since the JPEG code is intended to run in small memory model on 80x86
  172837. * machines, we can't just allocate the histogram in one chunk. Instead
  172838. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  172839. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  172840. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  172841. * on 80x86 machines, the pointer row is in near memory but the actual
  172842. * arrays are in far memory (same arrangement as we use for image arrays).
  172843. */
  172844. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  172845. /* These will do the right thing for either R,G,B or B,G,R color order,
  172846. * but you may not like the results for other color orders.
  172847. */
  172848. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  172849. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  172850. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  172851. /* Number of elements along histogram axes. */
  172852. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  172853. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  172854. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  172855. /* These are the amounts to shift an input value to get a histogram index. */
  172856. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  172857. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  172858. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  172859. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  172860. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  172861. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  172862. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  172863. typedef hist2d * hist3d; /* type for top-level pointer */
  172864. /* Declarations for Floyd-Steinberg dithering.
  172865. *
  172866. * Errors are accumulated into the array fserrors[], at a resolution of
  172867. * 1/16th of a pixel count. The error at a given pixel is propagated
  172868. * to its not-yet-processed neighbors using the standard F-S fractions,
  172869. * ... (here) 7/16
  172870. * 3/16 5/16 1/16
  172871. * We work left-to-right on even rows, right-to-left on odd rows.
  172872. *
  172873. * We can get away with a single array (holding one row's worth of errors)
  172874. * by using it to store the current row's errors at pixel columns not yet
  172875. * processed, but the next row's errors at columns already processed. We
  172876. * need only a few extra variables to hold the errors immediately around the
  172877. * current column. (If we are lucky, those variables are in registers, but
  172878. * even if not, they're probably cheaper to access than array elements are.)
  172879. *
  172880. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  172881. * each end saves us from special-casing the first and last pixels.
  172882. * Each entry is three values long, one value for each color component.
  172883. *
  172884. * Note: on a wide image, we might not have enough room in a PC's near data
  172885. * segment to hold the error array; so it is allocated with alloc_large.
  172886. */
  172887. #if BITS_IN_JSAMPLE == 8
  172888. typedef INT16 FSERROR; /* 16 bits should be enough */
  172889. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  172890. #else
  172891. typedef INT32 FSERROR; /* may need more than 16 bits */
  172892. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  172893. #endif
  172894. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  172895. /* Private subobject */
  172896. typedef struct {
  172897. struct jpeg_color_quantizer pub; /* public fields */
  172898. /* Space for the eventually created colormap is stashed here */
  172899. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  172900. int desired; /* desired # of colors = size of colormap */
  172901. /* Variables for accumulating image statistics */
  172902. hist3d histogram; /* pointer to the histogram */
  172903. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  172904. /* Variables for Floyd-Steinberg dithering */
  172905. FSERRPTR fserrors; /* accumulated errors */
  172906. boolean on_odd_row; /* flag to remember which row we are on */
  172907. int * error_limiter; /* table for clamping the applied error */
  172908. } my_cquantizer2;
  172909. typedef my_cquantizer2 * my_cquantize_ptr2;
  172910. /*
  172911. * Prescan some rows of pixels.
  172912. * In this module the prescan simply updates the histogram, which has been
  172913. * initialized to zeroes by start_pass.
  172914. * An output_buf parameter is required by the method signature, but no data
  172915. * is actually output (in fact the buffer controller is probably passing a
  172916. * NULL pointer).
  172917. */
  172918. METHODDEF(void)
  172919. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172920. JSAMPARRAY output_buf, int num_rows)
  172921. {
  172922. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172923. register JSAMPROW ptr;
  172924. register histptr histp;
  172925. register hist3d histogram = cquantize->histogram;
  172926. int row;
  172927. JDIMENSION col;
  172928. JDIMENSION width = cinfo->output_width;
  172929. for (row = 0; row < num_rows; row++) {
  172930. ptr = input_buf[row];
  172931. for (col = width; col > 0; col--) {
  172932. /* get pixel value and index into the histogram */
  172933. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  172934. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  172935. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  172936. /* increment, check for overflow and undo increment if so. */
  172937. if (++(*histp) <= 0)
  172938. (*histp)--;
  172939. ptr += 3;
  172940. }
  172941. }
  172942. }
  172943. /*
  172944. * Next we have the really interesting routines: selection of a colormap
  172945. * given the completed histogram.
  172946. * These routines work with a list of "boxes", each representing a rectangular
  172947. * subset of the input color space (to histogram precision).
  172948. */
  172949. typedef struct {
  172950. /* The bounds of the box (inclusive); expressed as histogram indexes */
  172951. int c0min, c0max;
  172952. int c1min, c1max;
  172953. int c2min, c2max;
  172954. /* The volume (actually 2-norm) of the box */
  172955. INT32 volume;
  172956. /* The number of nonzero histogram cells within this box */
  172957. long colorcount;
  172958. } box;
  172959. typedef box * boxptr;
  172960. LOCAL(boxptr)
  172961. find_biggest_color_pop (boxptr boxlist, int numboxes)
  172962. /* Find the splittable box with the largest color population */
  172963. /* Returns NULL if no splittable boxes remain */
  172964. {
  172965. register boxptr boxp;
  172966. register int i;
  172967. register long maxc = 0;
  172968. boxptr which = NULL;
  172969. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  172970. if (boxp->colorcount > maxc && boxp->volume > 0) {
  172971. which = boxp;
  172972. maxc = boxp->colorcount;
  172973. }
  172974. }
  172975. return which;
  172976. }
  172977. LOCAL(boxptr)
  172978. find_biggest_volume (boxptr boxlist, int numboxes)
  172979. /* Find the splittable box with the largest (scaled) volume */
  172980. /* Returns NULL if no splittable boxes remain */
  172981. {
  172982. register boxptr boxp;
  172983. register int i;
  172984. register INT32 maxv = 0;
  172985. boxptr which = NULL;
  172986. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  172987. if (boxp->volume > maxv) {
  172988. which = boxp;
  172989. maxv = boxp->volume;
  172990. }
  172991. }
  172992. return which;
  172993. }
  172994. LOCAL(void)
  172995. update_box (j_decompress_ptr cinfo, boxptr boxp)
  172996. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  172997. /* and recompute its volume and population */
  172998. {
  172999. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173000. hist3d histogram = cquantize->histogram;
  173001. histptr histp;
  173002. int c0,c1,c2;
  173003. int c0min,c0max,c1min,c1max,c2min,c2max;
  173004. INT32 dist0,dist1,dist2;
  173005. long ccount;
  173006. c0min = boxp->c0min; c0max = boxp->c0max;
  173007. c1min = boxp->c1min; c1max = boxp->c1max;
  173008. c2min = boxp->c2min; c2max = boxp->c2max;
  173009. if (c0max > c0min)
  173010. for (c0 = c0min; c0 <= c0max; c0++)
  173011. for (c1 = c1min; c1 <= c1max; c1++) {
  173012. histp = & histogram[c0][c1][c2min];
  173013. for (c2 = c2min; c2 <= c2max; c2++)
  173014. if (*histp++ != 0) {
  173015. boxp->c0min = c0min = c0;
  173016. goto have_c0min;
  173017. }
  173018. }
  173019. have_c0min:
  173020. if (c0max > c0min)
  173021. for (c0 = c0max; c0 >= c0min; c0--)
  173022. for (c1 = c1min; c1 <= c1max; c1++) {
  173023. histp = & histogram[c0][c1][c2min];
  173024. for (c2 = c2min; c2 <= c2max; c2++)
  173025. if (*histp++ != 0) {
  173026. boxp->c0max = c0max = c0;
  173027. goto have_c0max;
  173028. }
  173029. }
  173030. have_c0max:
  173031. if (c1max > c1min)
  173032. for (c1 = c1min; c1 <= c1max; c1++)
  173033. for (c0 = c0min; c0 <= c0max; c0++) {
  173034. histp = & histogram[c0][c1][c2min];
  173035. for (c2 = c2min; c2 <= c2max; c2++)
  173036. if (*histp++ != 0) {
  173037. boxp->c1min = c1min = c1;
  173038. goto have_c1min;
  173039. }
  173040. }
  173041. have_c1min:
  173042. if (c1max > c1min)
  173043. for (c1 = c1max; c1 >= c1min; c1--)
  173044. for (c0 = c0min; c0 <= c0max; c0++) {
  173045. histp = & histogram[c0][c1][c2min];
  173046. for (c2 = c2min; c2 <= c2max; c2++)
  173047. if (*histp++ != 0) {
  173048. boxp->c1max = c1max = c1;
  173049. goto have_c1max;
  173050. }
  173051. }
  173052. have_c1max:
  173053. if (c2max > c2min)
  173054. for (c2 = c2min; c2 <= c2max; c2++)
  173055. for (c0 = c0min; c0 <= c0max; c0++) {
  173056. histp = & histogram[c0][c1min][c2];
  173057. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173058. if (*histp != 0) {
  173059. boxp->c2min = c2min = c2;
  173060. goto have_c2min;
  173061. }
  173062. }
  173063. have_c2min:
  173064. if (c2max > c2min)
  173065. for (c2 = c2max; c2 >= c2min; c2--)
  173066. for (c0 = c0min; c0 <= c0max; c0++) {
  173067. histp = & histogram[c0][c1min][c2];
  173068. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173069. if (*histp != 0) {
  173070. boxp->c2max = c2max = c2;
  173071. goto have_c2max;
  173072. }
  173073. }
  173074. have_c2max:
  173075. /* Update box volume.
  173076. * We use 2-norm rather than real volume here; this biases the method
  173077. * against making long narrow boxes, and it has the side benefit that
  173078. * a box is splittable iff norm > 0.
  173079. * Since the differences are expressed in histogram-cell units,
  173080. * we have to shift back to JSAMPLE units to get consistent distances;
  173081. * after which, we scale according to the selected distance scale factors.
  173082. */
  173083. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  173084. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  173085. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  173086. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  173087. /* Now scan remaining volume of box and compute population */
  173088. ccount = 0;
  173089. for (c0 = c0min; c0 <= c0max; c0++)
  173090. for (c1 = c1min; c1 <= c1max; c1++) {
  173091. histp = & histogram[c0][c1][c2min];
  173092. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  173093. if (*histp != 0) {
  173094. ccount++;
  173095. }
  173096. }
  173097. boxp->colorcount = ccount;
  173098. }
  173099. LOCAL(int)
  173100. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  173101. int desired_colors)
  173102. /* Repeatedly select and split the largest box until we have enough boxes */
  173103. {
  173104. int n,lb;
  173105. int c0,c1,c2,cmax;
  173106. register boxptr b1,b2;
  173107. while (numboxes < desired_colors) {
  173108. /* Select box to split.
  173109. * Current algorithm: by population for first half, then by volume.
  173110. */
  173111. if (numboxes*2 <= desired_colors) {
  173112. b1 = find_biggest_color_pop(boxlist, numboxes);
  173113. } else {
  173114. b1 = find_biggest_volume(boxlist, numboxes);
  173115. }
  173116. if (b1 == NULL) /* no splittable boxes left! */
  173117. break;
  173118. b2 = &boxlist[numboxes]; /* where new box will go */
  173119. /* Copy the color bounds to the new box. */
  173120. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  173121. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  173122. /* Choose which axis to split the box on.
  173123. * Current algorithm: longest scaled axis.
  173124. * See notes in update_box about scaling distances.
  173125. */
  173126. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  173127. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  173128. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  173129. /* We want to break any ties in favor of green, then red, blue last.
  173130. * This code does the right thing for R,G,B or B,G,R color orders only.
  173131. */
  173132. #if RGB_RED == 0
  173133. cmax = c1; n = 1;
  173134. if (c0 > cmax) { cmax = c0; n = 0; }
  173135. if (c2 > cmax) { n = 2; }
  173136. #else
  173137. cmax = c1; n = 1;
  173138. if (c2 > cmax) { cmax = c2; n = 2; }
  173139. if (c0 > cmax) { n = 0; }
  173140. #endif
  173141. /* Choose split point along selected axis, and update box bounds.
  173142. * Current algorithm: split at halfway point.
  173143. * (Since the box has been shrunk to minimum volume,
  173144. * any split will produce two nonempty subboxes.)
  173145. * Note that lb value is max for lower box, so must be < old max.
  173146. */
  173147. switch (n) {
  173148. case 0:
  173149. lb = (b1->c0max + b1->c0min) / 2;
  173150. b1->c0max = lb;
  173151. b2->c0min = lb+1;
  173152. break;
  173153. case 1:
  173154. lb = (b1->c1max + b1->c1min) / 2;
  173155. b1->c1max = lb;
  173156. b2->c1min = lb+1;
  173157. break;
  173158. case 2:
  173159. lb = (b1->c2max + b1->c2min) / 2;
  173160. b1->c2max = lb;
  173161. b2->c2min = lb+1;
  173162. break;
  173163. }
  173164. /* Update stats for boxes */
  173165. update_box(cinfo, b1);
  173166. update_box(cinfo, b2);
  173167. numboxes++;
  173168. }
  173169. return numboxes;
  173170. }
  173171. LOCAL(void)
  173172. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  173173. /* Compute representative color for a box, put it in colormap[icolor] */
  173174. {
  173175. /* Current algorithm: mean weighted by pixels (not colors) */
  173176. /* Note it is important to get the rounding correct! */
  173177. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173178. hist3d histogram = cquantize->histogram;
  173179. histptr histp;
  173180. int c0,c1,c2;
  173181. int c0min,c0max,c1min,c1max,c2min,c2max;
  173182. long count;
  173183. long total = 0;
  173184. long c0total = 0;
  173185. long c1total = 0;
  173186. long c2total = 0;
  173187. c0min = boxp->c0min; c0max = boxp->c0max;
  173188. c1min = boxp->c1min; c1max = boxp->c1max;
  173189. c2min = boxp->c2min; c2max = boxp->c2max;
  173190. for (c0 = c0min; c0 <= c0max; c0++)
  173191. for (c1 = c1min; c1 <= c1max; c1++) {
  173192. histp = & histogram[c0][c1][c2min];
  173193. for (c2 = c2min; c2 <= c2max; c2++) {
  173194. if ((count = *histp++) != 0) {
  173195. total += count;
  173196. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  173197. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  173198. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  173199. }
  173200. }
  173201. }
  173202. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  173203. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  173204. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  173205. }
  173206. LOCAL(void)
  173207. select_colors (j_decompress_ptr cinfo, int desired_colors)
  173208. /* Master routine for color selection */
  173209. {
  173210. boxptr boxlist;
  173211. int numboxes;
  173212. int i;
  173213. /* Allocate workspace for box list */
  173214. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  173215. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  173216. /* Initialize one box containing whole space */
  173217. numboxes = 1;
  173218. boxlist[0].c0min = 0;
  173219. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  173220. boxlist[0].c1min = 0;
  173221. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  173222. boxlist[0].c2min = 0;
  173223. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  173224. /* Shrink it to actually-used volume and set its statistics */
  173225. update_box(cinfo, & boxlist[0]);
  173226. /* Perform median-cut to produce final box list */
  173227. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  173228. /* Compute the representative color for each box, fill colormap */
  173229. for (i = 0; i < numboxes; i++)
  173230. compute_color(cinfo, & boxlist[i], i);
  173231. cinfo->actual_number_of_colors = numboxes;
  173232. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  173233. }
  173234. /*
  173235. * These routines are concerned with the time-critical task of mapping input
  173236. * colors to the nearest color in the selected colormap.
  173237. *
  173238. * We re-use the histogram space as an "inverse color map", essentially a
  173239. * cache for the results of nearest-color searches. All colors within a
  173240. * histogram cell will be mapped to the same colormap entry, namely the one
  173241. * closest to the cell's center. This may not be quite the closest entry to
  173242. * the actual input color, but it's almost as good. A zero in the cache
  173243. * indicates we haven't found the nearest color for that cell yet; the array
  173244. * is cleared to zeroes before starting the mapping pass. When we find the
  173245. * nearest color for a cell, its colormap index plus one is recorded in the
  173246. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  173247. * when they need to use an unfilled entry in the cache.
  173248. *
  173249. * Our method of efficiently finding nearest colors is based on the "locally
  173250. * sorted search" idea described by Heckbert and on the incremental distance
  173251. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  173252. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  173253. * the distances from a given colormap entry to each cell of the histogram can
  173254. * be computed quickly using an incremental method: the differences between
  173255. * distances to adjacent cells themselves differ by a constant. This allows a
  173256. * fairly fast implementation of the "brute force" approach of computing the
  173257. * distance from every colormap entry to every histogram cell. Unfortunately,
  173258. * it needs a work array to hold the best-distance-so-far for each histogram
  173259. * cell (because the inner loop has to be over cells, not colormap entries).
  173260. * The work array elements have to be INT32s, so the work array would need
  173261. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  173262. *
  173263. * To get around these problems, we apply Thomas' method to compute the
  173264. * nearest colors for only the cells within a small subbox of the histogram.
  173265. * The work array need be only as big as the subbox, so the memory usage
  173266. * problem is solved. Furthermore, we need not fill subboxes that are never
  173267. * referenced in pass2; many images use only part of the color gamut, so a
  173268. * fair amount of work is saved. An additional advantage of this
  173269. * approach is that we can apply Heckbert's locality criterion to quickly
  173270. * eliminate colormap entries that are far away from the subbox; typically
  173271. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  173272. * and we need not compute their distances to individual cells in the subbox.
  173273. * The speed of this approach is heavily influenced by the subbox size: too
  173274. * small means too much overhead, too big loses because Heckbert's criterion
  173275. * can't eliminate as many colormap entries. Empirically the best subbox
  173276. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  173277. *
  173278. * Thomas' article also describes a refined method which is asymptotically
  173279. * faster than the brute-force method, but it is also far more complex and
  173280. * cannot efficiently be applied to small subboxes. It is therefore not
  173281. * useful for programs intended to be portable to DOS machines. On machines
  173282. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  173283. * refined method might be faster than the present code --- but then again,
  173284. * it might not be any faster, and it's certainly more complicated.
  173285. */
  173286. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  173287. #define BOX_C0_LOG (HIST_C0_BITS-3)
  173288. #define BOX_C1_LOG (HIST_C1_BITS-3)
  173289. #define BOX_C2_LOG (HIST_C2_BITS-3)
  173290. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  173291. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  173292. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  173293. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  173294. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  173295. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  173296. /*
  173297. * The next three routines implement inverse colormap filling. They could
  173298. * all be folded into one big routine, but splitting them up this way saves
  173299. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  173300. * and may allow some compilers to produce better code by registerizing more
  173301. * inner-loop variables.
  173302. */
  173303. LOCAL(int)
  173304. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173305. JSAMPLE colorlist[])
  173306. /* Locate the colormap entries close enough to an update box to be candidates
  173307. * for the nearest entry to some cell(s) in the update box. The update box
  173308. * is specified by the center coordinates of its first cell. The number of
  173309. * candidate colormap entries is returned, and their colormap indexes are
  173310. * placed in colorlist[].
  173311. * This routine uses Heckbert's "locally sorted search" criterion to select
  173312. * the colors that need further consideration.
  173313. */
  173314. {
  173315. int numcolors = cinfo->actual_number_of_colors;
  173316. int maxc0, maxc1, maxc2;
  173317. int centerc0, centerc1, centerc2;
  173318. int i, x, ncolors;
  173319. INT32 minmaxdist, min_dist, max_dist, tdist;
  173320. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  173321. /* Compute true coordinates of update box's upper corner and center.
  173322. * Actually we compute the coordinates of the center of the upper-corner
  173323. * histogram cell, which are the upper bounds of the volume we care about.
  173324. * Note that since ">>" rounds down, the "center" values may be closer to
  173325. * min than to max; hence comparisons to them must be "<=", not "<".
  173326. */
  173327. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  173328. centerc0 = (minc0 + maxc0) >> 1;
  173329. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  173330. centerc1 = (minc1 + maxc1) >> 1;
  173331. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  173332. centerc2 = (minc2 + maxc2) >> 1;
  173333. /* For each color in colormap, find:
  173334. * 1. its minimum squared-distance to any point in the update box
  173335. * (zero if color is within update box);
  173336. * 2. its maximum squared-distance to any point in the update box.
  173337. * Both of these can be found by considering only the corners of the box.
  173338. * We save the minimum distance for each color in mindist[];
  173339. * only the smallest maximum distance is of interest.
  173340. */
  173341. minmaxdist = 0x7FFFFFFFL;
  173342. for (i = 0; i < numcolors; i++) {
  173343. /* We compute the squared-c0-distance term, then add in the other two. */
  173344. x = GETJSAMPLE(cinfo->colormap[0][i]);
  173345. if (x < minc0) {
  173346. tdist = (x - minc0) * C0_SCALE;
  173347. min_dist = tdist*tdist;
  173348. tdist = (x - maxc0) * C0_SCALE;
  173349. max_dist = tdist*tdist;
  173350. } else if (x > maxc0) {
  173351. tdist = (x - maxc0) * C0_SCALE;
  173352. min_dist = tdist*tdist;
  173353. tdist = (x - minc0) * C0_SCALE;
  173354. max_dist = tdist*tdist;
  173355. } else {
  173356. /* within cell range so no contribution to min_dist */
  173357. min_dist = 0;
  173358. if (x <= centerc0) {
  173359. tdist = (x - maxc0) * C0_SCALE;
  173360. max_dist = tdist*tdist;
  173361. } else {
  173362. tdist = (x - minc0) * C0_SCALE;
  173363. max_dist = tdist*tdist;
  173364. }
  173365. }
  173366. x = GETJSAMPLE(cinfo->colormap[1][i]);
  173367. if (x < minc1) {
  173368. tdist = (x - minc1) * C1_SCALE;
  173369. min_dist += tdist*tdist;
  173370. tdist = (x - maxc1) * C1_SCALE;
  173371. max_dist += tdist*tdist;
  173372. } else if (x > maxc1) {
  173373. tdist = (x - maxc1) * C1_SCALE;
  173374. min_dist += tdist*tdist;
  173375. tdist = (x - minc1) * C1_SCALE;
  173376. max_dist += tdist*tdist;
  173377. } else {
  173378. /* within cell range so no contribution to min_dist */
  173379. if (x <= centerc1) {
  173380. tdist = (x - maxc1) * C1_SCALE;
  173381. max_dist += tdist*tdist;
  173382. } else {
  173383. tdist = (x - minc1) * C1_SCALE;
  173384. max_dist += tdist*tdist;
  173385. }
  173386. }
  173387. x = GETJSAMPLE(cinfo->colormap[2][i]);
  173388. if (x < minc2) {
  173389. tdist = (x - minc2) * C2_SCALE;
  173390. min_dist += tdist*tdist;
  173391. tdist = (x - maxc2) * C2_SCALE;
  173392. max_dist += tdist*tdist;
  173393. } else if (x > maxc2) {
  173394. tdist = (x - maxc2) * C2_SCALE;
  173395. min_dist += tdist*tdist;
  173396. tdist = (x - minc2) * C2_SCALE;
  173397. max_dist += tdist*tdist;
  173398. } else {
  173399. /* within cell range so no contribution to min_dist */
  173400. if (x <= centerc2) {
  173401. tdist = (x - maxc2) * C2_SCALE;
  173402. max_dist += tdist*tdist;
  173403. } else {
  173404. tdist = (x - minc2) * C2_SCALE;
  173405. max_dist += tdist*tdist;
  173406. }
  173407. }
  173408. mindist[i] = min_dist; /* save away the results */
  173409. if (max_dist < minmaxdist)
  173410. minmaxdist = max_dist;
  173411. }
  173412. /* Now we know that no cell in the update box is more than minmaxdist
  173413. * away from some colormap entry. Therefore, only colors that are
  173414. * within minmaxdist of some part of the box need be considered.
  173415. */
  173416. ncolors = 0;
  173417. for (i = 0; i < numcolors; i++) {
  173418. if (mindist[i] <= minmaxdist)
  173419. colorlist[ncolors++] = (JSAMPLE) i;
  173420. }
  173421. return ncolors;
  173422. }
  173423. LOCAL(void)
  173424. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173425. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  173426. /* Find the closest colormap entry for each cell in the update box,
  173427. * given the list of candidate colors prepared by find_nearby_colors.
  173428. * Return the indexes of the closest entries in the bestcolor[] array.
  173429. * This routine uses Thomas' incremental distance calculation method to
  173430. * find the distance from a colormap entry to successive cells in the box.
  173431. */
  173432. {
  173433. int ic0, ic1, ic2;
  173434. int i, icolor;
  173435. register INT32 * bptr; /* pointer into bestdist[] array */
  173436. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  173437. INT32 dist0, dist1; /* initial distance values */
  173438. register INT32 dist2; /* current distance in inner loop */
  173439. INT32 xx0, xx1; /* distance increments */
  173440. register INT32 xx2;
  173441. INT32 inc0, inc1, inc2; /* initial values for increments */
  173442. /* This array holds the distance to the nearest-so-far color for each cell */
  173443. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  173444. /* Initialize best-distance for each cell of the update box */
  173445. bptr = bestdist;
  173446. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  173447. *bptr++ = 0x7FFFFFFFL;
  173448. /* For each color selected by find_nearby_colors,
  173449. * compute its distance to the center of each cell in the box.
  173450. * If that's less than best-so-far, update best distance and color number.
  173451. */
  173452. /* Nominal steps between cell centers ("x" in Thomas article) */
  173453. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  173454. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  173455. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  173456. for (i = 0; i < numcolors; i++) {
  173457. icolor = GETJSAMPLE(colorlist[i]);
  173458. /* Compute (square of) distance from minc0/c1/c2 to this color */
  173459. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  173460. dist0 = inc0*inc0;
  173461. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  173462. dist0 += inc1*inc1;
  173463. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  173464. dist0 += inc2*inc2;
  173465. /* Form the initial difference increments */
  173466. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  173467. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  173468. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  173469. /* Now loop over all cells in box, updating distance per Thomas method */
  173470. bptr = bestdist;
  173471. cptr = bestcolor;
  173472. xx0 = inc0;
  173473. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  173474. dist1 = dist0;
  173475. xx1 = inc1;
  173476. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  173477. dist2 = dist1;
  173478. xx2 = inc2;
  173479. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  173480. if (dist2 < *bptr) {
  173481. *bptr = dist2;
  173482. *cptr = (JSAMPLE) icolor;
  173483. }
  173484. dist2 += xx2;
  173485. xx2 += 2 * STEP_C2 * STEP_C2;
  173486. bptr++;
  173487. cptr++;
  173488. }
  173489. dist1 += xx1;
  173490. xx1 += 2 * STEP_C1 * STEP_C1;
  173491. }
  173492. dist0 += xx0;
  173493. xx0 += 2 * STEP_C0 * STEP_C0;
  173494. }
  173495. }
  173496. }
  173497. LOCAL(void)
  173498. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  173499. /* Fill the inverse-colormap entries in the update box that contains */
  173500. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  173501. /* we can fill as many others as we wish.) */
  173502. {
  173503. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173504. hist3d histogram = cquantize->histogram;
  173505. int minc0, minc1, minc2; /* lower left corner of update box */
  173506. int ic0, ic1, ic2;
  173507. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  173508. register histptr cachep; /* pointer into main cache array */
  173509. /* This array lists the candidate colormap indexes. */
  173510. JSAMPLE colorlist[MAXNUMCOLORS];
  173511. int numcolors; /* number of candidate colors */
  173512. /* This array holds the actually closest colormap index for each cell. */
  173513. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  173514. /* Convert cell coordinates to update box ID */
  173515. c0 >>= BOX_C0_LOG;
  173516. c1 >>= BOX_C1_LOG;
  173517. c2 >>= BOX_C2_LOG;
  173518. /* Compute true coordinates of update box's origin corner.
  173519. * Actually we compute the coordinates of the center of the corner
  173520. * histogram cell, which are the lower bounds of the volume we care about.
  173521. */
  173522. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  173523. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  173524. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  173525. /* Determine which colormap entries are close enough to be candidates
  173526. * for the nearest entry to some cell in the update box.
  173527. */
  173528. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  173529. /* Determine the actually nearest colors. */
  173530. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  173531. bestcolor);
  173532. /* Save the best color numbers (plus 1) in the main cache array */
  173533. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  173534. c1 <<= BOX_C1_LOG;
  173535. c2 <<= BOX_C2_LOG;
  173536. cptr = bestcolor;
  173537. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  173538. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  173539. cachep = & histogram[c0+ic0][c1+ic1][c2];
  173540. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  173541. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  173542. }
  173543. }
  173544. }
  173545. }
  173546. /*
  173547. * Map some rows of pixels to the output colormapped representation.
  173548. */
  173549. METHODDEF(void)
  173550. pass2_no_dither (j_decompress_ptr cinfo,
  173551. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  173552. /* This version performs no dithering */
  173553. {
  173554. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173555. hist3d histogram = cquantize->histogram;
  173556. register JSAMPROW inptr, outptr;
  173557. register histptr cachep;
  173558. register int c0, c1, c2;
  173559. int row;
  173560. JDIMENSION col;
  173561. JDIMENSION width = cinfo->output_width;
  173562. for (row = 0; row < num_rows; row++) {
  173563. inptr = input_buf[row];
  173564. outptr = output_buf[row];
  173565. for (col = width; col > 0; col--) {
  173566. /* get pixel value and index into the cache */
  173567. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  173568. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  173569. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  173570. cachep = & histogram[c0][c1][c2];
  173571. /* If we have not seen this color before, find nearest colormap entry */
  173572. /* and update the cache */
  173573. if (*cachep == 0)
  173574. fill_inverse_cmap(cinfo, c0,c1,c2);
  173575. /* Now emit the colormap index for this cell */
  173576. *outptr++ = (JSAMPLE) (*cachep - 1);
  173577. }
  173578. }
  173579. }
  173580. METHODDEF(void)
  173581. pass2_fs_dither (j_decompress_ptr cinfo,
  173582. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  173583. /* This version performs Floyd-Steinberg dithering */
  173584. {
  173585. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173586. hist3d histogram = cquantize->histogram;
  173587. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  173588. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  173589. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  173590. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  173591. JSAMPROW inptr; /* => current input pixel */
  173592. JSAMPROW outptr; /* => current output pixel */
  173593. histptr cachep;
  173594. int dir; /* +1 or -1 depending on direction */
  173595. int dir3; /* 3*dir, for advancing inptr & errorptr */
  173596. int row;
  173597. JDIMENSION col;
  173598. JDIMENSION width = cinfo->output_width;
  173599. JSAMPLE *range_limit = cinfo->sample_range_limit;
  173600. int *error_limit = cquantize->error_limiter;
  173601. JSAMPROW colormap0 = cinfo->colormap[0];
  173602. JSAMPROW colormap1 = cinfo->colormap[1];
  173603. JSAMPROW colormap2 = cinfo->colormap[2];
  173604. SHIFT_TEMPS
  173605. for (row = 0; row < num_rows; row++) {
  173606. inptr = input_buf[row];
  173607. outptr = output_buf[row];
  173608. if (cquantize->on_odd_row) {
  173609. /* work right to left in this row */
  173610. inptr += (width-1) * 3; /* so point to rightmost pixel */
  173611. outptr += width-1;
  173612. dir = -1;
  173613. dir3 = -3;
  173614. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  173615. cquantize->on_odd_row = FALSE; /* flip for next time */
  173616. } else {
  173617. /* work left to right in this row */
  173618. dir = 1;
  173619. dir3 = 3;
  173620. errorptr = cquantize->fserrors; /* => entry before first real column */
  173621. cquantize->on_odd_row = TRUE; /* flip for next time */
  173622. }
  173623. /* Preset error values: no error propagated to first pixel from left */
  173624. cur0 = cur1 = cur2 = 0;
  173625. /* and no error propagated to row below yet */
  173626. belowerr0 = belowerr1 = belowerr2 = 0;
  173627. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  173628. for (col = width; col > 0; col--) {
  173629. /* curN holds the error propagated from the previous pixel on the
  173630. * current line. Add the error propagated from the previous line
  173631. * to form the complete error correction term for this pixel, and
  173632. * round the error term (which is expressed * 16) to an integer.
  173633. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  173634. * for either sign of the error value.
  173635. * Note: errorptr points to *previous* column's array entry.
  173636. */
  173637. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  173638. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  173639. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  173640. /* Limit the error using transfer function set by init_error_limit.
  173641. * See comments with init_error_limit for rationale.
  173642. */
  173643. cur0 = error_limit[cur0];
  173644. cur1 = error_limit[cur1];
  173645. cur2 = error_limit[cur2];
  173646. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  173647. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  173648. * this sets the required size of the range_limit array.
  173649. */
  173650. cur0 += GETJSAMPLE(inptr[0]);
  173651. cur1 += GETJSAMPLE(inptr[1]);
  173652. cur2 += GETJSAMPLE(inptr[2]);
  173653. cur0 = GETJSAMPLE(range_limit[cur0]);
  173654. cur1 = GETJSAMPLE(range_limit[cur1]);
  173655. cur2 = GETJSAMPLE(range_limit[cur2]);
  173656. /* Index into the cache with adjusted pixel value */
  173657. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  173658. /* If we have not seen this color before, find nearest colormap */
  173659. /* entry and update the cache */
  173660. if (*cachep == 0)
  173661. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  173662. /* Now emit the colormap index for this cell */
  173663. { register int pixcode = *cachep - 1;
  173664. *outptr = (JSAMPLE) pixcode;
  173665. /* Compute representation error for this pixel */
  173666. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  173667. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  173668. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  173669. }
  173670. /* Compute error fractions to be propagated to adjacent pixels.
  173671. * Add these into the running sums, and simultaneously shift the
  173672. * next-line error sums left by 1 column.
  173673. */
  173674. { register LOCFSERROR bnexterr, delta;
  173675. bnexterr = cur0; /* Process component 0 */
  173676. delta = cur0 * 2;
  173677. cur0 += delta; /* form error * 3 */
  173678. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  173679. cur0 += delta; /* form error * 5 */
  173680. bpreverr0 = belowerr0 + cur0;
  173681. belowerr0 = bnexterr;
  173682. cur0 += delta; /* form error * 7 */
  173683. bnexterr = cur1; /* Process component 1 */
  173684. delta = cur1 * 2;
  173685. cur1 += delta; /* form error * 3 */
  173686. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  173687. cur1 += delta; /* form error * 5 */
  173688. bpreverr1 = belowerr1 + cur1;
  173689. belowerr1 = bnexterr;
  173690. cur1 += delta; /* form error * 7 */
  173691. bnexterr = cur2; /* Process component 2 */
  173692. delta = cur2 * 2;
  173693. cur2 += delta; /* form error * 3 */
  173694. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  173695. cur2 += delta; /* form error * 5 */
  173696. bpreverr2 = belowerr2 + cur2;
  173697. belowerr2 = bnexterr;
  173698. cur2 += delta; /* form error * 7 */
  173699. }
  173700. /* At this point curN contains the 7/16 error value to be propagated
  173701. * to the next pixel on the current line, and all the errors for the
  173702. * next line have been shifted over. We are therefore ready to move on.
  173703. */
  173704. inptr += dir3; /* Advance pixel pointers to next column */
  173705. outptr += dir;
  173706. errorptr += dir3; /* advance errorptr to current column */
  173707. }
  173708. /* Post-loop cleanup: we must unload the final error values into the
  173709. * final fserrors[] entry. Note we need not unload belowerrN because
  173710. * it is for the dummy column before or after the actual array.
  173711. */
  173712. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  173713. errorptr[1] = (FSERROR) bpreverr1;
  173714. errorptr[2] = (FSERROR) bpreverr2;
  173715. }
  173716. }
  173717. /*
  173718. * Initialize the error-limiting transfer function (lookup table).
  173719. * The raw F-S error computation can potentially compute error values of up to
  173720. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  173721. * much less, otherwise obviously wrong pixels will be created. (Typical
  173722. * effects include weird fringes at color-area boundaries, isolated bright
  173723. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  173724. * is to ensure that the "corners" of the color cube are allocated as output
  173725. * colors; then repeated errors in the same direction cannot cause cascading
  173726. * error buildup. However, that only prevents the error from getting
  173727. * completely out of hand; Aaron Giles reports that error limiting improves
  173728. * the results even with corner colors allocated.
  173729. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  173730. * well, but the smoother transfer function used below is even better. Thanks
  173731. * to Aaron Giles for this idea.
  173732. */
  173733. LOCAL(void)
  173734. init_error_limit (j_decompress_ptr cinfo)
  173735. /* Allocate and fill in the error_limiter table */
  173736. {
  173737. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173738. int * table;
  173739. int in, out;
  173740. table = (int *) (*cinfo->mem->alloc_small)
  173741. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  173742. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  173743. cquantize->error_limiter = table;
  173744. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  173745. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  173746. out = 0;
  173747. for (in = 0; in < STEPSIZE; in++, out++) {
  173748. table[in] = out; table[-in] = -out;
  173749. }
  173750. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  173751. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  173752. table[in] = out; table[-in] = -out;
  173753. }
  173754. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  173755. for (; in <= MAXJSAMPLE; in++) {
  173756. table[in] = out; table[-in] = -out;
  173757. }
  173758. #undef STEPSIZE
  173759. }
  173760. /*
  173761. * Finish up at the end of each pass.
  173762. */
  173763. METHODDEF(void)
  173764. finish_pass1 (j_decompress_ptr cinfo)
  173765. {
  173766. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173767. /* Select the representative colors and fill in cinfo->colormap */
  173768. cinfo->colormap = cquantize->sv_colormap;
  173769. select_colors(cinfo, cquantize->desired);
  173770. /* Force next pass to zero the color index table */
  173771. cquantize->needs_zeroed = TRUE;
  173772. }
  173773. METHODDEF(void)
  173774. finish_pass2 (j_decompress_ptr cinfo)
  173775. {
  173776. /* no work */
  173777. }
  173778. /*
  173779. * Initialize for each processing pass.
  173780. */
  173781. METHODDEF(void)
  173782. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  173783. {
  173784. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173785. hist3d histogram = cquantize->histogram;
  173786. int i;
  173787. /* Only F-S dithering or no dithering is supported. */
  173788. /* If user asks for ordered dither, give him F-S. */
  173789. if (cinfo->dither_mode != JDITHER_NONE)
  173790. cinfo->dither_mode = JDITHER_FS;
  173791. if (is_pre_scan) {
  173792. /* Set up method pointers */
  173793. cquantize->pub.color_quantize = prescan_quantize;
  173794. cquantize->pub.finish_pass = finish_pass1;
  173795. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  173796. } else {
  173797. /* Set up method pointers */
  173798. if (cinfo->dither_mode == JDITHER_FS)
  173799. cquantize->pub.color_quantize = pass2_fs_dither;
  173800. else
  173801. cquantize->pub.color_quantize = pass2_no_dither;
  173802. cquantize->pub.finish_pass = finish_pass2;
  173803. /* Make sure color count is acceptable */
  173804. i = cinfo->actual_number_of_colors;
  173805. if (i < 1)
  173806. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  173807. if (i > MAXNUMCOLORS)
  173808. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  173809. if (cinfo->dither_mode == JDITHER_FS) {
  173810. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  173811. (3 * SIZEOF(FSERROR)));
  173812. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  173813. if (cquantize->fserrors == NULL)
  173814. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  173815. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  173816. /* Initialize the propagated errors to zero. */
  173817. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  173818. /* Make the error-limit table if we didn't already. */
  173819. if (cquantize->error_limiter == NULL)
  173820. init_error_limit(cinfo);
  173821. cquantize->on_odd_row = FALSE;
  173822. }
  173823. }
  173824. /* Zero the histogram or inverse color map, if necessary */
  173825. if (cquantize->needs_zeroed) {
  173826. for (i = 0; i < HIST_C0_ELEMS; i++) {
  173827. jzero_far((void FAR *) histogram[i],
  173828. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  173829. }
  173830. cquantize->needs_zeroed = FALSE;
  173831. }
  173832. }
  173833. /*
  173834. * Switch to a new external colormap between output passes.
  173835. */
  173836. METHODDEF(void)
  173837. new_color_map_2_quant (j_decompress_ptr cinfo)
  173838. {
  173839. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173840. /* Reset the inverse color map */
  173841. cquantize->needs_zeroed = TRUE;
  173842. }
  173843. /*
  173844. * Module initialization routine for 2-pass color quantization.
  173845. */
  173846. GLOBAL(void)
  173847. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  173848. {
  173849. my_cquantize_ptr2 cquantize;
  173850. int i;
  173851. cquantize = (my_cquantize_ptr2)
  173852. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173853. SIZEOF(my_cquantizer2));
  173854. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  173855. cquantize->pub.start_pass = start_pass_2_quant;
  173856. cquantize->pub.new_color_map = new_color_map_2_quant;
  173857. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  173858. cquantize->error_limiter = NULL;
  173859. /* Make sure jdmaster didn't give me a case I can't handle */
  173860. if (cinfo->out_color_components != 3)
  173861. ERREXIT(cinfo, JERR_NOTIMPL);
  173862. /* Allocate the histogram/inverse colormap storage */
  173863. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  173864. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  173865. for (i = 0; i < HIST_C0_ELEMS; i++) {
  173866. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  173867. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173868. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  173869. }
  173870. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  173871. /* Allocate storage for the completed colormap, if required.
  173872. * We do this now since it is FAR storage and may affect
  173873. * the memory manager's space calculations.
  173874. */
  173875. if (cinfo->enable_2pass_quant) {
  173876. /* Make sure color count is acceptable */
  173877. int desired = cinfo->desired_number_of_colors;
  173878. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  173879. if (desired < 8)
  173880. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  173881. /* Make sure colormap indexes can be represented by JSAMPLEs */
  173882. if (desired > MAXNUMCOLORS)
  173883. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  173884. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  173885. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  173886. cquantize->desired = desired;
  173887. } else
  173888. cquantize->sv_colormap = NULL;
  173889. /* Only F-S dithering or no dithering is supported. */
  173890. /* If user asks for ordered dither, give him F-S. */
  173891. if (cinfo->dither_mode != JDITHER_NONE)
  173892. cinfo->dither_mode = JDITHER_FS;
  173893. /* Allocate Floyd-Steinberg workspace if necessary.
  173894. * This isn't really needed until pass 2, but again it is FAR storage.
  173895. * Although we will cope with a later change in dither_mode,
  173896. * we do not promise to honor max_memory_to_use if dither_mode changes.
  173897. */
  173898. if (cinfo->dither_mode == JDITHER_FS) {
  173899. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  173900. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173901. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  173902. /* Might as well create the error-limiting table too. */
  173903. init_error_limit(cinfo);
  173904. }
  173905. }
  173906. #endif /* QUANT_2PASS_SUPPORTED */
  173907. /********* End of inlined file: jquant2.c *********/
  173908. /********* Start of inlined file: jutils.c *********/
  173909. #define JPEG_INTERNALS
  173910. /*
  173911. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  173912. * of a DCT block read in natural order (left to right, top to bottom).
  173913. */
  173914. #if 0 /* This table is not actually needed in v6a */
  173915. const int jpeg_zigzag_order[DCTSIZE2] = {
  173916. 0, 1, 5, 6, 14, 15, 27, 28,
  173917. 2, 4, 7, 13, 16, 26, 29, 42,
  173918. 3, 8, 12, 17, 25, 30, 41, 43,
  173919. 9, 11, 18, 24, 31, 40, 44, 53,
  173920. 10, 19, 23, 32, 39, 45, 52, 54,
  173921. 20, 22, 33, 38, 46, 51, 55, 60,
  173922. 21, 34, 37, 47, 50, 56, 59, 61,
  173923. 35, 36, 48, 49, 57, 58, 62, 63
  173924. };
  173925. #endif
  173926. /*
  173927. * jpeg_natural_order[i] is the natural-order position of the i'th element
  173928. * of zigzag order.
  173929. *
  173930. * When reading corrupted data, the Huffman decoders could attempt
  173931. * to reference an entry beyond the end of this array (if the decoded
  173932. * zero run length reaches past the end of the block). To prevent
  173933. * wild stores without adding an inner-loop test, we put some extra
  173934. * "63"s after the real entries. This will cause the extra coefficient
  173935. * to be stored in location 63 of the block, not somewhere random.
  173936. * The worst case would be a run-length of 15, which means we need 16
  173937. * fake entries.
  173938. */
  173939. const int jpeg_natural_order[DCTSIZE2+16] = {
  173940. 0, 1, 8, 16, 9, 2, 3, 10,
  173941. 17, 24, 32, 25, 18, 11, 4, 5,
  173942. 12, 19, 26, 33, 40, 48, 41, 34,
  173943. 27, 20, 13, 6, 7, 14, 21, 28,
  173944. 35, 42, 49, 56, 57, 50, 43, 36,
  173945. 29, 22, 15, 23, 30, 37, 44, 51,
  173946. 58, 59, 52, 45, 38, 31, 39, 46,
  173947. 53, 60, 61, 54, 47, 55, 62, 63,
  173948. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  173949. 63, 63, 63, 63, 63, 63, 63, 63
  173950. };
  173951. /*
  173952. * Arithmetic utilities
  173953. */
  173954. GLOBAL(long)
  173955. jdiv_round_up (long a, long b)
  173956. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  173957. /* Assumes a >= 0, b > 0 */
  173958. {
  173959. return (a + b - 1L) / b;
  173960. }
  173961. GLOBAL(long)
  173962. jround_up (long a, long b)
  173963. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  173964. /* Assumes a >= 0, b > 0 */
  173965. {
  173966. a += b - 1L;
  173967. return a - (a % b);
  173968. }
  173969. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  173970. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  173971. * are FAR and we're assuming a small-pointer memory model. However, some
  173972. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  173973. * in the small-model libraries. These will be used if USE_FMEM is defined.
  173974. * Otherwise, the routines below do it the hard way. (The performance cost
  173975. * is not all that great, because these routines aren't very heavily used.)
  173976. */
  173977. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  173978. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  173979. #define FMEMZERO(target,size) MEMZERO(target,size)
  173980. #else /* 80x86 case, define if we can */
  173981. #ifdef USE_FMEM
  173982. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  173983. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  173984. #endif
  173985. #endif
  173986. GLOBAL(void)
  173987. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  173988. JSAMPARRAY output_array, int dest_row,
  173989. int num_rows, JDIMENSION num_cols)
  173990. /* Copy some rows of samples from one place to another.
  173991. * num_rows rows are copied from input_array[source_row++]
  173992. * to output_array[dest_row++]; these areas may overlap for duplication.
  173993. * The source and destination arrays must be at least as wide as num_cols.
  173994. */
  173995. {
  173996. register JSAMPROW inptr, outptr;
  173997. #ifdef FMEMCOPY
  173998. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  173999. #else
  174000. register JDIMENSION count;
  174001. #endif
  174002. register int row;
  174003. input_array += source_row;
  174004. output_array += dest_row;
  174005. for (row = num_rows; row > 0; row--) {
  174006. inptr = *input_array++;
  174007. outptr = *output_array++;
  174008. #ifdef FMEMCOPY
  174009. FMEMCOPY(outptr, inptr, count);
  174010. #else
  174011. for (count = num_cols; count > 0; count--)
  174012. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  174013. #endif
  174014. }
  174015. }
  174016. GLOBAL(void)
  174017. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  174018. JDIMENSION num_blocks)
  174019. /* Copy a row of coefficient blocks from one place to another. */
  174020. {
  174021. #ifdef FMEMCOPY
  174022. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  174023. #else
  174024. register JCOEFPTR inptr, outptr;
  174025. register long count;
  174026. inptr = (JCOEFPTR) input_row;
  174027. outptr = (JCOEFPTR) output_row;
  174028. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  174029. *outptr++ = *inptr++;
  174030. }
  174031. #endif
  174032. }
  174033. GLOBAL(void)
  174034. jzero_far (void FAR * target, size_t bytestozero)
  174035. /* Zero out a chunk of FAR memory. */
  174036. /* This might be sample-array data, block-array data, or alloc_large data. */
  174037. {
  174038. #ifdef FMEMZERO
  174039. FMEMZERO(target, bytestozero);
  174040. #else
  174041. register char FAR * ptr = (char FAR *) target;
  174042. register size_t count;
  174043. for (count = bytestozero; count > 0; count--) {
  174044. *ptr++ = 0;
  174045. }
  174046. #endif
  174047. }
  174048. /********* End of inlined file: jutils.c *********/
  174049. /********* Start of inlined file: transupp.c *********/
  174050. /* Although this file really shouldn't have access to the library internals,
  174051. * it's helpful to let it call jround_up() and jcopy_block_row().
  174052. */
  174053. #define JPEG_INTERNALS
  174054. /********* Start of inlined file: transupp.h *********/
  174055. /* If you happen not to want the image transform support, disable it here */
  174056. #ifndef TRANSFORMS_SUPPORTED
  174057. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  174058. #endif
  174059. /* Short forms of external names for systems with brain-damaged linkers. */
  174060. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174061. #define jtransform_request_workspace jTrRequest
  174062. #define jtransform_adjust_parameters jTrAdjust
  174063. #define jtransform_execute_transformation jTrExec
  174064. #define jcopy_markers_setup jCMrkSetup
  174065. #define jcopy_markers_execute jCMrkExec
  174066. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174067. /*
  174068. * Codes for supported types of image transformations.
  174069. */
  174070. typedef enum {
  174071. JXFORM_NONE, /* no transformation */
  174072. JXFORM_FLIP_H, /* horizontal flip */
  174073. JXFORM_FLIP_V, /* vertical flip */
  174074. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  174075. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  174076. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  174077. JXFORM_ROT_180, /* 180-degree rotation */
  174078. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  174079. } JXFORM_CODE;
  174080. /*
  174081. * Although rotating and flipping data expressed as DCT coefficients is not
  174082. * hard, there is an asymmetry in the JPEG format specification for images
  174083. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  174084. * image edges are padded out to the next iMCU boundary with junk data; but
  174085. * no padding is possible at the top and left edges. If we were to flip
  174086. * the whole image including the pad data, then pad garbage would become
  174087. * visible at the top and/or left, and real pixels would disappear into the
  174088. * pad margins --- perhaps permanently, since encoders & decoders may not
  174089. * bother to preserve DCT blocks that appear to be completely outside the
  174090. * nominal image area. So, we have to exclude any partial iMCUs from the
  174091. * basic transformation.
  174092. *
  174093. * Transpose is the only transformation that can handle partial iMCUs at the
  174094. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  174095. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  174096. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  174097. * The other transforms are defined as combinations of these basic transforms
  174098. * and process edge blocks in a way that preserves the equivalence.
  174099. *
  174100. * The "trim" option causes untransformable partial iMCUs to be dropped;
  174101. * this is not strictly lossless, but it usually gives the best-looking
  174102. * result for odd-size images. Note that when this option is active,
  174103. * the expected mathematical equivalences between the transforms may not hold.
  174104. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  174105. * followed by -rot 180 -trim trims both edges.)
  174106. *
  174107. * We also offer a "force to grayscale" option, which simply discards the
  174108. * chrominance channels of a YCbCr image. This is lossless in the sense that
  174109. * the luminance channel is preserved exactly. It's not the same kind of
  174110. * thing as the rotate/flip transformations, but it's convenient to handle it
  174111. * as part of this package, mainly because the transformation routines have to
  174112. * be aware of the option to know how many components to work on.
  174113. */
  174114. typedef struct {
  174115. /* Options: set by caller */
  174116. JXFORM_CODE transform; /* image transform operator */
  174117. boolean trim; /* if TRUE, trim partial MCUs as needed */
  174118. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  174119. /* Internal workspace: caller should not touch these */
  174120. int num_components; /* # of components in workspace */
  174121. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  174122. } jpeg_transform_info;
  174123. #if TRANSFORMS_SUPPORTED
  174124. /* Request any required workspace */
  174125. EXTERN(void) jtransform_request_workspace
  174126. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  174127. /* Adjust output image parameters */
  174128. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  174129. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174130. jvirt_barray_ptr *src_coef_arrays,
  174131. jpeg_transform_info *info));
  174132. /* Execute the actual transformation, if any */
  174133. EXTERN(void) jtransform_execute_transformation
  174134. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174135. jvirt_barray_ptr *src_coef_arrays,
  174136. jpeg_transform_info *info));
  174137. #endif /* TRANSFORMS_SUPPORTED */
  174138. /*
  174139. * Support for copying optional markers from source to destination file.
  174140. */
  174141. typedef enum {
  174142. JCOPYOPT_NONE, /* copy no optional markers */
  174143. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  174144. JCOPYOPT_ALL /* copy all optional markers */
  174145. } JCOPY_OPTION;
  174146. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  174147. /* Setup decompression object to save desired markers in memory */
  174148. EXTERN(void) jcopy_markers_setup
  174149. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  174150. /* Copy markers saved in the given source object to the destination object */
  174151. EXTERN(void) jcopy_markers_execute
  174152. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174153. JCOPY_OPTION option));
  174154. /********* End of inlined file: transupp.h *********/
  174155. /* My own external interface */
  174156. #if TRANSFORMS_SUPPORTED
  174157. /*
  174158. * Lossless image transformation routines. These routines work on DCT
  174159. * coefficient arrays and thus do not require any lossy decompression
  174160. * or recompression of the image.
  174161. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  174162. *
  174163. * Horizontal flipping is done in-place, using a single top-to-bottom
  174164. * pass through the virtual source array. It will thus be much the
  174165. * fastest option for images larger than main memory.
  174166. *
  174167. * The other routines require a set of destination virtual arrays, so they
  174168. * need twice as much memory as jpegtran normally does. The destination
  174169. * arrays are always written in normal scan order (top to bottom) because
  174170. * the virtual array manager expects this. The source arrays will be scanned
  174171. * in the corresponding order, which means multiple passes through the source
  174172. * arrays for most of the transforms. That could result in much thrashing
  174173. * if the image is larger than main memory.
  174174. *
  174175. * Some notes about the operating environment of the individual transform
  174176. * routines:
  174177. * 1. Both the source and destination virtual arrays are allocated from the
  174178. * source JPEG object, and therefore should be manipulated by calling the
  174179. * source's memory manager.
  174180. * 2. The destination's component count should be used. It may be smaller
  174181. * than the source's when forcing to grayscale.
  174182. * 3. Likewise the destination's sampling factors should be used. When
  174183. * forcing to grayscale the destination's sampling factors will be all 1,
  174184. * and we may as well take that as the effective iMCU size.
  174185. * 4. When "trim" is in effect, the destination's dimensions will be the
  174186. * trimmed values but the source's will be untrimmed.
  174187. * 5. All the routines assume that the source and destination buffers are
  174188. * padded out to a full iMCU boundary. This is true, although for the
  174189. * source buffer it is an undocumented property of jdcoefct.c.
  174190. * Notes 2,3,4 boil down to this: generally we should use the destination's
  174191. * dimensions and ignore the source's.
  174192. */
  174193. LOCAL(void)
  174194. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174195. jvirt_barray_ptr *src_coef_arrays)
  174196. /* Horizontal flip; done in-place, so no separate dest array is required */
  174197. {
  174198. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  174199. int ci, k, offset_y;
  174200. JBLOCKARRAY buffer;
  174201. JCOEFPTR ptr1, ptr2;
  174202. JCOEF temp1, temp2;
  174203. jpeg_component_info *compptr;
  174204. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  174205. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  174206. * mirroring by changing the signs of odd-numbered columns.
  174207. * Partial iMCUs at the right edge are left untouched.
  174208. */
  174209. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174210. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174211. compptr = dstinfo->comp_info + ci;
  174212. comp_width = MCU_cols * compptr->h_samp_factor;
  174213. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  174214. blk_y += compptr->v_samp_factor) {
  174215. buffer = (*srcinfo->mem->access_virt_barray)
  174216. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  174217. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174218. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174219. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  174220. ptr1 = buffer[offset_y][blk_x];
  174221. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  174222. /* this unrolled loop doesn't need to know which row it's on... */
  174223. for (k = 0; k < DCTSIZE2; k += 2) {
  174224. temp1 = *ptr1; /* swap even column */
  174225. temp2 = *ptr2;
  174226. *ptr1++ = temp2;
  174227. *ptr2++ = temp1;
  174228. temp1 = *ptr1; /* swap odd column with sign change */
  174229. temp2 = *ptr2;
  174230. *ptr1++ = -temp2;
  174231. *ptr2++ = -temp1;
  174232. }
  174233. }
  174234. }
  174235. }
  174236. }
  174237. }
  174238. LOCAL(void)
  174239. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174240. jvirt_barray_ptr *src_coef_arrays,
  174241. jvirt_barray_ptr *dst_coef_arrays)
  174242. /* Vertical flip */
  174243. {
  174244. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174245. int ci, i, j, offset_y;
  174246. JBLOCKARRAY src_buffer, dst_buffer;
  174247. JBLOCKROW src_row_ptr, dst_row_ptr;
  174248. JCOEFPTR src_ptr, dst_ptr;
  174249. jpeg_component_info *compptr;
  174250. /* We output into a separate array because we can't touch different
  174251. * rows of the source virtual array simultaneously. Otherwise, this
  174252. * is a pretty straightforward analog of horizontal flip.
  174253. * Within a DCT block, vertical mirroring is done by changing the signs
  174254. * of odd-numbered rows.
  174255. * Partial iMCUs at the bottom edge are copied verbatim.
  174256. */
  174257. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174258. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174259. compptr = dstinfo->comp_info + ci;
  174260. comp_height = MCU_rows * compptr->v_samp_factor;
  174261. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174262. dst_blk_y += compptr->v_samp_factor) {
  174263. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174264. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174265. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174266. if (dst_blk_y < comp_height) {
  174267. /* Row is within the mirrorable area. */
  174268. src_buffer = (*srcinfo->mem->access_virt_barray)
  174269. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174270. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174271. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174272. } else {
  174273. /* Bottom-edge blocks will be copied verbatim. */
  174274. src_buffer = (*srcinfo->mem->access_virt_barray)
  174275. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  174276. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174277. }
  174278. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174279. if (dst_blk_y < comp_height) {
  174280. /* Row is within the mirrorable area. */
  174281. dst_row_ptr = dst_buffer[offset_y];
  174282. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  174283. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174284. dst_blk_x++) {
  174285. dst_ptr = dst_row_ptr[dst_blk_x];
  174286. src_ptr = src_row_ptr[dst_blk_x];
  174287. for (i = 0; i < DCTSIZE; i += 2) {
  174288. /* copy even row */
  174289. for (j = 0; j < DCTSIZE; j++)
  174290. *dst_ptr++ = *src_ptr++;
  174291. /* copy odd row with sign change */
  174292. for (j = 0; j < DCTSIZE; j++)
  174293. *dst_ptr++ = - *src_ptr++;
  174294. }
  174295. }
  174296. } else {
  174297. /* Just copy row verbatim. */
  174298. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  174299. compptr->width_in_blocks);
  174300. }
  174301. }
  174302. }
  174303. }
  174304. }
  174305. LOCAL(void)
  174306. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174307. jvirt_barray_ptr *src_coef_arrays,
  174308. jvirt_barray_ptr *dst_coef_arrays)
  174309. /* Transpose source into destination */
  174310. {
  174311. JDIMENSION dst_blk_x, dst_blk_y;
  174312. int ci, i, j, offset_x, offset_y;
  174313. JBLOCKARRAY src_buffer, dst_buffer;
  174314. JCOEFPTR src_ptr, dst_ptr;
  174315. jpeg_component_info *compptr;
  174316. /* Transposing pixels within a block just requires transposing the
  174317. * DCT coefficients.
  174318. * Partial iMCUs at the edges require no special treatment; we simply
  174319. * process all the available DCT blocks for every component.
  174320. */
  174321. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174322. compptr = dstinfo->comp_info + ci;
  174323. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174324. dst_blk_y += compptr->v_samp_factor) {
  174325. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174326. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174327. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174328. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174329. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174330. dst_blk_x += compptr->h_samp_factor) {
  174331. src_buffer = (*srcinfo->mem->access_virt_barray)
  174332. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174333. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174334. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174335. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174336. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174337. for (i = 0; i < DCTSIZE; i++)
  174338. for (j = 0; j < DCTSIZE; j++)
  174339. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174340. }
  174341. }
  174342. }
  174343. }
  174344. }
  174345. }
  174346. LOCAL(void)
  174347. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174348. jvirt_barray_ptr *src_coef_arrays,
  174349. jvirt_barray_ptr *dst_coef_arrays)
  174350. /* 90 degree rotation is equivalent to
  174351. * 1. Transposing the image;
  174352. * 2. Horizontal mirroring.
  174353. * These two steps are merged into a single processing routine.
  174354. */
  174355. {
  174356. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  174357. int ci, i, j, offset_x, offset_y;
  174358. JBLOCKARRAY src_buffer, dst_buffer;
  174359. JCOEFPTR src_ptr, dst_ptr;
  174360. jpeg_component_info *compptr;
  174361. /* Because of the horizontal mirror step, we can't process partial iMCUs
  174362. * at the (output) right edge properly. They just get transposed and
  174363. * not mirrored.
  174364. */
  174365. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174366. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174367. compptr = dstinfo->comp_info + ci;
  174368. comp_width = MCU_cols * compptr->h_samp_factor;
  174369. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174370. dst_blk_y += compptr->v_samp_factor) {
  174371. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174372. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174373. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174374. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174375. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174376. dst_blk_x += compptr->h_samp_factor) {
  174377. src_buffer = (*srcinfo->mem->access_virt_barray)
  174378. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174379. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174380. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174381. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174382. if (dst_blk_x < comp_width) {
  174383. /* Block is within the mirrorable area. */
  174384. dst_ptr = dst_buffer[offset_y]
  174385. [comp_width - dst_blk_x - offset_x - 1];
  174386. for (i = 0; i < DCTSIZE; i++) {
  174387. for (j = 0; j < DCTSIZE; j++)
  174388. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174389. i++;
  174390. for (j = 0; j < DCTSIZE; j++)
  174391. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174392. }
  174393. } else {
  174394. /* Edge blocks are transposed but not mirrored. */
  174395. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174396. for (i = 0; i < DCTSIZE; i++)
  174397. for (j = 0; j < DCTSIZE; j++)
  174398. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174399. }
  174400. }
  174401. }
  174402. }
  174403. }
  174404. }
  174405. }
  174406. LOCAL(void)
  174407. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174408. jvirt_barray_ptr *src_coef_arrays,
  174409. jvirt_barray_ptr *dst_coef_arrays)
  174410. /* 270 degree rotation is equivalent to
  174411. * 1. Horizontal mirroring;
  174412. * 2. Transposing the image.
  174413. * These two steps are merged into a single processing routine.
  174414. */
  174415. {
  174416. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174417. int ci, i, j, offset_x, offset_y;
  174418. JBLOCKARRAY src_buffer, dst_buffer;
  174419. JCOEFPTR src_ptr, dst_ptr;
  174420. jpeg_component_info *compptr;
  174421. /* Because of the horizontal mirror step, we can't process partial iMCUs
  174422. * at the (output) bottom edge properly. They just get transposed and
  174423. * not mirrored.
  174424. */
  174425. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174426. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174427. compptr = dstinfo->comp_info + ci;
  174428. comp_height = MCU_rows * compptr->v_samp_factor;
  174429. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174430. dst_blk_y += compptr->v_samp_factor) {
  174431. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174432. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174433. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174434. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174435. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174436. dst_blk_x += compptr->h_samp_factor) {
  174437. src_buffer = (*srcinfo->mem->access_virt_barray)
  174438. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174439. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174440. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174441. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174442. if (dst_blk_y < comp_height) {
  174443. /* Block is within the mirrorable area. */
  174444. src_ptr = src_buffer[offset_x]
  174445. [comp_height - dst_blk_y - offset_y - 1];
  174446. for (i = 0; i < DCTSIZE; i++) {
  174447. for (j = 0; j < DCTSIZE; j++) {
  174448. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174449. j++;
  174450. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174451. }
  174452. }
  174453. } else {
  174454. /* Edge blocks are transposed but not mirrored. */
  174455. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174456. for (i = 0; i < DCTSIZE; i++)
  174457. for (j = 0; j < DCTSIZE; j++)
  174458. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174459. }
  174460. }
  174461. }
  174462. }
  174463. }
  174464. }
  174465. }
  174466. LOCAL(void)
  174467. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174468. jvirt_barray_ptr *src_coef_arrays,
  174469. jvirt_barray_ptr *dst_coef_arrays)
  174470. /* 180 degree rotation is equivalent to
  174471. * 1. Vertical mirroring;
  174472. * 2. Horizontal mirroring.
  174473. * These two steps are merged into a single processing routine.
  174474. */
  174475. {
  174476. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  174477. int ci, i, j, offset_y;
  174478. JBLOCKARRAY src_buffer, dst_buffer;
  174479. JBLOCKROW src_row_ptr, dst_row_ptr;
  174480. JCOEFPTR src_ptr, dst_ptr;
  174481. jpeg_component_info *compptr;
  174482. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174483. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174484. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174485. compptr = dstinfo->comp_info + ci;
  174486. comp_width = MCU_cols * compptr->h_samp_factor;
  174487. comp_height = MCU_rows * compptr->v_samp_factor;
  174488. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174489. dst_blk_y += compptr->v_samp_factor) {
  174490. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174491. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174492. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174493. if (dst_blk_y < comp_height) {
  174494. /* Row is within the vertically mirrorable area. */
  174495. src_buffer = (*srcinfo->mem->access_virt_barray)
  174496. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174497. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174498. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174499. } else {
  174500. /* Bottom-edge rows are only mirrored horizontally. */
  174501. src_buffer = (*srcinfo->mem->access_virt_barray)
  174502. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  174503. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174504. }
  174505. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174506. if (dst_blk_y < comp_height) {
  174507. /* Row is within the mirrorable area. */
  174508. dst_row_ptr = dst_buffer[offset_y];
  174509. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  174510. /* Process the blocks that can be mirrored both ways. */
  174511. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  174512. dst_ptr = dst_row_ptr[dst_blk_x];
  174513. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  174514. for (i = 0; i < DCTSIZE; i += 2) {
  174515. /* For even row, negate every odd column. */
  174516. for (j = 0; j < DCTSIZE; j += 2) {
  174517. *dst_ptr++ = *src_ptr++;
  174518. *dst_ptr++ = - *src_ptr++;
  174519. }
  174520. /* For odd row, negate every even column. */
  174521. for (j = 0; j < DCTSIZE; j += 2) {
  174522. *dst_ptr++ = - *src_ptr++;
  174523. *dst_ptr++ = *src_ptr++;
  174524. }
  174525. }
  174526. }
  174527. /* Any remaining right-edge blocks are only mirrored vertically. */
  174528. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  174529. dst_ptr = dst_row_ptr[dst_blk_x];
  174530. src_ptr = src_row_ptr[dst_blk_x];
  174531. for (i = 0; i < DCTSIZE; i += 2) {
  174532. for (j = 0; j < DCTSIZE; j++)
  174533. *dst_ptr++ = *src_ptr++;
  174534. for (j = 0; j < DCTSIZE; j++)
  174535. *dst_ptr++ = - *src_ptr++;
  174536. }
  174537. }
  174538. } else {
  174539. /* Remaining rows are just mirrored horizontally. */
  174540. dst_row_ptr = dst_buffer[offset_y];
  174541. src_row_ptr = src_buffer[offset_y];
  174542. /* Process the blocks that can be mirrored. */
  174543. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  174544. dst_ptr = dst_row_ptr[dst_blk_x];
  174545. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  174546. for (i = 0; i < DCTSIZE2; i += 2) {
  174547. *dst_ptr++ = *src_ptr++;
  174548. *dst_ptr++ = - *src_ptr++;
  174549. }
  174550. }
  174551. /* Any remaining right-edge blocks are only copied. */
  174552. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  174553. dst_ptr = dst_row_ptr[dst_blk_x];
  174554. src_ptr = src_row_ptr[dst_blk_x];
  174555. for (i = 0; i < DCTSIZE2; i++)
  174556. *dst_ptr++ = *src_ptr++;
  174557. }
  174558. }
  174559. }
  174560. }
  174561. }
  174562. }
  174563. LOCAL(void)
  174564. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174565. jvirt_barray_ptr *src_coef_arrays,
  174566. jvirt_barray_ptr *dst_coef_arrays)
  174567. /* Transverse transpose is equivalent to
  174568. * 1. 180 degree rotation;
  174569. * 2. Transposition;
  174570. * or
  174571. * 1. Horizontal mirroring;
  174572. * 2. Transposition;
  174573. * 3. Horizontal mirroring.
  174574. * These steps are merged into a single processing routine.
  174575. */
  174576. {
  174577. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  174578. int ci, i, j, offset_x, offset_y;
  174579. JBLOCKARRAY src_buffer, dst_buffer;
  174580. JCOEFPTR src_ptr, dst_ptr;
  174581. jpeg_component_info *compptr;
  174582. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174583. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174584. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174585. compptr = dstinfo->comp_info + ci;
  174586. comp_width = MCU_cols * compptr->h_samp_factor;
  174587. comp_height = MCU_rows * compptr->v_samp_factor;
  174588. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174589. dst_blk_y += compptr->v_samp_factor) {
  174590. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174591. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174592. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174593. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174594. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174595. dst_blk_x += compptr->h_samp_factor) {
  174596. src_buffer = (*srcinfo->mem->access_virt_barray)
  174597. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174598. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174599. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174600. if (dst_blk_y < comp_height) {
  174601. src_ptr = src_buffer[offset_x]
  174602. [comp_height - dst_blk_y - offset_y - 1];
  174603. if (dst_blk_x < comp_width) {
  174604. /* Block is within the mirrorable area. */
  174605. dst_ptr = dst_buffer[offset_y]
  174606. [comp_width - dst_blk_x - offset_x - 1];
  174607. for (i = 0; i < DCTSIZE; i++) {
  174608. for (j = 0; j < DCTSIZE; j++) {
  174609. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174610. j++;
  174611. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174612. }
  174613. i++;
  174614. for (j = 0; j < DCTSIZE; j++) {
  174615. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174616. j++;
  174617. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174618. }
  174619. }
  174620. } else {
  174621. /* Right-edge blocks are mirrored in y only */
  174622. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174623. for (i = 0; i < DCTSIZE; i++) {
  174624. for (j = 0; j < DCTSIZE; j++) {
  174625. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174626. j++;
  174627. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174628. }
  174629. }
  174630. }
  174631. } else {
  174632. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174633. if (dst_blk_x < comp_width) {
  174634. /* Bottom-edge blocks are mirrored in x only */
  174635. dst_ptr = dst_buffer[offset_y]
  174636. [comp_width - dst_blk_x - offset_x - 1];
  174637. for (i = 0; i < DCTSIZE; i++) {
  174638. for (j = 0; j < DCTSIZE; j++)
  174639. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174640. i++;
  174641. for (j = 0; j < DCTSIZE; j++)
  174642. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174643. }
  174644. } else {
  174645. /* At lower right corner, just transpose, no mirroring */
  174646. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174647. for (i = 0; i < DCTSIZE; i++)
  174648. for (j = 0; j < DCTSIZE; j++)
  174649. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174650. }
  174651. }
  174652. }
  174653. }
  174654. }
  174655. }
  174656. }
  174657. }
  174658. /* Request any required workspace.
  174659. *
  174660. * We allocate the workspace virtual arrays from the source decompression
  174661. * object, so that all the arrays (both the original data and the workspace)
  174662. * will be taken into account while making memory management decisions.
  174663. * Hence, this routine must be called after jpeg_read_header (which reads
  174664. * the image dimensions) and before jpeg_read_coefficients (which realizes
  174665. * the source's virtual arrays).
  174666. */
  174667. GLOBAL(void)
  174668. jtransform_request_workspace (j_decompress_ptr srcinfo,
  174669. jpeg_transform_info *info)
  174670. {
  174671. jvirt_barray_ptr *coef_arrays = NULL;
  174672. jpeg_component_info *compptr;
  174673. int ci;
  174674. if (info->force_grayscale &&
  174675. srcinfo->jpeg_color_space == JCS_YCbCr &&
  174676. srcinfo->num_components == 3) {
  174677. /* We'll only process the first component */
  174678. info->num_components = 1;
  174679. } else {
  174680. /* Process all the components */
  174681. info->num_components = srcinfo->num_components;
  174682. }
  174683. switch (info->transform) {
  174684. case JXFORM_NONE:
  174685. case JXFORM_FLIP_H:
  174686. /* Don't need a workspace array */
  174687. break;
  174688. case JXFORM_FLIP_V:
  174689. case JXFORM_ROT_180:
  174690. /* Need workspace arrays having same dimensions as source image.
  174691. * Note that we allocate arrays padded out to the next iMCU boundary,
  174692. * so that transform routines need not worry about missing edge blocks.
  174693. */
  174694. coef_arrays = (jvirt_barray_ptr *)
  174695. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  174696. SIZEOF(jvirt_barray_ptr) * info->num_components);
  174697. for (ci = 0; ci < info->num_components; ci++) {
  174698. compptr = srcinfo->comp_info + ci;
  174699. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  174700. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  174701. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  174702. (long) compptr->h_samp_factor),
  174703. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  174704. (long) compptr->v_samp_factor),
  174705. (JDIMENSION) compptr->v_samp_factor);
  174706. }
  174707. break;
  174708. case JXFORM_TRANSPOSE:
  174709. case JXFORM_TRANSVERSE:
  174710. case JXFORM_ROT_90:
  174711. case JXFORM_ROT_270:
  174712. /* Need workspace arrays having transposed dimensions.
  174713. * Note that we allocate arrays padded out to the next iMCU boundary,
  174714. * so that transform routines need not worry about missing edge blocks.
  174715. */
  174716. coef_arrays = (jvirt_barray_ptr *)
  174717. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  174718. SIZEOF(jvirt_barray_ptr) * info->num_components);
  174719. for (ci = 0; ci < info->num_components; ci++) {
  174720. compptr = srcinfo->comp_info + ci;
  174721. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  174722. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  174723. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  174724. (long) compptr->v_samp_factor),
  174725. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  174726. (long) compptr->h_samp_factor),
  174727. (JDIMENSION) compptr->h_samp_factor);
  174728. }
  174729. break;
  174730. }
  174731. info->workspace_coef_arrays = coef_arrays;
  174732. }
  174733. /* Transpose destination image parameters */
  174734. LOCAL(void)
  174735. transpose_critical_parameters (j_compress_ptr dstinfo)
  174736. {
  174737. int tblno, i, j, ci, itemp;
  174738. jpeg_component_info *compptr;
  174739. JQUANT_TBL *qtblptr;
  174740. JDIMENSION dtemp;
  174741. UINT16 qtemp;
  174742. /* Transpose basic image dimensions */
  174743. dtemp = dstinfo->image_width;
  174744. dstinfo->image_width = dstinfo->image_height;
  174745. dstinfo->image_height = dtemp;
  174746. /* Transpose sampling factors */
  174747. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174748. compptr = dstinfo->comp_info + ci;
  174749. itemp = compptr->h_samp_factor;
  174750. compptr->h_samp_factor = compptr->v_samp_factor;
  174751. compptr->v_samp_factor = itemp;
  174752. }
  174753. /* Transpose quantization tables */
  174754. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  174755. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  174756. if (qtblptr != NULL) {
  174757. for (i = 0; i < DCTSIZE; i++) {
  174758. for (j = 0; j < i; j++) {
  174759. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  174760. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  174761. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  174762. }
  174763. }
  174764. }
  174765. }
  174766. }
  174767. /* Trim off any partial iMCUs on the indicated destination edge */
  174768. LOCAL(void)
  174769. trim_right_edge (j_compress_ptr dstinfo)
  174770. {
  174771. int ci, max_h_samp_factor;
  174772. JDIMENSION MCU_cols;
  174773. /* We have to compute max_h_samp_factor ourselves,
  174774. * because it hasn't been set yet in the destination
  174775. * (and we don't want to use the source's value).
  174776. */
  174777. max_h_samp_factor = 1;
  174778. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174779. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  174780. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  174781. }
  174782. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  174783. if (MCU_cols > 0) /* can't trim to 0 pixels */
  174784. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  174785. }
  174786. LOCAL(void)
  174787. trim_bottom_edge (j_compress_ptr dstinfo)
  174788. {
  174789. int ci, max_v_samp_factor;
  174790. JDIMENSION MCU_rows;
  174791. /* We have to compute max_v_samp_factor ourselves,
  174792. * because it hasn't been set yet in the destination
  174793. * (and we don't want to use the source's value).
  174794. */
  174795. max_v_samp_factor = 1;
  174796. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174797. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  174798. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  174799. }
  174800. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  174801. if (MCU_rows > 0) /* can't trim to 0 pixels */
  174802. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  174803. }
  174804. /* Adjust output image parameters as needed.
  174805. *
  174806. * This must be called after jpeg_copy_critical_parameters()
  174807. * and before jpeg_write_coefficients().
  174808. *
  174809. * The return value is the set of virtual coefficient arrays to be written
  174810. * (either the ones allocated by jtransform_request_workspace, or the
  174811. * original source data arrays). The caller will need to pass this value
  174812. * to jpeg_write_coefficients().
  174813. */
  174814. GLOBAL(jvirt_barray_ptr *)
  174815. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  174816. j_compress_ptr dstinfo,
  174817. jvirt_barray_ptr *src_coef_arrays,
  174818. jpeg_transform_info *info)
  174819. {
  174820. /* If force-to-grayscale is requested, adjust destination parameters */
  174821. if (info->force_grayscale) {
  174822. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  174823. * properly. Among other things, the target h_samp_factor & v_samp_factor
  174824. * will get set to 1, which typically won't match the source.
  174825. * In fact we do this even if the source is already grayscale; that
  174826. * provides an easy way of coercing a grayscale JPEG with funny sampling
  174827. * factors to the customary 1,1. (Some decoders fail on other factors.)
  174828. */
  174829. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  174830. dstinfo->num_components == 3) ||
  174831. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  174832. dstinfo->num_components == 1)) {
  174833. /* We have to preserve the source's quantization table number. */
  174834. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  174835. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  174836. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  174837. } else {
  174838. /* Sorry, can't do it */
  174839. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  174840. }
  174841. }
  174842. /* Correct the destination's image dimensions etc if necessary */
  174843. switch (info->transform) {
  174844. case JXFORM_NONE:
  174845. /* Nothing to do */
  174846. break;
  174847. case JXFORM_FLIP_H:
  174848. if (info->trim)
  174849. trim_right_edge(dstinfo);
  174850. break;
  174851. case JXFORM_FLIP_V:
  174852. if (info->trim)
  174853. trim_bottom_edge(dstinfo);
  174854. break;
  174855. case JXFORM_TRANSPOSE:
  174856. transpose_critical_parameters(dstinfo);
  174857. /* transpose does NOT have to trim anything */
  174858. break;
  174859. case JXFORM_TRANSVERSE:
  174860. transpose_critical_parameters(dstinfo);
  174861. if (info->trim) {
  174862. trim_right_edge(dstinfo);
  174863. trim_bottom_edge(dstinfo);
  174864. }
  174865. break;
  174866. case JXFORM_ROT_90:
  174867. transpose_critical_parameters(dstinfo);
  174868. if (info->trim)
  174869. trim_right_edge(dstinfo);
  174870. break;
  174871. case JXFORM_ROT_180:
  174872. if (info->trim) {
  174873. trim_right_edge(dstinfo);
  174874. trim_bottom_edge(dstinfo);
  174875. }
  174876. break;
  174877. case JXFORM_ROT_270:
  174878. transpose_critical_parameters(dstinfo);
  174879. if (info->trim)
  174880. trim_bottom_edge(dstinfo);
  174881. break;
  174882. }
  174883. /* Return the appropriate output data set */
  174884. if (info->workspace_coef_arrays != NULL)
  174885. return info->workspace_coef_arrays;
  174886. return src_coef_arrays;
  174887. }
  174888. /* Execute the actual transformation, if any.
  174889. *
  174890. * This must be called *after* jpeg_write_coefficients, because it depends
  174891. * on jpeg_write_coefficients to have computed subsidiary values such as
  174892. * the per-component width and height fields in the destination object.
  174893. *
  174894. * Note that some transformations will modify the source data arrays!
  174895. */
  174896. GLOBAL(void)
  174897. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  174898. j_compress_ptr dstinfo,
  174899. jvirt_barray_ptr *src_coef_arrays,
  174900. jpeg_transform_info *info)
  174901. {
  174902. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  174903. switch (info->transform) {
  174904. case JXFORM_NONE:
  174905. break;
  174906. case JXFORM_FLIP_H:
  174907. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  174908. break;
  174909. case JXFORM_FLIP_V:
  174910. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174911. break;
  174912. case JXFORM_TRANSPOSE:
  174913. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174914. break;
  174915. case JXFORM_TRANSVERSE:
  174916. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174917. break;
  174918. case JXFORM_ROT_90:
  174919. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174920. break;
  174921. case JXFORM_ROT_180:
  174922. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174923. break;
  174924. case JXFORM_ROT_270:
  174925. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174926. break;
  174927. }
  174928. }
  174929. #endif /* TRANSFORMS_SUPPORTED */
  174930. /* Setup decompression object to save desired markers in memory.
  174931. * This must be called before jpeg_read_header() to have the desired effect.
  174932. */
  174933. GLOBAL(void)
  174934. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  174935. {
  174936. #ifdef SAVE_MARKERS_SUPPORTED
  174937. int m;
  174938. /* Save comments except under NONE option */
  174939. if (option != JCOPYOPT_NONE) {
  174940. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  174941. }
  174942. /* Save all types of APPn markers iff ALL option */
  174943. if (option == JCOPYOPT_ALL) {
  174944. for (m = 0; m < 16; m++)
  174945. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  174946. }
  174947. #endif /* SAVE_MARKERS_SUPPORTED */
  174948. }
  174949. /* Copy markers saved in the given source object to the destination object.
  174950. * This should be called just after jpeg_start_compress() or
  174951. * jpeg_write_coefficients().
  174952. * Note that those routines will have written the SOI, and also the
  174953. * JFIF APP0 or Adobe APP14 markers if selected.
  174954. */
  174955. GLOBAL(void)
  174956. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174957. JCOPY_OPTION option)
  174958. {
  174959. jpeg_saved_marker_ptr marker;
  174960. /* In the current implementation, we don't actually need to examine the
  174961. * option flag here; we just copy everything that got saved.
  174962. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  174963. * if the encoder library already wrote one.
  174964. */
  174965. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  174966. if (dstinfo->write_JFIF_header &&
  174967. marker->marker == JPEG_APP0 &&
  174968. marker->data_length >= 5 &&
  174969. GETJOCTET(marker->data[0]) == 0x4A &&
  174970. GETJOCTET(marker->data[1]) == 0x46 &&
  174971. GETJOCTET(marker->data[2]) == 0x49 &&
  174972. GETJOCTET(marker->data[3]) == 0x46 &&
  174973. GETJOCTET(marker->data[4]) == 0)
  174974. continue; /* reject duplicate JFIF */
  174975. if (dstinfo->write_Adobe_marker &&
  174976. marker->marker == JPEG_APP0+14 &&
  174977. marker->data_length >= 5 &&
  174978. GETJOCTET(marker->data[0]) == 0x41 &&
  174979. GETJOCTET(marker->data[1]) == 0x64 &&
  174980. GETJOCTET(marker->data[2]) == 0x6F &&
  174981. GETJOCTET(marker->data[3]) == 0x62 &&
  174982. GETJOCTET(marker->data[4]) == 0x65)
  174983. continue; /* reject duplicate Adobe */
  174984. #ifdef NEED_FAR_POINTERS
  174985. /* We could use jpeg_write_marker if the data weren't FAR... */
  174986. {
  174987. unsigned int i;
  174988. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  174989. for (i = 0; i < marker->data_length; i++)
  174990. jpeg_write_m_byte(dstinfo, marker->data[i]);
  174991. }
  174992. #else
  174993. jpeg_write_marker(dstinfo, marker->marker,
  174994. marker->data, marker->data_length);
  174995. #endif
  174996. }
  174997. }
  174998. /********* End of inlined file: transupp.c *********/
  174999. }
  175000. #else
  175001. #define JPEG_INTERNALS
  175002. #undef FAR
  175003. #include <jpeglib.h>
  175004. #endif
  175005. }
  175006. #if JUCE_MSVC
  175007. #pragma warning (pop)
  175008. #endif
  175009. BEGIN_JUCE_NAMESPACE
  175010. using namespace jpeglibNamespace;
  175011. #if ! JUCE_WIN32
  175012. using jpeglibNamespace::boolean;
  175013. #endif
  175014. struct JPEGDecodingFailure {};
  175015. static void fatalErrorHandler (j_common_ptr)
  175016. {
  175017. throw JPEGDecodingFailure();
  175018. }
  175019. static void silentErrorCallback1 (j_common_ptr) {}
  175020. static void silentErrorCallback2 (j_common_ptr, int) {}
  175021. static void silentErrorCallback3 (j_common_ptr, char*) {}
  175022. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  175023. {
  175024. zerostruct (err);
  175025. err.error_exit = fatalErrorHandler;
  175026. err.emit_message = silentErrorCallback2;
  175027. err.output_message = silentErrorCallback1;
  175028. err.format_message = silentErrorCallback3;
  175029. err.reset_error_mgr = silentErrorCallback1;
  175030. }
  175031. static void dummyCallback1 (j_decompress_ptr) throw()
  175032. {
  175033. }
  175034. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  175035. {
  175036. decompStruct->src->next_input_byte += num;
  175037. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  175038. decompStruct->src->bytes_in_buffer -= num;
  175039. }
  175040. static boolean jpegFill (j_decompress_ptr) throw()
  175041. {
  175042. return 0;
  175043. }
  175044. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  175045. {
  175046. MemoryBlock mb;
  175047. in.readIntoMemoryBlock (mb);
  175048. Image* image = 0;
  175049. if (mb.getSize() > 16)
  175050. {
  175051. struct jpeg_decompress_struct jpegDecompStruct;
  175052. struct jpeg_error_mgr jerr;
  175053. setupSilentErrorHandler (jerr);
  175054. jpegDecompStruct.err = &jerr;
  175055. jpeg_create_decompress (&jpegDecompStruct);
  175056. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  175057. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  175058. jpegDecompStruct.src->init_source = dummyCallback1;
  175059. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  175060. jpegDecompStruct.src->skip_input_data = jpegSkip;
  175061. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  175062. jpegDecompStruct.src->term_source = dummyCallback1;
  175063. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  175064. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  175065. try
  175066. {
  175067. jpeg_read_header (&jpegDecompStruct, TRUE);
  175068. jpeg_calc_output_dimensions (&jpegDecompStruct);
  175069. const int width = jpegDecompStruct.output_width;
  175070. const int height = jpegDecompStruct.output_height;
  175071. jpegDecompStruct.out_color_space = JCS_RGB;
  175072. JSAMPARRAY buffer
  175073. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  175074. JPOOL_IMAGE,
  175075. width * 3, 1);
  175076. if (jpeg_start_decompress (&jpegDecompStruct))
  175077. {
  175078. image = new Image (Image::RGB, width, height, false);
  175079. for (int y = 0; y < height; ++y)
  175080. {
  175081. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  175082. int stride, pixelStride;
  175083. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  175084. const uint8* src = *buffer;
  175085. uint8* dest = pixels;
  175086. for (int i = width; --i >= 0;)
  175087. {
  175088. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  175089. dest += pixelStride;
  175090. src += 3;
  175091. }
  175092. image->releasePixelDataReadWrite (pixels);
  175093. }
  175094. jpeg_finish_decompress (&jpegDecompStruct);
  175095. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  175096. }
  175097. jpeg_destroy_decompress (&jpegDecompStruct);
  175098. }
  175099. catch (...)
  175100. {}
  175101. }
  175102. return image;
  175103. }
  175104. static const int bufferSize = 512;
  175105. struct JuceJpegDest : public jpeg_destination_mgr
  175106. {
  175107. OutputStream* output;
  175108. char* buffer;
  175109. };
  175110. static void jpegWriteInit (j_compress_ptr) throw()
  175111. {
  175112. }
  175113. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  175114. {
  175115. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175116. const int numToWrite = bufferSize - dest->free_in_buffer;
  175117. dest->output->write (dest->buffer, numToWrite);
  175118. }
  175119. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  175120. {
  175121. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175122. const int numToWrite = bufferSize;
  175123. dest->next_output_byte = (JOCTET*) dest->buffer;
  175124. dest->free_in_buffer = bufferSize;
  175125. return dest->output->write (dest->buffer, numToWrite);
  175126. }
  175127. bool juce_writeJPEGImageToStream (const Image& image,
  175128. OutputStream& out,
  175129. float quality) throw()
  175130. {
  175131. if (image.hasAlphaChannel())
  175132. {
  175133. // this method could fill the background in white and still save the image..
  175134. jassertfalse
  175135. return true;
  175136. }
  175137. struct jpeg_compress_struct jpegCompStruct;
  175138. struct jpeg_error_mgr jerr;
  175139. setupSilentErrorHandler (jerr);
  175140. jpegCompStruct.err = &jerr;
  175141. jpeg_create_compress (&jpegCompStruct);
  175142. JuceJpegDest dest;
  175143. jpegCompStruct.dest = &dest;
  175144. dest.output = &out;
  175145. dest.buffer = (char*) juce_malloc (bufferSize);
  175146. dest.next_output_byte = (JOCTET*) dest.buffer;
  175147. dest.free_in_buffer = bufferSize;
  175148. dest.init_destination = jpegWriteInit;
  175149. dest.empty_output_buffer = jpegWriteFlush;
  175150. dest.term_destination = jpegWriteTerminate;
  175151. jpegCompStruct.image_width = image.getWidth();
  175152. jpegCompStruct.image_height = image.getHeight();
  175153. jpegCompStruct.input_components = 3;
  175154. jpegCompStruct.in_color_space = JCS_RGB;
  175155. jpegCompStruct.write_JFIF_header = 1;
  175156. jpegCompStruct.X_density = 72;
  175157. jpegCompStruct.Y_density = 72;
  175158. jpeg_set_defaults (&jpegCompStruct);
  175159. jpegCompStruct.dct_method = JDCT_FLOAT;
  175160. jpegCompStruct.optimize_coding = 1;
  175161. // jpegCompStruct.smoothing_factor = 10;
  175162. if (quality < 0.0f)
  175163. quality = 0.85f;
  175164. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  175165. jpeg_start_compress (&jpegCompStruct, TRUE);
  175166. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  175167. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  175168. JPOOL_IMAGE,
  175169. strideBytes, 1);
  175170. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  175171. {
  175172. int stride, pixelStride;
  175173. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  175174. const uint8* src = pixels;
  175175. uint8* dst = *buffer;
  175176. for (int i = jpegCompStruct.image_width; --i >= 0;)
  175177. {
  175178. *dst++ = ((const PixelRGB*) src)->getRed();
  175179. *dst++ = ((const PixelRGB*) src)->getGreen();
  175180. *dst++ = ((const PixelRGB*) src)->getBlue();
  175181. src += pixelStride;
  175182. }
  175183. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  175184. image.releasePixelDataReadOnly (pixels);
  175185. }
  175186. jpeg_finish_compress (&jpegCompStruct);
  175187. jpeg_destroy_compress (&jpegCompStruct);
  175188. juce_free (dest.buffer);
  175189. out.flush();
  175190. return true;
  175191. }
  175192. END_JUCE_NAMESPACE
  175193. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  175194. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  175195. #ifdef _MSC_VER
  175196. #pragma warning (push)
  175197. #pragma warning (disable: 4390 4611)
  175198. #endif
  175199. namespace zlibNamespace
  175200. {
  175201. #if JUCE_INCLUDE_ZLIB_CODE
  175202. #undef OS_CODE
  175203. #undef fdopen
  175204. #undef OS_CODE
  175205. #else
  175206. #include <zlib.h>
  175207. #endif
  175208. }
  175209. namespace pnglibNamespace
  175210. {
  175211. using namespace zlibNamespace;
  175212. #if JUCE_INCLUDE_PNGLIB_CODE
  175213. #if _MSC_VER != 1310
  175214. using ::calloc; // (causes conflict in VS.NET 2003)
  175215. using ::malloc;
  175216. using ::free;
  175217. #endif
  175218. extern "C"
  175219. {
  175220. using ::abs;
  175221. #define PNG_INTERNAL
  175222. #define NO_DUMMY_DECL
  175223. #define PNG_SETJMP_NOT_SUPPORTED
  175224. /********* Start of inlined file: png.h *********/
  175225. /* png.h - header file for PNG reference library
  175226. *
  175227. * libpng version 1.2.21 - October 4, 2007
  175228. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  175229. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  175230. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  175231. *
  175232. * Authors and maintainers:
  175233. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  175234. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  175235. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  175236. * See also "Contributing Authors", below.
  175237. *
  175238. * Note about libpng version numbers:
  175239. *
  175240. * Due to various miscommunications, unforeseen code incompatibilities
  175241. * and occasional factors outside the authors' control, version numbering
  175242. * on the library has not always been consistent and straightforward.
  175243. * The following table summarizes matters since version 0.89c, which was
  175244. * the first widely used release:
  175245. *
  175246. * source png.h png.h shared-lib
  175247. * version string int version
  175248. * ------- ------ ----- ----------
  175249. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  175250. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  175251. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  175252. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  175253. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  175254. * 0.97c 0.97 97 2.0.97
  175255. * 0.98 0.98 98 2.0.98
  175256. * 0.99 0.99 98 2.0.99
  175257. * 0.99a-m 0.99 99 2.0.99
  175258. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  175259. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  175260. * 1.0.1 png.h string is 10001 2.1.0
  175261. * 1.0.1a-e identical to the 10002 from here on, the shared library
  175262. * 1.0.2 source version) 10002 is 2.V where V is the source code
  175263. * 1.0.2a-b 10003 version, except as noted.
  175264. * 1.0.3 10003
  175265. * 1.0.3a-d 10004
  175266. * 1.0.4 10004
  175267. * 1.0.4a-f 10005
  175268. * 1.0.5 (+ 2 patches) 10005
  175269. * 1.0.5a-d 10006
  175270. * 1.0.5e-r 10100 (not source compatible)
  175271. * 1.0.5s-v 10006 (not binary compatible)
  175272. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  175273. * 1.0.6d-f 10007 (still binary incompatible)
  175274. * 1.0.6g 10007
  175275. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  175276. * 1.0.6i 10007 10.6i
  175277. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  175278. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  175279. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  175280. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  175281. * 1.0.7 1 10007 (still compatible)
  175282. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  175283. * 1.0.8rc1 1 10008 2.1.0.8rc1
  175284. * 1.0.8 1 10008 2.1.0.8
  175285. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  175286. * 1.0.9rc1 1 10009 2.1.0.9rc1
  175287. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  175288. * 1.0.9rc2 1 10009 2.1.0.9rc2
  175289. * 1.0.9 1 10009 2.1.0.9
  175290. * 1.0.10beta1 1 10010 2.1.0.10beta1
  175291. * 1.0.10rc1 1 10010 2.1.0.10rc1
  175292. * 1.0.10 1 10010 2.1.0.10
  175293. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  175294. * 1.0.11rc1 1 10011 2.1.0.11rc1
  175295. * 1.0.11 1 10011 2.1.0.11
  175296. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  175297. * 1.0.12rc1 2 10012 2.1.0.12rc1
  175298. * 1.0.12 2 10012 2.1.0.12
  175299. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  175300. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  175301. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  175302. * 1.2.0rc1 3 10200 3.1.2.0rc1
  175303. * 1.2.0 3 10200 3.1.2.0
  175304. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  175305. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  175306. * 1.2.1 3 10201 3.1.2.1
  175307. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  175308. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  175309. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  175310. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  175311. * 1.0.13 10 10013 10.so.0.1.0.13
  175312. * 1.2.2 12 10202 12.so.0.1.2.2
  175313. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  175314. * 1.2.3 12 10203 12.so.0.1.2.3
  175315. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  175316. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  175317. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  175318. * 1.0.14 10 10014 10.so.0.1.0.14
  175319. * 1.2.4 13 10204 12.so.0.1.2.4
  175320. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  175321. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  175322. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  175323. * 1.0.15 10 10015 10.so.0.1.0.15
  175324. * 1.2.5 13 10205 12.so.0.1.2.5
  175325. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  175326. * 1.0.16 10 10016 10.so.0.1.0.16
  175327. * 1.2.6 13 10206 12.so.0.1.2.6
  175328. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  175329. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  175330. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  175331. * 1.0.17 10 10017 10.so.0.1.0.17
  175332. * 1.2.7 13 10207 12.so.0.1.2.7
  175333. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  175334. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  175335. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  175336. * 1.0.18 10 10018 10.so.0.1.0.18
  175337. * 1.2.8 13 10208 12.so.0.1.2.8
  175338. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  175339. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  175340. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  175341. * 1.2.9 13 10209 12.so.0.9[.0]
  175342. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  175343. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  175344. * 1.2.10 13 10210 12.so.0.10[.0]
  175345. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  175346. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  175347. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  175348. * 1.0.19 10 10019 10.so.0.19[.0]
  175349. * 1.2.11 13 10211 12.so.0.11[.0]
  175350. * 1.0.20 10 10020 10.so.0.20[.0]
  175351. * 1.2.12 13 10212 12.so.0.12[.0]
  175352. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  175353. * 1.0.21 10 10021 10.so.0.21[.0]
  175354. * 1.2.13 13 10213 12.so.0.13[.0]
  175355. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  175356. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  175357. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  175358. * 1.0.22 10 10022 10.so.0.22[.0]
  175359. * 1.2.14 13 10214 12.so.0.14[.0]
  175360. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  175361. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  175362. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  175363. * 1.0.23 10 10023 10.so.0.23[.0]
  175364. * 1.2.15 13 10215 12.so.0.15[.0]
  175365. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  175366. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  175367. * 1.0.24 10 10024 10.so.0.24[.0]
  175368. * 1.2.16 13 10216 12.so.0.16[.0]
  175369. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  175370. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  175371. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  175372. * 1.0.25 10 10025 10.so.0.25[.0]
  175373. * 1.2.17 13 10217 12.so.0.17[.0]
  175374. * 1.0.26 10 10026 10.so.0.26[.0]
  175375. * 1.2.18 13 10218 12.so.0.18[.0]
  175376. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  175377. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  175378. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  175379. * 1.0.27 10 10027 10.so.0.27[.0]
  175380. * 1.2.19 13 10219 12.so.0.19[.0]
  175381. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  175382. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  175383. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  175384. * 1.0.28 10 10028 10.so.0.28[.0]
  175385. * 1.2.20 13 10220 12.so.0.20[.0]
  175386. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  175387. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  175388. * 1.0.29 10 10029 10.so.0.29[.0]
  175389. * 1.2.21 13 10221 12.so.0.21[.0]
  175390. *
  175391. * Henceforth the source version will match the shared-library major
  175392. * and minor numbers; the shared-library major version number will be
  175393. * used for changes in backward compatibility, as it is intended. The
  175394. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  175395. * for applications, is an unsigned integer of the form xyyzz corresponding
  175396. * to the source version x.y.z (leading zeros in y and z). Beta versions
  175397. * were given the previous public release number plus a letter, until
  175398. * version 1.0.6j; from then on they were given the upcoming public
  175399. * release number plus "betaNN" or "rcN".
  175400. *
  175401. * Binary incompatibility exists only when applications make direct access
  175402. * to the info_ptr or png_ptr members through png.h, and the compiled
  175403. * application is loaded with a different version of the library.
  175404. *
  175405. * DLLNUM will change each time there are forward or backward changes
  175406. * in binary compatibility (e.g., when a new feature is added).
  175407. *
  175408. * See libpng.txt or libpng.3 for more information. The PNG specification
  175409. * is available as a W3C Recommendation and as an ISO Specification,
  175410. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  175411. */
  175412. /*
  175413. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  175414. *
  175415. * If you modify libpng you may insert additional notices immediately following
  175416. * this sentence.
  175417. *
  175418. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  175419. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  175420. * distributed according to the same disclaimer and license as libpng-1.2.5
  175421. * with the following individual added to the list of Contributing Authors:
  175422. *
  175423. * Cosmin Truta
  175424. *
  175425. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  175426. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  175427. * distributed according to the same disclaimer and license as libpng-1.0.6
  175428. * with the following individuals added to the list of Contributing Authors:
  175429. *
  175430. * Simon-Pierre Cadieux
  175431. * Eric S. Raymond
  175432. * Gilles Vollant
  175433. *
  175434. * and with the following additions to the disclaimer:
  175435. *
  175436. * There is no warranty against interference with your enjoyment of the
  175437. * library or against infringement. There is no warranty that our
  175438. * efforts or the library will fulfill any of your particular purposes
  175439. * or needs. This library is provided with all faults, and the entire
  175440. * risk of satisfactory quality, performance, accuracy, and effort is with
  175441. * the user.
  175442. *
  175443. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  175444. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  175445. * distributed according to the same disclaimer and license as libpng-0.96,
  175446. * with the following individuals added to the list of Contributing Authors:
  175447. *
  175448. * Tom Lane
  175449. * Glenn Randers-Pehrson
  175450. * Willem van Schaik
  175451. *
  175452. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  175453. * Copyright (c) 1996, 1997 Andreas Dilger
  175454. * Distributed according to the same disclaimer and license as libpng-0.88,
  175455. * with the following individuals added to the list of Contributing Authors:
  175456. *
  175457. * John Bowler
  175458. * Kevin Bracey
  175459. * Sam Bushell
  175460. * Magnus Holmgren
  175461. * Greg Roelofs
  175462. * Tom Tanner
  175463. *
  175464. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  175465. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  175466. *
  175467. * For the purposes of this copyright and license, "Contributing Authors"
  175468. * is defined as the following set of individuals:
  175469. *
  175470. * Andreas Dilger
  175471. * Dave Martindale
  175472. * Guy Eric Schalnat
  175473. * Paul Schmidt
  175474. * Tim Wegner
  175475. *
  175476. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  175477. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  175478. * including, without limitation, the warranties of merchantability and of
  175479. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  175480. * assume no liability for direct, indirect, incidental, special, exemplary,
  175481. * or consequential damages, which may result from the use of the PNG
  175482. * Reference Library, even if advised of the possibility of such damage.
  175483. *
  175484. * Permission is hereby granted to use, copy, modify, and distribute this
  175485. * source code, or portions hereof, for any purpose, without fee, subject
  175486. * to the following restrictions:
  175487. *
  175488. * 1. The origin of this source code must not be misrepresented.
  175489. *
  175490. * 2. Altered versions must be plainly marked as such and
  175491. * must not be misrepresented as being the original source.
  175492. *
  175493. * 3. This Copyright notice may not be removed or altered from
  175494. * any source or altered source distribution.
  175495. *
  175496. * The Contributing Authors and Group 42, Inc. specifically permit, without
  175497. * fee, and encourage the use of this source code as a component to
  175498. * supporting the PNG file format in commercial products. If you use this
  175499. * source code in a product, acknowledgment is not required but would be
  175500. * appreciated.
  175501. */
  175502. /*
  175503. * A "png_get_copyright" function is available, for convenient use in "about"
  175504. * boxes and the like:
  175505. *
  175506. * printf("%s",png_get_copyright(NULL));
  175507. *
  175508. * Also, the PNG logo (in PNG format, of course) is supplied in the
  175509. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  175510. */
  175511. /*
  175512. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  175513. * certification mark of the Open Source Initiative.
  175514. */
  175515. /*
  175516. * The contributing authors would like to thank all those who helped
  175517. * with testing, bug fixes, and patience. This wouldn't have been
  175518. * possible without all of you.
  175519. *
  175520. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  175521. */
  175522. /*
  175523. * Y2K compliance in libpng:
  175524. * =========================
  175525. *
  175526. * October 4, 2007
  175527. *
  175528. * Since the PNG Development group is an ad-hoc body, we can't make
  175529. * an official declaration.
  175530. *
  175531. * This is your unofficial assurance that libpng from version 0.71 and
  175532. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  175533. * versions were also Y2K compliant.
  175534. *
  175535. * Libpng only has three year fields. One is a 2-byte unsigned integer
  175536. * that will hold years up to 65535. The other two hold the date in text
  175537. * format, and will hold years up to 9999.
  175538. *
  175539. * The integer is
  175540. * "png_uint_16 year" in png_time_struct.
  175541. *
  175542. * The strings are
  175543. * "png_charp time_buffer" in png_struct and
  175544. * "near_time_buffer", which is a local character string in png.c.
  175545. *
  175546. * There are seven time-related functions:
  175547. * png.c: png_convert_to_rfc_1123() in png.c
  175548. * (formerly png_convert_to_rfc_1152() in error)
  175549. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  175550. * png_convert_from_time_t() in pngwrite.c
  175551. * png_get_tIME() in pngget.c
  175552. * png_handle_tIME() in pngrutil.c, called in pngread.c
  175553. * png_set_tIME() in pngset.c
  175554. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  175555. *
  175556. * All handle dates properly in a Y2K environment. The
  175557. * png_convert_from_time_t() function calls gmtime() to convert from system
  175558. * clock time, which returns (year - 1900), which we properly convert to
  175559. * the full 4-digit year. There is a possibility that applications using
  175560. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  175561. * function, or that they are incorrectly passing only a 2-digit year
  175562. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  175563. * but this is not under our control. The libpng documentation has always
  175564. * stated that it works with 4-digit years, and the APIs have been
  175565. * documented as such.
  175566. *
  175567. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  175568. * integer to hold the year, and can hold years as large as 65535.
  175569. *
  175570. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  175571. * no date-related code.
  175572. *
  175573. * Glenn Randers-Pehrson
  175574. * libpng maintainer
  175575. * PNG Development Group
  175576. */
  175577. #ifndef PNG_H
  175578. #define PNG_H
  175579. /* This is not the place to learn how to use libpng. The file libpng.txt
  175580. * describes how to use libpng, and the file example.c summarizes it
  175581. * with some code on which to build. This file is useful for looking
  175582. * at the actual function definitions and structure components.
  175583. */
  175584. /* Version information for png.h - this should match the version in png.c */
  175585. #define PNG_LIBPNG_VER_STRING "1.2.21"
  175586. #define PNG_HEADER_VERSION_STRING \
  175587. " libpng version 1.2.21 - October 4, 2007\n"
  175588. #define PNG_LIBPNG_VER_SONUM 0
  175589. #define PNG_LIBPNG_VER_DLLNUM 13
  175590. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  175591. #define PNG_LIBPNG_VER_MAJOR 1
  175592. #define PNG_LIBPNG_VER_MINOR 2
  175593. #define PNG_LIBPNG_VER_RELEASE 21
  175594. /* This should match the numeric part of the final component of
  175595. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  175596. #define PNG_LIBPNG_VER_BUILD 0
  175597. /* Release Status */
  175598. #define PNG_LIBPNG_BUILD_ALPHA 1
  175599. #define PNG_LIBPNG_BUILD_BETA 2
  175600. #define PNG_LIBPNG_BUILD_RC 3
  175601. #define PNG_LIBPNG_BUILD_STABLE 4
  175602. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  175603. /* Release-Specific Flags */
  175604. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  175605. PNG_LIBPNG_BUILD_STABLE only */
  175606. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  175607. PNG_LIBPNG_BUILD_SPECIAL */
  175608. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  175609. PNG_LIBPNG_BUILD_PRIVATE */
  175610. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  175611. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  175612. * We must not include leading zeros.
  175613. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  175614. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  175615. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  175616. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  175617. #ifndef PNG_VERSION_INFO_ONLY
  175618. /* include the compression library's header */
  175619. #endif
  175620. /* include all user configurable info, including optional assembler routines */
  175621. /********* Start of inlined file: pngconf.h *********/
  175622. /* pngconf.h - machine configurable file for libpng
  175623. *
  175624. * libpng version 1.2.21 - October 4, 2007
  175625. * For conditions of distribution and use, see copyright notice in png.h
  175626. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  175627. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  175628. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  175629. */
  175630. /* Any machine specific code is near the front of this file, so if you
  175631. * are configuring libpng for a machine, you may want to read the section
  175632. * starting here down to where it starts to typedef png_color, png_text,
  175633. * and png_info.
  175634. */
  175635. #ifndef PNGCONF_H
  175636. #define PNGCONF_H
  175637. #define PNG_1_2_X
  175638. // These are some Juce config settings that should remove any unnecessary code bloat..
  175639. #define PNG_NO_STDIO 1
  175640. #define PNG_DEBUG 0
  175641. #define PNG_NO_WARNINGS 1
  175642. #define PNG_NO_ERROR_TEXT 1
  175643. #define PNG_NO_ERROR_NUMBERS 1
  175644. #define PNG_NO_USER_MEM 1
  175645. #define PNG_NO_READ_iCCP 1
  175646. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  175647. #define PNG_NO_READ_USER_CHUNKS 1
  175648. #define PNG_NO_READ_iTXt 1
  175649. #define PNG_NO_READ_sCAL 1
  175650. #define PNG_NO_READ_sPLT 1
  175651. #define png_error(a, b) png_err(a)
  175652. #define png_warning(a, b)
  175653. #define png_chunk_error(a, b) png_err(a)
  175654. #define png_chunk_warning(a, b)
  175655. /*
  175656. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  175657. * includes the resource compiler for Windows DLL configurations.
  175658. */
  175659. #ifdef PNG_USER_CONFIG
  175660. # ifndef PNG_USER_PRIVATEBUILD
  175661. # define PNG_USER_PRIVATEBUILD
  175662. # endif
  175663. #include "pngusr.h"
  175664. #endif
  175665. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  175666. #ifdef PNG_CONFIGURE_LIBPNG
  175667. #ifdef HAVE_CONFIG_H
  175668. #include "config.h"
  175669. #endif
  175670. #endif
  175671. /*
  175672. * Added at libpng-1.2.8
  175673. *
  175674. * If you create a private DLL you need to define in "pngusr.h" the followings:
  175675. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  175676. * the DLL was built>
  175677. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  175678. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  175679. * distinguish your DLL from those of the official release. These
  175680. * correspond to the trailing letters that come after the version
  175681. * number and must match your private DLL name>
  175682. * e.g. // private DLL "libpng13gx.dll"
  175683. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  175684. *
  175685. * The following macros are also at your disposal if you want to complete the
  175686. * DLL VERSIONINFO structure.
  175687. * - PNG_USER_VERSIONINFO_COMMENTS
  175688. * - PNG_USER_VERSIONINFO_COMPANYNAME
  175689. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  175690. */
  175691. #ifdef __STDC__
  175692. #ifdef SPECIALBUILD
  175693. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  175694. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  175695. #endif
  175696. #ifdef PRIVATEBUILD
  175697. # pragma message("PRIVATEBUILD is deprecated.\
  175698. Use PNG_USER_PRIVATEBUILD instead.")
  175699. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  175700. #endif
  175701. #endif /* __STDC__ */
  175702. #ifndef PNG_VERSION_INFO_ONLY
  175703. /* End of material added to libpng-1.2.8 */
  175704. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  175705. Restored at libpng-1.2.21 */
  175706. # define PNG_WARN_UNINITIALIZED_ROW 1
  175707. /* End of material added at libpng-1.2.19/1.2.21 */
  175708. /* This is the size of the compression buffer, and thus the size of
  175709. * an IDAT chunk. Make this whatever size you feel is best for your
  175710. * machine. One of these will be allocated per png_struct. When this
  175711. * is full, it writes the data to the disk, and does some other
  175712. * calculations. Making this an extremely small size will slow
  175713. * the library down, but you may want to experiment to determine
  175714. * where it becomes significant, if you are concerned with memory
  175715. * usage. Note that zlib allocates at least 32Kb also. For readers,
  175716. * this describes the size of the buffer available to read the data in.
  175717. * Unless this gets smaller than the size of a row (compressed),
  175718. * it should not make much difference how big this is.
  175719. */
  175720. #ifndef PNG_ZBUF_SIZE
  175721. # define PNG_ZBUF_SIZE 8192
  175722. #endif
  175723. /* Enable if you want a write-only libpng */
  175724. #ifndef PNG_NO_READ_SUPPORTED
  175725. # define PNG_READ_SUPPORTED
  175726. #endif
  175727. /* Enable if you want a read-only libpng */
  175728. #ifndef PNG_NO_WRITE_SUPPORTED
  175729. # define PNG_WRITE_SUPPORTED
  175730. #endif
  175731. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  175732. support PNGs that are embedded in MNG datastreams */
  175733. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  175734. # ifndef PNG_MNG_FEATURES_SUPPORTED
  175735. # define PNG_MNG_FEATURES_SUPPORTED
  175736. # endif
  175737. #endif
  175738. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  175739. # ifndef PNG_FLOATING_POINT_SUPPORTED
  175740. # define PNG_FLOATING_POINT_SUPPORTED
  175741. # endif
  175742. #endif
  175743. /* If you are running on a machine where you cannot allocate more
  175744. * than 64K of memory at once, uncomment this. While libpng will not
  175745. * normally need that much memory in a chunk (unless you load up a very
  175746. * large file), zlib needs to know how big of a chunk it can use, and
  175747. * libpng thus makes sure to check any memory allocation to verify it
  175748. * will fit into memory.
  175749. #define PNG_MAX_MALLOC_64K
  175750. */
  175751. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  175752. # define PNG_MAX_MALLOC_64K
  175753. #endif
  175754. /* Special munging to support doing things the 'cygwin' way:
  175755. * 'Normal' png-on-win32 defines/defaults:
  175756. * PNG_BUILD_DLL -- building dll
  175757. * PNG_USE_DLL -- building an application, linking to dll
  175758. * (no define) -- building static library, or building an
  175759. * application and linking to the static lib
  175760. * 'Cygwin' defines/defaults:
  175761. * PNG_BUILD_DLL -- (ignored) building the dll
  175762. * (no define) -- (ignored) building an application, linking to the dll
  175763. * PNG_STATIC -- (ignored) building the static lib, or building an
  175764. * application that links to the static lib.
  175765. * ALL_STATIC -- (ignored) building various static libs, or building an
  175766. * application that links to the static libs.
  175767. * Thus,
  175768. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  175769. * this bit of #ifdefs will define the 'correct' config variables based on
  175770. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  175771. * unnecessary.
  175772. *
  175773. * Also, the precedence order is:
  175774. * ALL_STATIC (since we can't #undef something outside our namespace)
  175775. * PNG_BUILD_DLL
  175776. * PNG_STATIC
  175777. * (nothing) == PNG_USE_DLL
  175778. *
  175779. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  175780. * of auto-import in binutils, we no longer need to worry about
  175781. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  175782. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  175783. * to __declspec() stuff. However, we DO need to worry about
  175784. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  175785. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  175786. */
  175787. #if defined(__CYGWIN__)
  175788. # if defined(ALL_STATIC)
  175789. # if defined(PNG_BUILD_DLL)
  175790. # undef PNG_BUILD_DLL
  175791. # endif
  175792. # if defined(PNG_USE_DLL)
  175793. # undef PNG_USE_DLL
  175794. # endif
  175795. # if defined(PNG_DLL)
  175796. # undef PNG_DLL
  175797. # endif
  175798. # if !defined(PNG_STATIC)
  175799. # define PNG_STATIC
  175800. # endif
  175801. # else
  175802. # if defined (PNG_BUILD_DLL)
  175803. # if defined(PNG_STATIC)
  175804. # undef PNG_STATIC
  175805. # endif
  175806. # if defined(PNG_USE_DLL)
  175807. # undef PNG_USE_DLL
  175808. # endif
  175809. # if !defined(PNG_DLL)
  175810. # define PNG_DLL
  175811. # endif
  175812. # else
  175813. # if defined(PNG_STATIC)
  175814. # if defined(PNG_USE_DLL)
  175815. # undef PNG_USE_DLL
  175816. # endif
  175817. # if defined(PNG_DLL)
  175818. # undef PNG_DLL
  175819. # endif
  175820. # else
  175821. # if !defined(PNG_USE_DLL)
  175822. # define PNG_USE_DLL
  175823. # endif
  175824. # if !defined(PNG_DLL)
  175825. # define PNG_DLL
  175826. # endif
  175827. # endif
  175828. # endif
  175829. # endif
  175830. #endif
  175831. /* This protects us against compilers that run on a windowing system
  175832. * and thus don't have or would rather us not use the stdio types:
  175833. * stdin, stdout, and stderr. The only one currently used is stderr
  175834. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  175835. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  175836. * will also prevent these, plus will prevent the entire set of stdio
  175837. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  175838. * unless (PNG_DEBUG > 0) has been #defined.
  175839. *
  175840. * #define PNG_NO_CONSOLE_IO
  175841. * #define PNG_NO_STDIO
  175842. */
  175843. #if defined(_WIN32_WCE)
  175844. # include <windows.h>
  175845. /* Console I/O functions are not supported on WindowsCE */
  175846. # define PNG_NO_CONSOLE_IO
  175847. # ifdef PNG_DEBUG
  175848. # undef PNG_DEBUG
  175849. # endif
  175850. #endif
  175851. #ifdef PNG_BUILD_DLL
  175852. # ifndef PNG_CONSOLE_IO_SUPPORTED
  175853. # ifndef PNG_NO_CONSOLE_IO
  175854. # define PNG_NO_CONSOLE_IO
  175855. # endif
  175856. # endif
  175857. #endif
  175858. # ifdef PNG_NO_STDIO
  175859. # ifndef PNG_NO_CONSOLE_IO
  175860. # define PNG_NO_CONSOLE_IO
  175861. # endif
  175862. # ifdef PNG_DEBUG
  175863. # if (PNG_DEBUG > 0)
  175864. # include <stdio.h>
  175865. # endif
  175866. # endif
  175867. # else
  175868. # if !defined(_WIN32_WCE)
  175869. /* "stdio.h" functions are not supported on WindowsCE */
  175870. # include <stdio.h>
  175871. # endif
  175872. # endif
  175873. /* This macro protects us against machines that don't have function
  175874. * prototypes (ie K&R style headers). If your compiler does not handle
  175875. * function prototypes, define this macro and use the included ansi2knr.
  175876. * I've always been able to use _NO_PROTO as the indicator, but you may
  175877. * need to drag the empty declaration out in front of here, or change the
  175878. * ifdef to suit your own needs.
  175879. */
  175880. #ifndef PNGARG
  175881. #ifdef OF /* zlib prototype munger */
  175882. # define PNGARG(arglist) OF(arglist)
  175883. #else
  175884. #ifdef _NO_PROTO
  175885. # define PNGARG(arglist) ()
  175886. # ifndef PNG_TYPECAST_NULL
  175887. # define PNG_TYPECAST_NULL
  175888. # endif
  175889. #else
  175890. # define PNGARG(arglist) arglist
  175891. #endif /* _NO_PROTO */
  175892. #endif /* OF */
  175893. #endif /* PNGARG */
  175894. /* Try to determine if we are compiling on a Mac. Note that testing for
  175895. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  175896. * on non-Mac platforms.
  175897. */
  175898. #ifndef MACOS
  175899. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  175900. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  175901. # define MACOS
  175902. # endif
  175903. #endif
  175904. /* enough people need this for various reasons to include it here */
  175905. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  175906. # include <sys/types.h>
  175907. #endif
  175908. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  175909. # define PNG_SETJMP_SUPPORTED
  175910. #endif
  175911. #ifdef PNG_SETJMP_SUPPORTED
  175912. /* This is an attempt to force a single setjmp behaviour on Linux. If
  175913. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  175914. */
  175915. # ifdef __linux__
  175916. # ifdef _BSD_SOURCE
  175917. # define PNG_SAVE_BSD_SOURCE
  175918. # undef _BSD_SOURCE
  175919. # endif
  175920. # ifdef _SETJMP_H
  175921. /* If you encounter a compiler error here, see the explanation
  175922. * near the end of INSTALL.
  175923. */
  175924. __png.h__ already includes setjmp.h;
  175925. __dont__ include it again.;
  175926. # endif
  175927. # endif /* __linux__ */
  175928. /* include setjmp.h for error handling */
  175929. # include <setjmp.h>
  175930. # ifdef __linux__
  175931. # ifdef PNG_SAVE_BSD_SOURCE
  175932. # define _BSD_SOURCE
  175933. # undef PNG_SAVE_BSD_SOURCE
  175934. # endif
  175935. # endif /* __linux__ */
  175936. #endif /* PNG_SETJMP_SUPPORTED */
  175937. #ifdef BSD
  175938. #if ! JUCE_MAC
  175939. # include <strings.h>
  175940. #endif
  175941. #else
  175942. # include <string.h>
  175943. #endif
  175944. /* Other defines for things like memory and the like can go here. */
  175945. #ifdef PNG_INTERNAL
  175946. #include <stdlib.h>
  175947. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  175948. * aren't usually used outside the library (as far as I know), so it is
  175949. * debatable if they should be exported at all. In the future, when it is
  175950. * possible to have run-time registry of chunk-handling functions, some of
  175951. * these will be made available again.
  175952. #define PNG_EXTERN extern
  175953. */
  175954. #define PNG_EXTERN
  175955. /* Other defines specific to compilers can go here. Try to keep
  175956. * them inside an appropriate ifdef/endif pair for portability.
  175957. */
  175958. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  175959. # if defined(MACOS)
  175960. /* We need to check that <math.h> hasn't already been included earlier
  175961. * as it seems it doesn't agree with <fp.h>, yet we should really use
  175962. * <fp.h> if possible.
  175963. */
  175964. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  175965. # include <fp.h>
  175966. # endif
  175967. # else
  175968. # include <math.h>
  175969. # endif
  175970. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  175971. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  175972. * MATH=68881
  175973. */
  175974. # include <m68881.h>
  175975. # endif
  175976. #endif
  175977. /* Codewarrior on NT has linking problems without this. */
  175978. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  175979. # define PNG_ALWAYS_EXTERN
  175980. #endif
  175981. /* This provides the non-ANSI (far) memory allocation routines. */
  175982. #if defined(__TURBOC__) && defined(__MSDOS__)
  175983. # include <mem.h>
  175984. # include <alloc.h>
  175985. #endif
  175986. /* I have no idea why is this necessary... */
  175987. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  175988. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  175989. # include <malloc.h>
  175990. #endif
  175991. /* This controls how fine the dithering gets. As this allocates
  175992. * a largish chunk of memory (32K), those who are not as concerned
  175993. * with dithering quality can decrease some or all of these.
  175994. */
  175995. #ifndef PNG_DITHER_RED_BITS
  175996. # define PNG_DITHER_RED_BITS 5
  175997. #endif
  175998. #ifndef PNG_DITHER_GREEN_BITS
  175999. # define PNG_DITHER_GREEN_BITS 5
  176000. #endif
  176001. #ifndef PNG_DITHER_BLUE_BITS
  176002. # define PNG_DITHER_BLUE_BITS 5
  176003. #endif
  176004. /* This controls how fine the gamma correction becomes when you
  176005. * are only interested in 8 bits anyway. Increasing this value
  176006. * results in more memory being used, and more pow() functions
  176007. * being called to fill in the gamma tables. Don't set this value
  176008. * less then 8, and even that may not work (I haven't tested it).
  176009. */
  176010. #ifndef PNG_MAX_GAMMA_8
  176011. # define PNG_MAX_GAMMA_8 11
  176012. #endif
  176013. /* This controls how much a difference in gamma we can tolerate before
  176014. * we actually start doing gamma conversion.
  176015. */
  176016. #ifndef PNG_GAMMA_THRESHOLD
  176017. # define PNG_GAMMA_THRESHOLD 0.05
  176018. #endif
  176019. #endif /* PNG_INTERNAL */
  176020. /* The following uses const char * instead of char * for error
  176021. * and warning message functions, so some compilers won't complain.
  176022. * If you do not want to use const, define PNG_NO_CONST here.
  176023. */
  176024. #ifndef PNG_NO_CONST
  176025. # define PNG_CONST const
  176026. #else
  176027. # define PNG_CONST
  176028. #endif
  176029. /* The following defines give you the ability to remove code from the
  176030. * library that you will not be using. I wish I could figure out how to
  176031. * automate this, but I can't do that without making it seriously hard
  176032. * on the users. So if you are not using an ability, change the #define
  176033. * to and #undef, and that part of the library will not be compiled. If
  176034. * your linker can't find a function, you may want to make sure the
  176035. * ability is defined here. Some of these depend upon some others being
  176036. * defined. I haven't figured out all the interactions here, so you may
  176037. * have to experiment awhile to get everything to compile. If you are
  176038. * creating or using a shared library, you probably shouldn't touch this,
  176039. * as it will affect the size of the structures, and this will cause bad
  176040. * things to happen if the library and/or application ever change.
  176041. */
  176042. /* Any features you will not be using can be undef'ed here */
  176043. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  176044. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  176045. * on the compile line, then pick and choose which ones to define without
  176046. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  176047. * if you only want to have a png-compliant reader/writer but don't need
  176048. * any of the extra transformations. This saves about 80 kbytes in a
  176049. * typical installation of the library. (PNG_NO_* form added in version
  176050. * 1.0.1c, for consistency)
  176051. */
  176052. /* The size of the png_text structure changed in libpng-1.0.6 when
  176053. * iTXt support was added. iTXt support was turned off by default through
  176054. * libpng-1.2.x, to support old apps that malloc the png_text structure
  176055. * instead of calling png_set_text() and letting libpng malloc it. It
  176056. * was turned on by default in libpng-1.3.0.
  176057. */
  176058. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176059. # ifndef PNG_NO_iTXt_SUPPORTED
  176060. # define PNG_NO_iTXt_SUPPORTED
  176061. # endif
  176062. # ifndef PNG_NO_READ_iTXt
  176063. # define PNG_NO_READ_iTXt
  176064. # endif
  176065. # ifndef PNG_NO_WRITE_iTXt
  176066. # define PNG_NO_WRITE_iTXt
  176067. # endif
  176068. #endif
  176069. #if !defined(PNG_NO_iTXt_SUPPORTED)
  176070. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  176071. # define PNG_READ_iTXt
  176072. # endif
  176073. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  176074. # define PNG_WRITE_iTXt
  176075. # endif
  176076. #endif
  176077. /* The following support, added after version 1.0.0, can be turned off here en
  176078. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  176079. * with old applications that require the length of png_struct and png_info
  176080. * to remain unchanged.
  176081. */
  176082. #ifdef PNG_LEGACY_SUPPORTED
  176083. # define PNG_NO_FREE_ME
  176084. # define PNG_NO_READ_UNKNOWN_CHUNKS
  176085. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  176086. # define PNG_NO_READ_USER_CHUNKS
  176087. # define PNG_NO_READ_iCCP
  176088. # define PNG_NO_WRITE_iCCP
  176089. # define PNG_NO_READ_iTXt
  176090. # define PNG_NO_WRITE_iTXt
  176091. # define PNG_NO_READ_sCAL
  176092. # define PNG_NO_WRITE_sCAL
  176093. # define PNG_NO_READ_sPLT
  176094. # define PNG_NO_WRITE_sPLT
  176095. # define PNG_NO_INFO_IMAGE
  176096. # define PNG_NO_READ_RGB_TO_GRAY
  176097. # define PNG_NO_READ_USER_TRANSFORM
  176098. # define PNG_NO_WRITE_USER_TRANSFORM
  176099. # define PNG_NO_USER_MEM
  176100. # define PNG_NO_READ_EMPTY_PLTE
  176101. # define PNG_NO_MNG_FEATURES
  176102. # define PNG_NO_FIXED_POINT_SUPPORTED
  176103. #endif
  176104. /* Ignore attempt to turn off both floating and fixed point support */
  176105. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  176106. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  176107. # define PNG_FIXED_POINT_SUPPORTED
  176108. #endif
  176109. #ifndef PNG_NO_FREE_ME
  176110. # define PNG_FREE_ME_SUPPORTED
  176111. #endif
  176112. #if defined(PNG_READ_SUPPORTED)
  176113. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  176114. !defined(PNG_NO_READ_TRANSFORMS)
  176115. # define PNG_READ_TRANSFORMS_SUPPORTED
  176116. #endif
  176117. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  176118. # ifndef PNG_NO_READ_EXPAND
  176119. # define PNG_READ_EXPAND_SUPPORTED
  176120. # endif
  176121. # ifndef PNG_NO_READ_SHIFT
  176122. # define PNG_READ_SHIFT_SUPPORTED
  176123. # endif
  176124. # ifndef PNG_NO_READ_PACK
  176125. # define PNG_READ_PACK_SUPPORTED
  176126. # endif
  176127. # ifndef PNG_NO_READ_BGR
  176128. # define PNG_READ_BGR_SUPPORTED
  176129. # endif
  176130. # ifndef PNG_NO_READ_SWAP
  176131. # define PNG_READ_SWAP_SUPPORTED
  176132. # endif
  176133. # ifndef PNG_NO_READ_PACKSWAP
  176134. # define PNG_READ_PACKSWAP_SUPPORTED
  176135. # endif
  176136. # ifndef PNG_NO_READ_INVERT
  176137. # define PNG_READ_INVERT_SUPPORTED
  176138. # endif
  176139. # ifndef PNG_NO_READ_DITHER
  176140. # define PNG_READ_DITHER_SUPPORTED
  176141. # endif
  176142. # ifndef PNG_NO_READ_BACKGROUND
  176143. # define PNG_READ_BACKGROUND_SUPPORTED
  176144. # endif
  176145. # ifndef PNG_NO_READ_16_TO_8
  176146. # define PNG_READ_16_TO_8_SUPPORTED
  176147. # endif
  176148. # ifndef PNG_NO_READ_FILLER
  176149. # define PNG_READ_FILLER_SUPPORTED
  176150. # endif
  176151. # ifndef PNG_NO_READ_GAMMA
  176152. # define PNG_READ_GAMMA_SUPPORTED
  176153. # endif
  176154. # ifndef PNG_NO_READ_GRAY_TO_RGB
  176155. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  176156. # endif
  176157. # ifndef PNG_NO_READ_SWAP_ALPHA
  176158. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  176159. # endif
  176160. # ifndef PNG_NO_READ_INVERT_ALPHA
  176161. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  176162. # endif
  176163. # ifndef PNG_NO_READ_STRIP_ALPHA
  176164. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  176165. # endif
  176166. # ifndef PNG_NO_READ_USER_TRANSFORM
  176167. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  176168. # endif
  176169. # ifndef PNG_NO_READ_RGB_TO_GRAY
  176170. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  176171. # endif
  176172. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  176173. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  176174. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  176175. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  176176. #endif /* about interlacing capability! You'll */
  176177. /* still have interlacing unless you change the following line: */
  176178. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  176179. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  176180. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  176181. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  176182. # endif
  176183. #endif
  176184. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176185. /* Deprecated, will be removed from version 2.0.0.
  176186. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  176187. #ifndef PNG_NO_READ_EMPTY_PLTE
  176188. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  176189. #endif
  176190. #endif
  176191. #endif /* PNG_READ_SUPPORTED */
  176192. #if defined(PNG_WRITE_SUPPORTED)
  176193. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  176194. !defined(PNG_NO_WRITE_TRANSFORMS)
  176195. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  176196. #endif
  176197. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  176198. # ifndef PNG_NO_WRITE_SHIFT
  176199. # define PNG_WRITE_SHIFT_SUPPORTED
  176200. # endif
  176201. # ifndef PNG_NO_WRITE_PACK
  176202. # define PNG_WRITE_PACK_SUPPORTED
  176203. # endif
  176204. # ifndef PNG_NO_WRITE_BGR
  176205. # define PNG_WRITE_BGR_SUPPORTED
  176206. # endif
  176207. # ifndef PNG_NO_WRITE_SWAP
  176208. # define PNG_WRITE_SWAP_SUPPORTED
  176209. # endif
  176210. # ifndef PNG_NO_WRITE_PACKSWAP
  176211. # define PNG_WRITE_PACKSWAP_SUPPORTED
  176212. # endif
  176213. # ifndef PNG_NO_WRITE_INVERT
  176214. # define PNG_WRITE_INVERT_SUPPORTED
  176215. # endif
  176216. # ifndef PNG_NO_WRITE_FILLER
  176217. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  176218. # endif
  176219. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  176220. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  176221. # endif
  176222. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  176223. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  176224. # endif
  176225. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  176226. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  176227. # endif
  176228. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  176229. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  176230. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176231. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  176232. encoders, but can cause trouble
  176233. if left undefined */
  176234. #endif
  176235. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  176236. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  176237. defined(PNG_FLOATING_POINT_SUPPORTED)
  176238. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  176239. #endif
  176240. #ifndef PNG_NO_WRITE_FLUSH
  176241. # define PNG_WRITE_FLUSH_SUPPORTED
  176242. #endif
  176243. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176244. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  176245. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  176246. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  176247. #endif
  176248. #endif
  176249. #endif /* PNG_WRITE_SUPPORTED */
  176250. #ifndef PNG_1_0_X
  176251. # ifndef PNG_NO_ERROR_NUMBERS
  176252. # define PNG_ERROR_NUMBERS_SUPPORTED
  176253. # endif
  176254. #endif /* PNG_1_0_X */
  176255. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176256. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176257. # ifndef PNG_NO_USER_TRANSFORM_PTR
  176258. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  176259. # endif
  176260. #endif
  176261. #ifndef PNG_NO_STDIO
  176262. # define PNG_TIME_RFC1123_SUPPORTED
  176263. #endif
  176264. /* This adds extra functions in pngget.c for accessing data from the
  176265. * info pointer (added in version 0.99)
  176266. * png_get_image_width()
  176267. * png_get_image_height()
  176268. * png_get_bit_depth()
  176269. * png_get_color_type()
  176270. * png_get_compression_type()
  176271. * png_get_filter_type()
  176272. * png_get_interlace_type()
  176273. * png_get_pixel_aspect_ratio()
  176274. * png_get_pixels_per_meter()
  176275. * png_get_x_offset_pixels()
  176276. * png_get_y_offset_pixels()
  176277. * png_get_x_offset_microns()
  176278. * png_get_y_offset_microns()
  176279. */
  176280. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  176281. # define PNG_EASY_ACCESS_SUPPORTED
  176282. #endif
  176283. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  176284. * and removed from version 1.2.20. The following will be removed
  176285. * from libpng-1.4.0
  176286. */
  176287. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  176288. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  176289. # define PNG_OPTIMIZED_CODE_SUPPORTED
  176290. # endif
  176291. #endif
  176292. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  176293. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  176294. # define PNG_ASSEMBLER_CODE_SUPPORTED
  176295. # endif
  176296. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  176297. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  176298. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176299. # define PNG_NO_MMX_CODE
  176300. # endif
  176301. # endif
  176302. # if defined(__APPLE__)
  176303. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176304. # define PNG_NO_MMX_CODE
  176305. # endif
  176306. # endif
  176307. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  176308. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176309. # define PNG_NO_MMX_CODE
  176310. # endif
  176311. # endif
  176312. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176313. # define PNG_MMX_CODE_SUPPORTED
  176314. # endif
  176315. #endif
  176316. /* end of obsolete code to be removed from libpng-1.4.0 */
  176317. #if !defined(PNG_1_0_X)
  176318. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  176319. # define PNG_USER_MEM_SUPPORTED
  176320. #endif
  176321. #endif /* PNG_1_0_X */
  176322. /* Added at libpng-1.2.6 */
  176323. #if !defined(PNG_1_0_X)
  176324. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  176325. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  176326. # define PNG_SET_USER_LIMITS_SUPPORTED
  176327. #endif
  176328. #endif
  176329. #endif /* PNG_1_0_X */
  176330. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  176331. * how large, set these limits to 0x7fffffffL
  176332. */
  176333. #ifndef PNG_USER_WIDTH_MAX
  176334. # define PNG_USER_WIDTH_MAX 1000000L
  176335. #endif
  176336. #ifndef PNG_USER_HEIGHT_MAX
  176337. # define PNG_USER_HEIGHT_MAX 1000000L
  176338. #endif
  176339. /* These are currently experimental features, define them if you want */
  176340. /* very little testing */
  176341. /*
  176342. #ifdef PNG_READ_SUPPORTED
  176343. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176344. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176345. # endif
  176346. #endif
  176347. */
  176348. /* This is only for PowerPC big-endian and 680x0 systems */
  176349. /* some testing */
  176350. /*
  176351. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  176352. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  176353. #endif
  176354. */
  176355. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  176356. /*
  176357. #define PNG_NO_POINTER_INDEXING
  176358. */
  176359. /* These functions are turned off by default, as they will be phased out. */
  176360. /*
  176361. #define PNG_USELESS_TESTS_SUPPORTED
  176362. #define PNG_CORRECT_PALETTE_SUPPORTED
  176363. */
  176364. /* Any chunks you are not interested in, you can undef here. The
  176365. * ones that allocate memory may be expecially important (hIST,
  176366. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  176367. * a bit smaller.
  176368. */
  176369. #if defined(PNG_READ_SUPPORTED) && \
  176370. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  176371. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  176372. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  176373. #endif
  176374. #if defined(PNG_WRITE_SUPPORTED) && \
  176375. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  176376. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  176377. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  176378. #endif
  176379. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  176380. #ifdef PNG_NO_READ_TEXT
  176381. # define PNG_NO_READ_iTXt
  176382. # define PNG_NO_READ_tEXt
  176383. # define PNG_NO_READ_zTXt
  176384. #endif
  176385. #ifndef PNG_NO_READ_bKGD
  176386. # define PNG_READ_bKGD_SUPPORTED
  176387. # define PNG_bKGD_SUPPORTED
  176388. #endif
  176389. #ifndef PNG_NO_READ_cHRM
  176390. # define PNG_READ_cHRM_SUPPORTED
  176391. # define PNG_cHRM_SUPPORTED
  176392. #endif
  176393. #ifndef PNG_NO_READ_gAMA
  176394. # define PNG_READ_gAMA_SUPPORTED
  176395. # define PNG_gAMA_SUPPORTED
  176396. #endif
  176397. #ifndef PNG_NO_READ_hIST
  176398. # define PNG_READ_hIST_SUPPORTED
  176399. # define PNG_hIST_SUPPORTED
  176400. #endif
  176401. #ifndef PNG_NO_READ_iCCP
  176402. # define PNG_READ_iCCP_SUPPORTED
  176403. # define PNG_iCCP_SUPPORTED
  176404. #endif
  176405. #ifndef PNG_NO_READ_iTXt
  176406. # ifndef PNG_READ_iTXt_SUPPORTED
  176407. # define PNG_READ_iTXt_SUPPORTED
  176408. # endif
  176409. # ifndef PNG_iTXt_SUPPORTED
  176410. # define PNG_iTXt_SUPPORTED
  176411. # endif
  176412. #endif
  176413. #ifndef PNG_NO_READ_oFFs
  176414. # define PNG_READ_oFFs_SUPPORTED
  176415. # define PNG_oFFs_SUPPORTED
  176416. #endif
  176417. #ifndef PNG_NO_READ_pCAL
  176418. # define PNG_READ_pCAL_SUPPORTED
  176419. # define PNG_pCAL_SUPPORTED
  176420. #endif
  176421. #ifndef PNG_NO_READ_sCAL
  176422. # define PNG_READ_sCAL_SUPPORTED
  176423. # define PNG_sCAL_SUPPORTED
  176424. #endif
  176425. #ifndef PNG_NO_READ_pHYs
  176426. # define PNG_READ_pHYs_SUPPORTED
  176427. # define PNG_pHYs_SUPPORTED
  176428. #endif
  176429. #ifndef PNG_NO_READ_sBIT
  176430. # define PNG_READ_sBIT_SUPPORTED
  176431. # define PNG_sBIT_SUPPORTED
  176432. #endif
  176433. #ifndef PNG_NO_READ_sPLT
  176434. # define PNG_READ_sPLT_SUPPORTED
  176435. # define PNG_sPLT_SUPPORTED
  176436. #endif
  176437. #ifndef PNG_NO_READ_sRGB
  176438. # define PNG_READ_sRGB_SUPPORTED
  176439. # define PNG_sRGB_SUPPORTED
  176440. #endif
  176441. #ifndef PNG_NO_READ_tEXt
  176442. # define PNG_READ_tEXt_SUPPORTED
  176443. # define PNG_tEXt_SUPPORTED
  176444. #endif
  176445. #ifndef PNG_NO_READ_tIME
  176446. # define PNG_READ_tIME_SUPPORTED
  176447. # define PNG_tIME_SUPPORTED
  176448. #endif
  176449. #ifndef PNG_NO_READ_tRNS
  176450. # define PNG_READ_tRNS_SUPPORTED
  176451. # define PNG_tRNS_SUPPORTED
  176452. #endif
  176453. #ifndef PNG_NO_READ_zTXt
  176454. # define PNG_READ_zTXt_SUPPORTED
  176455. # define PNG_zTXt_SUPPORTED
  176456. #endif
  176457. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  176458. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  176459. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  176460. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  176461. # endif
  176462. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  176463. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176464. # endif
  176465. #endif
  176466. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  176467. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  176468. # define PNG_READ_USER_CHUNKS_SUPPORTED
  176469. # define PNG_USER_CHUNKS_SUPPORTED
  176470. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  176471. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  176472. # endif
  176473. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  176474. # undef PNG_NO_HANDLE_AS_UNKNOWN
  176475. # endif
  176476. #endif
  176477. #ifndef PNG_NO_READ_OPT_PLTE
  176478. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  176479. #endif /* optional PLTE chunk in RGB and RGBA images */
  176480. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  176481. defined(PNG_READ_zTXt_SUPPORTED)
  176482. # define PNG_READ_TEXT_SUPPORTED
  176483. # define PNG_TEXT_SUPPORTED
  176484. #endif
  176485. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  176486. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  176487. #ifdef PNG_NO_WRITE_TEXT
  176488. # define PNG_NO_WRITE_iTXt
  176489. # define PNG_NO_WRITE_tEXt
  176490. # define PNG_NO_WRITE_zTXt
  176491. #endif
  176492. #ifndef PNG_NO_WRITE_bKGD
  176493. # define PNG_WRITE_bKGD_SUPPORTED
  176494. # ifndef PNG_bKGD_SUPPORTED
  176495. # define PNG_bKGD_SUPPORTED
  176496. # endif
  176497. #endif
  176498. #ifndef PNG_NO_WRITE_cHRM
  176499. # define PNG_WRITE_cHRM_SUPPORTED
  176500. # ifndef PNG_cHRM_SUPPORTED
  176501. # define PNG_cHRM_SUPPORTED
  176502. # endif
  176503. #endif
  176504. #ifndef PNG_NO_WRITE_gAMA
  176505. # define PNG_WRITE_gAMA_SUPPORTED
  176506. # ifndef PNG_gAMA_SUPPORTED
  176507. # define PNG_gAMA_SUPPORTED
  176508. # endif
  176509. #endif
  176510. #ifndef PNG_NO_WRITE_hIST
  176511. # define PNG_WRITE_hIST_SUPPORTED
  176512. # ifndef PNG_hIST_SUPPORTED
  176513. # define PNG_hIST_SUPPORTED
  176514. # endif
  176515. #endif
  176516. #ifndef PNG_NO_WRITE_iCCP
  176517. # define PNG_WRITE_iCCP_SUPPORTED
  176518. # ifndef PNG_iCCP_SUPPORTED
  176519. # define PNG_iCCP_SUPPORTED
  176520. # endif
  176521. #endif
  176522. #ifndef PNG_NO_WRITE_iTXt
  176523. # ifndef PNG_WRITE_iTXt_SUPPORTED
  176524. # define PNG_WRITE_iTXt_SUPPORTED
  176525. # endif
  176526. # ifndef PNG_iTXt_SUPPORTED
  176527. # define PNG_iTXt_SUPPORTED
  176528. # endif
  176529. #endif
  176530. #ifndef PNG_NO_WRITE_oFFs
  176531. # define PNG_WRITE_oFFs_SUPPORTED
  176532. # ifndef PNG_oFFs_SUPPORTED
  176533. # define PNG_oFFs_SUPPORTED
  176534. # endif
  176535. #endif
  176536. #ifndef PNG_NO_WRITE_pCAL
  176537. # define PNG_WRITE_pCAL_SUPPORTED
  176538. # ifndef PNG_pCAL_SUPPORTED
  176539. # define PNG_pCAL_SUPPORTED
  176540. # endif
  176541. #endif
  176542. #ifndef PNG_NO_WRITE_sCAL
  176543. # define PNG_WRITE_sCAL_SUPPORTED
  176544. # ifndef PNG_sCAL_SUPPORTED
  176545. # define PNG_sCAL_SUPPORTED
  176546. # endif
  176547. #endif
  176548. #ifndef PNG_NO_WRITE_pHYs
  176549. # define PNG_WRITE_pHYs_SUPPORTED
  176550. # ifndef PNG_pHYs_SUPPORTED
  176551. # define PNG_pHYs_SUPPORTED
  176552. # endif
  176553. #endif
  176554. #ifndef PNG_NO_WRITE_sBIT
  176555. # define PNG_WRITE_sBIT_SUPPORTED
  176556. # ifndef PNG_sBIT_SUPPORTED
  176557. # define PNG_sBIT_SUPPORTED
  176558. # endif
  176559. #endif
  176560. #ifndef PNG_NO_WRITE_sPLT
  176561. # define PNG_WRITE_sPLT_SUPPORTED
  176562. # ifndef PNG_sPLT_SUPPORTED
  176563. # define PNG_sPLT_SUPPORTED
  176564. # endif
  176565. #endif
  176566. #ifndef PNG_NO_WRITE_sRGB
  176567. # define PNG_WRITE_sRGB_SUPPORTED
  176568. # ifndef PNG_sRGB_SUPPORTED
  176569. # define PNG_sRGB_SUPPORTED
  176570. # endif
  176571. #endif
  176572. #ifndef PNG_NO_WRITE_tEXt
  176573. # define PNG_WRITE_tEXt_SUPPORTED
  176574. # ifndef PNG_tEXt_SUPPORTED
  176575. # define PNG_tEXt_SUPPORTED
  176576. # endif
  176577. #endif
  176578. #ifndef PNG_NO_WRITE_tIME
  176579. # define PNG_WRITE_tIME_SUPPORTED
  176580. # ifndef PNG_tIME_SUPPORTED
  176581. # define PNG_tIME_SUPPORTED
  176582. # endif
  176583. #endif
  176584. #ifndef PNG_NO_WRITE_tRNS
  176585. # define PNG_WRITE_tRNS_SUPPORTED
  176586. # ifndef PNG_tRNS_SUPPORTED
  176587. # define PNG_tRNS_SUPPORTED
  176588. # endif
  176589. #endif
  176590. #ifndef PNG_NO_WRITE_zTXt
  176591. # define PNG_WRITE_zTXt_SUPPORTED
  176592. # ifndef PNG_zTXt_SUPPORTED
  176593. # define PNG_zTXt_SUPPORTED
  176594. # endif
  176595. #endif
  176596. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  176597. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  176598. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  176599. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  176600. # endif
  176601. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  176602. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176603. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176604. # endif
  176605. # endif
  176606. #endif
  176607. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  176608. defined(PNG_WRITE_zTXt_SUPPORTED)
  176609. # define PNG_WRITE_TEXT_SUPPORTED
  176610. # ifndef PNG_TEXT_SUPPORTED
  176611. # define PNG_TEXT_SUPPORTED
  176612. # endif
  176613. #endif
  176614. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  176615. /* Turn this off to disable png_read_png() and
  176616. * png_write_png() and leave the row_pointers member
  176617. * out of the info structure.
  176618. */
  176619. #ifndef PNG_NO_INFO_IMAGE
  176620. # define PNG_INFO_IMAGE_SUPPORTED
  176621. #endif
  176622. /* need the time information for reading tIME chunks */
  176623. #if defined(PNG_tIME_SUPPORTED)
  176624. # if !defined(_WIN32_WCE)
  176625. /* "time.h" functions are not supported on WindowsCE */
  176626. # include <time.h>
  176627. # endif
  176628. #endif
  176629. /* Some typedefs to get us started. These should be safe on most of the
  176630. * common platforms. The typedefs should be at least as large as the
  176631. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  176632. * don't have to be exactly that size. Some compilers dislike passing
  176633. * unsigned shorts as function parameters, so you may be better off using
  176634. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  176635. * want to have unsigned int for png_uint_32 instead of unsigned long.
  176636. */
  176637. typedef unsigned long png_uint_32;
  176638. typedef long png_int_32;
  176639. typedef unsigned short png_uint_16;
  176640. typedef short png_int_16;
  176641. typedef unsigned char png_byte;
  176642. /* This is usually size_t. It is typedef'ed just in case you need it to
  176643. change (I'm not sure if you will or not, so I thought I'd be safe) */
  176644. #ifdef PNG_SIZE_T
  176645. typedef PNG_SIZE_T png_size_t;
  176646. # define png_sizeof(x) png_convert_size(sizeof (x))
  176647. #else
  176648. typedef size_t png_size_t;
  176649. # define png_sizeof(x) sizeof (x)
  176650. #endif
  176651. /* The following is needed for medium model support. It cannot be in the
  176652. * PNG_INTERNAL section. Needs modification for other compilers besides
  176653. * MSC. Model independent support declares all arrays and pointers to be
  176654. * large using the far keyword. The zlib version used must also support
  176655. * model independent data. As of version zlib 1.0.4, the necessary changes
  176656. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  176657. * changes that are needed. (Tim Wegner)
  176658. */
  176659. /* Separate compiler dependencies (problem here is that zlib.h always
  176660. defines FAR. (SJT) */
  176661. #ifdef __BORLANDC__
  176662. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  176663. # define LDATA 1
  176664. # else
  176665. # define LDATA 0
  176666. # endif
  176667. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  176668. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  176669. # define PNG_MAX_MALLOC_64K
  176670. # if (LDATA != 1)
  176671. # ifndef FAR
  176672. # define FAR __far
  176673. # endif
  176674. # define USE_FAR_KEYWORD
  176675. # endif /* LDATA != 1 */
  176676. /* Possibly useful for moving data out of default segment.
  176677. * Uncomment it if you want. Could also define FARDATA as
  176678. * const if your compiler supports it. (SJT)
  176679. # define FARDATA FAR
  176680. */
  176681. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  176682. #endif /* __BORLANDC__ */
  176683. /* Suggest testing for specific compiler first before testing for
  176684. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  176685. * making reliance oncertain keywords suspect. (SJT)
  176686. */
  176687. /* MSC Medium model */
  176688. #if defined(FAR)
  176689. # if defined(M_I86MM)
  176690. # define USE_FAR_KEYWORD
  176691. # define FARDATA FAR
  176692. # include <dos.h>
  176693. # endif
  176694. #endif
  176695. /* SJT: default case */
  176696. #ifndef FAR
  176697. # define FAR
  176698. #endif
  176699. /* At this point FAR is always defined */
  176700. #ifndef FARDATA
  176701. # define FARDATA
  176702. #endif
  176703. /* Typedef for floating-point numbers that are converted
  176704. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  176705. typedef png_int_32 png_fixed_point;
  176706. /* Add typedefs for pointers */
  176707. typedef void FAR * png_voidp;
  176708. typedef png_byte FAR * png_bytep;
  176709. typedef png_uint_32 FAR * png_uint_32p;
  176710. typedef png_int_32 FAR * png_int_32p;
  176711. typedef png_uint_16 FAR * png_uint_16p;
  176712. typedef png_int_16 FAR * png_int_16p;
  176713. typedef PNG_CONST char FAR * png_const_charp;
  176714. typedef char FAR * png_charp;
  176715. typedef png_fixed_point FAR * png_fixed_point_p;
  176716. #ifndef PNG_NO_STDIO
  176717. #if defined(_WIN32_WCE)
  176718. typedef HANDLE png_FILE_p;
  176719. #else
  176720. typedef FILE * png_FILE_p;
  176721. #endif
  176722. #endif
  176723. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176724. typedef double FAR * png_doublep;
  176725. #endif
  176726. /* Pointers to pointers; i.e. arrays */
  176727. typedef png_byte FAR * FAR * png_bytepp;
  176728. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  176729. typedef png_int_32 FAR * FAR * png_int_32pp;
  176730. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  176731. typedef png_int_16 FAR * FAR * png_int_16pp;
  176732. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  176733. typedef char FAR * FAR * png_charpp;
  176734. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  176735. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176736. typedef double FAR * FAR * png_doublepp;
  176737. #endif
  176738. /* Pointers to pointers to pointers; i.e., pointer to array */
  176739. typedef char FAR * FAR * FAR * png_charppp;
  176740. #if 0
  176741. /* SPC - Is this stuff deprecated? */
  176742. /* It'll be removed as of libpng-1.3.0 - GR-P */
  176743. /* libpng typedefs for types in zlib. If zlib changes
  176744. * or another compression library is used, then change these.
  176745. * Eliminates need to change all the source files.
  176746. */
  176747. typedef charf * png_zcharp;
  176748. typedef charf * FAR * png_zcharpp;
  176749. typedef z_stream FAR * png_zstreamp;
  176750. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  176751. /*
  176752. * Define PNG_BUILD_DLL if the module being built is a Windows
  176753. * LIBPNG DLL.
  176754. *
  176755. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  176756. * It is equivalent to Microsoft predefined macro _DLL that is
  176757. * automatically defined when you compile using the share
  176758. * version of the CRT (C Run-Time library)
  176759. *
  176760. * The cygwin mods make this behavior a little different:
  176761. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  176762. * Define PNG_STATIC if you are building a static library for use with cygwin,
  176763. * -or- if you are building an application that you want to link to the
  176764. * static library.
  176765. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  176766. * the other flags is defined.
  176767. */
  176768. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  176769. # define PNG_DLL
  176770. #endif
  176771. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  176772. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  176773. * command-line override
  176774. */
  176775. #if defined(__CYGWIN__)
  176776. # if !defined(PNG_STATIC)
  176777. # if defined(PNG_USE_GLOBAL_ARRAYS)
  176778. # undef PNG_USE_GLOBAL_ARRAYS
  176779. # endif
  176780. # if !defined(PNG_USE_LOCAL_ARRAYS)
  176781. # define PNG_USE_LOCAL_ARRAYS
  176782. # endif
  176783. # else
  176784. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  176785. # if defined(PNG_USE_GLOBAL_ARRAYS)
  176786. # undef PNG_USE_GLOBAL_ARRAYS
  176787. # endif
  176788. # endif
  176789. # endif
  176790. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  176791. # define PNG_USE_LOCAL_ARRAYS
  176792. # endif
  176793. #endif
  176794. /* Do not use global arrays (helps with building DLL's)
  176795. * They are no longer used in libpng itself, since version 1.0.5c,
  176796. * but might be required for some pre-1.0.5c applications.
  176797. */
  176798. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  176799. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  176800. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  176801. # define PNG_USE_LOCAL_ARRAYS
  176802. # else
  176803. # define PNG_USE_GLOBAL_ARRAYS
  176804. # endif
  176805. #endif
  176806. #if defined(__CYGWIN__)
  176807. # undef PNGAPI
  176808. # define PNGAPI __cdecl
  176809. # undef PNG_IMPEXP
  176810. # define PNG_IMPEXP
  176811. #endif
  176812. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  176813. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  176814. * Don't ignore those warnings; you must also reset the default calling
  176815. * convention in your compiler to match your PNGAPI, and you must build
  176816. * zlib and your applications the same way you build libpng.
  176817. */
  176818. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  176819. # ifndef PNG_NO_MODULEDEF
  176820. # define PNG_NO_MODULEDEF
  176821. # endif
  176822. #endif
  176823. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  176824. # define PNG_IMPEXP
  176825. #endif
  176826. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  176827. (( defined(_Windows) || defined(_WINDOWS) || \
  176828. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  176829. # ifndef PNGAPI
  176830. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  176831. # define PNGAPI __cdecl
  176832. # else
  176833. # define PNGAPI _cdecl
  176834. # endif
  176835. # endif
  176836. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  176837. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  176838. # define PNG_IMPEXP
  176839. # endif
  176840. # if !defined(PNG_IMPEXP)
  176841. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  176842. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  176843. /* Borland/Microsoft */
  176844. # if defined(_MSC_VER) || defined(__BORLANDC__)
  176845. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  176846. # define PNG_EXPORT PNG_EXPORT_TYPE1
  176847. # else
  176848. # define PNG_EXPORT PNG_EXPORT_TYPE2
  176849. # if defined(PNG_BUILD_DLL)
  176850. # define PNG_IMPEXP __export
  176851. # else
  176852. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  176853. VC++ */
  176854. # endif /* Exists in Borland C++ for
  176855. C++ classes (== huge) */
  176856. # endif
  176857. # endif
  176858. # if !defined(PNG_IMPEXP)
  176859. # if defined(PNG_BUILD_DLL)
  176860. # define PNG_IMPEXP __declspec(dllexport)
  176861. # else
  176862. # define PNG_IMPEXP __declspec(dllimport)
  176863. # endif
  176864. # endif
  176865. # endif /* PNG_IMPEXP */
  176866. #else /* !(DLL || non-cygwin WINDOWS) */
  176867. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  176868. # ifndef PNGAPI
  176869. # define PNGAPI _System
  176870. # endif
  176871. # else
  176872. # if 0 /* ... other platforms, with other meanings */
  176873. # endif
  176874. # endif
  176875. #endif
  176876. #ifndef PNGAPI
  176877. # define PNGAPI
  176878. #endif
  176879. #ifndef PNG_IMPEXP
  176880. # define PNG_IMPEXP
  176881. #endif
  176882. #ifdef PNG_BUILDSYMS
  176883. # ifndef PNG_EXPORT
  176884. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  176885. # endif
  176886. # ifdef PNG_USE_GLOBAL_ARRAYS
  176887. # ifndef PNG_EXPORT_VAR
  176888. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  176889. # endif
  176890. # endif
  176891. #endif
  176892. #ifndef PNG_EXPORT
  176893. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  176894. #endif
  176895. #ifdef PNG_USE_GLOBAL_ARRAYS
  176896. # ifndef PNG_EXPORT_VAR
  176897. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  176898. # endif
  176899. #endif
  176900. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  176901. * functions that are passed far data must be model independent.
  176902. */
  176903. #ifndef PNG_ABORT
  176904. # define PNG_ABORT() abort()
  176905. #endif
  176906. #ifdef PNG_SETJMP_SUPPORTED
  176907. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  176908. #else
  176909. # define png_jmpbuf(png_ptr) \
  176910. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  176911. #endif
  176912. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  176913. /* use this to make far-to-near assignments */
  176914. # define CHECK 1
  176915. # define NOCHECK 0
  176916. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  176917. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  176918. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  176919. # define png_strcpy _fstrcpy
  176920. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  176921. # define png_strlen _fstrlen
  176922. # define png_memcmp _fmemcmp /* SJT: added */
  176923. # define png_memcpy _fmemcpy
  176924. # define png_memset _fmemset
  176925. #else /* use the usual functions */
  176926. # define CVT_PTR(ptr) (ptr)
  176927. # define CVT_PTR_NOCHECK(ptr) (ptr)
  176928. # ifndef PNG_NO_SNPRINTF
  176929. # ifdef _MSC_VER
  176930. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  176931. # define png_snprintf2 _snprintf
  176932. # define png_snprintf6 _snprintf
  176933. # else
  176934. # define png_snprintf snprintf /* Added to v 1.2.19 */
  176935. # define png_snprintf2 snprintf
  176936. # define png_snprintf6 snprintf
  176937. # endif
  176938. # else
  176939. /* You don't have or don't want to use snprintf(). Caution: Using
  176940. * sprintf instead of snprintf exposes your application to accidental
  176941. * or malevolent buffer overflows. If you don't have snprintf()
  176942. * as a general rule you should provide one (you can get one from
  176943. * Portable OpenSSH). */
  176944. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  176945. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  176946. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  176947. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  176948. # endif
  176949. # define png_strcpy strcpy
  176950. # define png_strncpy strncpy /* Added to v 1.2.6 */
  176951. # define png_strlen strlen
  176952. # define png_memcmp memcmp /* SJT: added */
  176953. # define png_memcpy memcpy
  176954. # define png_memset memset
  176955. #endif
  176956. /* End of memory model independent support */
  176957. /* Just a little check that someone hasn't tried to define something
  176958. * contradictory.
  176959. */
  176960. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  176961. # undef PNG_ZBUF_SIZE
  176962. # define PNG_ZBUF_SIZE 65536L
  176963. #endif
  176964. /* Added at libpng-1.2.8 */
  176965. #endif /* PNG_VERSION_INFO_ONLY */
  176966. #endif /* PNGCONF_H */
  176967. /********* End of inlined file: pngconf.h *********/
  176968. #ifdef _MSC_VER
  176969. #pragma warning (disable: 4996 4100)
  176970. #endif
  176971. /*
  176972. * Added at libpng-1.2.8 */
  176973. /* Ref MSDN: Private as priority over Special
  176974. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  176975. * procedures. If this value is given, the StringFileInfo block must
  176976. * contain a PrivateBuild string.
  176977. *
  176978. * VS_FF_SPECIALBUILD File *was* built by the original company using
  176979. * standard release procedures but is a variation of the standard
  176980. * file of the same version number. If this value is given, the
  176981. * StringFileInfo block must contain a SpecialBuild string.
  176982. */
  176983. #if defined(PNG_USER_PRIVATEBUILD)
  176984. # define PNG_LIBPNG_BUILD_TYPE \
  176985. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  176986. #else
  176987. # if defined(PNG_LIBPNG_SPECIALBUILD)
  176988. # define PNG_LIBPNG_BUILD_TYPE \
  176989. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  176990. # else
  176991. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  176992. # endif
  176993. #endif
  176994. #ifndef PNG_VERSION_INFO_ONLY
  176995. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  176996. #ifdef __cplusplus
  176997. extern "C" {
  176998. #endif /* __cplusplus */
  176999. /* This file is arranged in several sections. The first section contains
  177000. * structure and type definitions. The second section contains the external
  177001. * library functions, while the third has the internal library functions,
  177002. * which applications aren't expected to use directly.
  177003. */
  177004. #ifndef PNG_NO_TYPECAST_NULL
  177005. #define int_p_NULL (int *)NULL
  177006. #define png_bytep_NULL (png_bytep)NULL
  177007. #define png_bytepp_NULL (png_bytepp)NULL
  177008. #define png_doublep_NULL (png_doublep)NULL
  177009. #define png_error_ptr_NULL (png_error_ptr)NULL
  177010. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  177011. #define png_free_ptr_NULL (png_free_ptr)NULL
  177012. #define png_infopp_NULL (png_infopp)NULL
  177013. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  177014. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  177015. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  177016. #define png_structp_NULL (png_structp)NULL
  177017. #define png_uint_16p_NULL (png_uint_16p)NULL
  177018. #define png_voidp_NULL (png_voidp)NULL
  177019. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  177020. #else
  177021. #define int_p_NULL NULL
  177022. #define png_bytep_NULL NULL
  177023. #define png_bytepp_NULL NULL
  177024. #define png_doublep_NULL NULL
  177025. #define png_error_ptr_NULL NULL
  177026. #define png_flush_ptr_NULL NULL
  177027. #define png_free_ptr_NULL NULL
  177028. #define png_infopp_NULL NULL
  177029. #define png_malloc_ptr_NULL NULL
  177030. #define png_read_status_ptr_NULL NULL
  177031. #define png_rw_ptr_NULL NULL
  177032. #define png_structp_NULL NULL
  177033. #define png_uint_16p_NULL NULL
  177034. #define png_voidp_NULL NULL
  177035. #define png_write_status_ptr_NULL NULL
  177036. #endif
  177037. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  177038. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  177039. /* Version information for C files, stored in png.c. This had better match
  177040. * the version above.
  177041. */
  177042. #ifdef PNG_USE_GLOBAL_ARRAYS
  177043. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  177044. /* need room for 99.99.99beta99z */
  177045. #else
  177046. #define png_libpng_ver png_get_header_ver(NULL)
  177047. #endif
  177048. #ifdef PNG_USE_GLOBAL_ARRAYS
  177049. /* This was removed in version 1.0.5c */
  177050. /* Structures to facilitate easy interlacing. See png.c for more details */
  177051. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  177052. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  177053. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  177054. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  177055. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  177056. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  177057. /* This isn't currently used. If you need it, see png.c for more details.
  177058. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  177059. */
  177060. #endif
  177061. #endif /* PNG_NO_EXTERN */
  177062. /* Three color definitions. The order of the red, green, and blue, (and the
  177063. * exact size) is not important, although the size of the fields need to
  177064. * be png_byte or png_uint_16 (as defined below).
  177065. */
  177066. typedef struct png_color_struct
  177067. {
  177068. png_byte red;
  177069. png_byte green;
  177070. png_byte blue;
  177071. } png_color;
  177072. typedef png_color FAR * png_colorp;
  177073. typedef png_color FAR * FAR * png_colorpp;
  177074. typedef struct png_color_16_struct
  177075. {
  177076. png_byte index; /* used for palette files */
  177077. png_uint_16 red; /* for use in red green blue files */
  177078. png_uint_16 green;
  177079. png_uint_16 blue;
  177080. png_uint_16 gray; /* for use in grayscale files */
  177081. } png_color_16;
  177082. typedef png_color_16 FAR * png_color_16p;
  177083. typedef png_color_16 FAR * FAR * png_color_16pp;
  177084. typedef struct png_color_8_struct
  177085. {
  177086. png_byte red; /* for use in red green blue files */
  177087. png_byte green;
  177088. png_byte blue;
  177089. png_byte gray; /* for use in grayscale files */
  177090. png_byte alpha; /* for alpha channel files */
  177091. } png_color_8;
  177092. typedef png_color_8 FAR * png_color_8p;
  177093. typedef png_color_8 FAR * FAR * png_color_8pp;
  177094. /*
  177095. * The following two structures are used for the in-core representation
  177096. * of sPLT chunks.
  177097. */
  177098. typedef struct png_sPLT_entry_struct
  177099. {
  177100. png_uint_16 red;
  177101. png_uint_16 green;
  177102. png_uint_16 blue;
  177103. png_uint_16 alpha;
  177104. png_uint_16 frequency;
  177105. } png_sPLT_entry;
  177106. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  177107. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  177108. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  177109. * occupy the LSB of their respective members, and the MSB of each member
  177110. * is zero-filled. The frequency member always occupies the full 16 bits.
  177111. */
  177112. typedef struct png_sPLT_struct
  177113. {
  177114. png_charp name; /* palette name */
  177115. png_byte depth; /* depth of palette samples */
  177116. png_sPLT_entryp entries; /* palette entries */
  177117. png_int_32 nentries; /* number of palette entries */
  177118. } png_sPLT_t;
  177119. typedef png_sPLT_t FAR * png_sPLT_tp;
  177120. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  177121. #ifdef PNG_TEXT_SUPPORTED
  177122. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  177123. * and whether that contents is compressed or not. The "key" field
  177124. * points to a regular zero-terminated C string. The "text", "lang", and
  177125. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  177126. * However, the * structure returned by png_get_text() will always contain
  177127. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  177128. * so they can be safely used in printf() and other string-handling functions.
  177129. */
  177130. typedef struct png_text_struct
  177131. {
  177132. int compression; /* compression value:
  177133. -1: tEXt, none
  177134. 0: zTXt, deflate
  177135. 1: iTXt, none
  177136. 2: iTXt, deflate */
  177137. png_charp key; /* keyword, 1-79 character description of "text" */
  177138. png_charp text; /* comment, may be an empty string (ie "")
  177139. or a NULL pointer */
  177140. png_size_t text_length; /* length of the text string */
  177141. #ifdef PNG_iTXt_SUPPORTED
  177142. png_size_t itxt_length; /* length of the itxt string */
  177143. png_charp lang; /* language code, 0-79 characters
  177144. or a NULL pointer */
  177145. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  177146. chars or a NULL pointer */
  177147. #endif
  177148. } png_text;
  177149. typedef png_text FAR * png_textp;
  177150. typedef png_text FAR * FAR * png_textpp;
  177151. #endif
  177152. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  177153. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  177154. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  177155. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  177156. #define PNG_TEXT_COMPRESSION_NONE -1
  177157. #define PNG_TEXT_COMPRESSION_zTXt 0
  177158. #define PNG_ITXT_COMPRESSION_NONE 1
  177159. #define PNG_ITXT_COMPRESSION_zTXt 2
  177160. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  177161. /* png_time is a way to hold the time in an machine independent way.
  177162. * Two conversions are provided, both from time_t and struct tm. There
  177163. * is no portable way to convert to either of these structures, as far
  177164. * as I know. If you know of a portable way, send it to me. As a side
  177165. * note - PNG has always been Year 2000 compliant!
  177166. */
  177167. typedef struct png_time_struct
  177168. {
  177169. png_uint_16 year; /* full year, as in, 1995 */
  177170. png_byte month; /* month of year, 1 - 12 */
  177171. png_byte day; /* day of month, 1 - 31 */
  177172. png_byte hour; /* hour of day, 0 - 23 */
  177173. png_byte minute; /* minute of hour, 0 - 59 */
  177174. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  177175. } png_time;
  177176. typedef png_time FAR * png_timep;
  177177. typedef png_time FAR * FAR * png_timepp;
  177178. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177179. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  177180. * no specific support. The idea is that we can use this to queue
  177181. * up private chunks for output even though the library doesn't actually
  177182. * know about their semantics.
  177183. */
  177184. typedef struct png_unknown_chunk_t
  177185. {
  177186. png_byte name[5];
  177187. png_byte *data;
  177188. png_size_t size;
  177189. /* libpng-using applications should NOT directly modify this byte. */
  177190. png_byte location; /* mode of operation at read time */
  177191. }
  177192. png_unknown_chunk;
  177193. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  177194. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  177195. #endif
  177196. /* png_info is a structure that holds the information in a PNG file so
  177197. * that the application can find out the characteristics of the image.
  177198. * If you are reading the file, this structure will tell you what is
  177199. * in the PNG file. If you are writing the file, fill in the information
  177200. * you want to put into the PNG file, then call png_write_info().
  177201. * The names chosen should be very close to the PNG specification, so
  177202. * consult that document for information about the meaning of each field.
  177203. *
  177204. * With libpng < 0.95, it was only possible to directly set and read the
  177205. * the values in the png_info_struct, which meant that the contents and
  177206. * order of the values had to remain fixed. With libpng 0.95 and later,
  177207. * however, there are now functions that abstract the contents of
  177208. * png_info_struct from the application, so this makes it easier to use
  177209. * libpng with dynamic libraries, and even makes it possible to use
  177210. * libraries that don't have all of the libpng ancillary chunk-handing
  177211. * functionality.
  177212. *
  177213. * In any case, the order of the parameters in png_info_struct should NOT
  177214. * be changed for as long as possible to keep compatibility with applications
  177215. * that use the old direct-access method with png_info_struct.
  177216. *
  177217. * The following members may have allocated storage attached that should be
  177218. * cleaned up before the structure is discarded: palette, trans, text,
  177219. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  177220. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  177221. * are automatically freed when the info structure is deallocated, if they were
  177222. * allocated internally by libpng. This behavior can be changed by means
  177223. * of the png_data_freer() function.
  177224. *
  177225. * More allocation details: all the chunk-reading functions that
  177226. * change these members go through the corresponding png_set_*
  177227. * functions. A function to clear these members is available: see
  177228. * png_free_data(). The png_set_* functions do not depend on being
  177229. * able to point info structure members to any of the storage they are
  177230. * passed (they make their own copies), EXCEPT that the png_set_text
  177231. * functions use the same storage passed to them in the text_ptr or
  177232. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  177233. * functions do not make their own copies.
  177234. */
  177235. typedef struct png_info_struct
  177236. {
  177237. /* the following are necessary for every PNG file */
  177238. png_uint_32 width; /* width of image in pixels (from IHDR) */
  177239. png_uint_32 height; /* height of image in pixels (from IHDR) */
  177240. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  177241. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  177242. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  177243. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  177244. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  177245. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  177246. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  177247. /* The following three should have been named *_method not *_type */
  177248. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  177249. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  177250. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  177251. /* The following is informational only on read, and not used on writes. */
  177252. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  177253. png_byte pixel_depth; /* number of bits per pixel */
  177254. png_byte spare_byte; /* to align the data, and for future use */
  177255. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  177256. /* The rest of the data is optional. If you are reading, check the
  177257. * valid field to see if the information in these are valid. If you
  177258. * are writing, set the valid field to those chunks you want written,
  177259. * and initialize the appropriate fields below.
  177260. */
  177261. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  177262. /* The gAMA chunk describes the gamma characteristics of the system
  177263. * on which the image was created, normally in the range [1.0, 2.5].
  177264. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  177265. */
  177266. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  177267. #endif
  177268. #if defined(PNG_sRGB_SUPPORTED)
  177269. /* GR-P, 0.96a */
  177270. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  177271. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  177272. #endif
  177273. #if defined(PNG_TEXT_SUPPORTED)
  177274. /* The tEXt, and zTXt chunks contain human-readable textual data in
  177275. * uncompressed, compressed, and optionally compressed forms, respectively.
  177276. * The data in "text" is an array of pointers to uncompressed,
  177277. * null-terminated C strings. Each chunk has a keyword that describes the
  177278. * textual data contained in that chunk. Keywords are not required to be
  177279. * unique, and the text string may be empty. Any number of text chunks may
  177280. * be in an image.
  177281. */
  177282. int num_text; /* number of comments read/to write */
  177283. int max_text; /* current size of text array */
  177284. png_textp text; /* array of comments read/to write */
  177285. #endif /* PNG_TEXT_SUPPORTED */
  177286. #if defined(PNG_tIME_SUPPORTED)
  177287. /* The tIME chunk holds the last time the displayed image data was
  177288. * modified. See the png_time struct for the contents of this struct.
  177289. */
  177290. png_time mod_time;
  177291. #endif
  177292. #if defined(PNG_sBIT_SUPPORTED)
  177293. /* The sBIT chunk specifies the number of significant high-order bits
  177294. * in the pixel data. Values are in the range [1, bit_depth], and are
  177295. * only specified for the channels in the pixel data. The contents of
  177296. * the low-order bits is not specified. Data is valid if
  177297. * (valid & PNG_INFO_sBIT) is non-zero.
  177298. */
  177299. png_color_8 sig_bit; /* significant bits in color channels */
  177300. #endif
  177301. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  177302. defined(PNG_READ_BACKGROUND_SUPPORTED)
  177303. /* The tRNS chunk supplies transparency data for paletted images and
  177304. * other image types that don't need a full alpha channel. There are
  177305. * "num_trans" transparency values for a paletted image, stored in the
  177306. * same order as the palette colors, starting from index 0. Values
  177307. * for the data are in the range [0, 255], ranging from fully transparent
  177308. * to fully opaque, respectively. For non-paletted images, there is a
  177309. * single color specified that should be treated as fully transparent.
  177310. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  177311. */
  177312. png_bytep trans; /* transparent values for paletted image */
  177313. png_color_16 trans_values; /* transparent color for non-palette image */
  177314. #endif
  177315. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177316. /* The bKGD chunk gives the suggested image background color if the
  177317. * display program does not have its own background color and the image
  177318. * is needs to composited onto a background before display. The colors
  177319. * in "background" are normally in the same color space/depth as the
  177320. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  177321. */
  177322. png_color_16 background;
  177323. #endif
  177324. #if defined(PNG_oFFs_SUPPORTED)
  177325. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  177326. * and downwards from the top-left corner of the display, page, or other
  177327. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  177328. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  177329. */
  177330. png_int_32 x_offset; /* x offset on page */
  177331. png_int_32 y_offset; /* y offset on page */
  177332. png_byte offset_unit_type; /* offset units type */
  177333. #endif
  177334. #if defined(PNG_pHYs_SUPPORTED)
  177335. /* The pHYs chunk gives the physical pixel density of the image for
  177336. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  177337. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  177338. */
  177339. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  177340. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  177341. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  177342. #endif
  177343. #if defined(PNG_hIST_SUPPORTED)
  177344. /* The hIST chunk contains the relative frequency or importance of the
  177345. * various palette entries, so that a viewer can intelligently select a
  177346. * reduced-color palette, if required. Data is an array of "num_palette"
  177347. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  177348. * is non-zero.
  177349. */
  177350. png_uint_16p hist;
  177351. #endif
  177352. #ifdef PNG_cHRM_SUPPORTED
  177353. /* The cHRM chunk describes the CIE color characteristics of the monitor
  177354. * on which the PNG was created. This data allows the viewer to do gamut
  177355. * mapping of the input image to ensure that the viewer sees the same
  177356. * colors in the image as the creator. Values are in the range
  177357. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  177358. */
  177359. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177360. float x_white;
  177361. float y_white;
  177362. float x_red;
  177363. float y_red;
  177364. float x_green;
  177365. float y_green;
  177366. float x_blue;
  177367. float y_blue;
  177368. #endif
  177369. #endif
  177370. #if defined(PNG_pCAL_SUPPORTED)
  177371. /* The pCAL chunk describes a transformation between the stored pixel
  177372. * values and original physical data values used to create the image.
  177373. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  177374. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  177375. * (possibly non-linear) transformation function given by "pcal_type"
  177376. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  177377. * defines below, and the PNG-Group's PNG extensions document for a
  177378. * complete description of the transformations and how they should be
  177379. * implemented, and for a description of the ASCII parameter strings.
  177380. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  177381. */
  177382. png_charp pcal_purpose; /* pCAL chunk description string */
  177383. png_int_32 pcal_X0; /* minimum value */
  177384. png_int_32 pcal_X1; /* maximum value */
  177385. png_charp pcal_units; /* Latin-1 string giving physical units */
  177386. png_charpp pcal_params; /* ASCII strings containing parameter values */
  177387. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  177388. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  177389. #endif
  177390. /* New members added in libpng-1.0.6 */
  177391. #ifdef PNG_FREE_ME_SUPPORTED
  177392. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  177393. #endif
  177394. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177395. /* storage for unknown chunks that the library doesn't recognize. */
  177396. png_unknown_chunkp unknown_chunks;
  177397. png_size_t unknown_chunks_num;
  177398. #endif
  177399. #if defined(PNG_iCCP_SUPPORTED)
  177400. /* iCCP chunk data. */
  177401. png_charp iccp_name; /* profile name */
  177402. png_charp iccp_profile; /* International Color Consortium profile data */
  177403. /* Note to maintainer: should be png_bytep */
  177404. png_uint_32 iccp_proflen; /* ICC profile data length */
  177405. png_byte iccp_compression; /* Always zero */
  177406. #endif
  177407. #if defined(PNG_sPLT_SUPPORTED)
  177408. /* data on sPLT chunks (there may be more than one). */
  177409. png_sPLT_tp splt_palettes;
  177410. png_uint_32 splt_palettes_num;
  177411. #endif
  177412. #if defined(PNG_sCAL_SUPPORTED)
  177413. /* The sCAL chunk describes the actual physical dimensions of the
  177414. * subject matter of the graphic. The chunk contains a unit specification
  177415. * a byte value, and two ASCII strings representing floating-point
  177416. * values. The values are width and height corresponsing to one pixel
  177417. * in the image. This external representation is converted to double
  177418. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  177419. */
  177420. png_byte scal_unit; /* unit of physical scale */
  177421. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177422. double scal_pixel_width; /* width of one pixel */
  177423. double scal_pixel_height; /* height of one pixel */
  177424. #endif
  177425. #ifdef PNG_FIXED_POINT_SUPPORTED
  177426. png_charp scal_s_width; /* string containing height */
  177427. png_charp scal_s_height; /* string containing width */
  177428. #endif
  177429. #endif
  177430. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177431. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  177432. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  177433. png_bytepp row_pointers; /* the image bits */
  177434. #endif
  177435. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  177436. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  177437. #endif
  177438. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  177439. png_fixed_point int_x_white;
  177440. png_fixed_point int_y_white;
  177441. png_fixed_point int_x_red;
  177442. png_fixed_point int_y_red;
  177443. png_fixed_point int_x_green;
  177444. png_fixed_point int_y_green;
  177445. png_fixed_point int_x_blue;
  177446. png_fixed_point int_y_blue;
  177447. #endif
  177448. } png_info;
  177449. typedef png_info FAR * png_infop;
  177450. typedef png_info FAR * FAR * png_infopp;
  177451. /* Maximum positive integer used in PNG is (2^31)-1 */
  177452. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  177453. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  177454. #define PNG_SIZE_MAX ((png_size_t)(-1))
  177455. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177456. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  177457. #define PNG_MAX_UINT PNG_UINT_31_MAX
  177458. #endif
  177459. /* These describe the color_type field in png_info. */
  177460. /* color type masks */
  177461. #define PNG_COLOR_MASK_PALETTE 1
  177462. #define PNG_COLOR_MASK_COLOR 2
  177463. #define PNG_COLOR_MASK_ALPHA 4
  177464. /* color types. Note that not all combinations are legal */
  177465. #define PNG_COLOR_TYPE_GRAY 0
  177466. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  177467. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  177468. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  177469. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  177470. /* aliases */
  177471. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  177472. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  177473. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  177474. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  177475. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  177476. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  177477. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  177478. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  177479. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  177480. /* These are for the interlacing type. These values should NOT be changed. */
  177481. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  177482. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  177483. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  177484. /* These are for the oFFs chunk. These values should NOT be changed. */
  177485. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  177486. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  177487. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  177488. /* These are for the pCAL chunk. These values should NOT be changed. */
  177489. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  177490. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  177491. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  177492. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  177493. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  177494. /* These are for the sCAL chunk. These values should NOT be changed. */
  177495. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  177496. #define PNG_SCALE_METER 1 /* meters per pixel */
  177497. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  177498. #define PNG_SCALE_LAST 3 /* Not a valid value */
  177499. /* These are for the pHYs chunk. These values should NOT be changed. */
  177500. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  177501. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  177502. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  177503. /* These are for the sRGB chunk. These values should NOT be changed. */
  177504. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  177505. #define PNG_sRGB_INTENT_RELATIVE 1
  177506. #define PNG_sRGB_INTENT_SATURATION 2
  177507. #define PNG_sRGB_INTENT_ABSOLUTE 3
  177508. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  177509. /* This is for text chunks */
  177510. #define PNG_KEYWORD_MAX_LENGTH 79
  177511. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  177512. #define PNG_MAX_PALETTE_LENGTH 256
  177513. /* These determine if an ancillary chunk's data has been successfully read
  177514. * from the PNG header, or if the application has filled in the corresponding
  177515. * data in the info_struct to be written into the output file. The values
  177516. * of the PNG_INFO_<chunk> defines should NOT be changed.
  177517. */
  177518. #define PNG_INFO_gAMA 0x0001
  177519. #define PNG_INFO_sBIT 0x0002
  177520. #define PNG_INFO_cHRM 0x0004
  177521. #define PNG_INFO_PLTE 0x0008
  177522. #define PNG_INFO_tRNS 0x0010
  177523. #define PNG_INFO_bKGD 0x0020
  177524. #define PNG_INFO_hIST 0x0040
  177525. #define PNG_INFO_pHYs 0x0080
  177526. #define PNG_INFO_oFFs 0x0100
  177527. #define PNG_INFO_tIME 0x0200
  177528. #define PNG_INFO_pCAL 0x0400
  177529. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  177530. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  177531. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  177532. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  177533. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  177534. /* This is used for the transformation routines, as some of them
  177535. * change these values for the row. It also should enable using
  177536. * the routines for other purposes.
  177537. */
  177538. typedef struct png_row_info_struct
  177539. {
  177540. png_uint_32 width; /* width of row */
  177541. png_uint_32 rowbytes; /* number of bytes in row */
  177542. png_byte color_type; /* color type of row */
  177543. png_byte bit_depth; /* bit depth of row */
  177544. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  177545. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  177546. } png_row_info;
  177547. typedef png_row_info FAR * png_row_infop;
  177548. typedef png_row_info FAR * FAR * png_row_infopp;
  177549. /* These are the function types for the I/O functions and for the functions
  177550. * that allow the user to override the default I/O functions with his or her
  177551. * own. The png_error_ptr type should match that of user-supplied warning
  177552. * and error functions, while the png_rw_ptr type should match that of the
  177553. * user read/write data functions.
  177554. */
  177555. typedef struct png_struct_def png_struct;
  177556. typedef png_struct FAR * png_structp;
  177557. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  177558. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  177559. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  177560. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  177561. int));
  177562. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  177563. int));
  177564. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177565. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  177566. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  177567. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  177568. png_uint_32, int));
  177569. #endif
  177570. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177571. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  177572. defined(PNG_LEGACY_SUPPORTED)
  177573. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  177574. png_row_infop, png_bytep));
  177575. #endif
  177576. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  177577. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  177578. #endif
  177579. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177580. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  177581. #endif
  177582. /* Transform masks for the high-level interface */
  177583. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  177584. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  177585. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  177586. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  177587. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  177588. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  177589. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  177590. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  177591. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  177592. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  177593. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  177594. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  177595. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  177596. /* Flags for MNG supported features */
  177597. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  177598. #define PNG_FLAG_MNG_FILTER_64 0x04
  177599. #define PNG_ALL_MNG_FEATURES 0x05
  177600. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  177601. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  177602. /* The structure that holds the information to read and write PNG files.
  177603. * The only people who need to care about what is inside of this are the
  177604. * people who will be modifying the library for their own special needs.
  177605. * It should NOT be accessed directly by an application, except to store
  177606. * the jmp_buf.
  177607. */
  177608. struct png_struct_def
  177609. {
  177610. #ifdef PNG_SETJMP_SUPPORTED
  177611. jmp_buf jmpbuf; /* used in png_error */
  177612. #endif
  177613. png_error_ptr error_fn; /* function for printing errors and aborting */
  177614. png_error_ptr warning_fn; /* function for printing warnings */
  177615. png_voidp error_ptr; /* user supplied struct for error functions */
  177616. png_rw_ptr write_data_fn; /* function for writing output data */
  177617. png_rw_ptr read_data_fn; /* function for reading input data */
  177618. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  177619. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  177620. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  177621. #endif
  177622. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  177623. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  177624. #endif
  177625. /* These were added in libpng-1.0.2 */
  177626. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  177627. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177628. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  177629. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  177630. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  177631. png_byte user_transform_channels; /* channels in user transformed pixels */
  177632. #endif
  177633. #endif
  177634. png_uint_32 mode; /* tells us where we are in the PNG file */
  177635. png_uint_32 flags; /* flags indicating various things to libpng */
  177636. png_uint_32 transformations; /* which transformations to perform */
  177637. z_stream zstream; /* pointer to decompression structure (below) */
  177638. png_bytep zbuf; /* buffer for zlib */
  177639. png_size_t zbuf_size; /* size of zbuf */
  177640. int zlib_level; /* holds zlib compression level */
  177641. int zlib_method; /* holds zlib compression method */
  177642. int zlib_window_bits; /* holds zlib compression window bits */
  177643. int zlib_mem_level; /* holds zlib compression memory level */
  177644. int zlib_strategy; /* holds zlib compression strategy */
  177645. png_uint_32 width; /* width of image in pixels */
  177646. png_uint_32 height; /* height of image in pixels */
  177647. png_uint_32 num_rows; /* number of rows in current pass */
  177648. png_uint_32 usr_width; /* width of row at start of write */
  177649. png_uint_32 rowbytes; /* size of row in bytes */
  177650. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  177651. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  177652. png_uint_32 row_number; /* current row in interlace pass */
  177653. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  177654. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  177655. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  177656. png_bytep up_row; /* buffer to save "up" row when filtering */
  177657. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  177658. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  177659. png_row_info row_info; /* used for transformation routines */
  177660. png_uint_32 idat_size; /* current IDAT size for read */
  177661. png_uint_32 crc; /* current chunk CRC value */
  177662. png_colorp palette; /* palette from the input file */
  177663. png_uint_16 num_palette; /* number of color entries in palette */
  177664. png_uint_16 num_trans; /* number of transparency values */
  177665. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  177666. png_byte compression; /* file compression type (always 0) */
  177667. png_byte filter; /* file filter type (always 0) */
  177668. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  177669. png_byte pass; /* current interlace pass (0 - 6) */
  177670. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  177671. png_byte color_type; /* color type of file */
  177672. png_byte bit_depth; /* bit depth of file */
  177673. png_byte usr_bit_depth; /* bit depth of users row */
  177674. png_byte pixel_depth; /* number of bits per pixel */
  177675. png_byte channels; /* number of channels in file */
  177676. png_byte usr_channels; /* channels at start of write */
  177677. png_byte sig_bytes; /* magic bytes read/written from start of file */
  177678. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  177679. #ifdef PNG_LEGACY_SUPPORTED
  177680. png_byte filler; /* filler byte for pixel expansion */
  177681. #else
  177682. png_uint_16 filler; /* filler bytes for pixel expansion */
  177683. #endif
  177684. #endif
  177685. #if defined(PNG_bKGD_SUPPORTED)
  177686. png_byte background_gamma_type;
  177687. # ifdef PNG_FLOATING_POINT_SUPPORTED
  177688. float background_gamma;
  177689. # endif
  177690. png_color_16 background; /* background color in screen gamma space */
  177691. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177692. png_color_16 background_1; /* background normalized to gamma 1.0 */
  177693. #endif
  177694. #endif /* PNG_bKGD_SUPPORTED */
  177695. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177696. png_flush_ptr output_flush_fn;/* Function for flushing output */
  177697. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  177698. png_uint_32 flush_rows; /* number of rows written since last flush */
  177699. #endif
  177700. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177701. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  177702. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177703. float gamma; /* file gamma value */
  177704. float screen_gamma; /* screen gamma value (display_exponent) */
  177705. #endif
  177706. #endif
  177707. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177708. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  177709. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  177710. png_bytep gamma_to_1; /* converts from file to 1.0 */
  177711. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  177712. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  177713. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  177714. #endif
  177715. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  177716. png_color_8 sig_bit; /* significant bits in each available channel */
  177717. #endif
  177718. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  177719. png_color_8 shift; /* shift for significant bit tranformation */
  177720. #endif
  177721. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  177722. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177723. png_bytep trans; /* transparency values for paletted files */
  177724. png_color_16 trans_values; /* transparency values for non-paletted files */
  177725. #endif
  177726. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  177727. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  177728. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177729. png_progressive_info_ptr info_fn; /* called after header data fully read */
  177730. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  177731. png_progressive_end_ptr end_fn; /* called after image is complete */
  177732. png_bytep save_buffer_ptr; /* current location in save_buffer */
  177733. png_bytep save_buffer; /* buffer for previously read data */
  177734. png_bytep current_buffer_ptr; /* current location in current_buffer */
  177735. png_bytep current_buffer; /* buffer for recently used data */
  177736. png_uint_32 push_length; /* size of current input chunk */
  177737. png_uint_32 skip_length; /* bytes to skip in input data */
  177738. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  177739. png_size_t save_buffer_max; /* total size of save_buffer */
  177740. png_size_t buffer_size; /* total amount of available input data */
  177741. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  177742. int process_mode; /* what push library is currently doing */
  177743. int cur_palette; /* current push library palette index */
  177744. # if defined(PNG_TEXT_SUPPORTED)
  177745. png_size_t current_text_size; /* current size of text input data */
  177746. png_size_t current_text_left; /* how much text left to read in input */
  177747. png_charp current_text; /* current text chunk buffer */
  177748. png_charp current_text_ptr; /* current location in current_text */
  177749. # endif /* PNG_TEXT_SUPPORTED */
  177750. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  177751. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  177752. /* for the Borland special 64K segment handler */
  177753. png_bytepp offset_table_ptr;
  177754. png_bytep offset_table;
  177755. png_uint_16 offset_table_number;
  177756. png_uint_16 offset_table_count;
  177757. png_uint_16 offset_table_count_free;
  177758. #endif
  177759. #if defined(PNG_READ_DITHER_SUPPORTED)
  177760. png_bytep palette_lookup; /* lookup table for dithering */
  177761. png_bytep dither_index; /* index translation for palette files */
  177762. #endif
  177763. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  177764. png_uint_16p hist; /* histogram */
  177765. #endif
  177766. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  177767. png_byte heuristic_method; /* heuristic for row filter selection */
  177768. png_byte num_prev_filters; /* number of weights for previous rows */
  177769. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  177770. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  177771. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  177772. png_uint_16p filter_costs; /* relative filter calculation cost */
  177773. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  177774. #endif
  177775. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  177776. png_charp time_buffer; /* String to hold RFC 1123 time text */
  177777. #endif
  177778. /* New members added in libpng-1.0.6 */
  177779. #ifdef PNG_FREE_ME_SUPPORTED
  177780. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  177781. #endif
  177782. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  177783. png_voidp user_chunk_ptr;
  177784. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  177785. #endif
  177786. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177787. int num_chunk_list;
  177788. png_bytep chunk_list;
  177789. #endif
  177790. /* New members added in libpng-1.0.3 */
  177791. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  177792. png_byte rgb_to_gray_status;
  177793. /* These were changed from png_byte in libpng-1.0.6 */
  177794. png_uint_16 rgb_to_gray_red_coeff;
  177795. png_uint_16 rgb_to_gray_green_coeff;
  177796. png_uint_16 rgb_to_gray_blue_coeff;
  177797. #endif
  177798. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  177799. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  177800. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  177801. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  177802. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  177803. #ifdef PNG_1_0_X
  177804. png_byte mng_features_permitted;
  177805. #else
  177806. png_uint_32 mng_features_permitted;
  177807. #endif /* PNG_1_0_X */
  177808. #endif
  177809. /* New member added in libpng-1.0.7 */
  177810. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177811. png_fixed_point int_gamma;
  177812. #endif
  177813. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  177814. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  177815. png_byte filter_type;
  177816. #endif
  177817. #if defined(PNG_1_0_X)
  177818. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  177819. png_uint_32 row_buf_size;
  177820. #endif
  177821. /* New members added in libpng-1.2.0 */
  177822. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177823. # if !defined(PNG_1_0_X)
  177824. # if defined(PNG_MMX_CODE_SUPPORTED)
  177825. png_byte mmx_bitdepth_threshold;
  177826. png_uint_32 mmx_rowbytes_threshold;
  177827. # endif
  177828. png_uint_32 asm_flags;
  177829. # endif
  177830. #endif
  177831. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  177832. #ifdef PNG_USER_MEM_SUPPORTED
  177833. png_voidp mem_ptr; /* user supplied struct for mem functions */
  177834. png_malloc_ptr malloc_fn; /* function for allocating memory */
  177835. png_free_ptr free_fn; /* function for freeing memory */
  177836. #endif
  177837. /* New member added in libpng-1.0.13 and 1.2.0 */
  177838. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  177839. #if defined(PNG_READ_DITHER_SUPPORTED)
  177840. /* The following three members were added at version 1.0.14 and 1.2.4 */
  177841. png_bytep dither_sort; /* working sort array */
  177842. png_bytep index_to_palette; /* where the original index currently is */
  177843. /* in the palette */
  177844. png_bytep palette_to_index; /* which original index points to this */
  177845. /* palette color */
  177846. #endif
  177847. /* New members added in libpng-1.0.16 and 1.2.6 */
  177848. png_byte compression_type;
  177849. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  177850. png_uint_32 user_width_max;
  177851. png_uint_32 user_height_max;
  177852. #endif
  177853. /* New member added in libpng-1.0.25 and 1.2.17 */
  177854. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177855. /* storage for unknown chunk that the library doesn't recognize. */
  177856. png_unknown_chunk unknown_chunk;
  177857. #endif
  177858. };
  177859. /* This triggers a compiler error in png.c, if png.c and png.h
  177860. * do not agree upon the version number.
  177861. */
  177862. typedef png_structp version_1_2_21;
  177863. typedef png_struct FAR * FAR * png_structpp;
  177864. /* Here are the function definitions most commonly used. This is not
  177865. * the place to find out how to use libpng. See libpng.txt for the
  177866. * full explanation, see example.c for the summary. This just provides
  177867. * a simple one line description of the use of each function.
  177868. */
  177869. /* Returns the version number of the library */
  177870. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  177871. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  177872. * Handling more than 8 bytes from the beginning of the file is an error.
  177873. */
  177874. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  177875. int num_bytes));
  177876. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  177877. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  177878. * signature, and non-zero otherwise. Having num_to_check == 0 or
  177879. * start > 7 will always fail (ie return non-zero).
  177880. */
  177881. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  177882. png_size_t num_to_check));
  177883. /* Simple signature checking function. This is the same as calling
  177884. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  177885. */
  177886. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  177887. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  177888. extern PNG_EXPORT(png_structp,png_create_read_struct)
  177889. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  177890. png_error_ptr error_fn, png_error_ptr warn_fn));
  177891. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  177892. extern PNG_EXPORT(png_structp,png_create_write_struct)
  177893. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  177894. png_error_ptr error_fn, png_error_ptr warn_fn));
  177895. #ifdef PNG_WRITE_SUPPORTED
  177896. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  177897. PNGARG((png_structp png_ptr));
  177898. #endif
  177899. #ifdef PNG_WRITE_SUPPORTED
  177900. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  177901. PNGARG((png_structp png_ptr, png_uint_32 size));
  177902. #endif
  177903. /* Reset the compression stream */
  177904. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  177905. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  177906. #ifdef PNG_USER_MEM_SUPPORTED
  177907. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  177908. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  177909. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  177910. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  177911. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  177912. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  177913. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  177914. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  177915. #endif
  177916. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  177917. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  177918. png_bytep chunk_name, png_bytep data, png_size_t length));
  177919. /* Write the start of a PNG chunk - length and chunk name. */
  177920. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  177921. png_bytep chunk_name, png_uint_32 length));
  177922. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  177923. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  177924. png_bytep data, png_size_t length));
  177925. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  177926. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  177927. /* Allocate and initialize the info structure */
  177928. extern PNG_EXPORT(png_infop,png_create_info_struct)
  177929. PNGARG((png_structp png_ptr));
  177930. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177931. /* Initialize the info structure (old interface - DEPRECATED) */
  177932. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  177933. #undef png_info_init
  177934. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  177935. png_sizeof(png_info));
  177936. #endif
  177937. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  177938. png_size_t png_info_struct_size));
  177939. /* Writes all the PNG information before the image. */
  177940. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  177941. png_infop info_ptr));
  177942. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  177943. png_infop info_ptr));
  177944. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177945. /* read the information before the actual image data. */
  177946. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  177947. png_infop info_ptr));
  177948. #endif
  177949. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  177950. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  177951. PNGARG((png_structp png_ptr, png_timep ptime));
  177952. #endif
  177953. #if !defined(_WIN32_WCE)
  177954. /* "time.h" functions are not supported on WindowsCE */
  177955. #if defined(PNG_WRITE_tIME_SUPPORTED)
  177956. /* convert from a struct tm to png_time */
  177957. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  177958. struct tm FAR * ttime));
  177959. /* convert from time_t to png_time. Uses gmtime() */
  177960. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  177961. time_t ttime));
  177962. #endif /* PNG_WRITE_tIME_SUPPORTED */
  177963. #endif /* _WIN32_WCE */
  177964. #if defined(PNG_READ_EXPAND_SUPPORTED)
  177965. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  177966. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  177967. #if !defined(PNG_1_0_X)
  177968. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  177969. png_ptr));
  177970. #endif
  177971. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  177972. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  177973. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177974. /* Deprecated */
  177975. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  177976. #endif
  177977. #endif
  177978. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  177979. /* Use blue, green, red order for pixels. */
  177980. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  177981. #endif
  177982. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  177983. /* Expand the grayscale to 24-bit RGB if necessary. */
  177984. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  177985. #endif
  177986. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  177987. /* Reduce RGB to grayscale. */
  177988. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177989. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  177990. int error_action, double red, double green ));
  177991. #endif
  177992. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  177993. int error_action, png_fixed_point red, png_fixed_point green ));
  177994. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  177995. png_ptr));
  177996. #endif
  177997. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  177998. png_colorp palette));
  177999. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  178000. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  178001. #endif
  178002. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  178003. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  178004. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  178005. #endif
  178006. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  178007. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  178008. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  178009. #endif
  178010. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178011. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  178012. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  178013. png_uint_32 filler, int flags));
  178014. /* The values of the PNG_FILLER_ defines should NOT be changed */
  178015. #define PNG_FILLER_BEFORE 0
  178016. #define PNG_FILLER_AFTER 1
  178017. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  178018. #if !defined(PNG_1_0_X)
  178019. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  178020. png_uint_32 filler, int flags));
  178021. #endif
  178022. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  178023. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  178024. /* Swap bytes in 16-bit depth files. */
  178025. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  178026. #endif
  178027. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  178028. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  178029. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  178030. #endif
  178031. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  178032. /* Swap packing order of pixels in bytes. */
  178033. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  178034. #endif
  178035. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178036. /* Converts files to legal bit depths. */
  178037. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  178038. png_color_8p true_bits));
  178039. #endif
  178040. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  178041. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178042. /* Have the code handle the interlacing. Returns the number of passes. */
  178043. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  178044. #endif
  178045. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  178046. /* Invert monochrome files */
  178047. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  178048. #endif
  178049. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  178050. /* Handle alpha and tRNS by replacing with a background color. */
  178051. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178052. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  178053. png_color_16p background_color, int background_gamma_code,
  178054. int need_expand, double background_gamma));
  178055. #endif
  178056. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  178057. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  178058. #define PNG_BACKGROUND_GAMMA_FILE 2
  178059. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  178060. #endif
  178061. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  178062. /* strip the second byte of information from a 16-bit depth file. */
  178063. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  178064. #endif
  178065. #if defined(PNG_READ_DITHER_SUPPORTED)
  178066. /* Turn on dithering, and reduce the palette to the number of colors available. */
  178067. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  178068. png_colorp palette, int num_palette, int maximum_colors,
  178069. png_uint_16p histogram, int full_dither));
  178070. #endif
  178071. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178072. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  178073. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178074. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  178075. double screen_gamma, double default_file_gamma));
  178076. #endif
  178077. #endif
  178078. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178079. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178080. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178081. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  178082. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  178083. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  178084. int empty_plte_permitted));
  178085. #endif
  178086. #endif
  178087. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178088. /* Set how many lines between output flushes - 0 for no flushing */
  178089. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  178090. /* Flush the current PNG output buffer */
  178091. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  178092. #endif
  178093. /* optional update palette with requested transformations */
  178094. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  178095. /* optional call to update the users info structure */
  178096. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  178097. png_infop info_ptr));
  178098. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178099. /* read one or more rows of image data. */
  178100. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  178101. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  178102. #endif
  178103. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178104. /* read a row of data. */
  178105. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  178106. png_bytep row,
  178107. png_bytep display_row));
  178108. #endif
  178109. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178110. /* read the whole image into memory at once. */
  178111. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  178112. png_bytepp image));
  178113. #endif
  178114. /* write a row of image data */
  178115. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  178116. png_bytep row));
  178117. /* write a few rows of image data */
  178118. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  178119. png_bytepp row, png_uint_32 num_rows));
  178120. /* write the image data */
  178121. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  178122. png_bytepp image));
  178123. /* writes the end of the PNG file. */
  178124. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  178125. png_infop info_ptr));
  178126. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178127. /* read the end of the PNG file. */
  178128. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  178129. png_infop info_ptr));
  178130. #endif
  178131. /* free any memory associated with the png_info_struct */
  178132. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  178133. png_infopp info_ptr_ptr));
  178134. /* free any memory associated with the png_struct and the png_info_structs */
  178135. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  178136. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  178137. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  178138. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  178139. png_infop end_info_ptr));
  178140. /* free any memory associated with the png_struct and the png_info_structs */
  178141. extern PNG_EXPORT(void,png_destroy_write_struct)
  178142. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  178143. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  178144. extern void png_write_destroy PNGARG((png_structp png_ptr));
  178145. /* set the libpng method of handling chunk CRC errors */
  178146. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  178147. int crit_action, int ancil_action));
  178148. /* Values for png_set_crc_action() to say how to handle CRC errors in
  178149. * ancillary and critical chunks, and whether to use the data contained
  178150. * therein. Note that it is impossible to "discard" data in a critical
  178151. * chunk. For versions prior to 0.90, the action was always error/quit,
  178152. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  178153. * chunks is warn/discard. These values should NOT be changed.
  178154. *
  178155. * value action:critical action:ancillary
  178156. */
  178157. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  178158. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  178159. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  178160. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  178161. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  178162. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  178163. /* These functions give the user control over the scan-line filtering in
  178164. * libpng and the compression methods used by zlib. These functions are
  178165. * mainly useful for testing, as the defaults should work with most users.
  178166. * Those users who are tight on memory or want faster performance at the
  178167. * expense of compression can modify them. See the compression library
  178168. * header file (zlib.h) for an explination of the compression functions.
  178169. */
  178170. /* set the filtering method(s) used by libpng. Currently, the only valid
  178171. * value for "method" is 0.
  178172. */
  178173. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  178174. int filters));
  178175. /* Flags for png_set_filter() to say which filters to use. The flags
  178176. * are chosen so that they don't conflict with real filter types
  178177. * below, in case they are supplied instead of the #defined constants.
  178178. * These values should NOT be changed.
  178179. */
  178180. #define PNG_NO_FILTERS 0x00
  178181. #define PNG_FILTER_NONE 0x08
  178182. #define PNG_FILTER_SUB 0x10
  178183. #define PNG_FILTER_UP 0x20
  178184. #define PNG_FILTER_AVG 0x40
  178185. #define PNG_FILTER_PAETH 0x80
  178186. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  178187. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  178188. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  178189. * These defines should NOT be changed.
  178190. */
  178191. #define PNG_FILTER_VALUE_NONE 0
  178192. #define PNG_FILTER_VALUE_SUB 1
  178193. #define PNG_FILTER_VALUE_UP 2
  178194. #define PNG_FILTER_VALUE_AVG 3
  178195. #define PNG_FILTER_VALUE_PAETH 4
  178196. #define PNG_FILTER_VALUE_LAST 5
  178197. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  178198. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  178199. * defines, either the default (minimum-sum-of-absolute-differences), or
  178200. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  178201. *
  178202. * Weights are factors >= 1.0, indicating how important it is to keep the
  178203. * filter type consistent between rows. Larger numbers mean the current
  178204. * filter is that many times as likely to be the same as the "num_weights"
  178205. * previous filters. This is cumulative for each previous row with a weight.
  178206. * There needs to be "num_weights" values in "filter_weights", or it can be
  178207. * NULL if the weights aren't being specified. Weights have no influence on
  178208. * the selection of the first row filter. Well chosen weights can (in theory)
  178209. * improve the compression for a given image.
  178210. *
  178211. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  178212. * filter type. Higher costs indicate more decoding expense, and are
  178213. * therefore less likely to be selected over a filter with lower computational
  178214. * costs. There needs to be a value in "filter_costs" for each valid filter
  178215. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  178216. * setting the costs. Costs try to improve the speed of decompression without
  178217. * unduly increasing the compressed image size.
  178218. *
  178219. * A negative weight or cost indicates the default value is to be used, and
  178220. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  178221. * The default values for both weights and costs are currently 1.0, but may
  178222. * change if good general weighting/cost heuristics can be found. If both
  178223. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  178224. * to the UNWEIGHTED method, but with added encoding time/computation.
  178225. */
  178226. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178227. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  178228. int heuristic_method, int num_weights, png_doublep filter_weights,
  178229. png_doublep filter_costs));
  178230. #endif
  178231. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  178232. /* Heuristic used for row filter selection. These defines should NOT be
  178233. * changed.
  178234. */
  178235. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  178236. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  178237. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  178238. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  178239. /* Set the library compression level. Currently, valid values range from
  178240. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  178241. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  178242. * shown that zlib compression levels 3-6 usually perform as well as level 9
  178243. * for PNG images, and do considerably fewer caclulations. In the future,
  178244. * these values may not correspond directly to the zlib compression levels.
  178245. */
  178246. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  178247. int level));
  178248. extern PNG_EXPORT(void,png_set_compression_mem_level)
  178249. PNGARG((png_structp png_ptr, int mem_level));
  178250. extern PNG_EXPORT(void,png_set_compression_strategy)
  178251. PNGARG((png_structp png_ptr, int strategy));
  178252. extern PNG_EXPORT(void,png_set_compression_window_bits)
  178253. PNGARG((png_structp png_ptr, int window_bits));
  178254. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  178255. int method));
  178256. /* These next functions are called for input/output, memory, and error
  178257. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  178258. * and call standard C I/O routines such as fread(), fwrite(), and
  178259. * fprintf(). These functions can be made to use other I/O routines
  178260. * at run time for those applications that need to handle I/O in a
  178261. * different manner by calling png_set_???_fn(). See libpng.txt for
  178262. * more information.
  178263. */
  178264. #if !defined(PNG_NO_STDIO)
  178265. /* Initialize the input/output for the PNG file to the default functions. */
  178266. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  178267. #endif
  178268. /* Replace the (error and abort), and warning functions with user
  178269. * supplied functions. If no messages are to be printed you must still
  178270. * write and use replacement functions. The replacement error_fn should
  178271. * still do a longjmp to the last setjmp location if you are using this
  178272. * method of error handling. If error_fn or warning_fn is NULL, the
  178273. * default function will be used.
  178274. */
  178275. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  178276. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  178277. /* Return the user pointer associated with the error functions */
  178278. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  178279. /* Replace the default data output functions with a user supplied one(s).
  178280. * If buffered output is not used, then output_flush_fn can be set to NULL.
  178281. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  178282. * output_flush_fn will be ignored (and thus can be NULL).
  178283. */
  178284. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  178285. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  178286. /* Replace the default data input function with a user supplied one. */
  178287. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  178288. png_voidp io_ptr, png_rw_ptr read_data_fn));
  178289. /* Return the user pointer associated with the I/O functions */
  178290. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  178291. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  178292. png_read_status_ptr read_row_fn));
  178293. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  178294. png_write_status_ptr write_row_fn));
  178295. #ifdef PNG_USER_MEM_SUPPORTED
  178296. /* Replace the default memory allocation functions with user supplied one(s). */
  178297. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  178298. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178299. /* Return the user pointer associated with the memory functions */
  178300. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  178301. #endif
  178302. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178303. defined(PNG_LEGACY_SUPPORTED)
  178304. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  178305. png_ptr, png_user_transform_ptr read_user_transform_fn));
  178306. #endif
  178307. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178308. defined(PNG_LEGACY_SUPPORTED)
  178309. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  178310. png_ptr, png_user_transform_ptr write_user_transform_fn));
  178311. #endif
  178312. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178313. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178314. defined(PNG_LEGACY_SUPPORTED)
  178315. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  178316. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  178317. int user_transform_channels));
  178318. /* Return the user pointer associated with the user transform functions */
  178319. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  178320. PNGARG((png_structp png_ptr));
  178321. #endif
  178322. #ifdef PNG_USER_CHUNKS_SUPPORTED
  178323. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  178324. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  178325. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  178326. png_ptr));
  178327. #endif
  178328. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178329. /* Sets the function callbacks for the push reader, and a pointer to a
  178330. * user-defined structure available to the callback functions.
  178331. */
  178332. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  178333. png_voidp progressive_ptr,
  178334. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  178335. png_progressive_end_ptr end_fn));
  178336. /* returns the user pointer associated with the push read functions */
  178337. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  178338. PNGARG((png_structp png_ptr));
  178339. /* function to be called when data becomes available */
  178340. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  178341. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  178342. /* function that combines rows. Not very much different than the
  178343. * png_combine_row() call. Is this even used?????
  178344. */
  178345. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  178346. png_bytep old_row, png_bytep new_row));
  178347. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178348. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  178349. png_uint_32 size));
  178350. #if defined(PNG_1_0_X)
  178351. # define png_malloc_warn png_malloc
  178352. #else
  178353. /* Added at libpng version 1.2.4 */
  178354. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  178355. png_uint_32 size));
  178356. #endif
  178357. /* frees a pointer allocated by png_malloc() */
  178358. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  178359. #if defined(PNG_1_0_X)
  178360. /* Function to allocate memory for zlib. */
  178361. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  178362. uInt size));
  178363. /* Function to free memory for zlib */
  178364. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  178365. #endif
  178366. /* Free data that was allocated internally */
  178367. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  178368. png_infop info_ptr, png_uint_32 free_me, int num));
  178369. #ifdef PNG_FREE_ME_SUPPORTED
  178370. /* Reassign responsibility for freeing existing data, whether allocated
  178371. * by libpng or by the application */
  178372. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  178373. png_infop info_ptr, int freer, png_uint_32 mask));
  178374. #endif
  178375. /* assignments for png_data_freer */
  178376. #define PNG_DESTROY_WILL_FREE_DATA 1
  178377. #define PNG_SET_WILL_FREE_DATA 1
  178378. #define PNG_USER_WILL_FREE_DATA 2
  178379. /* Flags for png_ptr->free_me and info_ptr->free_me */
  178380. #define PNG_FREE_HIST 0x0008
  178381. #define PNG_FREE_ICCP 0x0010
  178382. #define PNG_FREE_SPLT 0x0020
  178383. #define PNG_FREE_ROWS 0x0040
  178384. #define PNG_FREE_PCAL 0x0080
  178385. #define PNG_FREE_SCAL 0x0100
  178386. #define PNG_FREE_UNKN 0x0200
  178387. #define PNG_FREE_LIST 0x0400
  178388. #define PNG_FREE_PLTE 0x1000
  178389. #define PNG_FREE_TRNS 0x2000
  178390. #define PNG_FREE_TEXT 0x4000
  178391. #define PNG_FREE_ALL 0x7fff
  178392. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  178393. #ifdef PNG_USER_MEM_SUPPORTED
  178394. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  178395. png_uint_32 size));
  178396. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  178397. png_voidp ptr));
  178398. #endif
  178399. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  178400. png_voidp s1, png_voidp s2, png_uint_32 size));
  178401. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  178402. png_voidp s1, int value, png_uint_32 size));
  178403. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  178404. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  178405. int check));
  178406. #endif /* USE_FAR_KEYWORD */
  178407. #ifndef PNG_NO_ERROR_TEXT
  178408. /* Fatal error in PNG image of libpng - can't continue */
  178409. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  178410. png_const_charp error_message));
  178411. /* The same, but the chunk name is prepended to the error string. */
  178412. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  178413. png_const_charp error_message));
  178414. #else
  178415. /* Fatal error in PNG image of libpng - can't continue */
  178416. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  178417. #endif
  178418. #ifndef PNG_NO_WARNINGS
  178419. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  178420. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  178421. png_const_charp warning_message));
  178422. #ifdef PNG_READ_SUPPORTED
  178423. /* Non-fatal error in libpng, chunk name is prepended to message. */
  178424. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  178425. png_const_charp warning_message));
  178426. #endif /* PNG_READ_SUPPORTED */
  178427. #endif /* PNG_NO_WARNINGS */
  178428. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  178429. * Similarly, the png_get_<chunk> calls are used to read values from the
  178430. * png_info_struct, either storing the parameters in the passed variables, or
  178431. * setting pointers into the png_info_struct where the data is stored. The
  178432. * png_get_<chunk> functions return a non-zero value if the data was available
  178433. * in info_ptr, or return zero and do not change any of the parameters if the
  178434. * data was not available.
  178435. *
  178436. * These functions should be used instead of directly accessing png_info
  178437. * to avoid problems with future changes in the size and internal layout of
  178438. * png_info_struct.
  178439. */
  178440. /* Returns "flag" if chunk data is valid in info_ptr. */
  178441. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  178442. png_infop info_ptr, png_uint_32 flag));
  178443. /* Returns number of bytes needed to hold a transformed row. */
  178444. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  178445. png_infop info_ptr));
  178446. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178447. /* Returns row_pointers, which is an array of pointers to scanlines that was
  178448. returned from png_read_png(). */
  178449. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  178450. png_infop info_ptr));
  178451. /* Set row_pointers, which is an array of pointers to scanlines for use
  178452. by png_write_png(). */
  178453. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  178454. png_infop info_ptr, png_bytepp row_pointers));
  178455. #endif
  178456. /* Returns number of color channels in image. */
  178457. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  178458. png_infop info_ptr));
  178459. #ifdef PNG_EASY_ACCESS_SUPPORTED
  178460. /* Returns image width in pixels. */
  178461. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  178462. png_ptr, png_infop info_ptr));
  178463. /* Returns image height in pixels. */
  178464. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  178465. png_ptr, png_infop info_ptr));
  178466. /* Returns image bit_depth. */
  178467. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  178468. png_ptr, png_infop info_ptr));
  178469. /* Returns image color_type. */
  178470. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  178471. png_ptr, png_infop info_ptr));
  178472. /* Returns image filter_type. */
  178473. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  178474. png_ptr, png_infop info_ptr));
  178475. /* Returns image interlace_type. */
  178476. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  178477. png_ptr, png_infop info_ptr));
  178478. /* Returns image compression_type. */
  178479. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  178480. png_ptr, png_infop info_ptr));
  178481. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  178482. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  178483. png_ptr, png_infop info_ptr));
  178484. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  178485. png_ptr, png_infop info_ptr));
  178486. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  178487. png_ptr, png_infop info_ptr));
  178488. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  178489. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178490. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  178491. png_ptr, png_infop info_ptr));
  178492. #endif
  178493. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  178494. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  178495. png_ptr, png_infop info_ptr));
  178496. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  178497. png_ptr, png_infop info_ptr));
  178498. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  178499. png_ptr, png_infop info_ptr));
  178500. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  178501. png_ptr, png_infop info_ptr));
  178502. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  178503. /* Returns pointer to signature string read from PNG header */
  178504. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  178505. png_infop info_ptr));
  178506. #if defined(PNG_bKGD_SUPPORTED)
  178507. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  178508. png_infop info_ptr, png_color_16p *background));
  178509. #endif
  178510. #if defined(PNG_bKGD_SUPPORTED)
  178511. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  178512. png_infop info_ptr, png_color_16p background));
  178513. #endif
  178514. #if defined(PNG_cHRM_SUPPORTED)
  178515. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178516. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  178517. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  178518. double *red_y, double *green_x, double *green_y, double *blue_x,
  178519. double *blue_y));
  178520. #endif
  178521. #ifdef PNG_FIXED_POINT_SUPPORTED
  178522. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  178523. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  178524. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  178525. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  178526. *int_blue_x, png_fixed_point *int_blue_y));
  178527. #endif
  178528. #endif
  178529. #if defined(PNG_cHRM_SUPPORTED)
  178530. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178531. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  178532. png_infop info_ptr, double white_x, double white_y, double red_x,
  178533. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  178534. #endif
  178535. #ifdef PNG_FIXED_POINT_SUPPORTED
  178536. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  178537. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  178538. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  178539. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  178540. png_fixed_point int_blue_y));
  178541. #endif
  178542. #endif
  178543. #if defined(PNG_gAMA_SUPPORTED)
  178544. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178545. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  178546. png_infop info_ptr, double *file_gamma));
  178547. #endif
  178548. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  178549. png_infop info_ptr, png_fixed_point *int_file_gamma));
  178550. #endif
  178551. #if defined(PNG_gAMA_SUPPORTED)
  178552. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178553. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  178554. png_infop info_ptr, double file_gamma));
  178555. #endif
  178556. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  178557. png_infop info_ptr, png_fixed_point int_file_gamma));
  178558. #endif
  178559. #if defined(PNG_hIST_SUPPORTED)
  178560. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  178561. png_infop info_ptr, png_uint_16p *hist));
  178562. #endif
  178563. #if defined(PNG_hIST_SUPPORTED)
  178564. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  178565. png_infop info_ptr, png_uint_16p hist));
  178566. #endif
  178567. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  178568. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  178569. int *bit_depth, int *color_type, int *interlace_method,
  178570. int *compression_method, int *filter_method));
  178571. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  178572. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  178573. int color_type, int interlace_method, int compression_method,
  178574. int filter_method));
  178575. #if defined(PNG_oFFs_SUPPORTED)
  178576. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  178577. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  178578. int *unit_type));
  178579. #endif
  178580. #if defined(PNG_oFFs_SUPPORTED)
  178581. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  178582. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  178583. int unit_type));
  178584. #endif
  178585. #if defined(PNG_pCAL_SUPPORTED)
  178586. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  178587. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  178588. int *type, int *nparams, png_charp *units, png_charpp *params));
  178589. #endif
  178590. #if defined(PNG_pCAL_SUPPORTED)
  178591. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  178592. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  178593. int type, int nparams, png_charp units, png_charpp params));
  178594. #endif
  178595. #if defined(PNG_pHYs_SUPPORTED)
  178596. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  178597. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  178598. #endif
  178599. #if defined(PNG_pHYs_SUPPORTED)
  178600. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  178601. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  178602. #endif
  178603. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  178604. png_infop info_ptr, png_colorp *palette, int *num_palette));
  178605. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  178606. png_infop info_ptr, png_colorp palette, int num_palette));
  178607. #if defined(PNG_sBIT_SUPPORTED)
  178608. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  178609. png_infop info_ptr, png_color_8p *sig_bit));
  178610. #endif
  178611. #if defined(PNG_sBIT_SUPPORTED)
  178612. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  178613. png_infop info_ptr, png_color_8p sig_bit));
  178614. #endif
  178615. #if defined(PNG_sRGB_SUPPORTED)
  178616. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  178617. png_infop info_ptr, int *intent));
  178618. #endif
  178619. #if defined(PNG_sRGB_SUPPORTED)
  178620. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  178621. png_infop info_ptr, int intent));
  178622. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  178623. png_infop info_ptr, int intent));
  178624. #endif
  178625. #if defined(PNG_iCCP_SUPPORTED)
  178626. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  178627. png_infop info_ptr, png_charpp name, int *compression_type,
  178628. png_charpp profile, png_uint_32 *proflen));
  178629. /* Note to maintainer: profile should be png_bytepp */
  178630. #endif
  178631. #if defined(PNG_iCCP_SUPPORTED)
  178632. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  178633. png_infop info_ptr, png_charp name, int compression_type,
  178634. png_charp profile, png_uint_32 proflen));
  178635. /* Note to maintainer: profile should be png_bytep */
  178636. #endif
  178637. #if defined(PNG_sPLT_SUPPORTED)
  178638. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  178639. png_infop info_ptr, png_sPLT_tpp entries));
  178640. #endif
  178641. #if defined(PNG_sPLT_SUPPORTED)
  178642. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  178643. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  178644. #endif
  178645. #if defined(PNG_TEXT_SUPPORTED)
  178646. /* png_get_text also returns the number of text chunks in *num_text */
  178647. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  178648. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  178649. #endif
  178650. /*
  178651. * Note while png_set_text() will accept a structure whose text,
  178652. * language, and translated keywords are NULL pointers, the structure
  178653. * returned by png_get_text will always contain regular
  178654. * zero-terminated C strings. They might be empty strings but
  178655. * they will never be NULL pointers.
  178656. */
  178657. #if defined(PNG_TEXT_SUPPORTED)
  178658. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  178659. png_infop info_ptr, png_textp text_ptr, int num_text));
  178660. #endif
  178661. #if defined(PNG_tIME_SUPPORTED)
  178662. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  178663. png_infop info_ptr, png_timep *mod_time));
  178664. #endif
  178665. #if defined(PNG_tIME_SUPPORTED)
  178666. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  178667. png_infop info_ptr, png_timep mod_time));
  178668. #endif
  178669. #if defined(PNG_tRNS_SUPPORTED)
  178670. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  178671. png_infop info_ptr, png_bytep *trans, int *num_trans,
  178672. png_color_16p *trans_values));
  178673. #endif
  178674. #if defined(PNG_tRNS_SUPPORTED)
  178675. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  178676. png_infop info_ptr, png_bytep trans, int num_trans,
  178677. png_color_16p trans_values));
  178678. #endif
  178679. #if defined(PNG_tRNS_SUPPORTED)
  178680. #endif
  178681. #if defined(PNG_sCAL_SUPPORTED)
  178682. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178683. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  178684. png_infop info_ptr, int *unit, double *width, double *height));
  178685. #else
  178686. #ifdef PNG_FIXED_POINT_SUPPORTED
  178687. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  178688. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  178689. #endif
  178690. #endif
  178691. #endif /* PNG_sCAL_SUPPORTED */
  178692. #if defined(PNG_sCAL_SUPPORTED)
  178693. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178694. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  178695. png_infop info_ptr, int unit, double width, double height));
  178696. #else
  178697. #ifdef PNG_FIXED_POINT_SUPPORTED
  178698. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  178699. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  178700. #endif
  178701. #endif
  178702. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  178703. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178704. /* provide a list of chunks and how they are to be handled, if the built-in
  178705. handling or default unknown chunk handling is not desired. Any chunks not
  178706. listed will be handled in the default manner. The IHDR and IEND chunks
  178707. must not be listed.
  178708. keep = 0: follow default behaviour
  178709. = 1: do not keep
  178710. = 2: keep only if safe-to-copy
  178711. = 3: keep even if unsafe-to-copy
  178712. */
  178713. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  178714. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  178715. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  178716. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  178717. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  178718. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  178719. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  178720. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  178721. #endif
  178722. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178723. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  178724. chunk_name));
  178725. #endif
  178726. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  178727. If you need to turn it off for a chunk that your application has freed,
  178728. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  178729. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  178730. png_infop info_ptr, int mask));
  178731. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178732. /* The "params" pointer is currently not used and is for future expansion. */
  178733. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  178734. png_infop info_ptr,
  178735. int transforms,
  178736. png_voidp params));
  178737. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  178738. png_infop info_ptr,
  178739. int transforms,
  178740. png_voidp params));
  178741. #endif
  178742. /* Define PNG_DEBUG at compile time for debugging information. Higher
  178743. * numbers for PNG_DEBUG mean more debugging information. This has
  178744. * only been added since version 0.95 so it is not implemented throughout
  178745. * libpng yet, but more support will be added as needed.
  178746. */
  178747. #ifdef PNG_DEBUG
  178748. #if (PNG_DEBUG > 0)
  178749. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  178750. #include <crtdbg.h>
  178751. #if (PNG_DEBUG > 1)
  178752. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  178753. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  178754. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  178755. #endif
  178756. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  178757. #ifndef PNG_DEBUG_FILE
  178758. #define PNG_DEBUG_FILE stderr
  178759. #endif /* PNG_DEBUG_FILE */
  178760. #if (PNG_DEBUG > 1)
  178761. #define png_debug(l,m) \
  178762. { \
  178763. int num_tabs=l; \
  178764. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  178765. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  178766. }
  178767. #define png_debug1(l,m,p1) \
  178768. { \
  178769. int num_tabs=l; \
  178770. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  178771. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  178772. }
  178773. #define png_debug2(l,m,p1,p2) \
  178774. { \
  178775. int num_tabs=l; \
  178776. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  178777. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  178778. }
  178779. #endif /* (PNG_DEBUG > 1) */
  178780. #endif /* _MSC_VER */
  178781. #endif /* (PNG_DEBUG > 0) */
  178782. #endif /* PNG_DEBUG */
  178783. #ifndef png_debug
  178784. #define png_debug(l, m)
  178785. #endif
  178786. #ifndef png_debug1
  178787. #define png_debug1(l, m, p1)
  178788. #endif
  178789. #ifndef png_debug2
  178790. #define png_debug2(l, m, p1, p2)
  178791. #endif
  178792. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  178793. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  178794. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  178795. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  178796. #ifdef PNG_MNG_FEATURES_SUPPORTED
  178797. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  178798. png_ptr, png_uint_32 mng_features_permitted));
  178799. #endif
  178800. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  178801. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  178802. #define PNG_HANDLE_CHUNK_NEVER 1
  178803. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  178804. #define PNG_HANDLE_CHUNK_ALWAYS 3
  178805. /* Added to version 1.2.0 */
  178806. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178807. #if defined(PNG_MMX_CODE_SUPPORTED)
  178808. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  178809. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  178810. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  178811. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  178812. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  178813. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  178814. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  178815. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  178816. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  178817. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  178818. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  178819. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  178820. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  178821. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  178822. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  178823. #define PNG_MMX_WRITE_FLAGS ( 0 )
  178824. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  178825. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  178826. | PNG_MMX_READ_FLAGS \
  178827. | PNG_MMX_WRITE_FLAGS )
  178828. #define PNG_SELECT_READ 1
  178829. #define PNG_SELECT_WRITE 2
  178830. #endif /* PNG_MMX_CODE_SUPPORTED */
  178831. #if !defined(PNG_1_0_X)
  178832. /* pngget.c */
  178833. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  178834. PNGARG((int flag_select, int *compilerID));
  178835. /* pngget.c */
  178836. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  178837. PNGARG((int flag_select));
  178838. /* pngget.c */
  178839. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  178840. PNGARG((png_structp png_ptr));
  178841. /* pngget.c */
  178842. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  178843. PNGARG((png_structp png_ptr));
  178844. /* pngget.c */
  178845. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  178846. PNGARG((png_structp png_ptr));
  178847. /* pngset.c */
  178848. extern PNG_EXPORT(void,png_set_asm_flags)
  178849. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  178850. /* pngset.c */
  178851. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  178852. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  178853. png_uint_32 mmx_rowbytes_threshold));
  178854. #endif /* PNG_1_0_X */
  178855. #if !defined(PNG_1_0_X)
  178856. /* png.c, pnggccrd.c, or pngvcrd.c */
  178857. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  178858. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  178859. /* Strip the prepended error numbers ("#nnn ") from error and warning
  178860. * messages before passing them to the error or warning handler. */
  178861. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178862. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  178863. png_ptr, png_uint_32 strip_mode));
  178864. #endif
  178865. #endif /* PNG_1_0_X */
  178866. /* Added at libpng-1.2.6 */
  178867. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  178868. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  178869. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  178870. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  178871. png_ptr));
  178872. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  178873. png_ptr));
  178874. #endif
  178875. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  178876. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  178877. /* With these routines we avoid an integer divide, which will be slower on
  178878. * most machines. However, it does take more operations than the corresponding
  178879. * divide method, so it may be slower on a few RISC systems. There are two
  178880. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  178881. *
  178882. * Note that the rounding factors are NOT supposed to be the same! 128 and
  178883. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  178884. * standard method.
  178885. *
  178886. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  178887. */
  178888. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  178889. # define png_composite(composite, fg, alpha, bg) \
  178890. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  178891. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  178892. (png_uint_16)(alpha)) + (png_uint_16)128); \
  178893. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  178894. # define png_composite_16(composite, fg, alpha, bg) \
  178895. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  178896. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  178897. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  178898. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  178899. #else /* standard method using integer division */
  178900. # define png_composite(composite, fg, alpha, bg) \
  178901. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  178902. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  178903. (png_uint_16)127) / 255)
  178904. # define png_composite_16(composite, fg, alpha, bg) \
  178905. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  178906. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  178907. (png_uint_32)32767) / (png_uint_32)65535L)
  178908. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  178909. /* Inline macros to do direct reads of bytes from the input buffer. These
  178910. * require that you are using an architecture that uses PNG byte ordering
  178911. * (MSB first) and supports unaligned data storage. I think that PowerPC
  178912. * in big-endian mode and 680x0 are the only ones that will support this.
  178913. * The x86 line of processors definitely do not. The png_get_int_32()
  178914. * routine also assumes we are using two's complement format for negative
  178915. * values, which is almost certainly true.
  178916. */
  178917. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  178918. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  178919. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  178920. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  178921. #else
  178922. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  178923. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  178924. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  178925. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  178926. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  178927. PNGARG((png_structp png_ptr, png_bytep buf));
  178928. /* No png_get_int_16 -- may be added if there's a real need for it. */
  178929. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  178930. */
  178931. extern PNG_EXPORT(void,png_save_uint_32)
  178932. PNGARG((png_bytep buf, png_uint_32 i));
  178933. extern PNG_EXPORT(void,png_save_int_32)
  178934. PNGARG((png_bytep buf, png_int_32 i));
  178935. /* Place a 16-bit number into a buffer in PNG byte order.
  178936. * The parameter is declared unsigned int, not png_uint_16,
  178937. * just to avoid potential problems on pre-ANSI C compilers.
  178938. */
  178939. extern PNG_EXPORT(void,png_save_uint_16)
  178940. PNGARG((png_bytep buf, unsigned int i));
  178941. /* No png_save_int_16 -- may be added if there's a real need for it. */
  178942. /* ************************************************************************* */
  178943. /* These next functions are used internally in the code. They generally
  178944. * shouldn't be used unless you are writing code to add or replace some
  178945. * functionality in libpng. More information about most functions can
  178946. * be found in the files where the functions are located.
  178947. */
  178948. /* Various modes of operation, that are visible to applications because
  178949. * they are used for unknown chunk location.
  178950. */
  178951. #define PNG_HAVE_IHDR 0x01
  178952. #define PNG_HAVE_PLTE 0x02
  178953. #define PNG_HAVE_IDAT 0x04
  178954. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  178955. #define PNG_HAVE_IEND 0x10
  178956. #if defined(PNG_INTERNAL)
  178957. /* More modes of operation. Note that after an init, mode is set to
  178958. * zero automatically when the structure is created.
  178959. */
  178960. #define PNG_HAVE_gAMA 0x20
  178961. #define PNG_HAVE_cHRM 0x40
  178962. #define PNG_HAVE_sRGB 0x80
  178963. #define PNG_HAVE_CHUNK_HEADER 0x100
  178964. #define PNG_WROTE_tIME 0x200
  178965. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  178966. #define PNG_BACKGROUND_IS_GRAY 0x800
  178967. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  178968. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  178969. /* flags for the transformations the PNG library does on the image data */
  178970. #define PNG_BGR 0x0001
  178971. #define PNG_INTERLACE 0x0002
  178972. #define PNG_PACK 0x0004
  178973. #define PNG_SHIFT 0x0008
  178974. #define PNG_SWAP_BYTES 0x0010
  178975. #define PNG_INVERT_MONO 0x0020
  178976. #define PNG_DITHER 0x0040
  178977. #define PNG_BACKGROUND 0x0080
  178978. #define PNG_BACKGROUND_EXPAND 0x0100
  178979. /* 0x0200 unused */
  178980. #define PNG_16_TO_8 0x0400
  178981. #define PNG_RGBA 0x0800
  178982. #define PNG_EXPAND 0x1000
  178983. #define PNG_GAMMA 0x2000
  178984. #define PNG_GRAY_TO_RGB 0x4000
  178985. #define PNG_FILLER 0x8000L
  178986. #define PNG_PACKSWAP 0x10000L
  178987. #define PNG_SWAP_ALPHA 0x20000L
  178988. #define PNG_STRIP_ALPHA 0x40000L
  178989. #define PNG_INVERT_ALPHA 0x80000L
  178990. #define PNG_USER_TRANSFORM 0x100000L
  178991. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  178992. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  178993. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  178994. /* 0x800000L Unused */
  178995. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  178996. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  178997. /* 0x4000000L unused */
  178998. /* 0x8000000L unused */
  178999. /* 0x10000000L unused */
  179000. /* 0x20000000L unused */
  179001. /* 0x40000000L unused */
  179002. /* flags for png_create_struct */
  179003. #define PNG_STRUCT_PNG 0x0001
  179004. #define PNG_STRUCT_INFO 0x0002
  179005. /* Scaling factor for filter heuristic weighting calculations */
  179006. #define PNG_WEIGHT_SHIFT 8
  179007. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  179008. #define PNG_COST_SHIFT 3
  179009. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  179010. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  179011. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  179012. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  179013. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  179014. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  179015. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  179016. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  179017. #define PNG_FLAG_ROW_INIT 0x0040
  179018. #define PNG_FLAG_FILLER_AFTER 0x0080
  179019. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  179020. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  179021. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  179022. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  179023. #define PNG_FLAG_FREE_PLTE 0x1000
  179024. #define PNG_FLAG_FREE_TRNS 0x2000
  179025. #define PNG_FLAG_FREE_HIST 0x4000
  179026. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  179027. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  179028. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  179029. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  179030. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  179031. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  179032. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  179033. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  179034. /* 0x800000L unused */
  179035. /* 0x1000000L unused */
  179036. /* 0x2000000L unused */
  179037. /* 0x4000000L unused */
  179038. /* 0x8000000L unused */
  179039. /* 0x10000000L unused */
  179040. /* 0x20000000L unused */
  179041. /* 0x40000000L unused */
  179042. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  179043. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  179044. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  179045. PNG_FLAG_CRC_CRITICAL_IGNORE)
  179046. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  179047. PNG_FLAG_CRC_CRITICAL_MASK)
  179048. /* save typing and make code easier to understand */
  179049. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  179050. abs((int)((c1).green) - (int)((c2).green)) + \
  179051. abs((int)((c1).blue) - (int)((c2).blue)))
  179052. /* Added to libpng-1.2.6 JB */
  179053. #define PNG_ROWBYTES(pixel_bits, width) \
  179054. ((pixel_bits) >= 8 ? \
  179055. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  179056. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  179057. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  179058. ideal-delta..ideal+delta. Each argument is evaluated twice.
  179059. "ideal" and "delta" should be constants, normally simple
  179060. integers, "value" a variable. Added to libpng-1.2.6 JB */
  179061. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  179062. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  179063. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  179064. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  179065. /* place to hold the signature string for a PNG file. */
  179066. #ifdef PNG_USE_GLOBAL_ARRAYS
  179067. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  179068. #else
  179069. #endif
  179070. #endif /* PNG_NO_EXTERN */
  179071. /* Constant strings for known chunk types. If you need to add a chunk,
  179072. * define the name here, and add an invocation of the macro in png.c and
  179073. * wherever it's needed.
  179074. */
  179075. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  179076. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  179077. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  179078. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  179079. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  179080. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  179081. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  179082. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  179083. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  179084. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  179085. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  179086. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  179087. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  179088. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  179089. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  179090. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  179091. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  179092. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  179093. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  179094. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  179095. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  179096. #ifdef PNG_USE_GLOBAL_ARRAYS
  179097. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  179098. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  179099. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  179100. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  179101. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  179102. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  179103. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  179104. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  179105. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  179106. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  179107. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  179108. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  179109. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  179110. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  179111. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  179112. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  179113. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  179114. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  179115. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  179116. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  179117. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  179118. #endif /* PNG_USE_GLOBAL_ARRAYS */
  179119. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179120. /* Initialize png_ptr struct for reading, and allocate any other memory.
  179121. * (old interface - DEPRECATED - use png_create_read_struct instead).
  179122. */
  179123. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  179124. #undef png_read_init
  179125. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  179126. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179127. #endif
  179128. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  179129. png_const_charp user_png_ver, png_size_t png_struct_size));
  179130. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179131. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  179132. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179133. png_info_size));
  179134. #endif
  179135. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179136. /* Initialize png_ptr struct for writing, and allocate any other memory.
  179137. * (old interface - DEPRECATED - use png_create_write_struct instead).
  179138. */
  179139. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  179140. #undef png_write_init
  179141. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  179142. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179143. #endif
  179144. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  179145. png_const_charp user_png_ver, png_size_t png_struct_size));
  179146. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  179147. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179148. png_info_size));
  179149. /* Allocate memory for an internal libpng struct */
  179150. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  179151. /* Free memory from internal libpng struct */
  179152. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  179153. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  179154. malloc_fn, png_voidp mem_ptr));
  179155. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  179156. png_free_ptr free_fn, png_voidp mem_ptr));
  179157. /* Free any memory that info_ptr points to and reset struct. */
  179158. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  179159. png_infop info_ptr));
  179160. #ifndef PNG_1_0_X
  179161. /* Function to allocate memory for zlib. */
  179162. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  179163. /* Function to free memory for zlib */
  179164. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  179165. #ifdef PNG_SIZE_T
  179166. /* Function to convert a sizeof an item to png_sizeof item */
  179167. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  179168. #endif
  179169. /* Next four functions are used internally as callbacks. PNGAPI is required
  179170. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  179171. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  179172. png_bytep data, png_size_t length));
  179173. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179174. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  179175. png_bytep buffer, png_size_t length));
  179176. #endif
  179177. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  179178. png_bytep data, png_size_t length));
  179179. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179180. #if !defined(PNG_NO_STDIO)
  179181. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  179182. #endif
  179183. #endif
  179184. #else /* PNG_1_0_X */
  179185. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179186. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  179187. png_bytep buffer, png_size_t length));
  179188. #endif
  179189. #endif /* PNG_1_0_X */
  179190. /* Reset the CRC variable */
  179191. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  179192. /* Write the "data" buffer to whatever output you are using. */
  179193. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  179194. png_size_t length));
  179195. /* Read data from whatever input you are using into the "data" buffer */
  179196. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  179197. png_size_t length));
  179198. /* Read bytes into buf, and update png_ptr->crc */
  179199. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  179200. png_size_t length));
  179201. /* Decompress data in a chunk that uses compression */
  179202. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  179203. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  179204. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  179205. int comp_type, png_charp chunkdata, png_size_t chunklength,
  179206. png_size_t prefix_length, png_size_t *data_length));
  179207. #endif
  179208. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  179209. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  179210. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  179211. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  179212. /* Calculate the CRC over a section of data. Note that we are only
  179213. * passing a maximum of 64K on systems that have this as a memory limit,
  179214. * since this is the maximum buffer size we can specify.
  179215. */
  179216. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  179217. png_size_t length));
  179218. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179219. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  179220. #endif
  179221. /* simple function to write the signature */
  179222. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  179223. /* write various chunks */
  179224. /* Write the IHDR chunk, and update the png_struct with the necessary
  179225. * information.
  179226. */
  179227. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  179228. png_uint_32 height,
  179229. int bit_depth, int color_type, int compression_method, int filter_method,
  179230. int interlace_method));
  179231. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  179232. png_uint_32 num_pal));
  179233. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  179234. png_size_t length));
  179235. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  179236. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  179237. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179238. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  179239. #endif
  179240. #ifdef PNG_FIXED_POINT_SUPPORTED
  179241. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  179242. file_gamma));
  179243. #endif
  179244. #endif
  179245. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  179246. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  179247. int color_type));
  179248. #endif
  179249. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  179250. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179251. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  179252. double white_x, double white_y,
  179253. double red_x, double red_y, double green_x, double green_y,
  179254. double blue_x, double blue_y));
  179255. #endif
  179256. #ifdef PNG_FIXED_POINT_SUPPORTED
  179257. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  179258. png_fixed_point int_white_x, png_fixed_point int_white_y,
  179259. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179260. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179261. png_fixed_point int_blue_y));
  179262. #endif
  179263. #endif
  179264. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  179265. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  179266. int intent));
  179267. #endif
  179268. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  179269. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  179270. png_charp name, int compression_type,
  179271. png_charp profile, int proflen));
  179272. /* Note to maintainer: profile should be png_bytep */
  179273. #endif
  179274. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  179275. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  179276. png_sPLT_tp palette));
  179277. #endif
  179278. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  179279. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  179280. png_color_16p values, int number, int color_type));
  179281. #endif
  179282. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  179283. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  179284. png_color_16p values, int color_type));
  179285. #endif
  179286. #if defined(PNG_WRITE_hIST_SUPPORTED)
  179287. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  179288. int num_hist));
  179289. #endif
  179290. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  179291. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  179292. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  179293. png_charp key, png_charpp new_key));
  179294. #endif
  179295. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  179296. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  179297. png_charp text, png_size_t text_len));
  179298. #endif
  179299. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  179300. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  179301. png_charp text, png_size_t text_len, int compression));
  179302. #endif
  179303. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  179304. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  179305. int compression, png_charp key, png_charp lang, png_charp lang_key,
  179306. png_charp text));
  179307. #endif
  179308. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  179309. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  179310. png_infop info_ptr, png_textp text_ptr, int num_text));
  179311. #endif
  179312. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  179313. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  179314. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  179315. #endif
  179316. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  179317. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  179318. png_int_32 X0, png_int_32 X1, int type, int nparams,
  179319. png_charp units, png_charpp params));
  179320. #endif
  179321. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  179322. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  179323. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  179324. int unit_type));
  179325. #endif
  179326. #if defined(PNG_WRITE_tIME_SUPPORTED)
  179327. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  179328. png_timep mod_time));
  179329. #endif
  179330. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  179331. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  179332. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  179333. int unit, double width, double height));
  179334. #else
  179335. #ifdef PNG_FIXED_POINT_SUPPORTED
  179336. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  179337. int unit, png_charp width, png_charp height));
  179338. #endif
  179339. #endif
  179340. #endif
  179341. /* Called when finished processing a row of data */
  179342. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  179343. /* Internal use only. Called before first row of data */
  179344. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  179345. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179346. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  179347. #endif
  179348. /* combine a row of data, dealing with alpha, etc. if requested */
  179349. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  179350. int mask));
  179351. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  179352. /* expand an interlaced row */
  179353. /* OLD pre-1.0.9 interface:
  179354. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  179355. png_bytep row, int pass, png_uint_32 transformations));
  179356. */
  179357. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  179358. #endif
  179359. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  179360. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  179361. /* grab pixels out of a row for an interlaced pass */
  179362. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  179363. png_bytep row, int pass));
  179364. #endif
  179365. /* unfilter a row */
  179366. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  179367. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  179368. /* Choose the best filter to use and filter the row data */
  179369. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  179370. png_row_infop row_info));
  179371. /* Write out the filtered row. */
  179372. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  179373. png_bytep filtered_row));
  179374. /* finish a row while reading, dealing with interlacing passes, etc. */
  179375. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  179376. /* initialize the row buffers, etc. */
  179377. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  179378. /* optional call to update the users info structure */
  179379. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  179380. png_infop info_ptr));
  179381. /* these are the functions that do the transformations */
  179382. #if defined(PNG_READ_FILLER_SUPPORTED)
  179383. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  179384. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  179385. #endif
  179386. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  179387. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  179388. png_bytep row));
  179389. #endif
  179390. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  179391. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  179392. png_bytep row));
  179393. #endif
  179394. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  179395. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  179396. png_bytep row));
  179397. #endif
  179398. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  179399. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  179400. png_bytep row));
  179401. #endif
  179402. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  179403. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  179404. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  179405. png_bytep row, png_uint_32 flags));
  179406. #endif
  179407. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  179408. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  179409. #endif
  179410. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  179411. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  179412. #endif
  179413. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179414. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  179415. row_info, png_bytep row));
  179416. #endif
  179417. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  179418. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  179419. png_bytep row));
  179420. #endif
  179421. #if defined(PNG_READ_PACK_SUPPORTED)
  179422. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  179423. #endif
  179424. #if defined(PNG_READ_SHIFT_SUPPORTED)
  179425. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  179426. png_color_8p sig_bits));
  179427. #endif
  179428. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  179429. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  179430. #endif
  179431. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  179432. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  179433. #endif
  179434. #if defined(PNG_READ_DITHER_SUPPORTED)
  179435. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  179436. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  179437. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  179438. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  179439. png_colorp palette, int num_palette));
  179440. # endif
  179441. #endif
  179442. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  179443. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  179444. #endif
  179445. #if defined(PNG_WRITE_PACK_SUPPORTED)
  179446. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  179447. png_bytep row, png_uint_32 bit_depth));
  179448. #endif
  179449. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  179450. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  179451. png_color_8p bit_depth));
  179452. #endif
  179453. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  179454. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179455. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  179456. png_color_16p trans_values, png_color_16p background,
  179457. png_color_16p background_1,
  179458. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  179459. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  179460. png_uint_16pp gamma_16_to_1, int gamma_shift));
  179461. #else
  179462. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  179463. png_color_16p trans_values, png_color_16p background));
  179464. #endif
  179465. #endif
  179466. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179467. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  179468. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  179469. int gamma_shift));
  179470. #endif
  179471. #if defined(PNG_READ_EXPAND_SUPPORTED)
  179472. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  179473. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  179474. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  179475. png_bytep row, png_color_16p trans_value));
  179476. #endif
  179477. /* The following decodes the appropriate chunks, and does error correction,
  179478. * then calls the appropriate callback for the chunk if it is valid.
  179479. */
  179480. /* decode the IHDR chunk */
  179481. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  179482. png_uint_32 length));
  179483. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  179484. png_uint_32 length));
  179485. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  179486. png_uint_32 length));
  179487. #if defined(PNG_READ_bKGD_SUPPORTED)
  179488. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  179489. png_uint_32 length));
  179490. #endif
  179491. #if defined(PNG_READ_cHRM_SUPPORTED)
  179492. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  179493. png_uint_32 length));
  179494. #endif
  179495. #if defined(PNG_READ_gAMA_SUPPORTED)
  179496. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  179497. png_uint_32 length));
  179498. #endif
  179499. #if defined(PNG_READ_hIST_SUPPORTED)
  179500. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  179501. png_uint_32 length));
  179502. #endif
  179503. #if defined(PNG_READ_iCCP_SUPPORTED)
  179504. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  179505. png_uint_32 length));
  179506. #endif /* PNG_READ_iCCP_SUPPORTED */
  179507. #if defined(PNG_READ_iTXt_SUPPORTED)
  179508. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  179509. png_uint_32 length));
  179510. #endif
  179511. #if defined(PNG_READ_oFFs_SUPPORTED)
  179512. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  179513. png_uint_32 length));
  179514. #endif
  179515. #if defined(PNG_READ_pCAL_SUPPORTED)
  179516. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  179517. png_uint_32 length));
  179518. #endif
  179519. #if defined(PNG_READ_pHYs_SUPPORTED)
  179520. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  179521. png_uint_32 length));
  179522. #endif
  179523. #if defined(PNG_READ_sBIT_SUPPORTED)
  179524. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  179525. png_uint_32 length));
  179526. #endif
  179527. #if defined(PNG_READ_sCAL_SUPPORTED)
  179528. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  179529. png_uint_32 length));
  179530. #endif
  179531. #if defined(PNG_READ_sPLT_SUPPORTED)
  179532. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  179533. png_uint_32 length));
  179534. #endif /* PNG_READ_sPLT_SUPPORTED */
  179535. #if defined(PNG_READ_sRGB_SUPPORTED)
  179536. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  179537. png_uint_32 length));
  179538. #endif
  179539. #if defined(PNG_READ_tEXt_SUPPORTED)
  179540. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  179541. png_uint_32 length));
  179542. #endif
  179543. #if defined(PNG_READ_tIME_SUPPORTED)
  179544. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  179545. png_uint_32 length));
  179546. #endif
  179547. #if defined(PNG_READ_tRNS_SUPPORTED)
  179548. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  179549. png_uint_32 length));
  179550. #endif
  179551. #if defined(PNG_READ_zTXt_SUPPORTED)
  179552. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  179553. png_uint_32 length));
  179554. #endif
  179555. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  179556. png_infop info_ptr, png_uint_32 length));
  179557. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  179558. png_bytep chunk_name));
  179559. /* handle the transformations for reading and writing */
  179560. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  179561. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  179562. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  179563. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179564. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  179565. png_infop info_ptr));
  179566. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  179567. png_infop info_ptr));
  179568. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  179569. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  179570. png_uint_32 length));
  179571. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  179572. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  179573. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  179574. png_bytep buffer, png_size_t buffer_length));
  179575. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  179576. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  179577. png_bytep buffer, png_size_t buffer_length));
  179578. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  179579. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  179580. png_infop info_ptr, png_uint_32 length));
  179581. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  179582. png_infop info_ptr));
  179583. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  179584. png_infop info_ptr));
  179585. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  179586. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  179587. png_infop info_ptr));
  179588. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  179589. png_infop info_ptr));
  179590. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  179591. #if defined(PNG_READ_tEXt_SUPPORTED)
  179592. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  179593. png_infop info_ptr, png_uint_32 length));
  179594. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  179595. png_infop info_ptr));
  179596. #endif
  179597. #if defined(PNG_READ_zTXt_SUPPORTED)
  179598. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  179599. png_infop info_ptr, png_uint_32 length));
  179600. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  179601. png_infop info_ptr));
  179602. #endif
  179603. #if defined(PNG_READ_iTXt_SUPPORTED)
  179604. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  179605. png_infop info_ptr, png_uint_32 length));
  179606. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  179607. png_infop info_ptr));
  179608. #endif
  179609. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179610. #ifdef PNG_MNG_FEATURES_SUPPORTED
  179611. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  179612. png_bytep row));
  179613. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  179614. png_bytep row));
  179615. #endif
  179616. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179617. #if defined(PNG_MMX_CODE_SUPPORTED)
  179618. /* png.c */ /* PRIVATE */
  179619. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  179620. #endif
  179621. #endif
  179622. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179623. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  179624. png_infop info_ptr));
  179625. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  179626. png_infop info_ptr));
  179627. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  179628. png_infop info_ptr));
  179629. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  179630. png_infop info_ptr));
  179631. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  179632. png_infop info_ptr));
  179633. #if defined(PNG_pHYs_SUPPORTED)
  179634. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  179635. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  179636. #endif /* PNG_pHYs_SUPPORTED */
  179637. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  179638. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  179639. #endif /* PNG_INTERNAL */
  179640. #ifdef __cplusplus
  179641. }
  179642. #endif
  179643. #endif /* PNG_VERSION_INFO_ONLY */
  179644. /* do not put anything past this line */
  179645. #endif /* PNG_H */
  179646. /********* End of inlined file: png.h *********/
  179647. #define PNG_NO_EXTERN
  179648. /********* Start of inlined file: png.c *********/
  179649. /* png.c - location for general purpose libpng functions
  179650. *
  179651. * Last changed in libpng 1.2.21 [October 4, 2007]
  179652. * For conditions of distribution and use, see copyright notice in png.h
  179653. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179654. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179655. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179656. */
  179657. #define PNG_INTERNAL
  179658. #define PNG_NO_EXTERN
  179659. /* Generate a compiler error if there is an old png.h in the search path. */
  179660. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  179661. /* Version information for C files. This had better match the version
  179662. * string defined in png.h. */
  179663. #ifdef PNG_USE_GLOBAL_ARRAYS
  179664. /* png_libpng_ver was changed to a function in version 1.0.5c */
  179665. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  179666. #ifdef PNG_READ_SUPPORTED
  179667. /* png_sig was changed to a function in version 1.0.5c */
  179668. /* Place to hold the signature string for a PNG file. */
  179669. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  179670. #endif /* PNG_READ_SUPPORTED */
  179671. /* Invoke global declarations for constant strings for known chunk types */
  179672. PNG_IHDR;
  179673. PNG_IDAT;
  179674. PNG_IEND;
  179675. PNG_PLTE;
  179676. PNG_bKGD;
  179677. PNG_cHRM;
  179678. PNG_gAMA;
  179679. PNG_hIST;
  179680. PNG_iCCP;
  179681. PNG_iTXt;
  179682. PNG_oFFs;
  179683. PNG_pCAL;
  179684. PNG_sCAL;
  179685. PNG_pHYs;
  179686. PNG_sBIT;
  179687. PNG_sPLT;
  179688. PNG_sRGB;
  179689. PNG_tEXt;
  179690. PNG_tIME;
  179691. PNG_tRNS;
  179692. PNG_zTXt;
  179693. #ifdef PNG_READ_SUPPORTED
  179694. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  179695. /* start of interlace block */
  179696. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  179697. /* offset to next interlace block */
  179698. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  179699. /* start of interlace block in the y direction */
  179700. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  179701. /* offset to next interlace block in the y direction */
  179702. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  179703. /* Height of interlace block. This is not currently used - if you need
  179704. * it, uncomment it here and in png.h
  179705. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  179706. */
  179707. /* Mask to determine which pixels are valid in a pass */
  179708. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  179709. /* Mask to determine which pixels to overwrite while displaying */
  179710. PNG_CONST int FARDATA png_pass_dsp_mask[]
  179711. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  179712. #endif /* PNG_READ_SUPPORTED */
  179713. #endif /* PNG_USE_GLOBAL_ARRAYS */
  179714. /* Tells libpng that we have already handled the first "num_bytes" bytes
  179715. * of the PNG file signature. If the PNG data is embedded into another
  179716. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  179717. * or write any of the magic bytes before it starts on the IHDR.
  179718. */
  179719. #ifdef PNG_READ_SUPPORTED
  179720. void PNGAPI
  179721. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  179722. {
  179723. if(png_ptr == NULL) return;
  179724. png_debug(1, "in png_set_sig_bytes\n");
  179725. if (num_bytes > 8)
  179726. png_error(png_ptr, "Too many bytes for PNG signature.");
  179727. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  179728. }
  179729. /* Checks whether the supplied bytes match the PNG signature. We allow
  179730. * checking less than the full 8-byte signature so that those apps that
  179731. * already read the first few bytes of a file to determine the file type
  179732. * can simply check the remaining bytes for extra assurance. Returns
  179733. * an integer less than, equal to, or greater than zero if sig is found,
  179734. * respectively, to be less than, to match, or be greater than the correct
  179735. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  179736. */
  179737. int PNGAPI
  179738. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  179739. {
  179740. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  179741. if (num_to_check > 8)
  179742. num_to_check = 8;
  179743. else if (num_to_check < 1)
  179744. return (-1);
  179745. if (start > 7)
  179746. return (-1);
  179747. if (start + num_to_check > 8)
  179748. num_to_check = 8 - start;
  179749. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  179750. }
  179751. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  179752. /* (Obsolete) function to check signature bytes. It does not allow one
  179753. * to check a partial signature. This function might be removed in the
  179754. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  179755. */
  179756. int PNGAPI
  179757. png_check_sig(png_bytep sig, int num)
  179758. {
  179759. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  179760. }
  179761. #endif
  179762. #endif /* PNG_READ_SUPPORTED */
  179763. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179764. /* Function to allocate memory for zlib and clear it to 0. */
  179765. #ifdef PNG_1_0_X
  179766. voidpf PNGAPI
  179767. #else
  179768. voidpf /* private */
  179769. #endif
  179770. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  179771. {
  179772. png_voidp ptr;
  179773. png_structp p=(png_structp)png_ptr;
  179774. png_uint_32 save_flags=p->flags;
  179775. png_uint_32 num_bytes;
  179776. if(png_ptr == NULL) return (NULL);
  179777. if (items > PNG_UINT_32_MAX/size)
  179778. {
  179779. png_warning (p, "Potential overflow in png_zalloc()");
  179780. return (NULL);
  179781. }
  179782. num_bytes = (png_uint_32)items * size;
  179783. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  179784. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  179785. p->flags=save_flags;
  179786. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  179787. if (ptr == NULL)
  179788. return ((voidpf)ptr);
  179789. if (num_bytes > (png_uint_32)0x8000L)
  179790. {
  179791. png_memset(ptr, 0, (png_size_t)0x8000L);
  179792. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  179793. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  179794. }
  179795. else
  179796. {
  179797. png_memset(ptr, 0, (png_size_t)num_bytes);
  179798. }
  179799. #endif
  179800. return ((voidpf)ptr);
  179801. }
  179802. /* function to free memory for zlib */
  179803. #ifdef PNG_1_0_X
  179804. void PNGAPI
  179805. #else
  179806. void /* private */
  179807. #endif
  179808. png_zfree(voidpf png_ptr, voidpf ptr)
  179809. {
  179810. png_free((png_structp)png_ptr, (png_voidp)ptr);
  179811. }
  179812. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  179813. * in case CRC is > 32 bits to leave the top bits 0.
  179814. */
  179815. void /* PRIVATE */
  179816. png_reset_crc(png_structp png_ptr)
  179817. {
  179818. png_ptr->crc = crc32(0, Z_NULL, 0);
  179819. }
  179820. /* Calculate the CRC over a section of data. We can only pass as
  179821. * much data to this routine as the largest single buffer size. We
  179822. * also check that this data will actually be used before going to the
  179823. * trouble of calculating it.
  179824. */
  179825. void /* PRIVATE */
  179826. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  179827. {
  179828. int need_crc = 1;
  179829. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  179830. {
  179831. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  179832. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  179833. need_crc = 0;
  179834. }
  179835. else /* critical */
  179836. {
  179837. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  179838. need_crc = 0;
  179839. }
  179840. if (need_crc)
  179841. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  179842. }
  179843. /* Allocate the memory for an info_struct for the application. We don't
  179844. * really need the png_ptr, but it could potentially be useful in the
  179845. * future. This should be used in favour of malloc(png_sizeof(png_info))
  179846. * and png_info_init() so that applications that want to use a shared
  179847. * libpng don't have to be recompiled if png_info changes size.
  179848. */
  179849. png_infop PNGAPI
  179850. png_create_info_struct(png_structp png_ptr)
  179851. {
  179852. png_infop info_ptr;
  179853. png_debug(1, "in png_create_info_struct\n");
  179854. if(png_ptr == NULL) return (NULL);
  179855. #ifdef PNG_USER_MEM_SUPPORTED
  179856. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  179857. png_ptr->malloc_fn, png_ptr->mem_ptr);
  179858. #else
  179859. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  179860. #endif
  179861. if (info_ptr != NULL)
  179862. png_info_init_3(&info_ptr, png_sizeof(png_info));
  179863. return (info_ptr);
  179864. }
  179865. /* This function frees the memory associated with a single info struct.
  179866. * Normally, one would use either png_destroy_read_struct() or
  179867. * png_destroy_write_struct() to free an info struct, but this may be
  179868. * useful for some applications.
  179869. */
  179870. void PNGAPI
  179871. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  179872. {
  179873. png_infop info_ptr = NULL;
  179874. if(png_ptr == NULL) return;
  179875. png_debug(1, "in png_destroy_info_struct\n");
  179876. if (info_ptr_ptr != NULL)
  179877. info_ptr = *info_ptr_ptr;
  179878. if (info_ptr != NULL)
  179879. {
  179880. png_info_destroy(png_ptr, info_ptr);
  179881. #ifdef PNG_USER_MEM_SUPPORTED
  179882. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  179883. png_ptr->mem_ptr);
  179884. #else
  179885. png_destroy_struct((png_voidp)info_ptr);
  179886. #endif
  179887. *info_ptr_ptr = NULL;
  179888. }
  179889. }
  179890. /* Initialize the info structure. This is now an internal function (0.89)
  179891. * and applications using it are urged to use png_create_info_struct()
  179892. * instead.
  179893. */
  179894. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  179895. #undef png_info_init
  179896. void PNGAPI
  179897. png_info_init(png_infop info_ptr)
  179898. {
  179899. /* We only come here via pre-1.0.12-compiled applications */
  179900. png_info_init_3(&info_ptr, 0);
  179901. }
  179902. #endif
  179903. void PNGAPI
  179904. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  179905. {
  179906. png_infop info_ptr = *ptr_ptr;
  179907. if(info_ptr == NULL) return;
  179908. png_debug(1, "in png_info_init_3\n");
  179909. if(png_sizeof(png_info) > png_info_struct_size)
  179910. {
  179911. png_destroy_struct(info_ptr);
  179912. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  179913. *ptr_ptr = info_ptr;
  179914. }
  179915. /* set everything to 0 */
  179916. png_memset(info_ptr, 0, png_sizeof (png_info));
  179917. }
  179918. #ifdef PNG_FREE_ME_SUPPORTED
  179919. void PNGAPI
  179920. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  179921. int freer, png_uint_32 mask)
  179922. {
  179923. png_debug(1, "in png_data_freer\n");
  179924. if (png_ptr == NULL || info_ptr == NULL)
  179925. return;
  179926. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  179927. info_ptr->free_me |= mask;
  179928. else if(freer == PNG_USER_WILL_FREE_DATA)
  179929. info_ptr->free_me &= ~mask;
  179930. else
  179931. png_warning(png_ptr,
  179932. "Unknown freer parameter in png_data_freer.");
  179933. }
  179934. #endif
  179935. void PNGAPI
  179936. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  179937. int num)
  179938. {
  179939. png_debug(1, "in png_free_data\n");
  179940. if (png_ptr == NULL || info_ptr == NULL)
  179941. return;
  179942. #if defined(PNG_TEXT_SUPPORTED)
  179943. /* free text item num or (if num == -1) all text items */
  179944. #ifdef PNG_FREE_ME_SUPPORTED
  179945. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  179946. #else
  179947. if (mask & PNG_FREE_TEXT)
  179948. #endif
  179949. {
  179950. if (num != -1)
  179951. {
  179952. if (info_ptr->text && info_ptr->text[num].key)
  179953. {
  179954. png_free(png_ptr, info_ptr->text[num].key);
  179955. info_ptr->text[num].key = NULL;
  179956. }
  179957. }
  179958. else
  179959. {
  179960. int i;
  179961. for (i = 0; i < info_ptr->num_text; i++)
  179962. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  179963. png_free(png_ptr, info_ptr->text);
  179964. info_ptr->text = NULL;
  179965. info_ptr->num_text=0;
  179966. }
  179967. }
  179968. #endif
  179969. #if defined(PNG_tRNS_SUPPORTED)
  179970. /* free any tRNS entry */
  179971. #ifdef PNG_FREE_ME_SUPPORTED
  179972. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  179973. #else
  179974. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  179975. #endif
  179976. {
  179977. png_free(png_ptr, info_ptr->trans);
  179978. info_ptr->valid &= ~PNG_INFO_tRNS;
  179979. #ifndef PNG_FREE_ME_SUPPORTED
  179980. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  179981. #endif
  179982. info_ptr->trans = NULL;
  179983. }
  179984. #endif
  179985. #if defined(PNG_sCAL_SUPPORTED)
  179986. /* free any sCAL entry */
  179987. #ifdef PNG_FREE_ME_SUPPORTED
  179988. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  179989. #else
  179990. if (mask & PNG_FREE_SCAL)
  179991. #endif
  179992. {
  179993. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  179994. png_free(png_ptr, info_ptr->scal_s_width);
  179995. png_free(png_ptr, info_ptr->scal_s_height);
  179996. info_ptr->scal_s_width = NULL;
  179997. info_ptr->scal_s_height = NULL;
  179998. #endif
  179999. info_ptr->valid &= ~PNG_INFO_sCAL;
  180000. }
  180001. #endif
  180002. #if defined(PNG_pCAL_SUPPORTED)
  180003. /* free any pCAL entry */
  180004. #ifdef PNG_FREE_ME_SUPPORTED
  180005. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  180006. #else
  180007. if (mask & PNG_FREE_PCAL)
  180008. #endif
  180009. {
  180010. png_free(png_ptr, info_ptr->pcal_purpose);
  180011. png_free(png_ptr, info_ptr->pcal_units);
  180012. info_ptr->pcal_purpose = NULL;
  180013. info_ptr->pcal_units = NULL;
  180014. if (info_ptr->pcal_params != NULL)
  180015. {
  180016. int i;
  180017. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  180018. {
  180019. png_free(png_ptr, info_ptr->pcal_params[i]);
  180020. info_ptr->pcal_params[i]=NULL;
  180021. }
  180022. png_free(png_ptr, info_ptr->pcal_params);
  180023. info_ptr->pcal_params = NULL;
  180024. }
  180025. info_ptr->valid &= ~PNG_INFO_pCAL;
  180026. }
  180027. #endif
  180028. #if defined(PNG_iCCP_SUPPORTED)
  180029. /* free any iCCP entry */
  180030. #ifdef PNG_FREE_ME_SUPPORTED
  180031. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  180032. #else
  180033. if (mask & PNG_FREE_ICCP)
  180034. #endif
  180035. {
  180036. png_free(png_ptr, info_ptr->iccp_name);
  180037. png_free(png_ptr, info_ptr->iccp_profile);
  180038. info_ptr->iccp_name = NULL;
  180039. info_ptr->iccp_profile = NULL;
  180040. info_ptr->valid &= ~PNG_INFO_iCCP;
  180041. }
  180042. #endif
  180043. #if defined(PNG_sPLT_SUPPORTED)
  180044. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  180045. #ifdef PNG_FREE_ME_SUPPORTED
  180046. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  180047. #else
  180048. if (mask & PNG_FREE_SPLT)
  180049. #endif
  180050. {
  180051. if (num != -1)
  180052. {
  180053. if(info_ptr->splt_palettes)
  180054. {
  180055. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  180056. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  180057. info_ptr->splt_palettes[num].name = NULL;
  180058. info_ptr->splt_palettes[num].entries = NULL;
  180059. }
  180060. }
  180061. else
  180062. {
  180063. if(info_ptr->splt_palettes_num)
  180064. {
  180065. int i;
  180066. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  180067. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  180068. png_free(png_ptr, info_ptr->splt_palettes);
  180069. info_ptr->splt_palettes = NULL;
  180070. info_ptr->splt_palettes_num = 0;
  180071. }
  180072. info_ptr->valid &= ~PNG_INFO_sPLT;
  180073. }
  180074. }
  180075. #endif
  180076. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180077. if(png_ptr->unknown_chunk.data)
  180078. {
  180079. png_free(png_ptr, png_ptr->unknown_chunk.data);
  180080. png_ptr->unknown_chunk.data = NULL;
  180081. }
  180082. #ifdef PNG_FREE_ME_SUPPORTED
  180083. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  180084. #else
  180085. if (mask & PNG_FREE_UNKN)
  180086. #endif
  180087. {
  180088. if (num != -1)
  180089. {
  180090. if(info_ptr->unknown_chunks)
  180091. {
  180092. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  180093. info_ptr->unknown_chunks[num].data = NULL;
  180094. }
  180095. }
  180096. else
  180097. {
  180098. int i;
  180099. if(info_ptr->unknown_chunks_num)
  180100. {
  180101. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  180102. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  180103. png_free(png_ptr, info_ptr->unknown_chunks);
  180104. info_ptr->unknown_chunks = NULL;
  180105. info_ptr->unknown_chunks_num = 0;
  180106. }
  180107. }
  180108. }
  180109. #endif
  180110. #if defined(PNG_hIST_SUPPORTED)
  180111. /* free any hIST entry */
  180112. #ifdef PNG_FREE_ME_SUPPORTED
  180113. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  180114. #else
  180115. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  180116. #endif
  180117. {
  180118. png_free(png_ptr, info_ptr->hist);
  180119. info_ptr->hist = NULL;
  180120. info_ptr->valid &= ~PNG_INFO_hIST;
  180121. #ifndef PNG_FREE_ME_SUPPORTED
  180122. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  180123. #endif
  180124. }
  180125. #endif
  180126. /* free any PLTE entry that was internally allocated */
  180127. #ifdef PNG_FREE_ME_SUPPORTED
  180128. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  180129. #else
  180130. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  180131. #endif
  180132. {
  180133. png_zfree(png_ptr, info_ptr->palette);
  180134. info_ptr->palette = NULL;
  180135. info_ptr->valid &= ~PNG_INFO_PLTE;
  180136. #ifndef PNG_FREE_ME_SUPPORTED
  180137. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  180138. #endif
  180139. info_ptr->num_palette = 0;
  180140. }
  180141. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180142. /* free any image bits attached to the info structure */
  180143. #ifdef PNG_FREE_ME_SUPPORTED
  180144. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  180145. #else
  180146. if (mask & PNG_FREE_ROWS)
  180147. #endif
  180148. {
  180149. if(info_ptr->row_pointers)
  180150. {
  180151. int row;
  180152. for (row = 0; row < (int)info_ptr->height; row++)
  180153. {
  180154. png_free(png_ptr, info_ptr->row_pointers[row]);
  180155. info_ptr->row_pointers[row]=NULL;
  180156. }
  180157. png_free(png_ptr, info_ptr->row_pointers);
  180158. info_ptr->row_pointers=NULL;
  180159. }
  180160. info_ptr->valid &= ~PNG_INFO_IDAT;
  180161. }
  180162. #endif
  180163. #ifdef PNG_FREE_ME_SUPPORTED
  180164. if(num == -1)
  180165. info_ptr->free_me &= ~mask;
  180166. else
  180167. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  180168. #endif
  180169. }
  180170. /* This is an internal routine to free any memory that the info struct is
  180171. * pointing to before re-using it or freeing the struct itself. Recall
  180172. * that png_free() checks for NULL pointers for us.
  180173. */
  180174. void /* PRIVATE */
  180175. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  180176. {
  180177. png_debug(1, "in png_info_destroy\n");
  180178. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  180179. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180180. if (png_ptr->num_chunk_list)
  180181. {
  180182. png_free(png_ptr, png_ptr->chunk_list);
  180183. png_ptr->chunk_list=NULL;
  180184. png_ptr->num_chunk_list=0;
  180185. }
  180186. #endif
  180187. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180188. }
  180189. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180190. /* This function returns a pointer to the io_ptr associated with the user
  180191. * functions. The application should free any memory associated with this
  180192. * pointer before png_write_destroy() or png_read_destroy() are called.
  180193. */
  180194. png_voidp PNGAPI
  180195. png_get_io_ptr(png_structp png_ptr)
  180196. {
  180197. if(png_ptr == NULL) return (NULL);
  180198. return (png_ptr->io_ptr);
  180199. }
  180200. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180201. #if !defined(PNG_NO_STDIO)
  180202. /* Initialize the default input/output functions for the PNG file. If you
  180203. * use your own read or write routines, you can call either png_set_read_fn()
  180204. * or png_set_write_fn() instead of png_init_io(). If you have defined
  180205. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  180206. * necessarily available.
  180207. */
  180208. void PNGAPI
  180209. png_init_io(png_structp png_ptr, png_FILE_p fp)
  180210. {
  180211. png_debug(1, "in png_init_io\n");
  180212. if(png_ptr == NULL) return;
  180213. png_ptr->io_ptr = (png_voidp)fp;
  180214. }
  180215. #endif
  180216. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  180217. /* Convert the supplied time into an RFC 1123 string suitable for use in
  180218. * a "Creation Time" or other text-based time string.
  180219. */
  180220. png_charp PNGAPI
  180221. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  180222. {
  180223. static PNG_CONST char short_months[12][4] =
  180224. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  180225. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  180226. if(png_ptr == NULL) return (NULL);
  180227. if (png_ptr->time_buffer == NULL)
  180228. {
  180229. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  180230. png_sizeof(char)));
  180231. }
  180232. #if defined(_WIN32_WCE)
  180233. {
  180234. wchar_t time_buf[29];
  180235. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  180236. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180237. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180238. ptime->second % 61);
  180239. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  180240. NULL, NULL);
  180241. }
  180242. #else
  180243. #ifdef USE_FAR_KEYWORD
  180244. {
  180245. char near_time_buf[29];
  180246. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  180247. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180248. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180249. ptime->second % 61);
  180250. png_memcpy(png_ptr->time_buffer, near_time_buf,
  180251. 29*png_sizeof(char));
  180252. }
  180253. #else
  180254. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  180255. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180256. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180257. ptime->second % 61);
  180258. #endif
  180259. #endif /* _WIN32_WCE */
  180260. return ((png_charp)png_ptr->time_buffer);
  180261. }
  180262. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  180263. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180264. png_charp PNGAPI
  180265. png_get_copyright(png_structp png_ptr)
  180266. {
  180267. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180268. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  180269. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  180270. Copyright (c) 1996-1997 Andreas Dilger\n\
  180271. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  180272. }
  180273. /* The following return the library version as a short string in the
  180274. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  180275. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  180276. * is defined in png.h.
  180277. * Note: now there is no difference between png_get_libpng_ver() and
  180278. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  180279. * it is guaranteed that png.c uses the correct version of png.h.
  180280. */
  180281. png_charp PNGAPI
  180282. png_get_libpng_ver(png_structp png_ptr)
  180283. {
  180284. /* Version of *.c files used when building libpng */
  180285. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180286. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180287. }
  180288. png_charp PNGAPI
  180289. png_get_header_ver(png_structp png_ptr)
  180290. {
  180291. /* Version of *.h files used when building libpng */
  180292. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180293. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180294. }
  180295. png_charp PNGAPI
  180296. png_get_header_version(png_structp png_ptr)
  180297. {
  180298. /* Returns longer string containing both version and date */
  180299. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180300. return ((png_charp) PNG_HEADER_VERSION_STRING
  180301. #ifndef PNG_READ_SUPPORTED
  180302. " (NO READ SUPPORT)"
  180303. #endif
  180304. "\n");
  180305. }
  180306. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180307. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180308. int PNGAPI
  180309. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  180310. {
  180311. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  180312. int i;
  180313. png_bytep p;
  180314. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  180315. return 0;
  180316. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  180317. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  180318. if (!png_memcmp(chunk_name, p, 4))
  180319. return ((int)*(p+4));
  180320. return 0;
  180321. }
  180322. #endif
  180323. /* This function, added to libpng-1.0.6g, is untested. */
  180324. int PNGAPI
  180325. png_reset_zstream(png_structp png_ptr)
  180326. {
  180327. if (png_ptr == NULL) return Z_STREAM_ERROR;
  180328. return (inflateReset(&png_ptr->zstream));
  180329. }
  180330. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180331. /* This function was added to libpng-1.0.7 */
  180332. png_uint_32 PNGAPI
  180333. png_access_version_number(void)
  180334. {
  180335. /* Version of *.c files used when building libpng */
  180336. return((png_uint_32) PNG_LIBPNG_VER);
  180337. }
  180338. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180339. #if !defined(PNG_1_0_X)
  180340. /* this function was added to libpng 1.2.0 */
  180341. int PNGAPI
  180342. png_mmx_support(void)
  180343. {
  180344. /* obsolete, to be removed from libpng-1.4.0 */
  180345. return -1;
  180346. }
  180347. #endif /* PNG_1_0_X */
  180348. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  180349. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180350. #ifdef PNG_SIZE_T
  180351. /* Added at libpng version 1.2.6 */
  180352. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  180353. png_size_t PNGAPI
  180354. png_convert_size(size_t size)
  180355. {
  180356. if (size > (png_size_t)-1)
  180357. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  180358. return ((png_size_t)size);
  180359. }
  180360. #endif /* PNG_SIZE_T */
  180361. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180362. /********* End of inlined file: png.c *********/
  180363. /********* Start of inlined file: pngerror.c *********/
  180364. /* pngerror.c - stub functions for i/o and memory allocation
  180365. *
  180366. * Last changed in libpng 1.2.20 October 4, 2007
  180367. * For conditions of distribution and use, see copyright notice in png.h
  180368. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180369. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180370. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180371. *
  180372. * This file provides a location for all error handling. Users who
  180373. * need special error handling are expected to write replacement functions
  180374. * and use png_set_error_fn() to use those functions. See the instructions
  180375. * at each function.
  180376. */
  180377. #define PNG_INTERNAL
  180378. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180379. static void /* PRIVATE */
  180380. png_default_error PNGARG((png_structp png_ptr,
  180381. png_const_charp error_message));
  180382. #ifndef PNG_NO_WARNINGS
  180383. static void /* PRIVATE */
  180384. png_default_warning PNGARG((png_structp png_ptr,
  180385. png_const_charp warning_message));
  180386. #endif /* PNG_NO_WARNINGS */
  180387. /* This function is called whenever there is a fatal error. This function
  180388. * should not be changed. If there is a need to handle errors differently,
  180389. * you should supply a replacement error function and use png_set_error_fn()
  180390. * to replace the error function at run-time.
  180391. */
  180392. #ifndef PNG_NO_ERROR_TEXT
  180393. void PNGAPI
  180394. png_error(png_structp png_ptr, png_const_charp error_message)
  180395. {
  180396. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180397. char msg[16];
  180398. if (png_ptr != NULL)
  180399. {
  180400. if (png_ptr->flags&
  180401. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  180402. {
  180403. if (*error_message == '#')
  180404. {
  180405. int offset;
  180406. for (offset=1; offset<15; offset++)
  180407. if (*(error_message+offset) == ' ')
  180408. break;
  180409. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  180410. {
  180411. int i;
  180412. for (i=0; i<offset-1; i++)
  180413. msg[i]=error_message[i+1];
  180414. msg[i]='\0';
  180415. error_message=msg;
  180416. }
  180417. else
  180418. error_message+=offset;
  180419. }
  180420. else
  180421. {
  180422. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  180423. {
  180424. msg[0]='0';
  180425. msg[1]='\0';
  180426. error_message=msg;
  180427. }
  180428. }
  180429. }
  180430. }
  180431. #endif
  180432. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  180433. (*(png_ptr->error_fn))(png_ptr, error_message);
  180434. /* If the custom handler doesn't exist, or if it returns,
  180435. use the default handler, which will not return. */
  180436. png_default_error(png_ptr, error_message);
  180437. }
  180438. #else
  180439. void PNGAPI
  180440. png_err(png_structp png_ptr)
  180441. {
  180442. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  180443. (*(png_ptr->error_fn))(png_ptr, '\0');
  180444. /* If the custom handler doesn't exist, or if it returns,
  180445. use the default handler, which will not return. */
  180446. png_default_error(png_ptr, '\0');
  180447. }
  180448. #endif /* PNG_NO_ERROR_TEXT */
  180449. #ifndef PNG_NO_WARNINGS
  180450. /* This function is called whenever there is a non-fatal error. This function
  180451. * should not be changed. If there is a need to handle warnings differently,
  180452. * you should supply a replacement warning function and use
  180453. * png_set_error_fn() to replace the warning function at run-time.
  180454. */
  180455. void PNGAPI
  180456. png_warning(png_structp png_ptr, png_const_charp warning_message)
  180457. {
  180458. int offset = 0;
  180459. if (png_ptr != NULL)
  180460. {
  180461. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180462. if (png_ptr->flags&
  180463. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  180464. #endif
  180465. {
  180466. if (*warning_message == '#')
  180467. {
  180468. for (offset=1; offset<15; offset++)
  180469. if (*(warning_message+offset) == ' ')
  180470. break;
  180471. }
  180472. }
  180473. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  180474. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  180475. }
  180476. else
  180477. png_default_warning(png_ptr, warning_message+offset);
  180478. }
  180479. #endif /* PNG_NO_WARNINGS */
  180480. /* These utilities are used internally to build an error message that relates
  180481. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  180482. * this is used to prefix the message. The message is limited in length
  180483. * to 63 bytes, the name characters are output as hex digits wrapped in []
  180484. * if the character is invalid.
  180485. */
  180486. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  180487. /*static PNG_CONST char png_digit[16] = {
  180488. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  180489. 'A', 'B', 'C', 'D', 'E', 'F'
  180490. };*/
  180491. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  180492. static void /* PRIVATE */
  180493. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  180494. error_message)
  180495. {
  180496. int iout = 0, iin = 0;
  180497. while (iin < 4)
  180498. {
  180499. int c = png_ptr->chunk_name[iin++];
  180500. if (isnonalpha(c))
  180501. {
  180502. buffer[iout++] = '[';
  180503. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  180504. buffer[iout++] = png_digit[c & 0x0f];
  180505. buffer[iout++] = ']';
  180506. }
  180507. else
  180508. {
  180509. buffer[iout++] = (png_byte)c;
  180510. }
  180511. }
  180512. if (error_message == NULL)
  180513. buffer[iout] = 0;
  180514. else
  180515. {
  180516. buffer[iout++] = ':';
  180517. buffer[iout++] = ' ';
  180518. png_strncpy(buffer+iout, error_message, 63);
  180519. buffer[iout+63] = 0;
  180520. }
  180521. }
  180522. #ifdef PNG_READ_SUPPORTED
  180523. void PNGAPI
  180524. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  180525. {
  180526. char msg[18+64];
  180527. if (png_ptr == NULL)
  180528. png_error(png_ptr, error_message);
  180529. else
  180530. {
  180531. png_format_buffer(png_ptr, msg, error_message);
  180532. png_error(png_ptr, msg);
  180533. }
  180534. }
  180535. #endif /* PNG_READ_SUPPORTED */
  180536. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  180537. #ifndef PNG_NO_WARNINGS
  180538. void PNGAPI
  180539. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  180540. {
  180541. char msg[18+64];
  180542. if (png_ptr == NULL)
  180543. png_warning(png_ptr, warning_message);
  180544. else
  180545. {
  180546. png_format_buffer(png_ptr, msg, warning_message);
  180547. png_warning(png_ptr, msg);
  180548. }
  180549. }
  180550. #endif /* PNG_NO_WARNINGS */
  180551. /* This is the default error handling function. Note that replacements for
  180552. * this function MUST NOT RETURN, or the program will likely crash. This
  180553. * function is used by default, or if the program supplies NULL for the
  180554. * error function pointer in png_set_error_fn().
  180555. */
  180556. static void /* PRIVATE */
  180557. png_default_error(png_structp png_ptr, png_const_charp error_message)
  180558. {
  180559. #ifndef PNG_NO_CONSOLE_IO
  180560. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180561. if (*error_message == '#')
  180562. {
  180563. int offset;
  180564. char error_number[16];
  180565. for (offset=0; offset<15; offset++)
  180566. {
  180567. error_number[offset] = *(error_message+offset+1);
  180568. if (*(error_message+offset) == ' ')
  180569. break;
  180570. }
  180571. if((offset > 1) && (offset < 15))
  180572. {
  180573. error_number[offset-1]='\0';
  180574. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  180575. error_message+offset);
  180576. }
  180577. else
  180578. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  180579. }
  180580. else
  180581. #endif
  180582. fprintf(stderr, "libpng error: %s\n", error_message);
  180583. #endif
  180584. #ifdef PNG_SETJMP_SUPPORTED
  180585. if (png_ptr)
  180586. {
  180587. # ifdef USE_FAR_KEYWORD
  180588. {
  180589. jmp_buf jmpbuf;
  180590. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  180591. longjmp(jmpbuf, 1);
  180592. }
  180593. # else
  180594. longjmp(png_ptr->jmpbuf, 1);
  180595. # endif
  180596. }
  180597. #else
  180598. PNG_ABORT();
  180599. #endif
  180600. #ifdef PNG_NO_CONSOLE_IO
  180601. error_message = error_message; /* make compiler happy */
  180602. #endif
  180603. }
  180604. #ifndef PNG_NO_WARNINGS
  180605. /* This function is called when there is a warning, but the library thinks
  180606. * it can continue anyway. Replacement functions don't have to do anything
  180607. * here if you don't want them to. In the default configuration, png_ptr is
  180608. * not used, but it is passed in case it may be useful.
  180609. */
  180610. static void /* PRIVATE */
  180611. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  180612. {
  180613. #ifndef PNG_NO_CONSOLE_IO
  180614. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180615. if (*warning_message == '#')
  180616. {
  180617. int offset;
  180618. char warning_number[16];
  180619. for (offset=0; offset<15; offset++)
  180620. {
  180621. warning_number[offset]=*(warning_message+offset+1);
  180622. if (*(warning_message+offset) == ' ')
  180623. break;
  180624. }
  180625. if((offset > 1) && (offset < 15))
  180626. {
  180627. warning_number[offset-1]='\0';
  180628. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  180629. warning_message+offset);
  180630. }
  180631. else
  180632. fprintf(stderr, "libpng warning: %s\n", warning_message);
  180633. }
  180634. else
  180635. # endif
  180636. fprintf(stderr, "libpng warning: %s\n", warning_message);
  180637. #else
  180638. warning_message = warning_message; /* make compiler happy */
  180639. #endif
  180640. png_ptr = png_ptr; /* make compiler happy */
  180641. }
  180642. #endif /* PNG_NO_WARNINGS */
  180643. /* This function is called when the application wants to use another method
  180644. * of handling errors and warnings. Note that the error function MUST NOT
  180645. * return to the calling routine or serious problems will occur. The return
  180646. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  180647. */
  180648. void PNGAPI
  180649. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  180650. png_error_ptr error_fn, png_error_ptr warning_fn)
  180651. {
  180652. if (png_ptr == NULL)
  180653. return;
  180654. png_ptr->error_ptr = error_ptr;
  180655. png_ptr->error_fn = error_fn;
  180656. png_ptr->warning_fn = warning_fn;
  180657. }
  180658. /* This function returns a pointer to the error_ptr associated with the user
  180659. * functions. The application should free any memory associated with this
  180660. * pointer before png_write_destroy and png_read_destroy are called.
  180661. */
  180662. png_voidp PNGAPI
  180663. png_get_error_ptr(png_structp png_ptr)
  180664. {
  180665. if (png_ptr == NULL)
  180666. return NULL;
  180667. return ((png_voidp)png_ptr->error_ptr);
  180668. }
  180669. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180670. void PNGAPI
  180671. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  180672. {
  180673. if(png_ptr != NULL)
  180674. {
  180675. png_ptr->flags &=
  180676. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  180677. }
  180678. }
  180679. #endif
  180680. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  180681. /********* End of inlined file: pngerror.c *********/
  180682. /********* Start of inlined file: pngget.c *********/
  180683. /* pngget.c - retrieval of values from info struct
  180684. *
  180685. * Last changed in libpng 1.2.15 January 5, 2007
  180686. * For conditions of distribution and use, see copyright notice in png.h
  180687. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180688. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180689. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180690. */
  180691. #define PNG_INTERNAL
  180692. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180693. png_uint_32 PNGAPI
  180694. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  180695. {
  180696. if (png_ptr != NULL && info_ptr != NULL)
  180697. return(info_ptr->valid & flag);
  180698. else
  180699. return(0);
  180700. }
  180701. png_uint_32 PNGAPI
  180702. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  180703. {
  180704. if (png_ptr != NULL && info_ptr != NULL)
  180705. return(info_ptr->rowbytes);
  180706. else
  180707. return(0);
  180708. }
  180709. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180710. png_bytepp PNGAPI
  180711. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  180712. {
  180713. if (png_ptr != NULL && info_ptr != NULL)
  180714. return(info_ptr->row_pointers);
  180715. else
  180716. return(0);
  180717. }
  180718. #endif
  180719. #ifdef PNG_EASY_ACCESS_SUPPORTED
  180720. /* easy access to info, added in libpng-0.99 */
  180721. png_uint_32 PNGAPI
  180722. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  180723. {
  180724. if (png_ptr != NULL && info_ptr != NULL)
  180725. {
  180726. return info_ptr->width;
  180727. }
  180728. return (0);
  180729. }
  180730. png_uint_32 PNGAPI
  180731. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  180732. {
  180733. if (png_ptr != NULL && info_ptr != NULL)
  180734. {
  180735. return info_ptr->height;
  180736. }
  180737. return (0);
  180738. }
  180739. png_byte PNGAPI
  180740. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  180741. {
  180742. if (png_ptr != NULL && info_ptr != NULL)
  180743. {
  180744. return info_ptr->bit_depth;
  180745. }
  180746. return (0);
  180747. }
  180748. png_byte PNGAPI
  180749. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  180750. {
  180751. if (png_ptr != NULL && info_ptr != NULL)
  180752. {
  180753. return info_ptr->color_type;
  180754. }
  180755. return (0);
  180756. }
  180757. png_byte PNGAPI
  180758. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  180759. {
  180760. if (png_ptr != NULL && info_ptr != NULL)
  180761. {
  180762. return info_ptr->filter_type;
  180763. }
  180764. return (0);
  180765. }
  180766. png_byte PNGAPI
  180767. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  180768. {
  180769. if (png_ptr != NULL && info_ptr != NULL)
  180770. {
  180771. return info_ptr->interlace_type;
  180772. }
  180773. return (0);
  180774. }
  180775. png_byte PNGAPI
  180776. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  180777. {
  180778. if (png_ptr != NULL && info_ptr != NULL)
  180779. {
  180780. return info_ptr->compression_type;
  180781. }
  180782. return (0);
  180783. }
  180784. png_uint_32 PNGAPI
  180785. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  180786. {
  180787. if (png_ptr != NULL && info_ptr != NULL)
  180788. #if defined(PNG_pHYs_SUPPORTED)
  180789. if (info_ptr->valid & PNG_INFO_pHYs)
  180790. {
  180791. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  180792. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  180793. return (0);
  180794. else return (info_ptr->x_pixels_per_unit);
  180795. }
  180796. #else
  180797. return (0);
  180798. #endif
  180799. return (0);
  180800. }
  180801. png_uint_32 PNGAPI
  180802. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  180803. {
  180804. if (png_ptr != NULL && info_ptr != NULL)
  180805. #if defined(PNG_pHYs_SUPPORTED)
  180806. if (info_ptr->valid & PNG_INFO_pHYs)
  180807. {
  180808. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  180809. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  180810. return (0);
  180811. else return (info_ptr->y_pixels_per_unit);
  180812. }
  180813. #else
  180814. return (0);
  180815. #endif
  180816. return (0);
  180817. }
  180818. png_uint_32 PNGAPI
  180819. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  180820. {
  180821. if (png_ptr != NULL && info_ptr != NULL)
  180822. #if defined(PNG_pHYs_SUPPORTED)
  180823. if (info_ptr->valid & PNG_INFO_pHYs)
  180824. {
  180825. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  180826. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  180827. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  180828. return (0);
  180829. else return (info_ptr->x_pixels_per_unit);
  180830. }
  180831. #else
  180832. return (0);
  180833. #endif
  180834. return (0);
  180835. }
  180836. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180837. float PNGAPI
  180838. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  180839. {
  180840. if (png_ptr != NULL && info_ptr != NULL)
  180841. #if defined(PNG_pHYs_SUPPORTED)
  180842. if (info_ptr->valid & PNG_INFO_pHYs)
  180843. {
  180844. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  180845. if (info_ptr->x_pixels_per_unit == 0)
  180846. return ((float)0.0);
  180847. else
  180848. return ((float)((float)info_ptr->y_pixels_per_unit
  180849. /(float)info_ptr->x_pixels_per_unit));
  180850. }
  180851. #else
  180852. return (0.0);
  180853. #endif
  180854. return ((float)0.0);
  180855. }
  180856. #endif
  180857. png_int_32 PNGAPI
  180858. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  180859. {
  180860. if (png_ptr != NULL && info_ptr != NULL)
  180861. #if defined(PNG_oFFs_SUPPORTED)
  180862. if (info_ptr->valid & PNG_INFO_oFFs)
  180863. {
  180864. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  180865. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  180866. return (0);
  180867. else return (info_ptr->x_offset);
  180868. }
  180869. #else
  180870. return (0);
  180871. #endif
  180872. return (0);
  180873. }
  180874. png_int_32 PNGAPI
  180875. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  180876. {
  180877. if (png_ptr != NULL && info_ptr != NULL)
  180878. #if defined(PNG_oFFs_SUPPORTED)
  180879. if (info_ptr->valid & PNG_INFO_oFFs)
  180880. {
  180881. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  180882. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  180883. return (0);
  180884. else return (info_ptr->y_offset);
  180885. }
  180886. #else
  180887. return (0);
  180888. #endif
  180889. return (0);
  180890. }
  180891. png_int_32 PNGAPI
  180892. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  180893. {
  180894. if (png_ptr != NULL && info_ptr != NULL)
  180895. #if defined(PNG_oFFs_SUPPORTED)
  180896. if (info_ptr->valid & PNG_INFO_oFFs)
  180897. {
  180898. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  180899. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  180900. return (0);
  180901. else return (info_ptr->x_offset);
  180902. }
  180903. #else
  180904. return (0);
  180905. #endif
  180906. return (0);
  180907. }
  180908. png_int_32 PNGAPI
  180909. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  180910. {
  180911. if (png_ptr != NULL && info_ptr != NULL)
  180912. #if defined(PNG_oFFs_SUPPORTED)
  180913. if (info_ptr->valid & PNG_INFO_oFFs)
  180914. {
  180915. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  180916. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  180917. return (0);
  180918. else return (info_ptr->y_offset);
  180919. }
  180920. #else
  180921. return (0);
  180922. #endif
  180923. return (0);
  180924. }
  180925. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  180926. png_uint_32 PNGAPI
  180927. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  180928. {
  180929. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  180930. *.0254 +.5));
  180931. }
  180932. png_uint_32 PNGAPI
  180933. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  180934. {
  180935. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  180936. *.0254 +.5));
  180937. }
  180938. png_uint_32 PNGAPI
  180939. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  180940. {
  180941. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  180942. *.0254 +.5));
  180943. }
  180944. float PNGAPI
  180945. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  180946. {
  180947. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  180948. *.00003937);
  180949. }
  180950. float PNGAPI
  180951. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  180952. {
  180953. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  180954. *.00003937);
  180955. }
  180956. #if defined(PNG_pHYs_SUPPORTED)
  180957. png_uint_32 PNGAPI
  180958. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  180959. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  180960. {
  180961. png_uint_32 retval = 0;
  180962. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  180963. {
  180964. png_debug1(1, "in %s retrieval function\n", "pHYs");
  180965. if (res_x != NULL)
  180966. {
  180967. *res_x = info_ptr->x_pixels_per_unit;
  180968. retval |= PNG_INFO_pHYs;
  180969. }
  180970. if (res_y != NULL)
  180971. {
  180972. *res_y = info_ptr->y_pixels_per_unit;
  180973. retval |= PNG_INFO_pHYs;
  180974. }
  180975. if (unit_type != NULL)
  180976. {
  180977. *unit_type = (int)info_ptr->phys_unit_type;
  180978. retval |= PNG_INFO_pHYs;
  180979. if(*unit_type == 1)
  180980. {
  180981. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  180982. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  180983. }
  180984. }
  180985. }
  180986. return (retval);
  180987. }
  180988. #endif /* PNG_pHYs_SUPPORTED */
  180989. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  180990. /* png_get_channels really belongs in here, too, but it's been around longer */
  180991. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  180992. png_byte PNGAPI
  180993. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  180994. {
  180995. if (png_ptr != NULL && info_ptr != NULL)
  180996. return(info_ptr->channels);
  180997. else
  180998. return (0);
  180999. }
  181000. png_bytep PNGAPI
  181001. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  181002. {
  181003. if (png_ptr != NULL && info_ptr != NULL)
  181004. return(info_ptr->signature);
  181005. else
  181006. return (NULL);
  181007. }
  181008. #if defined(PNG_bKGD_SUPPORTED)
  181009. png_uint_32 PNGAPI
  181010. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  181011. png_color_16p *background)
  181012. {
  181013. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  181014. && background != NULL)
  181015. {
  181016. png_debug1(1, "in %s retrieval function\n", "bKGD");
  181017. *background = &(info_ptr->background);
  181018. return (PNG_INFO_bKGD);
  181019. }
  181020. return (0);
  181021. }
  181022. #endif
  181023. #if defined(PNG_cHRM_SUPPORTED)
  181024. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181025. png_uint_32 PNGAPI
  181026. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  181027. double *white_x, double *white_y, double *red_x, double *red_y,
  181028. double *green_x, double *green_y, double *blue_x, double *blue_y)
  181029. {
  181030. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181031. {
  181032. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181033. if (white_x != NULL)
  181034. *white_x = (double)info_ptr->x_white;
  181035. if (white_y != NULL)
  181036. *white_y = (double)info_ptr->y_white;
  181037. if (red_x != NULL)
  181038. *red_x = (double)info_ptr->x_red;
  181039. if (red_y != NULL)
  181040. *red_y = (double)info_ptr->y_red;
  181041. if (green_x != NULL)
  181042. *green_x = (double)info_ptr->x_green;
  181043. if (green_y != NULL)
  181044. *green_y = (double)info_ptr->y_green;
  181045. if (blue_x != NULL)
  181046. *blue_x = (double)info_ptr->x_blue;
  181047. if (blue_y != NULL)
  181048. *blue_y = (double)info_ptr->y_blue;
  181049. return (PNG_INFO_cHRM);
  181050. }
  181051. return (0);
  181052. }
  181053. #endif
  181054. #ifdef PNG_FIXED_POINT_SUPPORTED
  181055. png_uint_32 PNGAPI
  181056. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  181057. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  181058. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  181059. png_fixed_point *blue_x, png_fixed_point *blue_y)
  181060. {
  181061. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181062. {
  181063. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181064. if (white_x != NULL)
  181065. *white_x = info_ptr->int_x_white;
  181066. if (white_y != NULL)
  181067. *white_y = info_ptr->int_y_white;
  181068. if (red_x != NULL)
  181069. *red_x = info_ptr->int_x_red;
  181070. if (red_y != NULL)
  181071. *red_y = info_ptr->int_y_red;
  181072. if (green_x != NULL)
  181073. *green_x = info_ptr->int_x_green;
  181074. if (green_y != NULL)
  181075. *green_y = info_ptr->int_y_green;
  181076. if (blue_x != NULL)
  181077. *blue_x = info_ptr->int_x_blue;
  181078. if (blue_y != NULL)
  181079. *blue_y = info_ptr->int_y_blue;
  181080. return (PNG_INFO_cHRM);
  181081. }
  181082. return (0);
  181083. }
  181084. #endif
  181085. #endif
  181086. #if defined(PNG_gAMA_SUPPORTED)
  181087. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181088. png_uint_32 PNGAPI
  181089. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  181090. {
  181091. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181092. && file_gamma != NULL)
  181093. {
  181094. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181095. *file_gamma = (double)info_ptr->gamma;
  181096. return (PNG_INFO_gAMA);
  181097. }
  181098. return (0);
  181099. }
  181100. #endif
  181101. #ifdef PNG_FIXED_POINT_SUPPORTED
  181102. png_uint_32 PNGAPI
  181103. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  181104. png_fixed_point *int_file_gamma)
  181105. {
  181106. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181107. && int_file_gamma != NULL)
  181108. {
  181109. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181110. *int_file_gamma = info_ptr->int_gamma;
  181111. return (PNG_INFO_gAMA);
  181112. }
  181113. return (0);
  181114. }
  181115. #endif
  181116. #endif
  181117. #if defined(PNG_sRGB_SUPPORTED)
  181118. png_uint_32 PNGAPI
  181119. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  181120. {
  181121. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  181122. && file_srgb_intent != NULL)
  181123. {
  181124. png_debug1(1, "in %s retrieval function\n", "sRGB");
  181125. *file_srgb_intent = (int)info_ptr->srgb_intent;
  181126. return (PNG_INFO_sRGB);
  181127. }
  181128. return (0);
  181129. }
  181130. #endif
  181131. #if defined(PNG_iCCP_SUPPORTED)
  181132. png_uint_32 PNGAPI
  181133. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  181134. png_charpp name, int *compression_type,
  181135. png_charpp profile, png_uint_32 *proflen)
  181136. {
  181137. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  181138. && name != NULL && profile != NULL && proflen != NULL)
  181139. {
  181140. png_debug1(1, "in %s retrieval function\n", "iCCP");
  181141. *name = info_ptr->iccp_name;
  181142. *profile = info_ptr->iccp_profile;
  181143. /* compression_type is a dummy so the API won't have to change
  181144. if we introduce multiple compression types later. */
  181145. *proflen = (int)info_ptr->iccp_proflen;
  181146. *compression_type = (int)info_ptr->iccp_compression;
  181147. return (PNG_INFO_iCCP);
  181148. }
  181149. return (0);
  181150. }
  181151. #endif
  181152. #if defined(PNG_sPLT_SUPPORTED)
  181153. png_uint_32 PNGAPI
  181154. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  181155. png_sPLT_tpp spalettes)
  181156. {
  181157. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  181158. {
  181159. *spalettes = info_ptr->splt_palettes;
  181160. return ((png_uint_32)info_ptr->splt_palettes_num);
  181161. }
  181162. return (0);
  181163. }
  181164. #endif
  181165. #if defined(PNG_hIST_SUPPORTED)
  181166. png_uint_32 PNGAPI
  181167. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  181168. {
  181169. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  181170. && hist != NULL)
  181171. {
  181172. png_debug1(1, "in %s retrieval function\n", "hIST");
  181173. *hist = info_ptr->hist;
  181174. return (PNG_INFO_hIST);
  181175. }
  181176. return (0);
  181177. }
  181178. #endif
  181179. png_uint_32 PNGAPI
  181180. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  181181. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  181182. int *color_type, int *interlace_type, int *compression_type,
  181183. int *filter_type)
  181184. {
  181185. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  181186. bit_depth != NULL && color_type != NULL)
  181187. {
  181188. png_debug1(1, "in %s retrieval function\n", "IHDR");
  181189. *width = info_ptr->width;
  181190. *height = info_ptr->height;
  181191. *bit_depth = info_ptr->bit_depth;
  181192. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  181193. png_error(png_ptr, "Invalid bit depth");
  181194. *color_type = info_ptr->color_type;
  181195. if (info_ptr->color_type > 6)
  181196. png_error(png_ptr, "Invalid color type");
  181197. if (compression_type != NULL)
  181198. *compression_type = info_ptr->compression_type;
  181199. if (filter_type != NULL)
  181200. *filter_type = info_ptr->filter_type;
  181201. if (interlace_type != NULL)
  181202. *interlace_type = info_ptr->interlace_type;
  181203. /* check for potential overflow of rowbytes */
  181204. if (*width == 0 || *width > PNG_UINT_31_MAX)
  181205. png_error(png_ptr, "Invalid image width");
  181206. if (*height == 0 || *height > PNG_UINT_31_MAX)
  181207. png_error(png_ptr, "Invalid image height");
  181208. if (info_ptr->width > (PNG_UINT_32_MAX
  181209. >> 3) /* 8-byte RGBA pixels */
  181210. - 64 /* bigrowbuf hack */
  181211. - 1 /* filter byte */
  181212. - 7*8 /* rounding of width to multiple of 8 pixels */
  181213. - 8) /* extra max_pixel_depth pad */
  181214. {
  181215. png_warning(png_ptr,
  181216. "Width too large for libpng to process image data.");
  181217. }
  181218. return (1);
  181219. }
  181220. return (0);
  181221. }
  181222. #if defined(PNG_oFFs_SUPPORTED)
  181223. png_uint_32 PNGAPI
  181224. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  181225. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  181226. {
  181227. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  181228. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  181229. {
  181230. png_debug1(1, "in %s retrieval function\n", "oFFs");
  181231. *offset_x = info_ptr->x_offset;
  181232. *offset_y = info_ptr->y_offset;
  181233. *unit_type = (int)info_ptr->offset_unit_type;
  181234. return (PNG_INFO_oFFs);
  181235. }
  181236. return (0);
  181237. }
  181238. #endif
  181239. #if defined(PNG_pCAL_SUPPORTED)
  181240. png_uint_32 PNGAPI
  181241. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  181242. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  181243. png_charp *units, png_charpp *params)
  181244. {
  181245. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  181246. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  181247. nparams != NULL && units != NULL && params != NULL)
  181248. {
  181249. png_debug1(1, "in %s retrieval function\n", "pCAL");
  181250. *purpose = info_ptr->pcal_purpose;
  181251. *X0 = info_ptr->pcal_X0;
  181252. *X1 = info_ptr->pcal_X1;
  181253. *type = (int)info_ptr->pcal_type;
  181254. *nparams = (int)info_ptr->pcal_nparams;
  181255. *units = info_ptr->pcal_units;
  181256. *params = info_ptr->pcal_params;
  181257. return (PNG_INFO_pCAL);
  181258. }
  181259. return (0);
  181260. }
  181261. #endif
  181262. #if defined(PNG_sCAL_SUPPORTED)
  181263. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181264. png_uint_32 PNGAPI
  181265. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  181266. int *unit, double *width, double *height)
  181267. {
  181268. if (png_ptr != NULL && info_ptr != NULL &&
  181269. (info_ptr->valid & PNG_INFO_sCAL))
  181270. {
  181271. *unit = info_ptr->scal_unit;
  181272. *width = info_ptr->scal_pixel_width;
  181273. *height = info_ptr->scal_pixel_height;
  181274. return (PNG_INFO_sCAL);
  181275. }
  181276. return(0);
  181277. }
  181278. #else
  181279. #ifdef PNG_FIXED_POINT_SUPPORTED
  181280. png_uint_32 PNGAPI
  181281. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  181282. int *unit, png_charpp width, png_charpp height)
  181283. {
  181284. if (png_ptr != NULL && info_ptr != NULL &&
  181285. (info_ptr->valid & PNG_INFO_sCAL))
  181286. {
  181287. *unit = info_ptr->scal_unit;
  181288. *width = info_ptr->scal_s_width;
  181289. *height = info_ptr->scal_s_height;
  181290. return (PNG_INFO_sCAL);
  181291. }
  181292. return(0);
  181293. }
  181294. #endif
  181295. #endif
  181296. #endif
  181297. #if defined(PNG_pHYs_SUPPORTED)
  181298. png_uint_32 PNGAPI
  181299. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  181300. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181301. {
  181302. png_uint_32 retval = 0;
  181303. if (png_ptr != NULL && info_ptr != NULL &&
  181304. (info_ptr->valid & PNG_INFO_pHYs))
  181305. {
  181306. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181307. if (res_x != NULL)
  181308. {
  181309. *res_x = info_ptr->x_pixels_per_unit;
  181310. retval |= PNG_INFO_pHYs;
  181311. }
  181312. if (res_y != NULL)
  181313. {
  181314. *res_y = info_ptr->y_pixels_per_unit;
  181315. retval |= PNG_INFO_pHYs;
  181316. }
  181317. if (unit_type != NULL)
  181318. {
  181319. *unit_type = (int)info_ptr->phys_unit_type;
  181320. retval |= PNG_INFO_pHYs;
  181321. }
  181322. }
  181323. return (retval);
  181324. }
  181325. #endif
  181326. png_uint_32 PNGAPI
  181327. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  181328. int *num_palette)
  181329. {
  181330. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  181331. && palette != NULL)
  181332. {
  181333. png_debug1(1, "in %s retrieval function\n", "PLTE");
  181334. *palette = info_ptr->palette;
  181335. *num_palette = info_ptr->num_palette;
  181336. png_debug1(3, "num_palette = %d\n", *num_palette);
  181337. return (PNG_INFO_PLTE);
  181338. }
  181339. return (0);
  181340. }
  181341. #if defined(PNG_sBIT_SUPPORTED)
  181342. png_uint_32 PNGAPI
  181343. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  181344. {
  181345. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  181346. && sig_bit != NULL)
  181347. {
  181348. png_debug1(1, "in %s retrieval function\n", "sBIT");
  181349. *sig_bit = &(info_ptr->sig_bit);
  181350. return (PNG_INFO_sBIT);
  181351. }
  181352. return (0);
  181353. }
  181354. #endif
  181355. #if defined(PNG_TEXT_SUPPORTED)
  181356. png_uint_32 PNGAPI
  181357. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  181358. int *num_text)
  181359. {
  181360. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  181361. {
  181362. png_debug1(1, "in %s retrieval function\n",
  181363. (png_ptr->chunk_name[0] == '\0' ? "text"
  181364. : (png_const_charp)png_ptr->chunk_name));
  181365. if (text_ptr != NULL)
  181366. *text_ptr = info_ptr->text;
  181367. if (num_text != NULL)
  181368. *num_text = info_ptr->num_text;
  181369. return ((png_uint_32)info_ptr->num_text);
  181370. }
  181371. if (num_text != NULL)
  181372. *num_text = 0;
  181373. return(0);
  181374. }
  181375. #endif
  181376. #if defined(PNG_tIME_SUPPORTED)
  181377. png_uint_32 PNGAPI
  181378. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  181379. {
  181380. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  181381. && mod_time != NULL)
  181382. {
  181383. png_debug1(1, "in %s retrieval function\n", "tIME");
  181384. *mod_time = &(info_ptr->mod_time);
  181385. return (PNG_INFO_tIME);
  181386. }
  181387. return (0);
  181388. }
  181389. #endif
  181390. #if defined(PNG_tRNS_SUPPORTED)
  181391. png_uint_32 PNGAPI
  181392. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  181393. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  181394. {
  181395. png_uint_32 retval = 0;
  181396. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  181397. {
  181398. png_debug1(1, "in %s retrieval function\n", "tRNS");
  181399. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  181400. {
  181401. if (trans != NULL)
  181402. {
  181403. *trans = info_ptr->trans;
  181404. retval |= PNG_INFO_tRNS;
  181405. }
  181406. if (trans_values != NULL)
  181407. *trans_values = &(info_ptr->trans_values);
  181408. }
  181409. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  181410. {
  181411. if (trans_values != NULL)
  181412. {
  181413. *trans_values = &(info_ptr->trans_values);
  181414. retval |= PNG_INFO_tRNS;
  181415. }
  181416. if(trans != NULL)
  181417. *trans = NULL;
  181418. }
  181419. if(num_trans != NULL)
  181420. {
  181421. *num_trans = info_ptr->num_trans;
  181422. retval |= PNG_INFO_tRNS;
  181423. }
  181424. }
  181425. return (retval);
  181426. }
  181427. #endif
  181428. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181429. png_uint_32 PNGAPI
  181430. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  181431. png_unknown_chunkpp unknowns)
  181432. {
  181433. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  181434. {
  181435. *unknowns = info_ptr->unknown_chunks;
  181436. return ((png_uint_32)info_ptr->unknown_chunks_num);
  181437. }
  181438. return (0);
  181439. }
  181440. #endif
  181441. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181442. png_byte PNGAPI
  181443. png_get_rgb_to_gray_status (png_structp png_ptr)
  181444. {
  181445. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  181446. }
  181447. #endif
  181448. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181449. png_voidp PNGAPI
  181450. png_get_user_chunk_ptr(png_structp png_ptr)
  181451. {
  181452. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  181453. }
  181454. #endif
  181455. #ifdef PNG_WRITE_SUPPORTED
  181456. png_uint_32 PNGAPI
  181457. png_get_compression_buffer_size(png_structp png_ptr)
  181458. {
  181459. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  181460. }
  181461. #endif
  181462. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  181463. #ifndef PNG_1_0_X
  181464. /* this function was added to libpng 1.2.0 and should exist by default */
  181465. png_uint_32 PNGAPI
  181466. png_get_asm_flags (png_structp png_ptr)
  181467. {
  181468. /* obsolete, to be removed from libpng-1.4.0 */
  181469. return (png_ptr? 0L: 0L);
  181470. }
  181471. /* this function was added to libpng 1.2.0 and should exist by default */
  181472. png_uint_32 PNGAPI
  181473. png_get_asm_flagmask (int flag_select)
  181474. {
  181475. /* obsolete, to be removed from libpng-1.4.0 */
  181476. flag_select=flag_select;
  181477. return 0L;
  181478. }
  181479. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  181480. /* this function was added to libpng 1.2.0 */
  181481. png_uint_32 PNGAPI
  181482. png_get_mmx_flagmask (int flag_select, int *compilerID)
  181483. {
  181484. /* obsolete, to be removed from libpng-1.4.0 */
  181485. flag_select=flag_select;
  181486. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  181487. return 0L;
  181488. }
  181489. /* this function was added to libpng 1.2.0 */
  181490. png_byte PNGAPI
  181491. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  181492. {
  181493. /* obsolete, to be removed from libpng-1.4.0 */
  181494. return (png_ptr? 0: 0);
  181495. }
  181496. /* this function was added to libpng 1.2.0 */
  181497. png_uint_32 PNGAPI
  181498. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  181499. {
  181500. /* obsolete, to be removed from libpng-1.4.0 */
  181501. return (png_ptr? 0L: 0L);
  181502. }
  181503. #endif /* ?PNG_1_0_X */
  181504. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  181505. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181506. /* these functions were added to libpng 1.2.6 */
  181507. png_uint_32 PNGAPI
  181508. png_get_user_width_max (png_structp png_ptr)
  181509. {
  181510. return (png_ptr? png_ptr->user_width_max : 0);
  181511. }
  181512. png_uint_32 PNGAPI
  181513. png_get_user_height_max (png_structp png_ptr)
  181514. {
  181515. return (png_ptr? png_ptr->user_height_max : 0);
  181516. }
  181517. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  181518. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181519. /********* End of inlined file: pngget.c *********/
  181520. /********* Start of inlined file: pngmem.c *********/
  181521. /* pngmem.c - stub functions for memory allocation
  181522. *
  181523. * Last changed in libpng 1.2.13 November 13, 2006
  181524. * For conditions of distribution and use, see copyright notice in png.h
  181525. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  181526. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181527. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181528. *
  181529. * This file provides a location for all memory allocation. Users who
  181530. * need special memory handling are expected to supply replacement
  181531. * functions for png_malloc() and png_free(), and to use
  181532. * png_create_read_struct_2() and png_create_write_struct_2() to
  181533. * identify the replacement functions.
  181534. */
  181535. #define PNG_INTERNAL
  181536. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181537. /* Borland DOS special memory handler */
  181538. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  181539. /* if you change this, be sure to change the one in png.h also */
  181540. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  181541. by a single call to calloc() if this is thought to improve performance. */
  181542. png_voidp /* PRIVATE */
  181543. png_create_struct(int type)
  181544. {
  181545. #ifdef PNG_USER_MEM_SUPPORTED
  181546. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  181547. }
  181548. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  181549. png_voidp /* PRIVATE */
  181550. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  181551. {
  181552. #endif /* PNG_USER_MEM_SUPPORTED */
  181553. png_size_t size;
  181554. png_voidp struct_ptr;
  181555. if (type == PNG_STRUCT_INFO)
  181556. size = png_sizeof(png_info);
  181557. else if (type == PNG_STRUCT_PNG)
  181558. size = png_sizeof(png_struct);
  181559. else
  181560. return (png_get_copyright(NULL));
  181561. #ifdef PNG_USER_MEM_SUPPORTED
  181562. if(malloc_fn != NULL)
  181563. {
  181564. png_struct dummy_struct;
  181565. png_structp png_ptr = &dummy_struct;
  181566. png_ptr->mem_ptr=mem_ptr;
  181567. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  181568. }
  181569. else
  181570. #endif /* PNG_USER_MEM_SUPPORTED */
  181571. struct_ptr = (png_voidp)farmalloc(size);
  181572. if (struct_ptr != NULL)
  181573. png_memset(struct_ptr, 0, size);
  181574. return (struct_ptr);
  181575. }
  181576. /* Free memory allocated by a png_create_struct() call */
  181577. void /* PRIVATE */
  181578. png_destroy_struct(png_voidp struct_ptr)
  181579. {
  181580. #ifdef PNG_USER_MEM_SUPPORTED
  181581. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  181582. }
  181583. /* Free memory allocated by a png_create_struct() call */
  181584. void /* PRIVATE */
  181585. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  181586. png_voidp mem_ptr)
  181587. {
  181588. #endif
  181589. if (struct_ptr != NULL)
  181590. {
  181591. #ifdef PNG_USER_MEM_SUPPORTED
  181592. if(free_fn != NULL)
  181593. {
  181594. png_struct dummy_struct;
  181595. png_structp png_ptr = &dummy_struct;
  181596. png_ptr->mem_ptr=mem_ptr;
  181597. (*(free_fn))(png_ptr, struct_ptr);
  181598. return;
  181599. }
  181600. #endif /* PNG_USER_MEM_SUPPORTED */
  181601. farfree (struct_ptr);
  181602. }
  181603. }
  181604. /* Allocate memory. For reasonable files, size should never exceed
  181605. * 64K. However, zlib may allocate more then 64K if you don't tell
  181606. * it not to. See zconf.h and png.h for more information. zlib does
  181607. * need to allocate exactly 64K, so whatever you call here must
  181608. * have the ability to do that.
  181609. *
  181610. * Borland seems to have a problem in DOS mode for exactly 64K.
  181611. * It gives you a segment with an offset of 8 (perhaps to store its
  181612. * memory stuff). zlib doesn't like this at all, so we have to
  181613. * detect and deal with it. This code should not be needed in
  181614. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  181615. * been updated by Alexander Lehmann for version 0.89 to waste less
  181616. * memory.
  181617. *
  181618. * Note that we can't use png_size_t for the "size" declaration,
  181619. * since on some systems a png_size_t is a 16-bit quantity, and as a
  181620. * result, we would be truncating potentially larger memory requests
  181621. * (which should cause a fatal error) and introducing major problems.
  181622. */
  181623. png_voidp PNGAPI
  181624. png_malloc(png_structp png_ptr, png_uint_32 size)
  181625. {
  181626. png_voidp ret;
  181627. if (png_ptr == NULL || size == 0)
  181628. return (NULL);
  181629. #ifdef PNG_USER_MEM_SUPPORTED
  181630. if(png_ptr->malloc_fn != NULL)
  181631. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  181632. else
  181633. ret = (png_malloc_default(png_ptr, size));
  181634. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181635. png_error(png_ptr, "Out of memory!");
  181636. return (ret);
  181637. }
  181638. png_voidp PNGAPI
  181639. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  181640. {
  181641. png_voidp ret;
  181642. #endif /* PNG_USER_MEM_SUPPORTED */
  181643. if (png_ptr == NULL || size == 0)
  181644. return (NULL);
  181645. #ifdef PNG_MAX_MALLOC_64K
  181646. if (size > (png_uint_32)65536L)
  181647. {
  181648. png_warning(png_ptr, "Cannot Allocate > 64K");
  181649. ret = NULL;
  181650. }
  181651. else
  181652. #endif
  181653. if (size != (size_t)size)
  181654. ret = NULL;
  181655. else if (size == (png_uint_32)65536L)
  181656. {
  181657. if (png_ptr->offset_table == NULL)
  181658. {
  181659. /* try to see if we need to do any of this fancy stuff */
  181660. ret = farmalloc(size);
  181661. if (ret == NULL || ((png_size_t)ret & 0xffff))
  181662. {
  181663. int num_blocks;
  181664. png_uint_32 total_size;
  181665. png_bytep table;
  181666. int i;
  181667. png_byte huge * hptr;
  181668. if (ret != NULL)
  181669. {
  181670. farfree(ret);
  181671. ret = NULL;
  181672. }
  181673. if(png_ptr->zlib_window_bits > 14)
  181674. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  181675. else
  181676. num_blocks = 1;
  181677. if (png_ptr->zlib_mem_level >= 7)
  181678. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  181679. else
  181680. num_blocks++;
  181681. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  181682. table = farmalloc(total_size);
  181683. if (table == NULL)
  181684. {
  181685. #ifndef PNG_USER_MEM_SUPPORTED
  181686. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181687. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  181688. else
  181689. png_warning(png_ptr, "Out Of Memory.");
  181690. #endif
  181691. return (NULL);
  181692. }
  181693. if ((png_size_t)table & 0xfff0)
  181694. {
  181695. #ifndef PNG_USER_MEM_SUPPORTED
  181696. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181697. png_error(png_ptr,
  181698. "Farmalloc didn't return normalized pointer");
  181699. else
  181700. png_warning(png_ptr,
  181701. "Farmalloc didn't return normalized pointer");
  181702. #endif
  181703. return (NULL);
  181704. }
  181705. png_ptr->offset_table = table;
  181706. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  181707. png_sizeof (png_bytep));
  181708. if (png_ptr->offset_table_ptr == NULL)
  181709. {
  181710. #ifndef PNG_USER_MEM_SUPPORTED
  181711. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181712. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  181713. else
  181714. png_warning(png_ptr, "Out Of memory.");
  181715. #endif
  181716. return (NULL);
  181717. }
  181718. hptr = (png_byte huge *)table;
  181719. if ((png_size_t)hptr & 0xf)
  181720. {
  181721. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  181722. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  181723. }
  181724. for (i = 0; i < num_blocks; i++)
  181725. {
  181726. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  181727. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  181728. }
  181729. png_ptr->offset_table_number = num_blocks;
  181730. png_ptr->offset_table_count = 0;
  181731. png_ptr->offset_table_count_free = 0;
  181732. }
  181733. }
  181734. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  181735. {
  181736. #ifndef PNG_USER_MEM_SUPPORTED
  181737. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181738. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  181739. else
  181740. png_warning(png_ptr, "Out of Memory.");
  181741. #endif
  181742. return (NULL);
  181743. }
  181744. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  181745. }
  181746. else
  181747. ret = farmalloc(size);
  181748. #ifndef PNG_USER_MEM_SUPPORTED
  181749. if (ret == NULL)
  181750. {
  181751. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181752. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  181753. else
  181754. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  181755. }
  181756. #endif
  181757. return (ret);
  181758. }
  181759. /* free a pointer allocated by png_malloc(). In the default
  181760. configuration, png_ptr is not used, but is passed in case it
  181761. is needed. If ptr is NULL, return without taking any action. */
  181762. void PNGAPI
  181763. png_free(png_structp png_ptr, png_voidp ptr)
  181764. {
  181765. if (png_ptr == NULL || ptr == NULL)
  181766. return;
  181767. #ifdef PNG_USER_MEM_SUPPORTED
  181768. if (png_ptr->free_fn != NULL)
  181769. {
  181770. (*(png_ptr->free_fn))(png_ptr, ptr);
  181771. return;
  181772. }
  181773. else png_free_default(png_ptr, ptr);
  181774. }
  181775. void PNGAPI
  181776. png_free_default(png_structp png_ptr, png_voidp ptr)
  181777. {
  181778. #endif /* PNG_USER_MEM_SUPPORTED */
  181779. if(png_ptr == NULL) return;
  181780. if (png_ptr->offset_table != NULL)
  181781. {
  181782. int i;
  181783. for (i = 0; i < png_ptr->offset_table_count; i++)
  181784. {
  181785. if (ptr == png_ptr->offset_table_ptr[i])
  181786. {
  181787. ptr = NULL;
  181788. png_ptr->offset_table_count_free++;
  181789. break;
  181790. }
  181791. }
  181792. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  181793. {
  181794. farfree(png_ptr->offset_table);
  181795. farfree(png_ptr->offset_table_ptr);
  181796. png_ptr->offset_table = NULL;
  181797. png_ptr->offset_table_ptr = NULL;
  181798. }
  181799. }
  181800. if (ptr != NULL)
  181801. {
  181802. farfree(ptr);
  181803. }
  181804. }
  181805. #else /* Not the Borland DOS special memory handler */
  181806. /* Allocate memory for a png_struct or a png_info. The malloc and
  181807. memset can be replaced by a single call to calloc() if this is thought
  181808. to improve performance noticably. */
  181809. png_voidp /* PRIVATE */
  181810. png_create_struct(int type)
  181811. {
  181812. #ifdef PNG_USER_MEM_SUPPORTED
  181813. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  181814. }
  181815. /* Allocate memory for a png_struct or a png_info. The malloc and
  181816. memset can be replaced by a single call to calloc() if this is thought
  181817. to improve performance noticably. */
  181818. png_voidp /* PRIVATE */
  181819. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  181820. {
  181821. #endif /* PNG_USER_MEM_SUPPORTED */
  181822. png_size_t size;
  181823. png_voidp struct_ptr;
  181824. if (type == PNG_STRUCT_INFO)
  181825. size = png_sizeof(png_info);
  181826. else if (type == PNG_STRUCT_PNG)
  181827. size = png_sizeof(png_struct);
  181828. else
  181829. return (NULL);
  181830. #ifdef PNG_USER_MEM_SUPPORTED
  181831. if(malloc_fn != NULL)
  181832. {
  181833. png_struct dummy_struct;
  181834. png_structp png_ptr = &dummy_struct;
  181835. png_ptr->mem_ptr=mem_ptr;
  181836. struct_ptr = (*(malloc_fn))(png_ptr, size);
  181837. if (struct_ptr != NULL)
  181838. png_memset(struct_ptr, 0, size);
  181839. return (struct_ptr);
  181840. }
  181841. #endif /* PNG_USER_MEM_SUPPORTED */
  181842. #if defined(__TURBOC__) && !defined(__FLAT__)
  181843. struct_ptr = (png_voidp)farmalloc(size);
  181844. #else
  181845. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181846. struct_ptr = (png_voidp)halloc(size,1);
  181847. # else
  181848. struct_ptr = (png_voidp)malloc(size);
  181849. # endif
  181850. #endif
  181851. if (struct_ptr != NULL)
  181852. png_memset(struct_ptr, 0, size);
  181853. return (struct_ptr);
  181854. }
  181855. /* Free memory allocated by a png_create_struct() call */
  181856. void /* PRIVATE */
  181857. png_destroy_struct(png_voidp struct_ptr)
  181858. {
  181859. #ifdef PNG_USER_MEM_SUPPORTED
  181860. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  181861. }
  181862. /* Free memory allocated by a png_create_struct() call */
  181863. void /* PRIVATE */
  181864. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  181865. png_voidp mem_ptr)
  181866. {
  181867. #endif /* PNG_USER_MEM_SUPPORTED */
  181868. if (struct_ptr != NULL)
  181869. {
  181870. #ifdef PNG_USER_MEM_SUPPORTED
  181871. if(free_fn != NULL)
  181872. {
  181873. png_struct dummy_struct;
  181874. png_structp png_ptr = &dummy_struct;
  181875. png_ptr->mem_ptr=mem_ptr;
  181876. (*(free_fn))(png_ptr, struct_ptr);
  181877. return;
  181878. }
  181879. #endif /* PNG_USER_MEM_SUPPORTED */
  181880. #if defined(__TURBOC__) && !defined(__FLAT__)
  181881. farfree(struct_ptr);
  181882. #else
  181883. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181884. hfree(struct_ptr);
  181885. # else
  181886. free(struct_ptr);
  181887. # endif
  181888. #endif
  181889. }
  181890. }
  181891. /* Allocate memory. For reasonable files, size should never exceed
  181892. 64K. However, zlib may allocate more then 64K if you don't tell
  181893. it not to. See zconf.h and png.h for more information. zlib does
  181894. need to allocate exactly 64K, so whatever you call here must
  181895. have the ability to do that. */
  181896. png_voidp PNGAPI
  181897. png_malloc(png_structp png_ptr, png_uint_32 size)
  181898. {
  181899. png_voidp ret;
  181900. #ifdef PNG_USER_MEM_SUPPORTED
  181901. if (png_ptr == NULL || size == 0)
  181902. return (NULL);
  181903. if(png_ptr->malloc_fn != NULL)
  181904. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  181905. else
  181906. ret = (png_malloc_default(png_ptr, size));
  181907. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181908. png_error(png_ptr, "Out of Memory!");
  181909. return (ret);
  181910. }
  181911. png_voidp PNGAPI
  181912. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  181913. {
  181914. png_voidp ret;
  181915. #endif /* PNG_USER_MEM_SUPPORTED */
  181916. if (png_ptr == NULL || size == 0)
  181917. return (NULL);
  181918. #ifdef PNG_MAX_MALLOC_64K
  181919. if (size > (png_uint_32)65536L)
  181920. {
  181921. #ifndef PNG_USER_MEM_SUPPORTED
  181922. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181923. png_error(png_ptr, "Cannot Allocate > 64K");
  181924. else
  181925. #endif
  181926. return NULL;
  181927. }
  181928. #endif
  181929. /* Check for overflow */
  181930. #if defined(__TURBOC__) && !defined(__FLAT__)
  181931. if (size != (unsigned long)size)
  181932. ret = NULL;
  181933. else
  181934. ret = farmalloc(size);
  181935. #else
  181936. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181937. if (size != (unsigned long)size)
  181938. ret = NULL;
  181939. else
  181940. ret = halloc(size, 1);
  181941. # else
  181942. if (size != (size_t)size)
  181943. ret = NULL;
  181944. else
  181945. ret = malloc((size_t)size);
  181946. # endif
  181947. #endif
  181948. #ifndef PNG_USER_MEM_SUPPORTED
  181949. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181950. png_error(png_ptr, "Out of Memory");
  181951. #endif
  181952. return (ret);
  181953. }
  181954. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  181955. without taking any action. */
  181956. void PNGAPI
  181957. png_free(png_structp png_ptr, png_voidp ptr)
  181958. {
  181959. if (png_ptr == NULL || ptr == NULL)
  181960. return;
  181961. #ifdef PNG_USER_MEM_SUPPORTED
  181962. if (png_ptr->free_fn != NULL)
  181963. {
  181964. (*(png_ptr->free_fn))(png_ptr, ptr);
  181965. return;
  181966. }
  181967. else png_free_default(png_ptr, ptr);
  181968. }
  181969. void PNGAPI
  181970. png_free_default(png_structp png_ptr, png_voidp ptr)
  181971. {
  181972. if (png_ptr == NULL || ptr == NULL)
  181973. return;
  181974. #endif /* PNG_USER_MEM_SUPPORTED */
  181975. #if defined(__TURBOC__) && !defined(__FLAT__)
  181976. farfree(ptr);
  181977. #else
  181978. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181979. hfree(ptr);
  181980. # else
  181981. free(ptr);
  181982. # endif
  181983. #endif
  181984. }
  181985. #endif /* Not Borland DOS special memory handler */
  181986. #if defined(PNG_1_0_X)
  181987. # define png_malloc_warn png_malloc
  181988. #else
  181989. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  181990. * function will set up png_malloc() to issue a png_warning and return NULL
  181991. * instead of issuing a png_error, if it fails to allocate the requested
  181992. * memory.
  181993. */
  181994. png_voidp PNGAPI
  181995. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  181996. {
  181997. png_voidp ptr;
  181998. png_uint_32 save_flags;
  181999. if(png_ptr == NULL) return (NULL);
  182000. save_flags=png_ptr->flags;
  182001. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  182002. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  182003. png_ptr->flags=save_flags;
  182004. return(ptr);
  182005. }
  182006. #endif
  182007. png_voidp PNGAPI
  182008. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  182009. png_uint_32 length)
  182010. {
  182011. png_size_t size;
  182012. size = (png_size_t)length;
  182013. if ((png_uint_32)size != length)
  182014. png_error(png_ptr,"Overflow in png_memcpy_check.");
  182015. return(png_memcpy (s1, s2, size));
  182016. }
  182017. png_voidp PNGAPI
  182018. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  182019. png_uint_32 length)
  182020. {
  182021. png_size_t size;
  182022. size = (png_size_t)length;
  182023. if ((png_uint_32)size != length)
  182024. png_error(png_ptr,"Overflow in png_memset_check.");
  182025. return (png_memset (s1, value, size));
  182026. }
  182027. #ifdef PNG_USER_MEM_SUPPORTED
  182028. /* This function is called when the application wants to use another method
  182029. * of allocating and freeing memory.
  182030. */
  182031. void PNGAPI
  182032. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  182033. malloc_fn, png_free_ptr free_fn)
  182034. {
  182035. if(png_ptr != NULL) {
  182036. png_ptr->mem_ptr = mem_ptr;
  182037. png_ptr->malloc_fn = malloc_fn;
  182038. png_ptr->free_fn = free_fn;
  182039. }
  182040. }
  182041. /* This function returns a pointer to the mem_ptr associated with the user
  182042. * functions. The application should free any memory associated with this
  182043. * pointer before png_write_destroy and png_read_destroy are called.
  182044. */
  182045. png_voidp PNGAPI
  182046. png_get_mem_ptr(png_structp png_ptr)
  182047. {
  182048. if(png_ptr == NULL) return (NULL);
  182049. return ((png_voidp)png_ptr->mem_ptr);
  182050. }
  182051. #endif /* PNG_USER_MEM_SUPPORTED */
  182052. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182053. /********* End of inlined file: pngmem.c *********/
  182054. /********* Start of inlined file: pngread.c *********/
  182055. /* pngread.c - read a PNG file
  182056. *
  182057. * Last changed in libpng 1.2.20 September 7, 2007
  182058. * For conditions of distribution and use, see copyright notice in png.h
  182059. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182060. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182061. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182062. *
  182063. * This file contains routines that an application calls directly to
  182064. * read a PNG file or stream.
  182065. */
  182066. #define PNG_INTERNAL
  182067. #if defined(PNG_READ_SUPPORTED)
  182068. /* Create a PNG structure for reading, and allocate any memory needed. */
  182069. png_structp PNGAPI
  182070. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  182071. png_error_ptr error_fn, png_error_ptr warn_fn)
  182072. {
  182073. #ifdef PNG_USER_MEM_SUPPORTED
  182074. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  182075. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  182076. }
  182077. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  182078. png_structp PNGAPI
  182079. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  182080. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182081. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  182082. {
  182083. #endif /* PNG_USER_MEM_SUPPORTED */
  182084. png_structp png_ptr;
  182085. #ifdef PNG_SETJMP_SUPPORTED
  182086. #ifdef USE_FAR_KEYWORD
  182087. jmp_buf jmpbuf;
  182088. #endif
  182089. #endif
  182090. int i;
  182091. png_debug(1, "in png_create_read_struct\n");
  182092. #ifdef PNG_USER_MEM_SUPPORTED
  182093. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  182094. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  182095. #else
  182096. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182097. #endif
  182098. if (png_ptr == NULL)
  182099. return (NULL);
  182100. /* added at libpng-1.2.6 */
  182101. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182102. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182103. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182104. #endif
  182105. #ifdef PNG_SETJMP_SUPPORTED
  182106. #ifdef USE_FAR_KEYWORD
  182107. if (setjmp(jmpbuf))
  182108. #else
  182109. if (setjmp(png_ptr->jmpbuf))
  182110. #endif
  182111. {
  182112. png_free(png_ptr, png_ptr->zbuf);
  182113. png_ptr->zbuf=NULL;
  182114. #ifdef PNG_USER_MEM_SUPPORTED
  182115. png_destroy_struct_2((png_voidp)png_ptr,
  182116. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  182117. #else
  182118. png_destroy_struct((png_voidp)png_ptr);
  182119. #endif
  182120. return (NULL);
  182121. }
  182122. #ifdef USE_FAR_KEYWORD
  182123. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182124. #endif
  182125. #endif
  182126. #ifdef PNG_USER_MEM_SUPPORTED
  182127. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  182128. #endif
  182129. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  182130. i=0;
  182131. do
  182132. {
  182133. if(user_png_ver[i] != png_libpng_ver[i])
  182134. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182135. } while (png_libpng_ver[i++]);
  182136. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  182137. {
  182138. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  182139. * we must recompile any applications that use any older library version.
  182140. * For versions after libpng 1.0, we will be compatible, so we need
  182141. * only check the first digit.
  182142. */
  182143. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  182144. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  182145. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  182146. {
  182147. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182148. char msg[80];
  182149. if (user_png_ver)
  182150. {
  182151. png_snprintf(msg, 80,
  182152. "Application was compiled with png.h from libpng-%.20s",
  182153. user_png_ver);
  182154. png_warning(png_ptr, msg);
  182155. }
  182156. png_snprintf(msg, 80,
  182157. "Application is running with png.c from libpng-%.20s",
  182158. png_libpng_ver);
  182159. png_warning(png_ptr, msg);
  182160. #endif
  182161. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182162. png_ptr->flags=0;
  182163. #endif
  182164. png_error(png_ptr,
  182165. "Incompatible libpng version in application and library");
  182166. }
  182167. }
  182168. /* initialize zbuf - compression buffer */
  182169. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182170. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182171. (png_uint_32)png_ptr->zbuf_size);
  182172. png_ptr->zstream.zalloc = png_zalloc;
  182173. png_ptr->zstream.zfree = png_zfree;
  182174. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182175. switch (inflateInit(&png_ptr->zstream))
  182176. {
  182177. case Z_OK: /* Do nothing */ break;
  182178. case Z_MEM_ERROR:
  182179. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  182180. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  182181. default: png_error(png_ptr, "Unknown zlib error");
  182182. }
  182183. png_ptr->zstream.next_out = png_ptr->zbuf;
  182184. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182185. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182186. #ifdef PNG_SETJMP_SUPPORTED
  182187. /* Applications that neglect to set up their own setjmp() and then encounter
  182188. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  182189. abort instead of returning. */
  182190. #ifdef USE_FAR_KEYWORD
  182191. if (setjmp(jmpbuf))
  182192. PNG_ABORT();
  182193. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182194. #else
  182195. if (setjmp(png_ptr->jmpbuf))
  182196. PNG_ABORT();
  182197. #endif
  182198. #endif
  182199. return (png_ptr);
  182200. }
  182201. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  182202. /* Initialize PNG structure for reading, and allocate any memory needed.
  182203. This interface is deprecated in favour of the png_create_read_struct(),
  182204. and it will disappear as of libpng-1.3.0. */
  182205. #undef png_read_init
  182206. void PNGAPI
  182207. png_read_init(png_structp png_ptr)
  182208. {
  182209. /* We only come here via pre-1.0.7-compiled applications */
  182210. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  182211. }
  182212. void PNGAPI
  182213. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  182214. png_size_t png_struct_size, png_size_t png_info_size)
  182215. {
  182216. /* We only come here via pre-1.0.12-compiled applications */
  182217. if(png_ptr == NULL) return;
  182218. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182219. if(png_sizeof(png_struct) > png_struct_size ||
  182220. png_sizeof(png_info) > png_info_size)
  182221. {
  182222. char msg[80];
  182223. png_ptr->warning_fn=NULL;
  182224. if (user_png_ver)
  182225. {
  182226. png_snprintf(msg, 80,
  182227. "Application was compiled with png.h from libpng-%.20s",
  182228. user_png_ver);
  182229. png_warning(png_ptr, msg);
  182230. }
  182231. png_snprintf(msg, 80,
  182232. "Application is running with png.c from libpng-%.20s",
  182233. png_libpng_ver);
  182234. png_warning(png_ptr, msg);
  182235. }
  182236. #endif
  182237. if(png_sizeof(png_struct) > png_struct_size)
  182238. {
  182239. png_ptr->error_fn=NULL;
  182240. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182241. png_ptr->flags=0;
  182242. #endif
  182243. png_error(png_ptr,
  182244. "The png struct allocated by the application for reading is too small.");
  182245. }
  182246. if(png_sizeof(png_info) > png_info_size)
  182247. {
  182248. png_ptr->error_fn=NULL;
  182249. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182250. png_ptr->flags=0;
  182251. #endif
  182252. png_error(png_ptr,
  182253. "The info struct allocated by application for reading is too small.");
  182254. }
  182255. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  182256. }
  182257. #endif /* PNG_1_0_X || PNG_1_2_X */
  182258. void PNGAPI
  182259. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  182260. png_size_t png_struct_size)
  182261. {
  182262. #ifdef PNG_SETJMP_SUPPORTED
  182263. jmp_buf tmp_jmp; /* to save current jump buffer */
  182264. #endif
  182265. int i=0;
  182266. png_structp png_ptr=*ptr_ptr;
  182267. if(png_ptr == NULL) return;
  182268. do
  182269. {
  182270. if(user_png_ver[i] != png_libpng_ver[i])
  182271. {
  182272. #ifdef PNG_LEGACY_SUPPORTED
  182273. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182274. #else
  182275. png_ptr->warning_fn=NULL;
  182276. png_warning(png_ptr,
  182277. "Application uses deprecated png_read_init() and should be recompiled.");
  182278. break;
  182279. #endif
  182280. }
  182281. } while (png_libpng_ver[i++]);
  182282. png_debug(1, "in png_read_init_3\n");
  182283. #ifdef PNG_SETJMP_SUPPORTED
  182284. /* save jump buffer and error functions */
  182285. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182286. #endif
  182287. if(png_sizeof(png_struct) > png_struct_size)
  182288. {
  182289. png_destroy_struct(png_ptr);
  182290. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182291. png_ptr = *ptr_ptr;
  182292. }
  182293. /* reset all variables to 0 */
  182294. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182295. #ifdef PNG_SETJMP_SUPPORTED
  182296. /* restore jump buffer */
  182297. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182298. #endif
  182299. /* added at libpng-1.2.6 */
  182300. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182301. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182302. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182303. #endif
  182304. /* initialize zbuf - compression buffer */
  182305. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182306. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182307. (png_uint_32)png_ptr->zbuf_size);
  182308. png_ptr->zstream.zalloc = png_zalloc;
  182309. png_ptr->zstream.zfree = png_zfree;
  182310. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182311. switch (inflateInit(&png_ptr->zstream))
  182312. {
  182313. case Z_OK: /* Do nothing */ break;
  182314. case Z_MEM_ERROR:
  182315. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  182316. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  182317. default: png_error(png_ptr, "Unknown zlib error");
  182318. }
  182319. png_ptr->zstream.next_out = png_ptr->zbuf;
  182320. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182321. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182322. }
  182323. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182324. /* Read the information before the actual image data. This has been
  182325. * changed in v0.90 to allow reading a file that already has the magic
  182326. * bytes read from the stream. You can tell libpng how many bytes have
  182327. * been read from the beginning of the stream (up to the maximum of 8)
  182328. * via png_set_sig_bytes(), and we will only check the remaining bytes
  182329. * here. The application can then have access to the signature bytes we
  182330. * read if it is determined that this isn't a valid PNG file.
  182331. */
  182332. void PNGAPI
  182333. png_read_info(png_structp png_ptr, png_infop info_ptr)
  182334. {
  182335. if(png_ptr == NULL) return;
  182336. png_debug(1, "in png_read_info\n");
  182337. /* If we haven't checked all of the PNG signature bytes, do so now. */
  182338. if (png_ptr->sig_bytes < 8)
  182339. {
  182340. png_size_t num_checked = png_ptr->sig_bytes,
  182341. num_to_check = 8 - num_checked;
  182342. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  182343. png_ptr->sig_bytes = 8;
  182344. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  182345. {
  182346. if (num_checked < 4 &&
  182347. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  182348. png_error(png_ptr, "Not a PNG file");
  182349. else
  182350. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  182351. }
  182352. if (num_checked < 3)
  182353. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  182354. }
  182355. for(;;)
  182356. {
  182357. #ifdef PNG_USE_LOCAL_ARRAYS
  182358. PNG_CONST PNG_IHDR;
  182359. PNG_CONST PNG_IDAT;
  182360. PNG_CONST PNG_IEND;
  182361. PNG_CONST PNG_PLTE;
  182362. #if defined(PNG_READ_bKGD_SUPPORTED)
  182363. PNG_CONST PNG_bKGD;
  182364. #endif
  182365. #if defined(PNG_READ_cHRM_SUPPORTED)
  182366. PNG_CONST PNG_cHRM;
  182367. #endif
  182368. #if defined(PNG_READ_gAMA_SUPPORTED)
  182369. PNG_CONST PNG_gAMA;
  182370. #endif
  182371. #if defined(PNG_READ_hIST_SUPPORTED)
  182372. PNG_CONST PNG_hIST;
  182373. #endif
  182374. #if defined(PNG_READ_iCCP_SUPPORTED)
  182375. PNG_CONST PNG_iCCP;
  182376. #endif
  182377. #if defined(PNG_READ_iTXt_SUPPORTED)
  182378. PNG_CONST PNG_iTXt;
  182379. #endif
  182380. #if defined(PNG_READ_oFFs_SUPPORTED)
  182381. PNG_CONST PNG_oFFs;
  182382. #endif
  182383. #if defined(PNG_READ_pCAL_SUPPORTED)
  182384. PNG_CONST PNG_pCAL;
  182385. #endif
  182386. #if defined(PNG_READ_pHYs_SUPPORTED)
  182387. PNG_CONST PNG_pHYs;
  182388. #endif
  182389. #if defined(PNG_READ_sBIT_SUPPORTED)
  182390. PNG_CONST PNG_sBIT;
  182391. #endif
  182392. #if defined(PNG_READ_sCAL_SUPPORTED)
  182393. PNG_CONST PNG_sCAL;
  182394. #endif
  182395. #if defined(PNG_READ_sPLT_SUPPORTED)
  182396. PNG_CONST PNG_sPLT;
  182397. #endif
  182398. #if defined(PNG_READ_sRGB_SUPPORTED)
  182399. PNG_CONST PNG_sRGB;
  182400. #endif
  182401. #if defined(PNG_READ_tEXt_SUPPORTED)
  182402. PNG_CONST PNG_tEXt;
  182403. #endif
  182404. #if defined(PNG_READ_tIME_SUPPORTED)
  182405. PNG_CONST PNG_tIME;
  182406. #endif
  182407. #if defined(PNG_READ_tRNS_SUPPORTED)
  182408. PNG_CONST PNG_tRNS;
  182409. #endif
  182410. #if defined(PNG_READ_zTXt_SUPPORTED)
  182411. PNG_CONST PNG_zTXt;
  182412. #endif
  182413. #endif /* PNG_USE_LOCAL_ARRAYS */
  182414. png_byte chunk_length[4];
  182415. png_uint_32 length;
  182416. png_read_data(png_ptr, chunk_length, 4);
  182417. length = png_get_uint_31(png_ptr,chunk_length);
  182418. png_reset_crc(png_ptr);
  182419. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182420. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  182421. length);
  182422. /* This should be a binary subdivision search or a hash for
  182423. * matching the chunk name rather than a linear search.
  182424. */
  182425. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182426. if(png_ptr->mode & PNG_AFTER_IDAT)
  182427. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  182428. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182429. png_handle_IHDR(png_ptr, info_ptr, length);
  182430. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182431. png_handle_IEND(png_ptr, info_ptr, length);
  182432. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182433. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182434. {
  182435. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182436. png_ptr->mode |= PNG_HAVE_IDAT;
  182437. png_handle_unknown(png_ptr, info_ptr, length);
  182438. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182439. png_ptr->mode |= PNG_HAVE_PLTE;
  182440. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182441. {
  182442. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182443. png_error(png_ptr, "Missing IHDR before IDAT");
  182444. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182445. !(png_ptr->mode & PNG_HAVE_PLTE))
  182446. png_error(png_ptr, "Missing PLTE before IDAT");
  182447. break;
  182448. }
  182449. }
  182450. #endif
  182451. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182452. png_handle_PLTE(png_ptr, info_ptr, length);
  182453. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182454. {
  182455. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182456. png_error(png_ptr, "Missing IHDR before IDAT");
  182457. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182458. !(png_ptr->mode & PNG_HAVE_PLTE))
  182459. png_error(png_ptr, "Missing PLTE before IDAT");
  182460. png_ptr->idat_size = length;
  182461. png_ptr->mode |= PNG_HAVE_IDAT;
  182462. break;
  182463. }
  182464. #if defined(PNG_READ_bKGD_SUPPORTED)
  182465. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182466. png_handle_bKGD(png_ptr, info_ptr, length);
  182467. #endif
  182468. #if defined(PNG_READ_cHRM_SUPPORTED)
  182469. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182470. png_handle_cHRM(png_ptr, info_ptr, length);
  182471. #endif
  182472. #if defined(PNG_READ_gAMA_SUPPORTED)
  182473. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182474. png_handle_gAMA(png_ptr, info_ptr, length);
  182475. #endif
  182476. #if defined(PNG_READ_hIST_SUPPORTED)
  182477. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182478. png_handle_hIST(png_ptr, info_ptr, length);
  182479. #endif
  182480. #if defined(PNG_READ_oFFs_SUPPORTED)
  182481. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182482. png_handle_oFFs(png_ptr, info_ptr, length);
  182483. #endif
  182484. #if defined(PNG_READ_pCAL_SUPPORTED)
  182485. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182486. png_handle_pCAL(png_ptr, info_ptr, length);
  182487. #endif
  182488. #if defined(PNG_READ_sCAL_SUPPORTED)
  182489. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182490. png_handle_sCAL(png_ptr, info_ptr, length);
  182491. #endif
  182492. #if defined(PNG_READ_pHYs_SUPPORTED)
  182493. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182494. png_handle_pHYs(png_ptr, info_ptr, length);
  182495. #endif
  182496. #if defined(PNG_READ_sBIT_SUPPORTED)
  182497. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  182498. png_handle_sBIT(png_ptr, info_ptr, length);
  182499. #endif
  182500. #if defined(PNG_READ_sRGB_SUPPORTED)
  182501. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  182502. png_handle_sRGB(png_ptr, info_ptr, length);
  182503. #endif
  182504. #if defined(PNG_READ_iCCP_SUPPORTED)
  182505. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  182506. png_handle_iCCP(png_ptr, info_ptr, length);
  182507. #endif
  182508. #if defined(PNG_READ_sPLT_SUPPORTED)
  182509. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182510. png_handle_sPLT(png_ptr, info_ptr, length);
  182511. #endif
  182512. #if defined(PNG_READ_tEXt_SUPPORTED)
  182513. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182514. png_handle_tEXt(png_ptr, info_ptr, length);
  182515. #endif
  182516. #if defined(PNG_READ_tIME_SUPPORTED)
  182517. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182518. png_handle_tIME(png_ptr, info_ptr, length);
  182519. #endif
  182520. #if defined(PNG_READ_tRNS_SUPPORTED)
  182521. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182522. png_handle_tRNS(png_ptr, info_ptr, length);
  182523. #endif
  182524. #if defined(PNG_READ_zTXt_SUPPORTED)
  182525. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182526. png_handle_zTXt(png_ptr, info_ptr, length);
  182527. #endif
  182528. #if defined(PNG_READ_iTXt_SUPPORTED)
  182529. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182530. png_handle_iTXt(png_ptr, info_ptr, length);
  182531. #endif
  182532. else
  182533. png_handle_unknown(png_ptr, info_ptr, length);
  182534. }
  182535. }
  182536. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182537. /* optional call to update the users info_ptr structure */
  182538. void PNGAPI
  182539. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  182540. {
  182541. png_debug(1, "in png_read_update_info\n");
  182542. if(png_ptr == NULL) return;
  182543. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  182544. png_read_start_row(png_ptr);
  182545. else
  182546. png_warning(png_ptr,
  182547. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  182548. png_read_transform_info(png_ptr, info_ptr);
  182549. }
  182550. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182551. /* Initialize palette, background, etc, after transformations
  182552. * are set, but before any reading takes place. This allows
  182553. * the user to obtain a gamma-corrected palette, for example.
  182554. * If the user doesn't call this, we will do it ourselves.
  182555. */
  182556. void PNGAPI
  182557. png_start_read_image(png_structp png_ptr)
  182558. {
  182559. png_debug(1, "in png_start_read_image\n");
  182560. if(png_ptr == NULL) return;
  182561. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  182562. png_read_start_row(png_ptr);
  182563. }
  182564. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182565. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182566. void PNGAPI
  182567. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  182568. {
  182569. #ifdef PNG_USE_LOCAL_ARRAYS
  182570. PNG_CONST PNG_IDAT;
  182571. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  182572. 0xff};
  182573. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  182574. #endif
  182575. int ret;
  182576. if(png_ptr == NULL) return;
  182577. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  182578. png_ptr->row_number, png_ptr->pass);
  182579. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  182580. png_read_start_row(png_ptr);
  182581. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  182582. {
  182583. /* check for transforms that have been set but were defined out */
  182584. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  182585. if (png_ptr->transformations & PNG_INVERT_MONO)
  182586. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  182587. #endif
  182588. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  182589. if (png_ptr->transformations & PNG_FILLER)
  182590. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  182591. #endif
  182592. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  182593. if (png_ptr->transformations & PNG_PACKSWAP)
  182594. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  182595. #endif
  182596. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  182597. if (png_ptr->transformations & PNG_PACK)
  182598. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  182599. #endif
  182600. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  182601. if (png_ptr->transformations & PNG_SHIFT)
  182602. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  182603. #endif
  182604. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  182605. if (png_ptr->transformations & PNG_BGR)
  182606. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  182607. #endif
  182608. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  182609. if (png_ptr->transformations & PNG_SWAP_BYTES)
  182610. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  182611. #endif
  182612. }
  182613. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  182614. /* if interlaced and we do not need a new row, combine row and return */
  182615. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  182616. {
  182617. switch (png_ptr->pass)
  182618. {
  182619. case 0:
  182620. if (png_ptr->row_number & 0x07)
  182621. {
  182622. if (dsp_row != NULL)
  182623. png_combine_row(png_ptr, dsp_row,
  182624. png_pass_dsp_mask[png_ptr->pass]);
  182625. png_read_finish_row(png_ptr);
  182626. return;
  182627. }
  182628. break;
  182629. case 1:
  182630. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  182631. {
  182632. if (dsp_row != NULL)
  182633. png_combine_row(png_ptr, dsp_row,
  182634. png_pass_dsp_mask[png_ptr->pass]);
  182635. png_read_finish_row(png_ptr);
  182636. return;
  182637. }
  182638. break;
  182639. case 2:
  182640. if ((png_ptr->row_number & 0x07) != 4)
  182641. {
  182642. if (dsp_row != NULL && (png_ptr->row_number & 4))
  182643. png_combine_row(png_ptr, dsp_row,
  182644. png_pass_dsp_mask[png_ptr->pass]);
  182645. png_read_finish_row(png_ptr);
  182646. return;
  182647. }
  182648. break;
  182649. case 3:
  182650. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  182651. {
  182652. if (dsp_row != NULL)
  182653. png_combine_row(png_ptr, dsp_row,
  182654. png_pass_dsp_mask[png_ptr->pass]);
  182655. png_read_finish_row(png_ptr);
  182656. return;
  182657. }
  182658. break;
  182659. case 4:
  182660. if ((png_ptr->row_number & 3) != 2)
  182661. {
  182662. if (dsp_row != NULL && (png_ptr->row_number & 2))
  182663. png_combine_row(png_ptr, dsp_row,
  182664. png_pass_dsp_mask[png_ptr->pass]);
  182665. png_read_finish_row(png_ptr);
  182666. return;
  182667. }
  182668. break;
  182669. case 5:
  182670. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  182671. {
  182672. if (dsp_row != NULL)
  182673. png_combine_row(png_ptr, dsp_row,
  182674. png_pass_dsp_mask[png_ptr->pass]);
  182675. png_read_finish_row(png_ptr);
  182676. return;
  182677. }
  182678. break;
  182679. case 6:
  182680. if (!(png_ptr->row_number & 1))
  182681. {
  182682. png_read_finish_row(png_ptr);
  182683. return;
  182684. }
  182685. break;
  182686. }
  182687. }
  182688. #endif
  182689. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  182690. png_error(png_ptr, "Invalid attempt to read row data");
  182691. png_ptr->zstream.next_out = png_ptr->row_buf;
  182692. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  182693. do
  182694. {
  182695. if (!(png_ptr->zstream.avail_in))
  182696. {
  182697. while (!png_ptr->idat_size)
  182698. {
  182699. png_byte chunk_length[4];
  182700. png_crc_finish(png_ptr, 0);
  182701. png_read_data(png_ptr, chunk_length, 4);
  182702. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  182703. png_reset_crc(png_ptr);
  182704. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182705. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182706. png_error(png_ptr, "Not enough image data");
  182707. }
  182708. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  182709. png_ptr->zstream.next_in = png_ptr->zbuf;
  182710. if (png_ptr->zbuf_size > png_ptr->idat_size)
  182711. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  182712. png_crc_read(png_ptr, png_ptr->zbuf,
  182713. (png_size_t)png_ptr->zstream.avail_in);
  182714. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  182715. }
  182716. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  182717. if (ret == Z_STREAM_END)
  182718. {
  182719. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  182720. png_ptr->idat_size)
  182721. png_error(png_ptr, "Extra compressed data");
  182722. png_ptr->mode |= PNG_AFTER_IDAT;
  182723. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  182724. break;
  182725. }
  182726. if (ret != Z_OK)
  182727. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  182728. "Decompression error");
  182729. } while (png_ptr->zstream.avail_out);
  182730. png_ptr->row_info.color_type = png_ptr->color_type;
  182731. png_ptr->row_info.width = png_ptr->iwidth;
  182732. png_ptr->row_info.channels = png_ptr->channels;
  182733. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  182734. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  182735. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  182736. png_ptr->row_info.width);
  182737. if(png_ptr->row_buf[0])
  182738. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  182739. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  182740. (int)(png_ptr->row_buf[0]));
  182741. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  182742. png_ptr->rowbytes + 1);
  182743. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182744. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  182745. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  182746. {
  182747. /* Intrapixel differencing */
  182748. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  182749. }
  182750. #endif
  182751. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  182752. png_do_read_transformations(png_ptr);
  182753. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  182754. /* blow up interlaced rows to full size */
  182755. if (png_ptr->interlaced &&
  182756. (png_ptr->transformations & PNG_INTERLACE))
  182757. {
  182758. if (png_ptr->pass < 6)
  182759. /* old interface (pre-1.0.9):
  182760. png_do_read_interlace(&(png_ptr->row_info),
  182761. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  182762. */
  182763. png_do_read_interlace(png_ptr);
  182764. if (dsp_row != NULL)
  182765. png_combine_row(png_ptr, dsp_row,
  182766. png_pass_dsp_mask[png_ptr->pass]);
  182767. if (row != NULL)
  182768. png_combine_row(png_ptr, row,
  182769. png_pass_mask[png_ptr->pass]);
  182770. }
  182771. else
  182772. #endif
  182773. {
  182774. if (row != NULL)
  182775. png_combine_row(png_ptr, row, 0xff);
  182776. if (dsp_row != NULL)
  182777. png_combine_row(png_ptr, dsp_row, 0xff);
  182778. }
  182779. png_read_finish_row(png_ptr);
  182780. if (png_ptr->read_row_fn != NULL)
  182781. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  182782. }
  182783. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182784. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182785. /* Read one or more rows of image data. If the image is interlaced,
  182786. * and png_set_interlace_handling() has been called, the rows need to
  182787. * contain the contents of the rows from the previous pass. If the
  182788. * image has alpha or transparency, and png_handle_alpha()[*] has been
  182789. * called, the rows contents must be initialized to the contents of the
  182790. * screen.
  182791. *
  182792. * "row" holds the actual image, and pixels are placed in it
  182793. * as they arrive. If the image is displayed after each pass, it will
  182794. * appear to "sparkle" in. "display_row" can be used to display a
  182795. * "chunky" progressive image, with finer detail added as it becomes
  182796. * available. If you do not want this "chunky" display, you may pass
  182797. * NULL for display_row. If you do not want the sparkle display, and
  182798. * you have not called png_handle_alpha(), you may pass NULL for rows.
  182799. * If you have called png_handle_alpha(), and the image has either an
  182800. * alpha channel or a transparency chunk, you must provide a buffer for
  182801. * rows. In this case, you do not have to provide a display_row buffer
  182802. * also, but you may. If the image is not interlaced, or if you have
  182803. * not called png_set_interlace_handling(), the display_row buffer will
  182804. * be ignored, so pass NULL to it.
  182805. *
  182806. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  182807. */
  182808. void PNGAPI
  182809. png_read_rows(png_structp png_ptr, png_bytepp row,
  182810. png_bytepp display_row, png_uint_32 num_rows)
  182811. {
  182812. png_uint_32 i;
  182813. png_bytepp rp;
  182814. png_bytepp dp;
  182815. png_debug(1, "in png_read_rows\n");
  182816. if(png_ptr == NULL) return;
  182817. rp = row;
  182818. dp = display_row;
  182819. if (rp != NULL && dp != NULL)
  182820. for (i = 0; i < num_rows; i++)
  182821. {
  182822. png_bytep rptr = *rp++;
  182823. png_bytep dptr = *dp++;
  182824. png_read_row(png_ptr, rptr, dptr);
  182825. }
  182826. else if(rp != NULL)
  182827. for (i = 0; i < num_rows; i++)
  182828. {
  182829. png_bytep rptr = *rp;
  182830. png_read_row(png_ptr, rptr, png_bytep_NULL);
  182831. rp++;
  182832. }
  182833. else if(dp != NULL)
  182834. for (i = 0; i < num_rows; i++)
  182835. {
  182836. png_bytep dptr = *dp;
  182837. png_read_row(png_ptr, png_bytep_NULL, dptr);
  182838. dp++;
  182839. }
  182840. }
  182841. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182842. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182843. /* Read the entire image. If the image has an alpha channel or a tRNS
  182844. * chunk, and you have called png_handle_alpha()[*], you will need to
  182845. * initialize the image to the current image that PNG will be overlaying.
  182846. * We set the num_rows again here, in case it was incorrectly set in
  182847. * png_read_start_row() by a call to png_read_update_info() or
  182848. * png_start_read_image() if png_set_interlace_handling() wasn't called
  182849. * prior to either of these functions like it should have been. You can
  182850. * only call this function once. If you desire to have an image for
  182851. * each pass of a interlaced image, use png_read_rows() instead.
  182852. *
  182853. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  182854. */
  182855. void PNGAPI
  182856. png_read_image(png_structp png_ptr, png_bytepp image)
  182857. {
  182858. png_uint_32 i,image_height;
  182859. int pass, j;
  182860. png_bytepp rp;
  182861. png_debug(1, "in png_read_image\n");
  182862. if(png_ptr == NULL) return;
  182863. #ifdef PNG_READ_INTERLACING_SUPPORTED
  182864. pass = png_set_interlace_handling(png_ptr);
  182865. #else
  182866. if (png_ptr->interlaced)
  182867. png_error(png_ptr,
  182868. "Cannot read interlaced image -- interlace handler disabled.");
  182869. pass = 1;
  182870. #endif
  182871. image_height=png_ptr->height;
  182872. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  182873. for (j = 0; j < pass; j++)
  182874. {
  182875. rp = image;
  182876. for (i = 0; i < image_height; i++)
  182877. {
  182878. png_read_row(png_ptr, *rp, png_bytep_NULL);
  182879. rp++;
  182880. }
  182881. }
  182882. }
  182883. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182884. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182885. /* Read the end of the PNG file. Will not read past the end of the
  182886. * file, will verify the end is accurate, and will read any comments
  182887. * or time information at the end of the file, if info is not NULL.
  182888. */
  182889. void PNGAPI
  182890. png_read_end(png_structp png_ptr, png_infop info_ptr)
  182891. {
  182892. png_byte chunk_length[4];
  182893. png_uint_32 length;
  182894. png_debug(1, "in png_read_end\n");
  182895. if(png_ptr == NULL) return;
  182896. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  182897. do
  182898. {
  182899. #ifdef PNG_USE_LOCAL_ARRAYS
  182900. PNG_CONST PNG_IHDR;
  182901. PNG_CONST PNG_IDAT;
  182902. PNG_CONST PNG_IEND;
  182903. PNG_CONST PNG_PLTE;
  182904. #if defined(PNG_READ_bKGD_SUPPORTED)
  182905. PNG_CONST PNG_bKGD;
  182906. #endif
  182907. #if defined(PNG_READ_cHRM_SUPPORTED)
  182908. PNG_CONST PNG_cHRM;
  182909. #endif
  182910. #if defined(PNG_READ_gAMA_SUPPORTED)
  182911. PNG_CONST PNG_gAMA;
  182912. #endif
  182913. #if defined(PNG_READ_hIST_SUPPORTED)
  182914. PNG_CONST PNG_hIST;
  182915. #endif
  182916. #if defined(PNG_READ_iCCP_SUPPORTED)
  182917. PNG_CONST PNG_iCCP;
  182918. #endif
  182919. #if defined(PNG_READ_iTXt_SUPPORTED)
  182920. PNG_CONST PNG_iTXt;
  182921. #endif
  182922. #if defined(PNG_READ_oFFs_SUPPORTED)
  182923. PNG_CONST PNG_oFFs;
  182924. #endif
  182925. #if defined(PNG_READ_pCAL_SUPPORTED)
  182926. PNG_CONST PNG_pCAL;
  182927. #endif
  182928. #if defined(PNG_READ_pHYs_SUPPORTED)
  182929. PNG_CONST PNG_pHYs;
  182930. #endif
  182931. #if defined(PNG_READ_sBIT_SUPPORTED)
  182932. PNG_CONST PNG_sBIT;
  182933. #endif
  182934. #if defined(PNG_READ_sCAL_SUPPORTED)
  182935. PNG_CONST PNG_sCAL;
  182936. #endif
  182937. #if defined(PNG_READ_sPLT_SUPPORTED)
  182938. PNG_CONST PNG_sPLT;
  182939. #endif
  182940. #if defined(PNG_READ_sRGB_SUPPORTED)
  182941. PNG_CONST PNG_sRGB;
  182942. #endif
  182943. #if defined(PNG_READ_tEXt_SUPPORTED)
  182944. PNG_CONST PNG_tEXt;
  182945. #endif
  182946. #if defined(PNG_READ_tIME_SUPPORTED)
  182947. PNG_CONST PNG_tIME;
  182948. #endif
  182949. #if defined(PNG_READ_tRNS_SUPPORTED)
  182950. PNG_CONST PNG_tRNS;
  182951. #endif
  182952. #if defined(PNG_READ_zTXt_SUPPORTED)
  182953. PNG_CONST PNG_zTXt;
  182954. #endif
  182955. #endif /* PNG_USE_LOCAL_ARRAYS */
  182956. png_read_data(png_ptr, chunk_length, 4);
  182957. length = png_get_uint_31(png_ptr,chunk_length);
  182958. png_reset_crc(png_ptr);
  182959. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182960. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  182961. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182962. png_handle_IHDR(png_ptr, info_ptr, length);
  182963. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182964. png_handle_IEND(png_ptr, info_ptr, length);
  182965. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182966. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182967. {
  182968. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182969. {
  182970. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182971. png_error(png_ptr, "Too many IDAT's found");
  182972. }
  182973. png_handle_unknown(png_ptr, info_ptr, length);
  182974. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182975. png_ptr->mode |= PNG_HAVE_PLTE;
  182976. }
  182977. #endif
  182978. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182979. {
  182980. /* Zero length IDATs are legal after the last IDAT has been
  182981. * read, but not after other chunks have been read.
  182982. */
  182983. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182984. png_error(png_ptr, "Too many IDAT's found");
  182985. png_crc_finish(png_ptr, length);
  182986. }
  182987. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182988. png_handle_PLTE(png_ptr, info_ptr, length);
  182989. #if defined(PNG_READ_bKGD_SUPPORTED)
  182990. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182991. png_handle_bKGD(png_ptr, info_ptr, length);
  182992. #endif
  182993. #if defined(PNG_READ_cHRM_SUPPORTED)
  182994. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182995. png_handle_cHRM(png_ptr, info_ptr, length);
  182996. #endif
  182997. #if defined(PNG_READ_gAMA_SUPPORTED)
  182998. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182999. png_handle_gAMA(png_ptr, info_ptr, length);
  183000. #endif
  183001. #if defined(PNG_READ_hIST_SUPPORTED)
  183002. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183003. png_handle_hIST(png_ptr, info_ptr, length);
  183004. #endif
  183005. #if defined(PNG_READ_oFFs_SUPPORTED)
  183006. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183007. png_handle_oFFs(png_ptr, info_ptr, length);
  183008. #endif
  183009. #if defined(PNG_READ_pCAL_SUPPORTED)
  183010. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183011. png_handle_pCAL(png_ptr, info_ptr, length);
  183012. #endif
  183013. #if defined(PNG_READ_sCAL_SUPPORTED)
  183014. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183015. png_handle_sCAL(png_ptr, info_ptr, length);
  183016. #endif
  183017. #if defined(PNG_READ_pHYs_SUPPORTED)
  183018. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183019. png_handle_pHYs(png_ptr, info_ptr, length);
  183020. #endif
  183021. #if defined(PNG_READ_sBIT_SUPPORTED)
  183022. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183023. png_handle_sBIT(png_ptr, info_ptr, length);
  183024. #endif
  183025. #if defined(PNG_READ_sRGB_SUPPORTED)
  183026. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183027. png_handle_sRGB(png_ptr, info_ptr, length);
  183028. #endif
  183029. #if defined(PNG_READ_iCCP_SUPPORTED)
  183030. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183031. png_handle_iCCP(png_ptr, info_ptr, length);
  183032. #endif
  183033. #if defined(PNG_READ_sPLT_SUPPORTED)
  183034. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183035. png_handle_sPLT(png_ptr, info_ptr, length);
  183036. #endif
  183037. #if defined(PNG_READ_tEXt_SUPPORTED)
  183038. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183039. png_handle_tEXt(png_ptr, info_ptr, length);
  183040. #endif
  183041. #if defined(PNG_READ_tIME_SUPPORTED)
  183042. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183043. png_handle_tIME(png_ptr, info_ptr, length);
  183044. #endif
  183045. #if defined(PNG_READ_tRNS_SUPPORTED)
  183046. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183047. png_handle_tRNS(png_ptr, info_ptr, length);
  183048. #endif
  183049. #if defined(PNG_READ_zTXt_SUPPORTED)
  183050. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183051. png_handle_zTXt(png_ptr, info_ptr, length);
  183052. #endif
  183053. #if defined(PNG_READ_iTXt_SUPPORTED)
  183054. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183055. png_handle_iTXt(png_ptr, info_ptr, length);
  183056. #endif
  183057. else
  183058. png_handle_unknown(png_ptr, info_ptr, length);
  183059. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  183060. }
  183061. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183062. /* free all memory used by the read */
  183063. void PNGAPI
  183064. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  183065. png_infopp end_info_ptr_ptr)
  183066. {
  183067. png_structp png_ptr = NULL;
  183068. png_infop info_ptr = NULL, end_info_ptr = NULL;
  183069. #ifdef PNG_USER_MEM_SUPPORTED
  183070. png_free_ptr free_fn;
  183071. png_voidp mem_ptr;
  183072. #endif
  183073. png_debug(1, "in png_destroy_read_struct\n");
  183074. if (png_ptr_ptr != NULL)
  183075. png_ptr = *png_ptr_ptr;
  183076. if (info_ptr_ptr != NULL)
  183077. info_ptr = *info_ptr_ptr;
  183078. if (end_info_ptr_ptr != NULL)
  183079. end_info_ptr = *end_info_ptr_ptr;
  183080. #ifdef PNG_USER_MEM_SUPPORTED
  183081. free_fn = png_ptr->free_fn;
  183082. mem_ptr = png_ptr->mem_ptr;
  183083. #endif
  183084. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  183085. if (info_ptr != NULL)
  183086. {
  183087. #if defined(PNG_TEXT_SUPPORTED)
  183088. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  183089. #endif
  183090. #ifdef PNG_USER_MEM_SUPPORTED
  183091. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  183092. (png_voidp)mem_ptr);
  183093. #else
  183094. png_destroy_struct((png_voidp)info_ptr);
  183095. #endif
  183096. *info_ptr_ptr = NULL;
  183097. }
  183098. if (end_info_ptr != NULL)
  183099. {
  183100. #if defined(PNG_READ_TEXT_SUPPORTED)
  183101. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  183102. #endif
  183103. #ifdef PNG_USER_MEM_SUPPORTED
  183104. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  183105. (png_voidp)mem_ptr);
  183106. #else
  183107. png_destroy_struct((png_voidp)end_info_ptr);
  183108. #endif
  183109. *end_info_ptr_ptr = NULL;
  183110. }
  183111. if (png_ptr != NULL)
  183112. {
  183113. #ifdef PNG_USER_MEM_SUPPORTED
  183114. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  183115. (png_voidp)mem_ptr);
  183116. #else
  183117. png_destroy_struct((png_voidp)png_ptr);
  183118. #endif
  183119. *png_ptr_ptr = NULL;
  183120. }
  183121. }
  183122. /* free all memory used by the read (old method) */
  183123. void /* PRIVATE */
  183124. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  183125. {
  183126. #ifdef PNG_SETJMP_SUPPORTED
  183127. jmp_buf tmp_jmp;
  183128. #endif
  183129. png_error_ptr error_fn;
  183130. png_error_ptr warning_fn;
  183131. png_voidp error_ptr;
  183132. #ifdef PNG_USER_MEM_SUPPORTED
  183133. png_free_ptr free_fn;
  183134. #endif
  183135. png_debug(1, "in png_read_destroy\n");
  183136. if (info_ptr != NULL)
  183137. png_info_destroy(png_ptr, info_ptr);
  183138. if (end_info_ptr != NULL)
  183139. png_info_destroy(png_ptr, end_info_ptr);
  183140. png_free(png_ptr, png_ptr->zbuf);
  183141. png_free(png_ptr, png_ptr->big_row_buf);
  183142. png_free(png_ptr, png_ptr->prev_row);
  183143. #if defined(PNG_READ_DITHER_SUPPORTED)
  183144. png_free(png_ptr, png_ptr->palette_lookup);
  183145. png_free(png_ptr, png_ptr->dither_index);
  183146. #endif
  183147. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183148. png_free(png_ptr, png_ptr->gamma_table);
  183149. #endif
  183150. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183151. png_free(png_ptr, png_ptr->gamma_from_1);
  183152. png_free(png_ptr, png_ptr->gamma_to_1);
  183153. #endif
  183154. #ifdef PNG_FREE_ME_SUPPORTED
  183155. if (png_ptr->free_me & PNG_FREE_PLTE)
  183156. png_zfree(png_ptr, png_ptr->palette);
  183157. png_ptr->free_me &= ~PNG_FREE_PLTE;
  183158. #else
  183159. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  183160. png_zfree(png_ptr, png_ptr->palette);
  183161. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  183162. #endif
  183163. #if defined(PNG_tRNS_SUPPORTED) || \
  183164. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183165. #ifdef PNG_FREE_ME_SUPPORTED
  183166. if (png_ptr->free_me & PNG_FREE_TRNS)
  183167. png_free(png_ptr, png_ptr->trans);
  183168. png_ptr->free_me &= ~PNG_FREE_TRNS;
  183169. #else
  183170. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  183171. png_free(png_ptr, png_ptr->trans);
  183172. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  183173. #endif
  183174. #endif
  183175. #if defined(PNG_READ_hIST_SUPPORTED)
  183176. #ifdef PNG_FREE_ME_SUPPORTED
  183177. if (png_ptr->free_me & PNG_FREE_HIST)
  183178. png_free(png_ptr, png_ptr->hist);
  183179. png_ptr->free_me &= ~PNG_FREE_HIST;
  183180. #else
  183181. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  183182. png_free(png_ptr, png_ptr->hist);
  183183. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  183184. #endif
  183185. #endif
  183186. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183187. if (png_ptr->gamma_16_table != NULL)
  183188. {
  183189. int i;
  183190. int istop = (1 << (8 - png_ptr->gamma_shift));
  183191. for (i = 0; i < istop; i++)
  183192. {
  183193. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  183194. }
  183195. png_free(png_ptr, png_ptr->gamma_16_table);
  183196. }
  183197. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183198. if (png_ptr->gamma_16_from_1 != NULL)
  183199. {
  183200. int i;
  183201. int istop = (1 << (8 - png_ptr->gamma_shift));
  183202. for (i = 0; i < istop; i++)
  183203. {
  183204. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  183205. }
  183206. png_free(png_ptr, png_ptr->gamma_16_from_1);
  183207. }
  183208. if (png_ptr->gamma_16_to_1 != NULL)
  183209. {
  183210. int i;
  183211. int istop = (1 << (8 - png_ptr->gamma_shift));
  183212. for (i = 0; i < istop; i++)
  183213. {
  183214. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  183215. }
  183216. png_free(png_ptr, png_ptr->gamma_16_to_1);
  183217. }
  183218. #endif
  183219. #endif
  183220. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183221. png_free(png_ptr, png_ptr->time_buffer);
  183222. #endif
  183223. inflateEnd(&png_ptr->zstream);
  183224. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183225. png_free(png_ptr, png_ptr->save_buffer);
  183226. #endif
  183227. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183228. #ifdef PNG_TEXT_SUPPORTED
  183229. png_free(png_ptr, png_ptr->current_text);
  183230. #endif /* PNG_TEXT_SUPPORTED */
  183231. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183232. /* Save the important info out of the png_struct, in case it is
  183233. * being used again.
  183234. */
  183235. #ifdef PNG_SETJMP_SUPPORTED
  183236. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  183237. #endif
  183238. error_fn = png_ptr->error_fn;
  183239. warning_fn = png_ptr->warning_fn;
  183240. error_ptr = png_ptr->error_ptr;
  183241. #ifdef PNG_USER_MEM_SUPPORTED
  183242. free_fn = png_ptr->free_fn;
  183243. #endif
  183244. png_memset(png_ptr, 0, png_sizeof (png_struct));
  183245. png_ptr->error_fn = error_fn;
  183246. png_ptr->warning_fn = warning_fn;
  183247. png_ptr->error_ptr = error_ptr;
  183248. #ifdef PNG_USER_MEM_SUPPORTED
  183249. png_ptr->free_fn = free_fn;
  183250. #endif
  183251. #ifdef PNG_SETJMP_SUPPORTED
  183252. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  183253. #endif
  183254. }
  183255. void PNGAPI
  183256. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  183257. {
  183258. if(png_ptr == NULL) return;
  183259. png_ptr->read_row_fn = read_row_fn;
  183260. }
  183261. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183262. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183263. void PNGAPI
  183264. png_read_png(png_structp png_ptr, png_infop info_ptr,
  183265. int transforms,
  183266. voidp params)
  183267. {
  183268. int row;
  183269. if(png_ptr == NULL) return;
  183270. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183271. /* invert the alpha channel from opacity to transparency
  183272. */
  183273. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  183274. png_set_invert_alpha(png_ptr);
  183275. #endif
  183276. /* png_read_info() gives us all of the information from the
  183277. * PNG file before the first IDAT (image data chunk).
  183278. */
  183279. png_read_info(png_ptr, info_ptr);
  183280. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  183281. png_error(png_ptr,"Image is too high to process with png_read_png()");
  183282. /* -------------- image transformations start here ------------------- */
  183283. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183284. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  183285. */
  183286. if (transforms & PNG_TRANSFORM_STRIP_16)
  183287. png_set_strip_16(png_ptr);
  183288. #endif
  183289. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183290. /* Strip alpha bytes from the input data without combining with
  183291. * the background (not recommended).
  183292. */
  183293. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  183294. png_set_strip_alpha(png_ptr);
  183295. #endif
  183296. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  183297. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  183298. * byte into separate bytes (useful for paletted and grayscale images).
  183299. */
  183300. if (transforms & PNG_TRANSFORM_PACKING)
  183301. png_set_packing(png_ptr);
  183302. #endif
  183303. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  183304. /* Change the order of packed pixels to least significant bit first
  183305. * (not useful if you are using png_set_packing).
  183306. */
  183307. if (transforms & PNG_TRANSFORM_PACKSWAP)
  183308. png_set_packswap(png_ptr);
  183309. #endif
  183310. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183311. /* Expand paletted colors into true RGB triplets
  183312. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  183313. * Expand paletted or RGB images with transparency to full alpha
  183314. * channels so the data will be available as RGBA quartets.
  183315. */
  183316. if (transforms & PNG_TRANSFORM_EXPAND)
  183317. if ((png_ptr->bit_depth < 8) ||
  183318. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  183319. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  183320. png_set_expand(png_ptr);
  183321. #endif
  183322. /* We don't handle background color or gamma transformation or dithering.
  183323. */
  183324. #if defined(PNG_READ_INVERT_SUPPORTED)
  183325. /* invert monochrome files to have 0 as white and 1 as black
  183326. */
  183327. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  183328. png_set_invert_mono(png_ptr);
  183329. #endif
  183330. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183331. /* If you want to shift the pixel values from the range [0,255] or
  183332. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  183333. * colors were originally in:
  183334. */
  183335. if ((transforms & PNG_TRANSFORM_SHIFT)
  183336. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  183337. {
  183338. png_color_8p sig_bit;
  183339. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  183340. png_set_shift(png_ptr, sig_bit);
  183341. }
  183342. #endif
  183343. #if defined(PNG_READ_BGR_SUPPORTED)
  183344. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  183345. */
  183346. if (transforms & PNG_TRANSFORM_BGR)
  183347. png_set_bgr(png_ptr);
  183348. #endif
  183349. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183350. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  183351. */
  183352. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  183353. png_set_swap_alpha(png_ptr);
  183354. #endif
  183355. #if defined(PNG_READ_SWAP_SUPPORTED)
  183356. /* swap bytes of 16 bit files to least significant byte first
  183357. */
  183358. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  183359. png_set_swap(png_ptr);
  183360. #endif
  183361. /* We don't handle adding filler bytes */
  183362. /* Optional call to gamma correct and add the background to the palette
  183363. * and update info structure. REQUIRED if you are expecting libpng to
  183364. * update the palette for you (i.e., you selected such a transform above).
  183365. */
  183366. png_read_update_info(png_ptr, info_ptr);
  183367. /* -------------- image transformations end here ------------------- */
  183368. #ifdef PNG_FREE_ME_SUPPORTED
  183369. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  183370. #endif
  183371. if(info_ptr->row_pointers == NULL)
  183372. {
  183373. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  183374. info_ptr->height * png_sizeof(png_bytep));
  183375. #ifdef PNG_FREE_ME_SUPPORTED
  183376. info_ptr->free_me |= PNG_FREE_ROWS;
  183377. #endif
  183378. for (row = 0; row < (int)info_ptr->height; row++)
  183379. {
  183380. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  183381. png_get_rowbytes(png_ptr, info_ptr));
  183382. }
  183383. }
  183384. png_read_image(png_ptr, info_ptr->row_pointers);
  183385. info_ptr->valid |= PNG_INFO_IDAT;
  183386. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  183387. png_read_end(png_ptr, info_ptr);
  183388. transforms = transforms; /* quiet compiler warnings */
  183389. params = params;
  183390. }
  183391. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  183392. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183393. #endif /* PNG_READ_SUPPORTED */
  183394. /********* End of inlined file: pngread.c *********/
  183395. /********* Start of inlined file: pngpread.c *********/
  183396. /* pngpread.c - read a png file in push mode
  183397. *
  183398. * Last changed in libpng 1.2.21 October 4, 2007
  183399. * For conditions of distribution and use, see copyright notice in png.h
  183400. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183401. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183402. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183403. */
  183404. #define PNG_INTERNAL
  183405. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183406. /* push model modes */
  183407. #define PNG_READ_SIG_MODE 0
  183408. #define PNG_READ_CHUNK_MODE 1
  183409. #define PNG_READ_IDAT_MODE 2
  183410. #define PNG_SKIP_MODE 3
  183411. #define PNG_READ_tEXt_MODE 4
  183412. #define PNG_READ_zTXt_MODE 5
  183413. #define PNG_READ_DONE_MODE 6
  183414. #define PNG_READ_iTXt_MODE 7
  183415. #define PNG_ERROR_MODE 8
  183416. void PNGAPI
  183417. png_process_data(png_structp png_ptr, png_infop info_ptr,
  183418. png_bytep buffer, png_size_t buffer_size)
  183419. {
  183420. if(png_ptr == NULL) return;
  183421. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  183422. while (png_ptr->buffer_size)
  183423. {
  183424. png_process_some_data(png_ptr, info_ptr);
  183425. }
  183426. }
  183427. /* What we do with the incoming data depends on what we were previously
  183428. * doing before we ran out of data...
  183429. */
  183430. void /* PRIVATE */
  183431. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  183432. {
  183433. if(png_ptr == NULL) return;
  183434. switch (png_ptr->process_mode)
  183435. {
  183436. case PNG_READ_SIG_MODE:
  183437. {
  183438. png_push_read_sig(png_ptr, info_ptr);
  183439. break;
  183440. }
  183441. case PNG_READ_CHUNK_MODE:
  183442. {
  183443. png_push_read_chunk(png_ptr, info_ptr);
  183444. break;
  183445. }
  183446. case PNG_READ_IDAT_MODE:
  183447. {
  183448. png_push_read_IDAT(png_ptr);
  183449. break;
  183450. }
  183451. #if defined(PNG_READ_tEXt_SUPPORTED)
  183452. case PNG_READ_tEXt_MODE:
  183453. {
  183454. png_push_read_tEXt(png_ptr, info_ptr);
  183455. break;
  183456. }
  183457. #endif
  183458. #if defined(PNG_READ_zTXt_SUPPORTED)
  183459. case PNG_READ_zTXt_MODE:
  183460. {
  183461. png_push_read_zTXt(png_ptr, info_ptr);
  183462. break;
  183463. }
  183464. #endif
  183465. #if defined(PNG_READ_iTXt_SUPPORTED)
  183466. case PNG_READ_iTXt_MODE:
  183467. {
  183468. png_push_read_iTXt(png_ptr, info_ptr);
  183469. break;
  183470. }
  183471. #endif
  183472. case PNG_SKIP_MODE:
  183473. {
  183474. png_push_crc_finish(png_ptr);
  183475. break;
  183476. }
  183477. default:
  183478. {
  183479. png_ptr->buffer_size = 0;
  183480. break;
  183481. }
  183482. }
  183483. }
  183484. /* Read any remaining signature bytes from the stream and compare them with
  183485. * the correct PNG signature. It is possible that this routine is called
  183486. * with bytes already read from the signature, either because they have been
  183487. * checked by the calling application, or because of multiple calls to this
  183488. * routine.
  183489. */
  183490. void /* PRIVATE */
  183491. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  183492. {
  183493. png_size_t num_checked = png_ptr->sig_bytes,
  183494. num_to_check = 8 - num_checked;
  183495. if (png_ptr->buffer_size < num_to_check)
  183496. {
  183497. num_to_check = png_ptr->buffer_size;
  183498. }
  183499. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  183500. num_to_check);
  183501. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  183502. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  183503. {
  183504. if (num_checked < 4 &&
  183505. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  183506. png_error(png_ptr, "Not a PNG file");
  183507. else
  183508. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  183509. }
  183510. else
  183511. {
  183512. if (png_ptr->sig_bytes >= 8)
  183513. {
  183514. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  183515. }
  183516. }
  183517. }
  183518. void /* PRIVATE */
  183519. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  183520. {
  183521. #ifdef PNG_USE_LOCAL_ARRAYS
  183522. PNG_CONST PNG_IHDR;
  183523. PNG_CONST PNG_IDAT;
  183524. PNG_CONST PNG_IEND;
  183525. PNG_CONST PNG_PLTE;
  183526. #if defined(PNG_READ_bKGD_SUPPORTED)
  183527. PNG_CONST PNG_bKGD;
  183528. #endif
  183529. #if defined(PNG_READ_cHRM_SUPPORTED)
  183530. PNG_CONST PNG_cHRM;
  183531. #endif
  183532. #if defined(PNG_READ_gAMA_SUPPORTED)
  183533. PNG_CONST PNG_gAMA;
  183534. #endif
  183535. #if defined(PNG_READ_hIST_SUPPORTED)
  183536. PNG_CONST PNG_hIST;
  183537. #endif
  183538. #if defined(PNG_READ_iCCP_SUPPORTED)
  183539. PNG_CONST PNG_iCCP;
  183540. #endif
  183541. #if defined(PNG_READ_iTXt_SUPPORTED)
  183542. PNG_CONST PNG_iTXt;
  183543. #endif
  183544. #if defined(PNG_READ_oFFs_SUPPORTED)
  183545. PNG_CONST PNG_oFFs;
  183546. #endif
  183547. #if defined(PNG_READ_pCAL_SUPPORTED)
  183548. PNG_CONST PNG_pCAL;
  183549. #endif
  183550. #if defined(PNG_READ_pHYs_SUPPORTED)
  183551. PNG_CONST PNG_pHYs;
  183552. #endif
  183553. #if defined(PNG_READ_sBIT_SUPPORTED)
  183554. PNG_CONST PNG_sBIT;
  183555. #endif
  183556. #if defined(PNG_READ_sCAL_SUPPORTED)
  183557. PNG_CONST PNG_sCAL;
  183558. #endif
  183559. #if defined(PNG_READ_sRGB_SUPPORTED)
  183560. PNG_CONST PNG_sRGB;
  183561. #endif
  183562. #if defined(PNG_READ_sPLT_SUPPORTED)
  183563. PNG_CONST PNG_sPLT;
  183564. #endif
  183565. #if defined(PNG_READ_tEXt_SUPPORTED)
  183566. PNG_CONST PNG_tEXt;
  183567. #endif
  183568. #if defined(PNG_READ_tIME_SUPPORTED)
  183569. PNG_CONST PNG_tIME;
  183570. #endif
  183571. #if defined(PNG_READ_tRNS_SUPPORTED)
  183572. PNG_CONST PNG_tRNS;
  183573. #endif
  183574. #if defined(PNG_READ_zTXt_SUPPORTED)
  183575. PNG_CONST PNG_zTXt;
  183576. #endif
  183577. #endif /* PNG_USE_LOCAL_ARRAYS */
  183578. /* First we make sure we have enough data for the 4 byte chunk name
  183579. * and the 4 byte chunk length before proceeding with decoding the
  183580. * chunk data. To fully decode each of these chunks, we also make
  183581. * sure we have enough data in the buffer for the 4 byte CRC at the
  183582. * end of every chunk (except IDAT, which is handled separately).
  183583. */
  183584. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  183585. {
  183586. png_byte chunk_length[4];
  183587. if (png_ptr->buffer_size < 8)
  183588. {
  183589. png_push_save_buffer(png_ptr);
  183590. return;
  183591. }
  183592. png_push_fill_buffer(png_ptr, chunk_length, 4);
  183593. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  183594. png_reset_crc(png_ptr);
  183595. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183596. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  183597. }
  183598. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183599. if(png_ptr->mode & PNG_AFTER_IDAT)
  183600. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  183601. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183602. {
  183603. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183604. {
  183605. png_push_save_buffer(png_ptr);
  183606. return;
  183607. }
  183608. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  183609. }
  183610. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183611. {
  183612. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183613. {
  183614. png_push_save_buffer(png_ptr);
  183615. return;
  183616. }
  183617. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  183618. png_ptr->process_mode = PNG_READ_DONE_MODE;
  183619. png_push_have_end(png_ptr, info_ptr);
  183620. }
  183621. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183622. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183623. {
  183624. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183625. {
  183626. png_push_save_buffer(png_ptr);
  183627. return;
  183628. }
  183629. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183630. png_ptr->mode |= PNG_HAVE_IDAT;
  183631. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  183632. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183633. png_ptr->mode |= PNG_HAVE_PLTE;
  183634. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183635. {
  183636. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183637. png_error(png_ptr, "Missing IHDR before IDAT");
  183638. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183639. !(png_ptr->mode & PNG_HAVE_PLTE))
  183640. png_error(png_ptr, "Missing PLTE before IDAT");
  183641. }
  183642. }
  183643. #endif
  183644. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183645. {
  183646. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183647. {
  183648. png_push_save_buffer(png_ptr);
  183649. return;
  183650. }
  183651. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  183652. }
  183653. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183654. {
  183655. /* If we reach an IDAT chunk, this means we have read all of the
  183656. * header chunks, and we can start reading the image (or if this
  183657. * is called after the image has been read - we have an error).
  183658. */
  183659. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183660. png_error(png_ptr, "Missing IHDR before IDAT");
  183661. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183662. !(png_ptr->mode & PNG_HAVE_PLTE))
  183663. png_error(png_ptr, "Missing PLTE before IDAT");
  183664. if (png_ptr->mode & PNG_HAVE_IDAT)
  183665. {
  183666. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183667. if (png_ptr->push_length == 0)
  183668. return;
  183669. if (png_ptr->mode & PNG_AFTER_IDAT)
  183670. png_error(png_ptr, "Too many IDAT's found");
  183671. }
  183672. png_ptr->idat_size = png_ptr->push_length;
  183673. png_ptr->mode |= PNG_HAVE_IDAT;
  183674. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  183675. png_push_have_info(png_ptr, info_ptr);
  183676. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183677. png_ptr->zstream.next_out = png_ptr->row_buf;
  183678. return;
  183679. }
  183680. #if defined(PNG_READ_gAMA_SUPPORTED)
  183681. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183682. {
  183683. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183684. {
  183685. png_push_save_buffer(png_ptr);
  183686. return;
  183687. }
  183688. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  183689. }
  183690. #endif
  183691. #if defined(PNG_READ_sBIT_SUPPORTED)
  183692. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183693. {
  183694. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183695. {
  183696. png_push_save_buffer(png_ptr);
  183697. return;
  183698. }
  183699. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  183700. }
  183701. #endif
  183702. #if defined(PNG_READ_cHRM_SUPPORTED)
  183703. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183704. {
  183705. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183706. {
  183707. png_push_save_buffer(png_ptr);
  183708. return;
  183709. }
  183710. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  183711. }
  183712. #endif
  183713. #if defined(PNG_READ_sRGB_SUPPORTED)
  183714. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183715. {
  183716. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183717. {
  183718. png_push_save_buffer(png_ptr);
  183719. return;
  183720. }
  183721. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  183722. }
  183723. #endif
  183724. #if defined(PNG_READ_iCCP_SUPPORTED)
  183725. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183726. {
  183727. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183728. {
  183729. png_push_save_buffer(png_ptr);
  183730. return;
  183731. }
  183732. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  183733. }
  183734. #endif
  183735. #if defined(PNG_READ_sPLT_SUPPORTED)
  183736. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183737. {
  183738. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183739. {
  183740. png_push_save_buffer(png_ptr);
  183741. return;
  183742. }
  183743. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  183744. }
  183745. #endif
  183746. #if defined(PNG_READ_tRNS_SUPPORTED)
  183747. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183748. {
  183749. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183750. {
  183751. png_push_save_buffer(png_ptr);
  183752. return;
  183753. }
  183754. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  183755. }
  183756. #endif
  183757. #if defined(PNG_READ_bKGD_SUPPORTED)
  183758. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183759. {
  183760. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183761. {
  183762. png_push_save_buffer(png_ptr);
  183763. return;
  183764. }
  183765. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  183766. }
  183767. #endif
  183768. #if defined(PNG_READ_hIST_SUPPORTED)
  183769. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183770. {
  183771. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183772. {
  183773. png_push_save_buffer(png_ptr);
  183774. return;
  183775. }
  183776. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  183777. }
  183778. #endif
  183779. #if defined(PNG_READ_pHYs_SUPPORTED)
  183780. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183781. {
  183782. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183783. {
  183784. png_push_save_buffer(png_ptr);
  183785. return;
  183786. }
  183787. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  183788. }
  183789. #endif
  183790. #if defined(PNG_READ_oFFs_SUPPORTED)
  183791. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183792. {
  183793. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183794. {
  183795. png_push_save_buffer(png_ptr);
  183796. return;
  183797. }
  183798. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  183799. }
  183800. #endif
  183801. #if defined(PNG_READ_pCAL_SUPPORTED)
  183802. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183803. {
  183804. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183805. {
  183806. png_push_save_buffer(png_ptr);
  183807. return;
  183808. }
  183809. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  183810. }
  183811. #endif
  183812. #if defined(PNG_READ_sCAL_SUPPORTED)
  183813. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183814. {
  183815. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183816. {
  183817. png_push_save_buffer(png_ptr);
  183818. return;
  183819. }
  183820. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  183821. }
  183822. #endif
  183823. #if defined(PNG_READ_tIME_SUPPORTED)
  183824. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183825. {
  183826. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183827. {
  183828. png_push_save_buffer(png_ptr);
  183829. return;
  183830. }
  183831. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  183832. }
  183833. #endif
  183834. #if defined(PNG_READ_tEXt_SUPPORTED)
  183835. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183836. {
  183837. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183838. {
  183839. png_push_save_buffer(png_ptr);
  183840. return;
  183841. }
  183842. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  183843. }
  183844. #endif
  183845. #if defined(PNG_READ_zTXt_SUPPORTED)
  183846. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183847. {
  183848. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183849. {
  183850. png_push_save_buffer(png_ptr);
  183851. return;
  183852. }
  183853. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  183854. }
  183855. #endif
  183856. #if defined(PNG_READ_iTXt_SUPPORTED)
  183857. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183858. {
  183859. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183860. {
  183861. png_push_save_buffer(png_ptr);
  183862. return;
  183863. }
  183864. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  183865. }
  183866. #endif
  183867. else
  183868. {
  183869. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183870. {
  183871. png_push_save_buffer(png_ptr);
  183872. return;
  183873. }
  183874. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  183875. }
  183876. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  183877. }
  183878. void /* PRIVATE */
  183879. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  183880. {
  183881. png_ptr->process_mode = PNG_SKIP_MODE;
  183882. png_ptr->skip_length = skip;
  183883. }
  183884. void /* PRIVATE */
  183885. png_push_crc_finish(png_structp png_ptr)
  183886. {
  183887. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  183888. {
  183889. png_size_t save_size;
  183890. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  183891. save_size = (png_size_t)png_ptr->skip_length;
  183892. else
  183893. save_size = png_ptr->save_buffer_size;
  183894. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183895. png_ptr->skip_length -= save_size;
  183896. png_ptr->buffer_size -= save_size;
  183897. png_ptr->save_buffer_size -= save_size;
  183898. png_ptr->save_buffer_ptr += save_size;
  183899. }
  183900. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  183901. {
  183902. png_size_t save_size;
  183903. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  183904. save_size = (png_size_t)png_ptr->skip_length;
  183905. else
  183906. save_size = png_ptr->current_buffer_size;
  183907. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183908. png_ptr->skip_length -= save_size;
  183909. png_ptr->buffer_size -= save_size;
  183910. png_ptr->current_buffer_size -= save_size;
  183911. png_ptr->current_buffer_ptr += save_size;
  183912. }
  183913. if (!png_ptr->skip_length)
  183914. {
  183915. if (png_ptr->buffer_size < 4)
  183916. {
  183917. png_push_save_buffer(png_ptr);
  183918. return;
  183919. }
  183920. png_crc_finish(png_ptr, 0);
  183921. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  183922. }
  183923. }
  183924. void PNGAPI
  183925. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  183926. {
  183927. png_bytep ptr;
  183928. if(png_ptr == NULL) return;
  183929. ptr = buffer;
  183930. if (png_ptr->save_buffer_size)
  183931. {
  183932. png_size_t save_size;
  183933. if (length < png_ptr->save_buffer_size)
  183934. save_size = length;
  183935. else
  183936. save_size = png_ptr->save_buffer_size;
  183937. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  183938. length -= save_size;
  183939. ptr += save_size;
  183940. png_ptr->buffer_size -= save_size;
  183941. png_ptr->save_buffer_size -= save_size;
  183942. png_ptr->save_buffer_ptr += save_size;
  183943. }
  183944. if (length && png_ptr->current_buffer_size)
  183945. {
  183946. png_size_t save_size;
  183947. if (length < png_ptr->current_buffer_size)
  183948. save_size = length;
  183949. else
  183950. save_size = png_ptr->current_buffer_size;
  183951. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  183952. png_ptr->buffer_size -= save_size;
  183953. png_ptr->current_buffer_size -= save_size;
  183954. png_ptr->current_buffer_ptr += save_size;
  183955. }
  183956. }
  183957. void /* PRIVATE */
  183958. png_push_save_buffer(png_structp png_ptr)
  183959. {
  183960. if (png_ptr->save_buffer_size)
  183961. {
  183962. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  183963. {
  183964. png_size_t i,istop;
  183965. png_bytep sp;
  183966. png_bytep dp;
  183967. istop = png_ptr->save_buffer_size;
  183968. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  183969. i < istop; i++, sp++, dp++)
  183970. {
  183971. *dp = *sp;
  183972. }
  183973. }
  183974. }
  183975. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  183976. png_ptr->save_buffer_max)
  183977. {
  183978. png_size_t new_max;
  183979. png_bytep old_buffer;
  183980. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  183981. (png_ptr->current_buffer_size + 256))
  183982. {
  183983. png_error(png_ptr, "Potential overflow of save_buffer");
  183984. }
  183985. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  183986. old_buffer = png_ptr->save_buffer;
  183987. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  183988. (png_uint_32)new_max);
  183989. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  183990. png_free(png_ptr, old_buffer);
  183991. png_ptr->save_buffer_max = new_max;
  183992. }
  183993. if (png_ptr->current_buffer_size)
  183994. {
  183995. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  183996. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  183997. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  183998. png_ptr->current_buffer_size = 0;
  183999. }
  184000. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  184001. png_ptr->buffer_size = 0;
  184002. }
  184003. void /* PRIVATE */
  184004. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  184005. png_size_t buffer_length)
  184006. {
  184007. png_ptr->current_buffer = buffer;
  184008. png_ptr->current_buffer_size = buffer_length;
  184009. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  184010. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  184011. }
  184012. void /* PRIVATE */
  184013. png_push_read_IDAT(png_structp png_ptr)
  184014. {
  184015. #ifdef PNG_USE_LOCAL_ARRAYS
  184016. PNG_CONST PNG_IDAT;
  184017. #endif
  184018. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184019. {
  184020. png_byte chunk_length[4];
  184021. if (png_ptr->buffer_size < 8)
  184022. {
  184023. png_push_save_buffer(png_ptr);
  184024. return;
  184025. }
  184026. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184027. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184028. png_reset_crc(png_ptr);
  184029. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184030. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184031. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184032. {
  184033. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184034. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184035. png_error(png_ptr, "Not enough compressed data");
  184036. return;
  184037. }
  184038. png_ptr->idat_size = png_ptr->push_length;
  184039. }
  184040. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  184041. {
  184042. png_size_t save_size;
  184043. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  184044. {
  184045. save_size = (png_size_t)png_ptr->idat_size;
  184046. /* check for overflow */
  184047. if((png_uint_32)save_size != png_ptr->idat_size)
  184048. png_error(png_ptr, "save_size overflowed in pngpread");
  184049. }
  184050. else
  184051. save_size = png_ptr->save_buffer_size;
  184052. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184053. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184054. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184055. png_ptr->idat_size -= save_size;
  184056. png_ptr->buffer_size -= save_size;
  184057. png_ptr->save_buffer_size -= save_size;
  184058. png_ptr->save_buffer_ptr += save_size;
  184059. }
  184060. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  184061. {
  184062. png_size_t save_size;
  184063. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  184064. {
  184065. save_size = (png_size_t)png_ptr->idat_size;
  184066. /* check for overflow */
  184067. if((png_uint_32)save_size != png_ptr->idat_size)
  184068. png_error(png_ptr, "save_size overflowed in pngpread");
  184069. }
  184070. else
  184071. save_size = png_ptr->current_buffer_size;
  184072. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184073. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184074. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184075. png_ptr->idat_size -= save_size;
  184076. png_ptr->buffer_size -= save_size;
  184077. png_ptr->current_buffer_size -= save_size;
  184078. png_ptr->current_buffer_ptr += save_size;
  184079. }
  184080. if (!png_ptr->idat_size)
  184081. {
  184082. if (png_ptr->buffer_size < 4)
  184083. {
  184084. png_push_save_buffer(png_ptr);
  184085. return;
  184086. }
  184087. png_crc_finish(png_ptr, 0);
  184088. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184089. png_ptr->mode |= PNG_AFTER_IDAT;
  184090. }
  184091. }
  184092. void /* PRIVATE */
  184093. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  184094. png_size_t buffer_length)
  184095. {
  184096. int ret;
  184097. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  184098. png_error(png_ptr, "Extra compression data");
  184099. png_ptr->zstream.next_in = buffer;
  184100. png_ptr->zstream.avail_in = (uInt)buffer_length;
  184101. for(;;)
  184102. {
  184103. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184104. if (ret != Z_OK)
  184105. {
  184106. if (ret == Z_STREAM_END)
  184107. {
  184108. if (png_ptr->zstream.avail_in)
  184109. png_error(png_ptr, "Extra compressed data");
  184110. if (!(png_ptr->zstream.avail_out))
  184111. {
  184112. png_push_process_row(png_ptr);
  184113. }
  184114. png_ptr->mode |= PNG_AFTER_IDAT;
  184115. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184116. break;
  184117. }
  184118. else if (ret == Z_BUF_ERROR)
  184119. break;
  184120. else
  184121. png_error(png_ptr, "Decompression Error");
  184122. }
  184123. if (!(png_ptr->zstream.avail_out))
  184124. {
  184125. if ((
  184126. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184127. png_ptr->interlaced && png_ptr->pass > 6) ||
  184128. (!png_ptr->interlaced &&
  184129. #endif
  184130. png_ptr->row_number == png_ptr->num_rows))
  184131. {
  184132. if (png_ptr->zstream.avail_in)
  184133. {
  184134. png_warning(png_ptr, "Too much data in IDAT chunks");
  184135. }
  184136. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184137. break;
  184138. }
  184139. png_push_process_row(png_ptr);
  184140. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184141. png_ptr->zstream.next_out = png_ptr->row_buf;
  184142. }
  184143. else
  184144. break;
  184145. }
  184146. }
  184147. void /* PRIVATE */
  184148. png_push_process_row(png_structp png_ptr)
  184149. {
  184150. png_ptr->row_info.color_type = png_ptr->color_type;
  184151. png_ptr->row_info.width = png_ptr->iwidth;
  184152. png_ptr->row_info.channels = png_ptr->channels;
  184153. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184154. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184155. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184156. png_ptr->row_info.width);
  184157. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184158. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184159. (int)(png_ptr->row_buf[0]));
  184160. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184161. png_ptr->rowbytes + 1);
  184162. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184163. png_do_read_transformations(png_ptr);
  184164. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184165. /* blow up interlaced rows to full size */
  184166. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184167. {
  184168. if (png_ptr->pass < 6)
  184169. /* old interface (pre-1.0.9):
  184170. png_do_read_interlace(&(png_ptr->row_info),
  184171. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184172. */
  184173. png_do_read_interlace(png_ptr);
  184174. switch (png_ptr->pass)
  184175. {
  184176. case 0:
  184177. {
  184178. int i;
  184179. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  184180. {
  184181. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184182. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  184183. }
  184184. if (png_ptr->pass == 2) /* pass 1 might be empty */
  184185. {
  184186. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184187. {
  184188. png_push_have_row(png_ptr, png_bytep_NULL);
  184189. png_read_push_finish_row(png_ptr);
  184190. }
  184191. }
  184192. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  184193. {
  184194. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184195. {
  184196. png_push_have_row(png_ptr, png_bytep_NULL);
  184197. png_read_push_finish_row(png_ptr);
  184198. }
  184199. }
  184200. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  184201. {
  184202. png_push_have_row(png_ptr, png_bytep_NULL);
  184203. png_read_push_finish_row(png_ptr);
  184204. }
  184205. break;
  184206. }
  184207. case 1:
  184208. {
  184209. int i;
  184210. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  184211. {
  184212. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184213. png_read_push_finish_row(png_ptr);
  184214. }
  184215. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  184216. {
  184217. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184218. {
  184219. png_push_have_row(png_ptr, png_bytep_NULL);
  184220. png_read_push_finish_row(png_ptr);
  184221. }
  184222. }
  184223. break;
  184224. }
  184225. case 2:
  184226. {
  184227. int i;
  184228. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184229. {
  184230. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184231. png_read_push_finish_row(png_ptr);
  184232. }
  184233. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184234. {
  184235. png_push_have_row(png_ptr, png_bytep_NULL);
  184236. png_read_push_finish_row(png_ptr);
  184237. }
  184238. if (png_ptr->pass == 4) /* pass 3 might be empty */
  184239. {
  184240. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184241. {
  184242. png_push_have_row(png_ptr, png_bytep_NULL);
  184243. png_read_push_finish_row(png_ptr);
  184244. }
  184245. }
  184246. break;
  184247. }
  184248. case 3:
  184249. {
  184250. int i;
  184251. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  184252. {
  184253. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184254. png_read_push_finish_row(png_ptr);
  184255. }
  184256. if (png_ptr->pass == 4) /* skip top two generated rows */
  184257. {
  184258. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184259. {
  184260. png_push_have_row(png_ptr, png_bytep_NULL);
  184261. png_read_push_finish_row(png_ptr);
  184262. }
  184263. }
  184264. break;
  184265. }
  184266. case 4:
  184267. {
  184268. int i;
  184269. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184270. {
  184271. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184272. png_read_push_finish_row(png_ptr);
  184273. }
  184274. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184275. {
  184276. png_push_have_row(png_ptr, png_bytep_NULL);
  184277. png_read_push_finish_row(png_ptr);
  184278. }
  184279. if (png_ptr->pass == 6) /* pass 5 might be empty */
  184280. {
  184281. png_push_have_row(png_ptr, png_bytep_NULL);
  184282. png_read_push_finish_row(png_ptr);
  184283. }
  184284. break;
  184285. }
  184286. case 5:
  184287. {
  184288. int i;
  184289. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  184290. {
  184291. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184292. png_read_push_finish_row(png_ptr);
  184293. }
  184294. if (png_ptr->pass == 6) /* skip top generated row */
  184295. {
  184296. png_push_have_row(png_ptr, png_bytep_NULL);
  184297. png_read_push_finish_row(png_ptr);
  184298. }
  184299. break;
  184300. }
  184301. case 6:
  184302. {
  184303. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184304. png_read_push_finish_row(png_ptr);
  184305. if (png_ptr->pass != 6)
  184306. break;
  184307. png_push_have_row(png_ptr, png_bytep_NULL);
  184308. png_read_push_finish_row(png_ptr);
  184309. }
  184310. }
  184311. }
  184312. else
  184313. #endif
  184314. {
  184315. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184316. png_read_push_finish_row(png_ptr);
  184317. }
  184318. }
  184319. void /* PRIVATE */
  184320. png_read_push_finish_row(png_structp png_ptr)
  184321. {
  184322. #ifdef PNG_USE_LOCAL_ARRAYS
  184323. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184324. /* start of interlace block */
  184325. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184326. /* offset to next interlace block */
  184327. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184328. /* start of interlace block in the y direction */
  184329. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184330. /* offset to next interlace block in the y direction */
  184331. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184332. /* Height of interlace block. This is not currently used - if you need
  184333. * it, uncomment it here and in png.h
  184334. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184335. */
  184336. #endif
  184337. png_ptr->row_number++;
  184338. if (png_ptr->row_number < png_ptr->num_rows)
  184339. return;
  184340. if (png_ptr->interlaced)
  184341. {
  184342. png_ptr->row_number = 0;
  184343. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  184344. png_ptr->rowbytes + 1);
  184345. do
  184346. {
  184347. png_ptr->pass++;
  184348. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  184349. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  184350. (png_ptr->pass == 5 && png_ptr->width < 2))
  184351. png_ptr->pass++;
  184352. if (png_ptr->pass > 7)
  184353. png_ptr->pass--;
  184354. if (png_ptr->pass >= 7)
  184355. break;
  184356. png_ptr->iwidth = (png_ptr->width +
  184357. png_pass_inc[png_ptr->pass] - 1 -
  184358. png_pass_start[png_ptr->pass]) /
  184359. png_pass_inc[png_ptr->pass];
  184360. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  184361. png_ptr->iwidth) + 1;
  184362. if (png_ptr->transformations & PNG_INTERLACE)
  184363. break;
  184364. png_ptr->num_rows = (png_ptr->height +
  184365. png_pass_yinc[png_ptr->pass] - 1 -
  184366. png_pass_ystart[png_ptr->pass]) /
  184367. png_pass_yinc[png_ptr->pass];
  184368. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  184369. }
  184370. }
  184371. #if defined(PNG_READ_tEXt_SUPPORTED)
  184372. void /* PRIVATE */
  184373. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184374. length)
  184375. {
  184376. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184377. {
  184378. png_error(png_ptr, "Out of place tEXt");
  184379. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184380. }
  184381. #ifdef PNG_MAX_MALLOC_64K
  184382. png_ptr->skip_length = 0; /* This may not be necessary */
  184383. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  184384. {
  184385. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  184386. png_ptr->skip_length = length - (png_uint_32)65535L;
  184387. length = (png_uint_32)65535L;
  184388. }
  184389. #endif
  184390. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184391. (png_uint_32)(length+1));
  184392. png_ptr->current_text[length] = '\0';
  184393. png_ptr->current_text_ptr = png_ptr->current_text;
  184394. png_ptr->current_text_size = (png_size_t)length;
  184395. png_ptr->current_text_left = (png_size_t)length;
  184396. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  184397. }
  184398. void /* PRIVATE */
  184399. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  184400. {
  184401. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184402. {
  184403. png_size_t text_size;
  184404. if (png_ptr->buffer_size < png_ptr->current_text_left)
  184405. text_size = png_ptr->buffer_size;
  184406. else
  184407. text_size = png_ptr->current_text_left;
  184408. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184409. png_ptr->current_text_left -= text_size;
  184410. png_ptr->current_text_ptr += text_size;
  184411. }
  184412. if (!(png_ptr->current_text_left))
  184413. {
  184414. png_textp text_ptr;
  184415. png_charp text;
  184416. png_charp key;
  184417. int ret;
  184418. if (png_ptr->buffer_size < 4)
  184419. {
  184420. png_push_save_buffer(png_ptr);
  184421. return;
  184422. }
  184423. png_push_crc_finish(png_ptr);
  184424. #if defined(PNG_MAX_MALLOC_64K)
  184425. if (png_ptr->skip_length)
  184426. return;
  184427. #endif
  184428. key = png_ptr->current_text;
  184429. for (text = key; *text; text++)
  184430. /* empty loop */ ;
  184431. if (text < key + png_ptr->current_text_size)
  184432. text++;
  184433. text_ptr = (png_textp)png_malloc(png_ptr,
  184434. (png_uint_32)png_sizeof(png_text));
  184435. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  184436. text_ptr->key = key;
  184437. #ifdef PNG_iTXt_SUPPORTED
  184438. text_ptr->lang = NULL;
  184439. text_ptr->lang_key = NULL;
  184440. #endif
  184441. text_ptr->text = text;
  184442. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  184443. png_free(png_ptr, key);
  184444. png_free(png_ptr, text_ptr);
  184445. png_ptr->current_text = NULL;
  184446. if (ret)
  184447. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  184448. }
  184449. }
  184450. #endif
  184451. #if defined(PNG_READ_zTXt_SUPPORTED)
  184452. void /* PRIVATE */
  184453. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184454. length)
  184455. {
  184456. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184457. {
  184458. png_error(png_ptr, "Out of place zTXt");
  184459. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184460. }
  184461. #ifdef PNG_MAX_MALLOC_64K
  184462. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  184463. * to be able to store the uncompressed data. Actually, the threshold
  184464. * is probably around 32K, but it isn't as definite as 64K is.
  184465. */
  184466. if (length > (png_uint_32)65535L)
  184467. {
  184468. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  184469. png_push_crc_skip(png_ptr, length);
  184470. return;
  184471. }
  184472. #endif
  184473. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184474. (png_uint_32)(length+1));
  184475. png_ptr->current_text[length] = '\0';
  184476. png_ptr->current_text_ptr = png_ptr->current_text;
  184477. png_ptr->current_text_size = (png_size_t)length;
  184478. png_ptr->current_text_left = (png_size_t)length;
  184479. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  184480. }
  184481. void /* PRIVATE */
  184482. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  184483. {
  184484. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184485. {
  184486. png_size_t text_size;
  184487. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  184488. text_size = png_ptr->buffer_size;
  184489. else
  184490. text_size = png_ptr->current_text_left;
  184491. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184492. png_ptr->current_text_left -= text_size;
  184493. png_ptr->current_text_ptr += text_size;
  184494. }
  184495. if (!(png_ptr->current_text_left))
  184496. {
  184497. png_textp text_ptr;
  184498. png_charp text;
  184499. png_charp key;
  184500. int ret;
  184501. png_size_t text_size, key_size;
  184502. if (png_ptr->buffer_size < 4)
  184503. {
  184504. png_push_save_buffer(png_ptr);
  184505. return;
  184506. }
  184507. png_push_crc_finish(png_ptr);
  184508. key = png_ptr->current_text;
  184509. for (text = key; *text; text++)
  184510. /* empty loop */ ;
  184511. /* zTXt can't have zero text */
  184512. if (text >= key + png_ptr->current_text_size)
  184513. {
  184514. png_ptr->current_text = NULL;
  184515. png_free(png_ptr, key);
  184516. return;
  184517. }
  184518. text++;
  184519. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  184520. {
  184521. png_ptr->current_text = NULL;
  184522. png_free(png_ptr, key);
  184523. return;
  184524. }
  184525. text++;
  184526. png_ptr->zstream.next_in = (png_bytep )text;
  184527. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  184528. (text - key));
  184529. png_ptr->zstream.next_out = png_ptr->zbuf;
  184530. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  184531. key_size = text - key;
  184532. text_size = 0;
  184533. text = NULL;
  184534. ret = Z_STREAM_END;
  184535. while (png_ptr->zstream.avail_in)
  184536. {
  184537. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184538. if (ret != Z_OK && ret != Z_STREAM_END)
  184539. {
  184540. inflateReset(&png_ptr->zstream);
  184541. png_ptr->zstream.avail_in = 0;
  184542. png_ptr->current_text = NULL;
  184543. png_free(png_ptr, key);
  184544. png_free(png_ptr, text);
  184545. return;
  184546. }
  184547. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  184548. {
  184549. if (text == NULL)
  184550. {
  184551. text = (png_charp)png_malloc(png_ptr,
  184552. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  184553. + key_size + 1));
  184554. png_memcpy(text + key_size, png_ptr->zbuf,
  184555. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  184556. png_memcpy(text, key, key_size);
  184557. text_size = key_size + png_ptr->zbuf_size -
  184558. png_ptr->zstream.avail_out;
  184559. *(text + text_size) = '\0';
  184560. }
  184561. else
  184562. {
  184563. png_charp tmp;
  184564. tmp = text;
  184565. text = (png_charp)png_malloc(png_ptr, text_size +
  184566. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  184567. + 1));
  184568. png_memcpy(text, tmp, text_size);
  184569. png_free(png_ptr, tmp);
  184570. png_memcpy(text + text_size, png_ptr->zbuf,
  184571. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  184572. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  184573. *(text + text_size) = '\0';
  184574. }
  184575. if (ret != Z_STREAM_END)
  184576. {
  184577. png_ptr->zstream.next_out = png_ptr->zbuf;
  184578. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  184579. }
  184580. }
  184581. else
  184582. {
  184583. break;
  184584. }
  184585. if (ret == Z_STREAM_END)
  184586. break;
  184587. }
  184588. inflateReset(&png_ptr->zstream);
  184589. png_ptr->zstream.avail_in = 0;
  184590. if (ret != Z_STREAM_END)
  184591. {
  184592. png_ptr->current_text = NULL;
  184593. png_free(png_ptr, key);
  184594. png_free(png_ptr, text);
  184595. return;
  184596. }
  184597. png_ptr->current_text = NULL;
  184598. png_free(png_ptr, key);
  184599. key = text;
  184600. text += key_size;
  184601. text_ptr = (png_textp)png_malloc(png_ptr,
  184602. (png_uint_32)png_sizeof(png_text));
  184603. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  184604. text_ptr->key = key;
  184605. #ifdef PNG_iTXt_SUPPORTED
  184606. text_ptr->lang = NULL;
  184607. text_ptr->lang_key = NULL;
  184608. #endif
  184609. text_ptr->text = text;
  184610. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  184611. png_free(png_ptr, key);
  184612. png_free(png_ptr, text_ptr);
  184613. if (ret)
  184614. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  184615. }
  184616. }
  184617. #endif
  184618. #if defined(PNG_READ_iTXt_SUPPORTED)
  184619. void /* PRIVATE */
  184620. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184621. length)
  184622. {
  184623. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184624. {
  184625. png_error(png_ptr, "Out of place iTXt");
  184626. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184627. }
  184628. #ifdef PNG_MAX_MALLOC_64K
  184629. png_ptr->skip_length = 0; /* This may not be necessary */
  184630. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  184631. {
  184632. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  184633. png_ptr->skip_length = length - (png_uint_32)65535L;
  184634. length = (png_uint_32)65535L;
  184635. }
  184636. #endif
  184637. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184638. (png_uint_32)(length+1));
  184639. png_ptr->current_text[length] = '\0';
  184640. png_ptr->current_text_ptr = png_ptr->current_text;
  184641. png_ptr->current_text_size = (png_size_t)length;
  184642. png_ptr->current_text_left = (png_size_t)length;
  184643. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  184644. }
  184645. void /* PRIVATE */
  184646. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  184647. {
  184648. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184649. {
  184650. png_size_t text_size;
  184651. if (png_ptr->buffer_size < png_ptr->current_text_left)
  184652. text_size = png_ptr->buffer_size;
  184653. else
  184654. text_size = png_ptr->current_text_left;
  184655. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184656. png_ptr->current_text_left -= text_size;
  184657. png_ptr->current_text_ptr += text_size;
  184658. }
  184659. if (!(png_ptr->current_text_left))
  184660. {
  184661. png_textp text_ptr;
  184662. png_charp key;
  184663. int comp_flag;
  184664. png_charp lang;
  184665. png_charp lang_key;
  184666. png_charp text;
  184667. int ret;
  184668. if (png_ptr->buffer_size < 4)
  184669. {
  184670. png_push_save_buffer(png_ptr);
  184671. return;
  184672. }
  184673. png_push_crc_finish(png_ptr);
  184674. #if defined(PNG_MAX_MALLOC_64K)
  184675. if (png_ptr->skip_length)
  184676. return;
  184677. #endif
  184678. key = png_ptr->current_text;
  184679. for (lang = key; *lang; lang++)
  184680. /* empty loop */ ;
  184681. if (lang < key + png_ptr->current_text_size - 3)
  184682. lang++;
  184683. comp_flag = *lang++;
  184684. lang++; /* skip comp_type, always zero */
  184685. for (lang_key = lang; *lang_key; lang_key++)
  184686. /* empty loop */ ;
  184687. lang_key++; /* skip NUL separator */
  184688. text=lang_key;
  184689. if (lang_key < key + png_ptr->current_text_size - 1)
  184690. {
  184691. for (; *text; text++)
  184692. /* empty loop */ ;
  184693. }
  184694. if (text < key + png_ptr->current_text_size)
  184695. text++;
  184696. text_ptr = (png_textp)png_malloc(png_ptr,
  184697. (png_uint_32)png_sizeof(png_text));
  184698. text_ptr->compression = comp_flag + 2;
  184699. text_ptr->key = key;
  184700. text_ptr->lang = lang;
  184701. text_ptr->lang_key = lang_key;
  184702. text_ptr->text = text;
  184703. text_ptr->text_length = 0;
  184704. text_ptr->itxt_length = png_strlen(text);
  184705. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  184706. png_ptr->current_text = NULL;
  184707. png_free(png_ptr, text_ptr);
  184708. if (ret)
  184709. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  184710. }
  184711. }
  184712. #endif
  184713. /* This function is called when we haven't found a handler for this
  184714. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  184715. * name or a critical chunk), the chunk is (currently) silently ignored.
  184716. */
  184717. void /* PRIVATE */
  184718. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184719. length)
  184720. {
  184721. png_uint_32 skip=0;
  184722. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  184723. if (!(png_ptr->chunk_name[0] & 0x20))
  184724. {
  184725. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  184726. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  184727. PNG_HANDLE_CHUNK_ALWAYS
  184728. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  184729. && png_ptr->read_user_chunk_fn == NULL
  184730. #endif
  184731. )
  184732. #endif
  184733. png_chunk_error(png_ptr, "unknown critical chunk");
  184734. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184735. }
  184736. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  184737. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  184738. {
  184739. #ifdef PNG_MAX_MALLOC_64K
  184740. if (length > (png_uint_32)65535L)
  184741. {
  184742. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  184743. skip = length - (png_uint_32)65535L;
  184744. length = (png_uint_32)65535L;
  184745. }
  184746. #endif
  184747. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  184748. (png_charp)png_ptr->chunk_name, 5);
  184749. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  184750. png_ptr->unknown_chunk.size = (png_size_t)length;
  184751. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  184752. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  184753. if(png_ptr->read_user_chunk_fn != NULL)
  184754. {
  184755. /* callback to user unknown chunk handler */
  184756. int ret;
  184757. ret = (*(png_ptr->read_user_chunk_fn))
  184758. (png_ptr, &png_ptr->unknown_chunk);
  184759. if (ret < 0)
  184760. png_chunk_error(png_ptr, "error in user chunk");
  184761. if (ret == 0)
  184762. {
  184763. if (!(png_ptr->chunk_name[0] & 0x20))
  184764. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  184765. PNG_HANDLE_CHUNK_ALWAYS)
  184766. png_chunk_error(png_ptr, "unknown critical chunk");
  184767. png_set_unknown_chunks(png_ptr, info_ptr,
  184768. &png_ptr->unknown_chunk, 1);
  184769. }
  184770. }
  184771. #else
  184772. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  184773. #endif
  184774. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184775. png_ptr->unknown_chunk.data = NULL;
  184776. }
  184777. else
  184778. #endif
  184779. skip=length;
  184780. png_push_crc_skip(png_ptr, skip);
  184781. }
  184782. void /* PRIVATE */
  184783. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  184784. {
  184785. if (png_ptr->info_fn != NULL)
  184786. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  184787. }
  184788. void /* PRIVATE */
  184789. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  184790. {
  184791. if (png_ptr->end_fn != NULL)
  184792. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  184793. }
  184794. void /* PRIVATE */
  184795. png_push_have_row(png_structp png_ptr, png_bytep row)
  184796. {
  184797. if (png_ptr->row_fn != NULL)
  184798. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  184799. (int)png_ptr->pass);
  184800. }
  184801. void PNGAPI
  184802. png_progressive_combine_row (png_structp png_ptr,
  184803. png_bytep old_row, png_bytep new_row)
  184804. {
  184805. #ifdef PNG_USE_LOCAL_ARRAYS
  184806. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  184807. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184808. #endif
  184809. if(png_ptr == NULL) return;
  184810. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  184811. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  184812. }
  184813. void PNGAPI
  184814. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  184815. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  184816. png_progressive_end_ptr end_fn)
  184817. {
  184818. if(png_ptr == NULL) return;
  184819. png_ptr->info_fn = info_fn;
  184820. png_ptr->row_fn = row_fn;
  184821. png_ptr->end_fn = end_fn;
  184822. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  184823. }
  184824. png_voidp PNGAPI
  184825. png_get_progressive_ptr(png_structp png_ptr)
  184826. {
  184827. if(png_ptr == NULL) return (NULL);
  184828. return png_ptr->io_ptr;
  184829. }
  184830. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184831. /********* End of inlined file: pngpread.c *********/
  184832. /********* Start of inlined file: pngrio.c *********/
  184833. /* pngrio.c - functions for data input
  184834. *
  184835. * Last changed in libpng 1.2.13 November 13, 2006
  184836. * For conditions of distribution and use, see copyright notice in png.h
  184837. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  184838. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184839. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184840. *
  184841. * This file provides a location for all input. Users who need
  184842. * special handling are expected to write a function that has the same
  184843. * arguments as this and performs a similar function, but that possibly
  184844. * has a different input method. Note that you shouldn't change this
  184845. * function, but rather write a replacement function and then make
  184846. * libpng use it at run time with png_set_read_fn(...).
  184847. */
  184848. #define PNG_INTERNAL
  184849. #if defined(PNG_READ_SUPPORTED)
  184850. /* Read the data from whatever input you are using. The default routine
  184851. reads from a file pointer. Note that this routine sometimes gets called
  184852. with very small lengths, so you should implement some kind of simple
  184853. buffering if you are using unbuffered reads. This should never be asked
  184854. to read more then 64K on a 16 bit machine. */
  184855. void /* PRIVATE */
  184856. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  184857. {
  184858. png_debug1(4,"reading %d bytes\n", (int)length);
  184859. if (png_ptr->read_data_fn != NULL)
  184860. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  184861. else
  184862. png_error(png_ptr, "Call to NULL read function");
  184863. }
  184864. #if !defined(PNG_NO_STDIO)
  184865. /* This is the function that does the actual reading of data. If you are
  184866. not reading from a standard C stream, you should create a replacement
  184867. read_data function and use it at run time with png_set_read_fn(), rather
  184868. than changing the library. */
  184869. #ifndef USE_FAR_KEYWORD
  184870. void PNGAPI
  184871. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  184872. {
  184873. png_size_t check;
  184874. if(png_ptr == NULL) return;
  184875. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  184876. * instead of an int, which is what fread() actually returns.
  184877. */
  184878. #if defined(_WIN32_WCE)
  184879. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  184880. check = 0;
  184881. #else
  184882. check = (png_size_t)fread(data, (png_size_t)1, length,
  184883. (png_FILE_p)png_ptr->io_ptr);
  184884. #endif
  184885. if (check != length)
  184886. png_error(png_ptr, "Read Error");
  184887. }
  184888. #else
  184889. /* this is the model-independent version. Since the standard I/O library
  184890. can't handle far buffers in the medium and small models, we have to copy
  184891. the data.
  184892. */
  184893. #define NEAR_BUF_SIZE 1024
  184894. #define MIN(a,b) (a <= b ? a : b)
  184895. static void PNGAPI
  184896. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  184897. {
  184898. int check;
  184899. png_byte *n_data;
  184900. png_FILE_p io_ptr;
  184901. if(png_ptr == NULL) return;
  184902. /* Check if data really is near. If so, use usual code. */
  184903. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  184904. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  184905. if ((png_bytep)n_data == data)
  184906. {
  184907. #if defined(_WIN32_WCE)
  184908. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  184909. check = 0;
  184910. #else
  184911. check = fread(n_data, 1, length, io_ptr);
  184912. #endif
  184913. }
  184914. else
  184915. {
  184916. png_byte buf[NEAR_BUF_SIZE];
  184917. png_size_t read, remaining, err;
  184918. check = 0;
  184919. remaining = length;
  184920. do
  184921. {
  184922. read = MIN(NEAR_BUF_SIZE, remaining);
  184923. #if defined(_WIN32_WCE)
  184924. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  184925. err = 0;
  184926. #else
  184927. err = fread(buf, (png_size_t)1, read, io_ptr);
  184928. #endif
  184929. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  184930. if(err != read)
  184931. break;
  184932. else
  184933. check += err;
  184934. data += read;
  184935. remaining -= read;
  184936. }
  184937. while (remaining != 0);
  184938. }
  184939. if ((png_uint_32)check != (png_uint_32)length)
  184940. png_error(png_ptr, "read Error");
  184941. }
  184942. #endif
  184943. #endif
  184944. /* This function allows the application to supply a new input function
  184945. for libpng if standard C streams aren't being used.
  184946. This function takes as its arguments:
  184947. png_ptr - pointer to a png input data structure
  184948. io_ptr - pointer to user supplied structure containing info about
  184949. the input functions. May be NULL.
  184950. read_data_fn - pointer to a new input function that takes as its
  184951. arguments a pointer to a png_struct, a pointer to
  184952. a location where input data can be stored, and a 32-bit
  184953. unsigned int that is the number of bytes to be read.
  184954. To exit and output any fatal error messages the new write
  184955. function should call png_error(png_ptr, "Error msg"). */
  184956. void PNGAPI
  184957. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  184958. png_rw_ptr read_data_fn)
  184959. {
  184960. if(png_ptr == NULL) return;
  184961. png_ptr->io_ptr = io_ptr;
  184962. #if !defined(PNG_NO_STDIO)
  184963. if (read_data_fn != NULL)
  184964. png_ptr->read_data_fn = read_data_fn;
  184965. else
  184966. png_ptr->read_data_fn = png_default_read_data;
  184967. #else
  184968. png_ptr->read_data_fn = read_data_fn;
  184969. #endif
  184970. /* It is an error to write to a read device */
  184971. if (png_ptr->write_data_fn != NULL)
  184972. {
  184973. png_ptr->write_data_fn = NULL;
  184974. png_warning(png_ptr,
  184975. "It's an error to set both read_data_fn and write_data_fn in the ");
  184976. png_warning(png_ptr,
  184977. "same structure. Resetting write_data_fn to NULL.");
  184978. }
  184979. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184980. png_ptr->output_flush_fn = NULL;
  184981. #endif
  184982. }
  184983. #endif /* PNG_READ_SUPPORTED */
  184984. /********* End of inlined file: pngrio.c *********/
  184985. /********* Start of inlined file: pngrtran.c *********/
  184986. /* pngrtran.c - transforms the data in a row for PNG readers
  184987. *
  184988. * Last changed in libpng 1.2.21 [October 4, 2007]
  184989. * For conditions of distribution and use, see copyright notice in png.h
  184990. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184991. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184992. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184993. *
  184994. * This file contains functions optionally called by an application
  184995. * in order to tell libpng how to handle data when reading a PNG.
  184996. * Transformations that are used in both reading and writing are
  184997. * in pngtrans.c.
  184998. */
  184999. #define PNG_INTERNAL
  185000. #if defined(PNG_READ_SUPPORTED)
  185001. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  185002. void PNGAPI
  185003. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  185004. {
  185005. png_debug(1, "in png_set_crc_action\n");
  185006. /* Tell libpng how we react to CRC errors in critical chunks */
  185007. if(png_ptr == NULL) return;
  185008. switch (crit_action)
  185009. {
  185010. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185011. break;
  185012. case PNG_CRC_WARN_USE: /* warn/use data */
  185013. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185014. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  185015. break;
  185016. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185017. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185018. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  185019. PNG_FLAG_CRC_CRITICAL_IGNORE;
  185020. break;
  185021. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  185022. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  185023. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185024. case PNG_CRC_DEFAULT:
  185025. default:
  185026. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185027. break;
  185028. }
  185029. switch (ancil_action)
  185030. {
  185031. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185032. break;
  185033. case PNG_CRC_WARN_USE: /* warn/use data */
  185034. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185035. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  185036. break;
  185037. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185038. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185039. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  185040. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185041. break;
  185042. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185043. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185044. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185045. break;
  185046. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  185047. case PNG_CRC_DEFAULT:
  185048. default:
  185049. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185050. break;
  185051. }
  185052. }
  185053. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  185054. defined(PNG_FLOATING_POINT_SUPPORTED)
  185055. /* handle alpha and tRNS via a background color */
  185056. void PNGAPI
  185057. png_set_background(png_structp png_ptr,
  185058. png_color_16p background_color, int background_gamma_code,
  185059. int need_expand, double background_gamma)
  185060. {
  185061. png_debug(1, "in png_set_background\n");
  185062. if(png_ptr == NULL) return;
  185063. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  185064. {
  185065. png_warning(png_ptr, "Application must supply a known background gamma");
  185066. return;
  185067. }
  185068. png_ptr->transformations |= PNG_BACKGROUND;
  185069. png_memcpy(&(png_ptr->background), background_color,
  185070. png_sizeof(png_color_16));
  185071. png_ptr->background_gamma = (float)background_gamma;
  185072. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  185073. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  185074. }
  185075. #endif
  185076. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185077. /* strip 16 bit depth files to 8 bit depth */
  185078. void PNGAPI
  185079. png_set_strip_16(png_structp png_ptr)
  185080. {
  185081. png_debug(1, "in png_set_strip_16\n");
  185082. if(png_ptr == NULL) return;
  185083. png_ptr->transformations |= PNG_16_TO_8;
  185084. }
  185085. #endif
  185086. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185087. void PNGAPI
  185088. png_set_strip_alpha(png_structp png_ptr)
  185089. {
  185090. png_debug(1, "in png_set_strip_alpha\n");
  185091. if(png_ptr == NULL) return;
  185092. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  185093. }
  185094. #endif
  185095. #if defined(PNG_READ_DITHER_SUPPORTED)
  185096. /* Dither file to 8 bit. Supply a palette, the current number
  185097. * of elements in the palette, the maximum number of elements
  185098. * allowed, and a histogram if possible. If the current number
  185099. * of colors is greater then the maximum number, the palette will be
  185100. * modified to fit in the maximum number. "full_dither" indicates
  185101. * whether we need a dithering cube set up for RGB images, or if we
  185102. * simply are reducing the number of colors in a paletted image.
  185103. */
  185104. typedef struct png_dsort_struct
  185105. {
  185106. struct png_dsort_struct FAR * next;
  185107. png_byte left;
  185108. png_byte right;
  185109. } png_dsort;
  185110. typedef png_dsort FAR * png_dsortp;
  185111. typedef png_dsort FAR * FAR * png_dsortpp;
  185112. void PNGAPI
  185113. png_set_dither(png_structp png_ptr, png_colorp palette,
  185114. int num_palette, int maximum_colors, png_uint_16p histogram,
  185115. int full_dither)
  185116. {
  185117. png_debug(1, "in png_set_dither\n");
  185118. if(png_ptr == NULL) return;
  185119. png_ptr->transformations |= PNG_DITHER;
  185120. if (!full_dither)
  185121. {
  185122. int i;
  185123. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  185124. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185125. for (i = 0; i < num_palette; i++)
  185126. png_ptr->dither_index[i] = (png_byte)i;
  185127. }
  185128. if (num_palette > maximum_colors)
  185129. {
  185130. if (histogram != NULL)
  185131. {
  185132. /* This is easy enough, just throw out the least used colors.
  185133. Perhaps not the best solution, but good enough. */
  185134. int i;
  185135. /* initialize an array to sort colors */
  185136. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  185137. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185138. /* initialize the dither_sort array */
  185139. for (i = 0; i < num_palette; i++)
  185140. png_ptr->dither_sort[i] = (png_byte)i;
  185141. /* Find the least used palette entries by starting a
  185142. bubble sort, and running it until we have sorted
  185143. out enough colors. Note that we don't care about
  185144. sorting all the colors, just finding which are
  185145. least used. */
  185146. for (i = num_palette - 1; i >= maximum_colors; i--)
  185147. {
  185148. int done; /* to stop early if the list is pre-sorted */
  185149. int j;
  185150. done = 1;
  185151. for (j = 0; j < i; j++)
  185152. {
  185153. if (histogram[png_ptr->dither_sort[j]]
  185154. < histogram[png_ptr->dither_sort[j + 1]])
  185155. {
  185156. png_byte t;
  185157. t = png_ptr->dither_sort[j];
  185158. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  185159. png_ptr->dither_sort[j + 1] = t;
  185160. done = 0;
  185161. }
  185162. }
  185163. if (done)
  185164. break;
  185165. }
  185166. /* swap the palette around, and set up a table, if necessary */
  185167. if (full_dither)
  185168. {
  185169. int j = num_palette;
  185170. /* put all the useful colors within the max, but don't
  185171. move the others */
  185172. for (i = 0; i < maximum_colors; i++)
  185173. {
  185174. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185175. {
  185176. do
  185177. j--;
  185178. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185179. palette[i] = palette[j];
  185180. }
  185181. }
  185182. }
  185183. else
  185184. {
  185185. int j = num_palette;
  185186. /* move all the used colors inside the max limit, and
  185187. develop a translation table */
  185188. for (i = 0; i < maximum_colors; i++)
  185189. {
  185190. /* only move the colors we need to */
  185191. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185192. {
  185193. png_color tmp_color;
  185194. do
  185195. j--;
  185196. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185197. tmp_color = palette[j];
  185198. palette[j] = palette[i];
  185199. palette[i] = tmp_color;
  185200. /* indicate where the color went */
  185201. png_ptr->dither_index[j] = (png_byte)i;
  185202. png_ptr->dither_index[i] = (png_byte)j;
  185203. }
  185204. }
  185205. /* find closest color for those colors we are not using */
  185206. for (i = 0; i < num_palette; i++)
  185207. {
  185208. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  185209. {
  185210. int min_d, k, min_k, d_index;
  185211. /* find the closest color to one we threw out */
  185212. d_index = png_ptr->dither_index[i];
  185213. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  185214. for (k = 1, min_k = 0; k < maximum_colors; k++)
  185215. {
  185216. int d;
  185217. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  185218. if (d < min_d)
  185219. {
  185220. min_d = d;
  185221. min_k = k;
  185222. }
  185223. }
  185224. /* point to closest color */
  185225. png_ptr->dither_index[i] = (png_byte)min_k;
  185226. }
  185227. }
  185228. }
  185229. png_free(png_ptr, png_ptr->dither_sort);
  185230. png_ptr->dither_sort=NULL;
  185231. }
  185232. else
  185233. {
  185234. /* This is much harder to do simply (and quickly). Perhaps
  185235. we need to go through a median cut routine, but those
  185236. don't always behave themselves with only a few colors
  185237. as input. So we will just find the closest two colors,
  185238. and throw out one of them (chosen somewhat randomly).
  185239. [We don't understand this at all, so if someone wants to
  185240. work on improving it, be our guest - AED, GRP]
  185241. */
  185242. int i;
  185243. int max_d;
  185244. int num_new_palette;
  185245. png_dsortp t;
  185246. png_dsortpp hash;
  185247. t=NULL;
  185248. /* initialize palette index arrays */
  185249. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  185250. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185251. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  185252. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185253. /* initialize the sort array */
  185254. for (i = 0; i < num_palette; i++)
  185255. {
  185256. png_ptr->index_to_palette[i] = (png_byte)i;
  185257. png_ptr->palette_to_index[i] = (png_byte)i;
  185258. }
  185259. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  185260. png_sizeof (png_dsortp)));
  185261. for (i = 0; i < 769; i++)
  185262. hash[i] = NULL;
  185263. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  185264. num_new_palette = num_palette;
  185265. /* initial wild guess at how far apart the farthest pixel
  185266. pair we will be eliminating will be. Larger
  185267. numbers mean more areas will be allocated, Smaller
  185268. numbers run the risk of not saving enough data, and
  185269. having to do this all over again.
  185270. I have not done extensive checking on this number.
  185271. */
  185272. max_d = 96;
  185273. while (num_new_palette > maximum_colors)
  185274. {
  185275. for (i = 0; i < num_new_palette - 1; i++)
  185276. {
  185277. int j;
  185278. for (j = i + 1; j < num_new_palette; j++)
  185279. {
  185280. int d;
  185281. d = PNG_COLOR_DIST(palette[i], palette[j]);
  185282. if (d <= max_d)
  185283. {
  185284. t = (png_dsortp)png_malloc_warn(png_ptr,
  185285. (png_uint_32)(png_sizeof(png_dsort)));
  185286. if (t == NULL)
  185287. break;
  185288. t->next = hash[d];
  185289. t->left = (png_byte)i;
  185290. t->right = (png_byte)j;
  185291. hash[d] = t;
  185292. }
  185293. }
  185294. if (t == NULL)
  185295. break;
  185296. }
  185297. if (t != NULL)
  185298. for (i = 0; i <= max_d; i++)
  185299. {
  185300. if (hash[i] != NULL)
  185301. {
  185302. png_dsortp p;
  185303. for (p = hash[i]; p; p = p->next)
  185304. {
  185305. if ((int)png_ptr->index_to_palette[p->left]
  185306. < num_new_palette &&
  185307. (int)png_ptr->index_to_palette[p->right]
  185308. < num_new_palette)
  185309. {
  185310. int j, next_j;
  185311. if (num_new_palette & 0x01)
  185312. {
  185313. j = p->left;
  185314. next_j = p->right;
  185315. }
  185316. else
  185317. {
  185318. j = p->right;
  185319. next_j = p->left;
  185320. }
  185321. num_new_palette--;
  185322. palette[png_ptr->index_to_palette[j]]
  185323. = palette[num_new_palette];
  185324. if (!full_dither)
  185325. {
  185326. int k;
  185327. for (k = 0; k < num_palette; k++)
  185328. {
  185329. if (png_ptr->dither_index[k] ==
  185330. png_ptr->index_to_palette[j])
  185331. png_ptr->dither_index[k] =
  185332. png_ptr->index_to_palette[next_j];
  185333. if ((int)png_ptr->dither_index[k] ==
  185334. num_new_palette)
  185335. png_ptr->dither_index[k] =
  185336. png_ptr->index_to_palette[j];
  185337. }
  185338. }
  185339. png_ptr->index_to_palette[png_ptr->palette_to_index
  185340. [num_new_palette]] = png_ptr->index_to_palette[j];
  185341. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  185342. = png_ptr->palette_to_index[num_new_palette];
  185343. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  185344. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  185345. }
  185346. if (num_new_palette <= maximum_colors)
  185347. break;
  185348. }
  185349. if (num_new_palette <= maximum_colors)
  185350. break;
  185351. }
  185352. }
  185353. for (i = 0; i < 769; i++)
  185354. {
  185355. if (hash[i] != NULL)
  185356. {
  185357. png_dsortp p = hash[i];
  185358. while (p)
  185359. {
  185360. t = p->next;
  185361. png_free(png_ptr, p);
  185362. p = t;
  185363. }
  185364. }
  185365. hash[i] = 0;
  185366. }
  185367. max_d += 96;
  185368. }
  185369. png_free(png_ptr, hash);
  185370. png_free(png_ptr, png_ptr->palette_to_index);
  185371. png_free(png_ptr, png_ptr->index_to_palette);
  185372. png_ptr->palette_to_index=NULL;
  185373. png_ptr->index_to_palette=NULL;
  185374. }
  185375. num_palette = maximum_colors;
  185376. }
  185377. if (png_ptr->palette == NULL)
  185378. {
  185379. png_ptr->palette = palette;
  185380. }
  185381. png_ptr->num_palette = (png_uint_16)num_palette;
  185382. if (full_dither)
  185383. {
  185384. int i;
  185385. png_bytep distance;
  185386. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  185387. PNG_DITHER_BLUE_BITS;
  185388. int num_red = (1 << PNG_DITHER_RED_BITS);
  185389. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  185390. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  185391. png_size_t num_entries = ((png_size_t)1 << total_bits);
  185392. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  185393. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  185394. png_memset(png_ptr->palette_lookup, 0, num_entries *
  185395. png_sizeof (png_byte));
  185396. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  185397. png_sizeof(png_byte)));
  185398. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  185399. for (i = 0; i < num_palette; i++)
  185400. {
  185401. int ir, ig, ib;
  185402. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  185403. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  185404. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  185405. for (ir = 0; ir < num_red; ir++)
  185406. {
  185407. /* int dr = abs(ir - r); */
  185408. int dr = ((ir > r) ? ir - r : r - ir);
  185409. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  185410. for (ig = 0; ig < num_green; ig++)
  185411. {
  185412. /* int dg = abs(ig - g); */
  185413. int dg = ((ig > g) ? ig - g : g - ig);
  185414. int dt = dr + dg;
  185415. int dm = ((dr > dg) ? dr : dg);
  185416. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  185417. for (ib = 0; ib < num_blue; ib++)
  185418. {
  185419. int d_index = index_g | ib;
  185420. /* int db = abs(ib - b); */
  185421. int db = ((ib > b) ? ib - b : b - ib);
  185422. int dmax = ((dm > db) ? dm : db);
  185423. int d = dmax + dt + db;
  185424. if (d < (int)distance[d_index])
  185425. {
  185426. distance[d_index] = (png_byte)d;
  185427. png_ptr->palette_lookup[d_index] = (png_byte)i;
  185428. }
  185429. }
  185430. }
  185431. }
  185432. }
  185433. png_free(png_ptr, distance);
  185434. }
  185435. }
  185436. #endif
  185437. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185438. /* Transform the image from the file_gamma to the screen_gamma. We
  185439. * only do transformations on images where the file_gamma and screen_gamma
  185440. * are not close reciprocals, otherwise it slows things down slightly, and
  185441. * also needlessly introduces small errors.
  185442. *
  185443. * We will turn off gamma transformation later if no semitransparent entries
  185444. * are present in the tRNS array for palette images. We can't do it here
  185445. * because we don't necessarily have the tRNS chunk yet.
  185446. */
  185447. void PNGAPI
  185448. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  185449. {
  185450. png_debug(1, "in png_set_gamma\n");
  185451. if(png_ptr == NULL) return;
  185452. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  185453. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  185454. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  185455. png_ptr->transformations |= PNG_GAMMA;
  185456. png_ptr->gamma = (float)file_gamma;
  185457. png_ptr->screen_gamma = (float)scrn_gamma;
  185458. }
  185459. #endif
  185460. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185461. /* Expand paletted images to RGB, expand grayscale images of
  185462. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  185463. * to alpha channels.
  185464. */
  185465. void PNGAPI
  185466. png_set_expand(png_structp png_ptr)
  185467. {
  185468. png_debug(1, "in png_set_expand\n");
  185469. if(png_ptr == NULL) return;
  185470. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185471. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185472. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185473. #endif
  185474. }
  185475. /* GRR 19990627: the following three functions currently are identical
  185476. * to png_set_expand(). However, it is entirely reasonable that someone
  185477. * might wish to expand an indexed image to RGB but *not* expand a single,
  185478. * fully transparent palette entry to a full alpha channel--perhaps instead
  185479. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  185480. * the transparent color with a particular RGB value, or drop tRNS entirely.
  185481. * IOW, a future version of the library may make the transformations flag
  185482. * a bit more fine-grained, with separate bits for each of these three
  185483. * functions.
  185484. *
  185485. * More to the point, these functions make it obvious what libpng will be
  185486. * doing, whereas "expand" can (and does) mean any number of things.
  185487. *
  185488. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  185489. * to expand only the sample depth but not to expand the tRNS to alpha.
  185490. */
  185491. /* Expand paletted images to RGB. */
  185492. void PNGAPI
  185493. png_set_palette_to_rgb(png_structp png_ptr)
  185494. {
  185495. png_debug(1, "in png_set_palette_to_rgb\n");
  185496. if(png_ptr == NULL) return;
  185497. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185498. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185499. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  185500. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185501. #endif
  185502. }
  185503. #if !defined(PNG_1_0_X)
  185504. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  185505. void PNGAPI
  185506. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  185507. {
  185508. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  185509. if(png_ptr == NULL) return;
  185510. png_ptr->transformations |= PNG_EXPAND;
  185511. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185512. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185513. #endif
  185514. }
  185515. #endif
  185516. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185517. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  185518. /* Deprecated as of libpng-1.2.9 */
  185519. void PNGAPI
  185520. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  185521. {
  185522. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  185523. if(png_ptr == NULL) return;
  185524. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185525. }
  185526. #endif
  185527. /* Expand tRNS chunks to alpha channels. */
  185528. void PNGAPI
  185529. png_set_tRNS_to_alpha(png_structp png_ptr)
  185530. {
  185531. png_debug(1, "in png_set_tRNS_to_alpha\n");
  185532. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185533. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185534. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185535. #endif
  185536. }
  185537. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  185538. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185539. void PNGAPI
  185540. png_set_gray_to_rgb(png_structp png_ptr)
  185541. {
  185542. png_debug(1, "in png_set_gray_to_rgb\n");
  185543. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  185544. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185545. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185546. #endif
  185547. }
  185548. #endif
  185549. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185550. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  185551. /* Convert a RGB image to a grayscale of the same width. This allows us,
  185552. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  185553. */
  185554. void PNGAPI
  185555. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  185556. double green)
  185557. {
  185558. int red_fixed = (int)((float)red*100000.0 + 0.5);
  185559. int green_fixed = (int)((float)green*100000.0 + 0.5);
  185560. if(png_ptr == NULL) return;
  185561. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  185562. }
  185563. #endif
  185564. void PNGAPI
  185565. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  185566. png_fixed_point red, png_fixed_point green)
  185567. {
  185568. png_debug(1, "in png_set_rgb_to_gray\n");
  185569. if(png_ptr == NULL) return;
  185570. switch(error_action)
  185571. {
  185572. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  185573. break;
  185574. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  185575. break;
  185576. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  185577. }
  185578. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185579. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185580. png_ptr->transformations |= PNG_EXPAND;
  185581. #else
  185582. {
  185583. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  185584. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  185585. }
  185586. #endif
  185587. {
  185588. png_uint_16 red_int, green_int;
  185589. if(red < 0 || green < 0)
  185590. {
  185591. red_int = 6968; /* .212671 * 32768 + .5 */
  185592. green_int = 23434; /* .715160 * 32768 + .5 */
  185593. }
  185594. else if(red + green < 100000L)
  185595. {
  185596. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  185597. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  185598. }
  185599. else
  185600. {
  185601. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  185602. red_int = 6968;
  185603. green_int = 23434;
  185604. }
  185605. png_ptr->rgb_to_gray_red_coeff = red_int;
  185606. png_ptr->rgb_to_gray_green_coeff = green_int;
  185607. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  185608. }
  185609. }
  185610. #endif
  185611. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  185612. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  185613. defined(PNG_LEGACY_SUPPORTED)
  185614. void PNGAPI
  185615. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  185616. read_user_transform_fn)
  185617. {
  185618. png_debug(1, "in png_set_read_user_transform_fn\n");
  185619. if(png_ptr == NULL) return;
  185620. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185621. png_ptr->transformations |= PNG_USER_TRANSFORM;
  185622. png_ptr->read_user_transform_fn = read_user_transform_fn;
  185623. #endif
  185624. #ifdef PNG_LEGACY_SUPPORTED
  185625. if(read_user_transform_fn)
  185626. png_warning(png_ptr,
  185627. "This version of libpng does not support user transforms");
  185628. #endif
  185629. }
  185630. #endif
  185631. /* Initialize everything needed for the read. This includes modifying
  185632. * the palette.
  185633. */
  185634. void /* PRIVATE */
  185635. png_init_read_transformations(png_structp png_ptr)
  185636. {
  185637. png_debug(1, "in png_init_read_transformations\n");
  185638. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185639. if(png_ptr != NULL)
  185640. #endif
  185641. {
  185642. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  185643. || defined(PNG_READ_GAMMA_SUPPORTED)
  185644. int color_type = png_ptr->color_type;
  185645. #endif
  185646. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  185647. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185648. /* Detect gray background and attempt to enable optimization
  185649. * for gray --> RGB case */
  185650. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  185651. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  185652. * background color might actually be gray yet not be flagged as such.
  185653. * This is not a problem for the current code, which uses
  185654. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  185655. * png_do_gray_to_rgb() transformation.
  185656. */
  185657. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  185658. !(color_type & PNG_COLOR_MASK_COLOR))
  185659. {
  185660. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  185661. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  185662. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  185663. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  185664. png_ptr->background.red == png_ptr->background.green &&
  185665. png_ptr->background.red == png_ptr->background.blue)
  185666. {
  185667. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  185668. png_ptr->background.gray = png_ptr->background.red;
  185669. }
  185670. #endif
  185671. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  185672. (png_ptr->transformations & PNG_EXPAND))
  185673. {
  185674. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  185675. {
  185676. /* expand background and tRNS chunks */
  185677. switch (png_ptr->bit_depth)
  185678. {
  185679. case 1:
  185680. png_ptr->background.gray *= (png_uint_16)0xff;
  185681. png_ptr->background.red = png_ptr->background.green
  185682. = png_ptr->background.blue = png_ptr->background.gray;
  185683. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  185684. {
  185685. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  185686. png_ptr->trans_values.red = png_ptr->trans_values.green
  185687. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  185688. }
  185689. break;
  185690. case 2:
  185691. png_ptr->background.gray *= (png_uint_16)0x55;
  185692. png_ptr->background.red = png_ptr->background.green
  185693. = png_ptr->background.blue = png_ptr->background.gray;
  185694. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  185695. {
  185696. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  185697. png_ptr->trans_values.red = png_ptr->trans_values.green
  185698. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  185699. }
  185700. break;
  185701. case 4:
  185702. png_ptr->background.gray *= (png_uint_16)0x11;
  185703. png_ptr->background.red = png_ptr->background.green
  185704. = png_ptr->background.blue = png_ptr->background.gray;
  185705. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  185706. {
  185707. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  185708. png_ptr->trans_values.red = png_ptr->trans_values.green
  185709. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  185710. }
  185711. break;
  185712. case 8:
  185713. case 16:
  185714. png_ptr->background.red = png_ptr->background.green
  185715. = png_ptr->background.blue = png_ptr->background.gray;
  185716. break;
  185717. }
  185718. }
  185719. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  185720. {
  185721. png_ptr->background.red =
  185722. png_ptr->palette[png_ptr->background.index].red;
  185723. png_ptr->background.green =
  185724. png_ptr->palette[png_ptr->background.index].green;
  185725. png_ptr->background.blue =
  185726. png_ptr->palette[png_ptr->background.index].blue;
  185727. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185728. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  185729. {
  185730. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185731. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  185732. #endif
  185733. {
  185734. /* invert the alpha channel (in tRNS) unless the pixels are
  185735. going to be expanded, in which case leave it for later */
  185736. int i,istop;
  185737. istop=(int)png_ptr->num_trans;
  185738. for (i=0; i<istop; i++)
  185739. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  185740. }
  185741. }
  185742. #endif
  185743. }
  185744. }
  185745. #endif
  185746. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  185747. png_ptr->background_1 = png_ptr->background;
  185748. #endif
  185749. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185750. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  185751. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  185752. < PNG_GAMMA_THRESHOLD))
  185753. {
  185754. int i,k;
  185755. k=0;
  185756. for (i=0; i<png_ptr->num_trans; i++)
  185757. {
  185758. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  185759. k=1; /* partial transparency is present */
  185760. }
  185761. if (k == 0)
  185762. png_ptr->transformations &= (~PNG_GAMMA);
  185763. }
  185764. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  185765. png_ptr->gamma != 0.0)
  185766. {
  185767. png_build_gamma_table(png_ptr);
  185768. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185769. if (png_ptr->transformations & PNG_BACKGROUND)
  185770. {
  185771. if (color_type == PNG_COLOR_TYPE_PALETTE)
  185772. {
  185773. /* could skip if no transparency and
  185774. */
  185775. png_color back, back_1;
  185776. png_colorp palette = png_ptr->palette;
  185777. int num_palette = png_ptr->num_palette;
  185778. int i;
  185779. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  185780. {
  185781. back.red = png_ptr->gamma_table[png_ptr->background.red];
  185782. back.green = png_ptr->gamma_table[png_ptr->background.green];
  185783. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  185784. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  185785. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  185786. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  185787. }
  185788. else
  185789. {
  185790. double g, gs;
  185791. switch (png_ptr->background_gamma_type)
  185792. {
  185793. case PNG_BACKGROUND_GAMMA_SCREEN:
  185794. g = (png_ptr->screen_gamma);
  185795. gs = 1.0;
  185796. break;
  185797. case PNG_BACKGROUND_GAMMA_FILE:
  185798. g = 1.0 / (png_ptr->gamma);
  185799. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  185800. break;
  185801. case PNG_BACKGROUND_GAMMA_UNIQUE:
  185802. g = 1.0 / (png_ptr->background_gamma);
  185803. gs = 1.0 / (png_ptr->background_gamma *
  185804. png_ptr->screen_gamma);
  185805. break;
  185806. default:
  185807. g = 1.0; /* back_1 */
  185808. gs = 1.0; /* back */
  185809. }
  185810. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  185811. {
  185812. back.red = (png_byte)png_ptr->background.red;
  185813. back.green = (png_byte)png_ptr->background.green;
  185814. back.blue = (png_byte)png_ptr->background.blue;
  185815. }
  185816. else
  185817. {
  185818. back.red = (png_byte)(pow(
  185819. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  185820. back.green = (png_byte)(pow(
  185821. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  185822. back.blue = (png_byte)(pow(
  185823. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  185824. }
  185825. back_1.red = (png_byte)(pow(
  185826. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  185827. back_1.green = (png_byte)(pow(
  185828. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  185829. back_1.blue = (png_byte)(pow(
  185830. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  185831. }
  185832. for (i = 0; i < num_palette; i++)
  185833. {
  185834. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  185835. {
  185836. if (png_ptr->trans[i] == 0)
  185837. {
  185838. palette[i] = back;
  185839. }
  185840. else /* if (png_ptr->trans[i] != 0xff) */
  185841. {
  185842. png_byte v, w;
  185843. v = png_ptr->gamma_to_1[palette[i].red];
  185844. png_composite(w, v, png_ptr->trans[i], back_1.red);
  185845. palette[i].red = png_ptr->gamma_from_1[w];
  185846. v = png_ptr->gamma_to_1[palette[i].green];
  185847. png_composite(w, v, png_ptr->trans[i], back_1.green);
  185848. palette[i].green = png_ptr->gamma_from_1[w];
  185849. v = png_ptr->gamma_to_1[palette[i].blue];
  185850. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  185851. palette[i].blue = png_ptr->gamma_from_1[w];
  185852. }
  185853. }
  185854. else
  185855. {
  185856. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185857. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185858. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185859. }
  185860. }
  185861. }
  185862. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  185863. else
  185864. /* color_type != PNG_COLOR_TYPE_PALETTE */
  185865. {
  185866. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  185867. double g = 1.0;
  185868. double gs = 1.0;
  185869. switch (png_ptr->background_gamma_type)
  185870. {
  185871. case PNG_BACKGROUND_GAMMA_SCREEN:
  185872. g = (png_ptr->screen_gamma);
  185873. gs = 1.0;
  185874. break;
  185875. case PNG_BACKGROUND_GAMMA_FILE:
  185876. g = 1.0 / (png_ptr->gamma);
  185877. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  185878. break;
  185879. case PNG_BACKGROUND_GAMMA_UNIQUE:
  185880. g = 1.0 / (png_ptr->background_gamma);
  185881. gs = 1.0 / (png_ptr->background_gamma *
  185882. png_ptr->screen_gamma);
  185883. break;
  185884. }
  185885. png_ptr->background_1.gray = (png_uint_16)(pow(
  185886. (double)png_ptr->background.gray / m, g) * m + .5);
  185887. png_ptr->background.gray = (png_uint_16)(pow(
  185888. (double)png_ptr->background.gray / m, gs) * m + .5);
  185889. if ((png_ptr->background.red != png_ptr->background.green) ||
  185890. (png_ptr->background.red != png_ptr->background.blue) ||
  185891. (png_ptr->background.red != png_ptr->background.gray))
  185892. {
  185893. /* RGB or RGBA with color background */
  185894. png_ptr->background_1.red = (png_uint_16)(pow(
  185895. (double)png_ptr->background.red / m, g) * m + .5);
  185896. png_ptr->background_1.green = (png_uint_16)(pow(
  185897. (double)png_ptr->background.green / m, g) * m + .5);
  185898. png_ptr->background_1.blue = (png_uint_16)(pow(
  185899. (double)png_ptr->background.blue / m, g) * m + .5);
  185900. png_ptr->background.red = (png_uint_16)(pow(
  185901. (double)png_ptr->background.red / m, gs) * m + .5);
  185902. png_ptr->background.green = (png_uint_16)(pow(
  185903. (double)png_ptr->background.green / m, gs) * m + .5);
  185904. png_ptr->background.blue = (png_uint_16)(pow(
  185905. (double)png_ptr->background.blue / m, gs) * m + .5);
  185906. }
  185907. else
  185908. {
  185909. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  185910. png_ptr->background_1.red = png_ptr->background_1.green
  185911. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  185912. png_ptr->background.red = png_ptr->background.green
  185913. = png_ptr->background.blue = png_ptr->background.gray;
  185914. }
  185915. }
  185916. }
  185917. else
  185918. /* transformation does not include PNG_BACKGROUND */
  185919. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  185920. if (color_type == PNG_COLOR_TYPE_PALETTE)
  185921. {
  185922. png_colorp palette = png_ptr->palette;
  185923. int num_palette = png_ptr->num_palette;
  185924. int i;
  185925. for (i = 0; i < num_palette; i++)
  185926. {
  185927. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185928. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185929. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185930. }
  185931. }
  185932. }
  185933. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185934. else
  185935. #endif
  185936. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  185937. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185938. /* No GAMMA transformation */
  185939. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  185940. (color_type == PNG_COLOR_TYPE_PALETTE))
  185941. {
  185942. int i;
  185943. int istop = (int)png_ptr->num_trans;
  185944. png_color back;
  185945. png_colorp palette = png_ptr->palette;
  185946. back.red = (png_byte)png_ptr->background.red;
  185947. back.green = (png_byte)png_ptr->background.green;
  185948. back.blue = (png_byte)png_ptr->background.blue;
  185949. for (i = 0; i < istop; i++)
  185950. {
  185951. if (png_ptr->trans[i] == 0)
  185952. {
  185953. palette[i] = back;
  185954. }
  185955. else if (png_ptr->trans[i] != 0xff)
  185956. {
  185957. /* The png_composite() macro is defined in png.h */
  185958. png_composite(palette[i].red, palette[i].red,
  185959. png_ptr->trans[i], back.red);
  185960. png_composite(palette[i].green, palette[i].green,
  185961. png_ptr->trans[i], back.green);
  185962. png_composite(palette[i].blue, palette[i].blue,
  185963. png_ptr->trans[i], back.blue);
  185964. }
  185965. }
  185966. }
  185967. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  185968. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185969. if ((png_ptr->transformations & PNG_SHIFT) &&
  185970. (color_type == PNG_COLOR_TYPE_PALETTE))
  185971. {
  185972. png_uint_16 i;
  185973. png_uint_16 istop = png_ptr->num_palette;
  185974. int sr = 8 - png_ptr->sig_bit.red;
  185975. int sg = 8 - png_ptr->sig_bit.green;
  185976. int sb = 8 - png_ptr->sig_bit.blue;
  185977. if (sr < 0 || sr > 8)
  185978. sr = 0;
  185979. if (sg < 0 || sg > 8)
  185980. sg = 0;
  185981. if (sb < 0 || sb > 8)
  185982. sb = 0;
  185983. for (i = 0; i < istop; i++)
  185984. {
  185985. png_ptr->palette[i].red >>= sr;
  185986. png_ptr->palette[i].green >>= sg;
  185987. png_ptr->palette[i].blue >>= sb;
  185988. }
  185989. }
  185990. #endif /* PNG_READ_SHIFT_SUPPORTED */
  185991. }
  185992. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  185993. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  185994. if(png_ptr)
  185995. return;
  185996. #endif
  185997. }
  185998. /* Modify the info structure to reflect the transformations. The
  185999. * info should be updated so a PNG file could be written with it,
  186000. * assuming the transformations result in valid PNG data.
  186001. */
  186002. void /* PRIVATE */
  186003. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  186004. {
  186005. png_debug(1, "in png_read_transform_info\n");
  186006. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186007. if (png_ptr->transformations & PNG_EXPAND)
  186008. {
  186009. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186010. {
  186011. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  186012. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  186013. else
  186014. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  186015. info_ptr->bit_depth = 8;
  186016. info_ptr->num_trans = 0;
  186017. }
  186018. else
  186019. {
  186020. if (png_ptr->num_trans)
  186021. {
  186022. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  186023. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186024. else
  186025. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186026. }
  186027. if (info_ptr->bit_depth < 8)
  186028. info_ptr->bit_depth = 8;
  186029. info_ptr->num_trans = 0;
  186030. }
  186031. }
  186032. #endif
  186033. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186034. if (png_ptr->transformations & PNG_BACKGROUND)
  186035. {
  186036. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186037. info_ptr->num_trans = 0;
  186038. info_ptr->background = png_ptr->background;
  186039. }
  186040. #endif
  186041. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186042. if (png_ptr->transformations & PNG_GAMMA)
  186043. {
  186044. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186045. info_ptr->gamma = png_ptr->gamma;
  186046. #endif
  186047. #ifdef PNG_FIXED_POINT_SUPPORTED
  186048. info_ptr->int_gamma = png_ptr->int_gamma;
  186049. #endif
  186050. }
  186051. #endif
  186052. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186053. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  186054. info_ptr->bit_depth = 8;
  186055. #endif
  186056. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186057. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  186058. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186059. #endif
  186060. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186061. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186062. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  186063. #endif
  186064. #if defined(PNG_READ_DITHER_SUPPORTED)
  186065. if (png_ptr->transformations & PNG_DITHER)
  186066. {
  186067. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186068. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  186069. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  186070. {
  186071. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  186072. }
  186073. }
  186074. #endif
  186075. #if defined(PNG_READ_PACK_SUPPORTED)
  186076. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  186077. info_ptr->bit_depth = 8;
  186078. #endif
  186079. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186080. info_ptr->channels = 1;
  186081. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  186082. info_ptr->channels = 3;
  186083. else
  186084. info_ptr->channels = 1;
  186085. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186086. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186087. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186088. #endif
  186089. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  186090. info_ptr->channels++;
  186091. #if defined(PNG_READ_FILLER_SUPPORTED)
  186092. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  186093. if ((png_ptr->transformations & PNG_FILLER) &&
  186094. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186095. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  186096. {
  186097. info_ptr->channels++;
  186098. /* if adding a true alpha channel not just filler */
  186099. #if !defined(PNG_1_0_X)
  186100. if (png_ptr->transformations & PNG_ADD_ALPHA)
  186101. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186102. #endif
  186103. }
  186104. #endif
  186105. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  186106. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186107. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  186108. {
  186109. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  186110. info_ptr->bit_depth = png_ptr->user_transform_depth;
  186111. if(info_ptr->channels < png_ptr->user_transform_channels)
  186112. info_ptr->channels = png_ptr->user_transform_channels;
  186113. }
  186114. #endif
  186115. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  186116. info_ptr->bit_depth);
  186117. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  186118. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  186119. if(png_ptr)
  186120. return;
  186121. #endif
  186122. }
  186123. /* Transform the row. The order of transformations is significant,
  186124. * and is very touchy. If you add a transformation, take care to
  186125. * decide how it fits in with the other transformations here.
  186126. */
  186127. void /* PRIVATE */
  186128. png_do_read_transformations(png_structp png_ptr)
  186129. {
  186130. png_debug(1, "in png_do_read_transformations\n");
  186131. if (png_ptr->row_buf == NULL)
  186132. {
  186133. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186134. char msg[50];
  186135. png_snprintf2(msg, 50,
  186136. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  186137. png_ptr->pass);
  186138. png_error(png_ptr, msg);
  186139. #else
  186140. png_error(png_ptr, "NULL row buffer");
  186141. #endif
  186142. }
  186143. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186144. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186145. /* Application has failed to call either png_read_start_image()
  186146. * or png_read_update_info() after setting transforms that expand
  186147. * pixels. This check added to libpng-1.2.19 */
  186148. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  186149. png_error(png_ptr, "Uninitialized row");
  186150. #else
  186151. png_warning(png_ptr, "Uninitialized row");
  186152. #endif
  186153. #endif
  186154. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186155. if (png_ptr->transformations & PNG_EXPAND)
  186156. {
  186157. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  186158. {
  186159. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186160. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  186161. }
  186162. else
  186163. {
  186164. if (png_ptr->num_trans &&
  186165. (png_ptr->transformations & PNG_EXPAND_tRNS))
  186166. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186167. &(png_ptr->trans_values));
  186168. else
  186169. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186170. NULL);
  186171. }
  186172. }
  186173. #endif
  186174. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186175. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186176. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186177. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  186178. #endif
  186179. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186180. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186181. {
  186182. int rgb_error =
  186183. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  186184. if(rgb_error)
  186185. {
  186186. png_ptr->rgb_to_gray_status=1;
  186187. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186188. PNG_RGB_TO_GRAY_WARN)
  186189. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186190. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186191. PNG_RGB_TO_GRAY_ERR)
  186192. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186193. }
  186194. }
  186195. #endif
  186196. /*
  186197. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  186198. In most cases, the "simple transparency" should be done prior to doing
  186199. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  186200. pixel is transparent. You would also need to make sure that the
  186201. transparency information is upgraded to RGB.
  186202. To summarize, the current flow is:
  186203. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  186204. with background "in place" if transparent,
  186205. convert to RGB if necessary
  186206. - Gray + alpha -> composite with gray background and remove alpha bytes,
  186207. convert to RGB if necessary
  186208. To support RGB backgrounds for gray images we need:
  186209. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  186210. 3 or 6 bytes and composite with background
  186211. "in place" if transparent (3x compare/pixel
  186212. compared to doing composite with gray bkgrnd)
  186213. - Gray + alpha -> convert to RGB + alpha, composite with background and
  186214. remove alpha bytes (3x float operations/pixel
  186215. compared with composite on gray background)
  186216. Greg's change will do this. The reason it wasn't done before is for
  186217. performance, as this increases the per-pixel operations. If we would check
  186218. in advance if the background was gray or RGB, and position the gray-to-RGB
  186219. transform appropriately, then it would save a lot of work/time.
  186220. */
  186221. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186222. /* if gray -> RGB, do so now only if background is non-gray; else do later
  186223. * for performance reasons */
  186224. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186225. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186226. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186227. #endif
  186228. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186229. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186230. ((png_ptr->num_trans != 0 ) ||
  186231. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  186232. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186233. &(png_ptr->trans_values), &(png_ptr->background)
  186234. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186235. , &(png_ptr->background_1),
  186236. png_ptr->gamma_table, png_ptr->gamma_from_1,
  186237. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  186238. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  186239. png_ptr->gamma_shift
  186240. #endif
  186241. );
  186242. #endif
  186243. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186244. if ((png_ptr->transformations & PNG_GAMMA) &&
  186245. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186246. !((png_ptr->transformations & PNG_BACKGROUND) &&
  186247. ((png_ptr->num_trans != 0) ||
  186248. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  186249. #endif
  186250. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  186251. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186252. png_ptr->gamma_table, png_ptr->gamma_16_table,
  186253. png_ptr->gamma_shift);
  186254. #endif
  186255. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186256. if (png_ptr->transformations & PNG_16_TO_8)
  186257. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186258. #endif
  186259. #if defined(PNG_READ_DITHER_SUPPORTED)
  186260. if (png_ptr->transformations & PNG_DITHER)
  186261. {
  186262. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  186263. png_ptr->palette_lookup, png_ptr->dither_index);
  186264. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  186265. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  186266. }
  186267. #endif
  186268. #if defined(PNG_READ_INVERT_SUPPORTED)
  186269. if (png_ptr->transformations & PNG_INVERT_MONO)
  186270. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186271. #endif
  186272. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186273. if (png_ptr->transformations & PNG_SHIFT)
  186274. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186275. &(png_ptr->shift));
  186276. #endif
  186277. #if defined(PNG_READ_PACK_SUPPORTED)
  186278. if (png_ptr->transformations & PNG_PACK)
  186279. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186280. #endif
  186281. #if defined(PNG_READ_BGR_SUPPORTED)
  186282. if (png_ptr->transformations & PNG_BGR)
  186283. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186284. #endif
  186285. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  186286. if (png_ptr->transformations & PNG_PACKSWAP)
  186287. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186288. #endif
  186289. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186290. /* if gray -> RGB, do so now only if we did not do so above */
  186291. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186292. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186293. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186294. #endif
  186295. #if defined(PNG_READ_FILLER_SUPPORTED)
  186296. if (png_ptr->transformations & PNG_FILLER)
  186297. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186298. (png_uint_32)png_ptr->filler, png_ptr->flags);
  186299. #endif
  186300. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186301. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186302. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186303. #endif
  186304. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  186305. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  186306. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186307. #endif
  186308. #if defined(PNG_READ_SWAP_SUPPORTED)
  186309. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186310. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186311. #endif
  186312. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186313. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  186314. {
  186315. if(png_ptr->read_user_transform_fn != NULL)
  186316. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  186317. (png_ptr, /* png_ptr */
  186318. &(png_ptr->row_info), /* row_info: */
  186319. /* png_uint_32 width; width of row */
  186320. /* png_uint_32 rowbytes; number of bytes in row */
  186321. /* png_byte color_type; color type of pixels */
  186322. /* png_byte bit_depth; bit depth of samples */
  186323. /* png_byte channels; number of channels (1-4) */
  186324. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  186325. png_ptr->row_buf + 1); /* start of pixel data for row */
  186326. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  186327. if(png_ptr->user_transform_depth)
  186328. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  186329. if(png_ptr->user_transform_channels)
  186330. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  186331. #endif
  186332. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  186333. png_ptr->row_info.channels);
  186334. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186335. png_ptr->row_info.width);
  186336. }
  186337. #endif
  186338. }
  186339. #if defined(PNG_READ_PACK_SUPPORTED)
  186340. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  186341. * without changing the actual values. Thus, if you had a row with
  186342. * a bit depth of 1, you would end up with bytes that only contained
  186343. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  186344. * png_do_shift() after this.
  186345. */
  186346. void /* PRIVATE */
  186347. png_do_unpack(png_row_infop row_info, png_bytep row)
  186348. {
  186349. png_debug(1, "in png_do_unpack\n");
  186350. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186351. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  186352. #else
  186353. if (row_info->bit_depth < 8)
  186354. #endif
  186355. {
  186356. png_uint_32 i;
  186357. png_uint_32 row_width=row_info->width;
  186358. switch (row_info->bit_depth)
  186359. {
  186360. case 1:
  186361. {
  186362. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  186363. png_bytep dp = row + (png_size_t)row_width - 1;
  186364. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  186365. for (i = 0; i < row_width; i++)
  186366. {
  186367. *dp = (png_byte)((*sp >> shift) & 0x01);
  186368. if (shift == 7)
  186369. {
  186370. shift = 0;
  186371. sp--;
  186372. }
  186373. else
  186374. shift++;
  186375. dp--;
  186376. }
  186377. break;
  186378. }
  186379. case 2:
  186380. {
  186381. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  186382. png_bytep dp = row + (png_size_t)row_width - 1;
  186383. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  186384. for (i = 0; i < row_width; i++)
  186385. {
  186386. *dp = (png_byte)((*sp >> shift) & 0x03);
  186387. if (shift == 6)
  186388. {
  186389. shift = 0;
  186390. sp--;
  186391. }
  186392. else
  186393. shift += 2;
  186394. dp--;
  186395. }
  186396. break;
  186397. }
  186398. case 4:
  186399. {
  186400. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  186401. png_bytep dp = row + (png_size_t)row_width - 1;
  186402. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  186403. for (i = 0; i < row_width; i++)
  186404. {
  186405. *dp = (png_byte)((*sp >> shift) & 0x0f);
  186406. if (shift == 4)
  186407. {
  186408. shift = 0;
  186409. sp--;
  186410. }
  186411. else
  186412. shift = 4;
  186413. dp--;
  186414. }
  186415. break;
  186416. }
  186417. }
  186418. row_info->bit_depth = 8;
  186419. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  186420. row_info->rowbytes = row_width * row_info->channels;
  186421. }
  186422. }
  186423. #endif
  186424. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186425. /* Reverse the effects of png_do_shift. This routine merely shifts the
  186426. * pixels back to their significant bits values. Thus, if you have
  186427. * a row of bit depth 8, but only 5 are significant, this will shift
  186428. * the values back to 0 through 31.
  186429. */
  186430. void /* PRIVATE */
  186431. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  186432. {
  186433. png_debug(1, "in png_do_unshift\n");
  186434. if (
  186435. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186436. row != NULL && row_info != NULL && sig_bits != NULL &&
  186437. #endif
  186438. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  186439. {
  186440. int shift[4];
  186441. int channels = 0;
  186442. int c;
  186443. png_uint_16 value = 0;
  186444. png_uint_32 row_width = row_info->width;
  186445. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  186446. {
  186447. shift[channels++] = row_info->bit_depth - sig_bits->red;
  186448. shift[channels++] = row_info->bit_depth - sig_bits->green;
  186449. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  186450. }
  186451. else
  186452. {
  186453. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  186454. }
  186455. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  186456. {
  186457. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  186458. }
  186459. for (c = 0; c < channels; c++)
  186460. {
  186461. if (shift[c] <= 0)
  186462. shift[c] = 0;
  186463. else
  186464. value = 1;
  186465. }
  186466. if (!value)
  186467. return;
  186468. switch (row_info->bit_depth)
  186469. {
  186470. case 2:
  186471. {
  186472. png_bytep bp;
  186473. png_uint_32 i;
  186474. png_uint_32 istop = row_info->rowbytes;
  186475. for (bp = row, i = 0; i < istop; i++)
  186476. {
  186477. *bp >>= 1;
  186478. *bp++ &= 0x55;
  186479. }
  186480. break;
  186481. }
  186482. case 4:
  186483. {
  186484. png_bytep bp = row;
  186485. png_uint_32 i;
  186486. png_uint_32 istop = row_info->rowbytes;
  186487. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  186488. (png_byte)((int)0xf >> shift[0]));
  186489. for (i = 0; i < istop; i++)
  186490. {
  186491. *bp >>= shift[0];
  186492. *bp++ &= mask;
  186493. }
  186494. break;
  186495. }
  186496. case 8:
  186497. {
  186498. png_bytep bp = row;
  186499. png_uint_32 i;
  186500. png_uint_32 istop = row_width * channels;
  186501. for (i = 0; i < istop; i++)
  186502. {
  186503. *bp++ >>= shift[i%channels];
  186504. }
  186505. break;
  186506. }
  186507. case 16:
  186508. {
  186509. png_bytep bp = row;
  186510. png_uint_32 i;
  186511. png_uint_32 istop = channels * row_width;
  186512. for (i = 0; i < istop; i++)
  186513. {
  186514. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  186515. value >>= shift[i%channels];
  186516. *bp++ = (png_byte)(value >> 8);
  186517. *bp++ = (png_byte)(value & 0xff);
  186518. }
  186519. break;
  186520. }
  186521. }
  186522. }
  186523. }
  186524. #endif
  186525. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186526. /* chop rows of bit depth 16 down to 8 */
  186527. void /* PRIVATE */
  186528. png_do_chop(png_row_infop row_info, png_bytep row)
  186529. {
  186530. png_debug(1, "in png_do_chop\n");
  186531. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186532. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  186533. #else
  186534. if (row_info->bit_depth == 16)
  186535. #endif
  186536. {
  186537. png_bytep sp = row;
  186538. png_bytep dp = row;
  186539. png_uint_32 i;
  186540. png_uint_32 istop = row_info->width * row_info->channels;
  186541. for (i = 0; i<istop; i++, sp += 2, dp++)
  186542. {
  186543. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  186544. /* This does a more accurate scaling of the 16-bit color
  186545. * value, rather than a simple low-byte truncation.
  186546. *
  186547. * What the ideal calculation should be:
  186548. * *dp = (((((png_uint_32)(*sp) << 8) |
  186549. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  186550. *
  186551. * GRR: no, I think this is what it really should be:
  186552. * *dp = (((((png_uint_32)(*sp) << 8) |
  186553. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  186554. *
  186555. * GRR: here's the exact calculation with shifts:
  186556. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  186557. * *dp = (temp - (temp >> 8)) >> 8;
  186558. *
  186559. * Approximate calculation with shift/add instead of multiply/divide:
  186560. * *dp = ((((png_uint_32)(*sp) << 8) |
  186561. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  186562. *
  186563. * What we actually do to avoid extra shifting and conversion:
  186564. */
  186565. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  186566. #else
  186567. /* Simply discard the low order byte */
  186568. *dp = *sp;
  186569. #endif
  186570. }
  186571. row_info->bit_depth = 8;
  186572. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  186573. row_info->rowbytes = row_info->width * row_info->channels;
  186574. }
  186575. }
  186576. #endif
  186577. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  186578. void /* PRIVATE */
  186579. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  186580. {
  186581. png_debug(1, "in png_do_read_swap_alpha\n");
  186582. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186583. if (row != NULL && row_info != NULL)
  186584. #endif
  186585. {
  186586. png_uint_32 row_width = row_info->width;
  186587. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  186588. {
  186589. /* This converts from RGBA to ARGB */
  186590. if (row_info->bit_depth == 8)
  186591. {
  186592. png_bytep sp = row + row_info->rowbytes;
  186593. png_bytep dp = sp;
  186594. png_byte save;
  186595. png_uint_32 i;
  186596. for (i = 0; i < row_width; i++)
  186597. {
  186598. save = *(--sp);
  186599. *(--dp) = *(--sp);
  186600. *(--dp) = *(--sp);
  186601. *(--dp) = *(--sp);
  186602. *(--dp) = save;
  186603. }
  186604. }
  186605. /* This converts from RRGGBBAA to AARRGGBB */
  186606. else
  186607. {
  186608. png_bytep sp = row + row_info->rowbytes;
  186609. png_bytep dp = sp;
  186610. png_byte save[2];
  186611. png_uint_32 i;
  186612. for (i = 0; i < row_width; i++)
  186613. {
  186614. save[0] = *(--sp);
  186615. save[1] = *(--sp);
  186616. *(--dp) = *(--sp);
  186617. *(--dp) = *(--sp);
  186618. *(--dp) = *(--sp);
  186619. *(--dp) = *(--sp);
  186620. *(--dp) = *(--sp);
  186621. *(--dp) = *(--sp);
  186622. *(--dp) = save[0];
  186623. *(--dp) = save[1];
  186624. }
  186625. }
  186626. }
  186627. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  186628. {
  186629. /* This converts from GA to AG */
  186630. if (row_info->bit_depth == 8)
  186631. {
  186632. png_bytep sp = row + row_info->rowbytes;
  186633. png_bytep dp = sp;
  186634. png_byte save;
  186635. png_uint_32 i;
  186636. for (i = 0; i < row_width; i++)
  186637. {
  186638. save = *(--sp);
  186639. *(--dp) = *(--sp);
  186640. *(--dp) = save;
  186641. }
  186642. }
  186643. /* This converts from GGAA to AAGG */
  186644. else
  186645. {
  186646. png_bytep sp = row + row_info->rowbytes;
  186647. png_bytep dp = sp;
  186648. png_byte save[2];
  186649. png_uint_32 i;
  186650. for (i = 0; i < row_width; i++)
  186651. {
  186652. save[0] = *(--sp);
  186653. save[1] = *(--sp);
  186654. *(--dp) = *(--sp);
  186655. *(--dp) = *(--sp);
  186656. *(--dp) = save[0];
  186657. *(--dp) = save[1];
  186658. }
  186659. }
  186660. }
  186661. }
  186662. }
  186663. #endif
  186664. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186665. void /* PRIVATE */
  186666. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  186667. {
  186668. png_debug(1, "in png_do_read_invert_alpha\n");
  186669. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186670. if (row != NULL && row_info != NULL)
  186671. #endif
  186672. {
  186673. png_uint_32 row_width = row_info->width;
  186674. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  186675. {
  186676. /* This inverts the alpha channel in RGBA */
  186677. if (row_info->bit_depth == 8)
  186678. {
  186679. png_bytep sp = row + row_info->rowbytes;
  186680. png_bytep dp = sp;
  186681. png_uint_32 i;
  186682. for (i = 0; i < row_width; i++)
  186683. {
  186684. *(--dp) = (png_byte)(255 - *(--sp));
  186685. /* This does nothing:
  186686. *(--dp) = *(--sp);
  186687. *(--dp) = *(--sp);
  186688. *(--dp) = *(--sp);
  186689. We can replace it with:
  186690. */
  186691. sp-=3;
  186692. dp=sp;
  186693. }
  186694. }
  186695. /* This inverts the alpha channel in RRGGBBAA */
  186696. else
  186697. {
  186698. png_bytep sp = row + row_info->rowbytes;
  186699. png_bytep dp = sp;
  186700. png_uint_32 i;
  186701. for (i = 0; i < row_width; i++)
  186702. {
  186703. *(--dp) = (png_byte)(255 - *(--sp));
  186704. *(--dp) = (png_byte)(255 - *(--sp));
  186705. /* This does nothing:
  186706. *(--dp) = *(--sp);
  186707. *(--dp) = *(--sp);
  186708. *(--dp) = *(--sp);
  186709. *(--dp) = *(--sp);
  186710. *(--dp) = *(--sp);
  186711. *(--dp) = *(--sp);
  186712. We can replace it with:
  186713. */
  186714. sp-=6;
  186715. dp=sp;
  186716. }
  186717. }
  186718. }
  186719. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  186720. {
  186721. /* This inverts the alpha channel in GA */
  186722. if (row_info->bit_depth == 8)
  186723. {
  186724. png_bytep sp = row + row_info->rowbytes;
  186725. png_bytep dp = sp;
  186726. png_uint_32 i;
  186727. for (i = 0; i < row_width; i++)
  186728. {
  186729. *(--dp) = (png_byte)(255 - *(--sp));
  186730. *(--dp) = *(--sp);
  186731. }
  186732. }
  186733. /* This inverts the alpha channel in GGAA */
  186734. else
  186735. {
  186736. png_bytep sp = row + row_info->rowbytes;
  186737. png_bytep dp = sp;
  186738. png_uint_32 i;
  186739. for (i = 0; i < row_width; i++)
  186740. {
  186741. *(--dp) = (png_byte)(255 - *(--sp));
  186742. *(--dp) = (png_byte)(255 - *(--sp));
  186743. /*
  186744. *(--dp) = *(--sp);
  186745. *(--dp) = *(--sp);
  186746. */
  186747. sp-=2;
  186748. dp=sp;
  186749. }
  186750. }
  186751. }
  186752. }
  186753. }
  186754. #endif
  186755. #if defined(PNG_READ_FILLER_SUPPORTED)
  186756. /* Add filler channel if we have RGB color */
  186757. void /* PRIVATE */
  186758. png_do_read_filler(png_row_infop row_info, png_bytep row,
  186759. png_uint_32 filler, png_uint_32 flags)
  186760. {
  186761. png_uint_32 i;
  186762. png_uint_32 row_width = row_info->width;
  186763. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  186764. png_byte lo_filler = (png_byte)(filler & 0xff);
  186765. png_debug(1, "in png_do_read_filler\n");
  186766. if (
  186767. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186768. row != NULL && row_info != NULL &&
  186769. #endif
  186770. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  186771. {
  186772. if(row_info->bit_depth == 8)
  186773. {
  186774. /* This changes the data from G to GX */
  186775. if (flags & PNG_FLAG_FILLER_AFTER)
  186776. {
  186777. png_bytep sp = row + (png_size_t)row_width;
  186778. png_bytep dp = sp + (png_size_t)row_width;
  186779. for (i = 1; i < row_width; i++)
  186780. {
  186781. *(--dp) = lo_filler;
  186782. *(--dp) = *(--sp);
  186783. }
  186784. *(--dp) = lo_filler;
  186785. row_info->channels = 2;
  186786. row_info->pixel_depth = 16;
  186787. row_info->rowbytes = row_width * 2;
  186788. }
  186789. /* This changes the data from G to XG */
  186790. else
  186791. {
  186792. png_bytep sp = row + (png_size_t)row_width;
  186793. png_bytep dp = sp + (png_size_t)row_width;
  186794. for (i = 0; i < row_width; i++)
  186795. {
  186796. *(--dp) = *(--sp);
  186797. *(--dp) = lo_filler;
  186798. }
  186799. row_info->channels = 2;
  186800. row_info->pixel_depth = 16;
  186801. row_info->rowbytes = row_width * 2;
  186802. }
  186803. }
  186804. else if(row_info->bit_depth == 16)
  186805. {
  186806. /* This changes the data from GG to GGXX */
  186807. if (flags & PNG_FLAG_FILLER_AFTER)
  186808. {
  186809. png_bytep sp = row + (png_size_t)row_width * 2;
  186810. png_bytep dp = sp + (png_size_t)row_width * 2;
  186811. for (i = 1; i < row_width; i++)
  186812. {
  186813. *(--dp) = hi_filler;
  186814. *(--dp) = lo_filler;
  186815. *(--dp) = *(--sp);
  186816. *(--dp) = *(--sp);
  186817. }
  186818. *(--dp) = hi_filler;
  186819. *(--dp) = lo_filler;
  186820. row_info->channels = 2;
  186821. row_info->pixel_depth = 32;
  186822. row_info->rowbytes = row_width * 4;
  186823. }
  186824. /* This changes the data from GG to XXGG */
  186825. else
  186826. {
  186827. png_bytep sp = row + (png_size_t)row_width * 2;
  186828. png_bytep dp = sp + (png_size_t)row_width * 2;
  186829. for (i = 0; i < row_width; i++)
  186830. {
  186831. *(--dp) = *(--sp);
  186832. *(--dp) = *(--sp);
  186833. *(--dp) = hi_filler;
  186834. *(--dp) = lo_filler;
  186835. }
  186836. row_info->channels = 2;
  186837. row_info->pixel_depth = 32;
  186838. row_info->rowbytes = row_width * 4;
  186839. }
  186840. }
  186841. } /* COLOR_TYPE == GRAY */
  186842. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  186843. {
  186844. if(row_info->bit_depth == 8)
  186845. {
  186846. /* This changes the data from RGB to RGBX */
  186847. if (flags & PNG_FLAG_FILLER_AFTER)
  186848. {
  186849. png_bytep sp = row + (png_size_t)row_width * 3;
  186850. png_bytep dp = sp + (png_size_t)row_width;
  186851. for (i = 1; i < row_width; i++)
  186852. {
  186853. *(--dp) = lo_filler;
  186854. *(--dp) = *(--sp);
  186855. *(--dp) = *(--sp);
  186856. *(--dp) = *(--sp);
  186857. }
  186858. *(--dp) = lo_filler;
  186859. row_info->channels = 4;
  186860. row_info->pixel_depth = 32;
  186861. row_info->rowbytes = row_width * 4;
  186862. }
  186863. /* This changes the data from RGB to XRGB */
  186864. else
  186865. {
  186866. png_bytep sp = row + (png_size_t)row_width * 3;
  186867. png_bytep dp = sp + (png_size_t)row_width;
  186868. for (i = 0; i < row_width; i++)
  186869. {
  186870. *(--dp) = *(--sp);
  186871. *(--dp) = *(--sp);
  186872. *(--dp) = *(--sp);
  186873. *(--dp) = lo_filler;
  186874. }
  186875. row_info->channels = 4;
  186876. row_info->pixel_depth = 32;
  186877. row_info->rowbytes = row_width * 4;
  186878. }
  186879. }
  186880. else if(row_info->bit_depth == 16)
  186881. {
  186882. /* This changes the data from RRGGBB to RRGGBBXX */
  186883. if (flags & PNG_FLAG_FILLER_AFTER)
  186884. {
  186885. png_bytep sp = row + (png_size_t)row_width * 6;
  186886. png_bytep dp = sp + (png_size_t)row_width * 2;
  186887. for (i = 1; i < row_width; i++)
  186888. {
  186889. *(--dp) = hi_filler;
  186890. *(--dp) = lo_filler;
  186891. *(--dp) = *(--sp);
  186892. *(--dp) = *(--sp);
  186893. *(--dp) = *(--sp);
  186894. *(--dp) = *(--sp);
  186895. *(--dp) = *(--sp);
  186896. *(--dp) = *(--sp);
  186897. }
  186898. *(--dp) = hi_filler;
  186899. *(--dp) = lo_filler;
  186900. row_info->channels = 4;
  186901. row_info->pixel_depth = 64;
  186902. row_info->rowbytes = row_width * 8;
  186903. }
  186904. /* This changes the data from RRGGBB to XXRRGGBB */
  186905. else
  186906. {
  186907. png_bytep sp = row + (png_size_t)row_width * 6;
  186908. png_bytep dp = sp + (png_size_t)row_width * 2;
  186909. for (i = 0; i < row_width; i++)
  186910. {
  186911. *(--dp) = *(--sp);
  186912. *(--dp) = *(--sp);
  186913. *(--dp) = *(--sp);
  186914. *(--dp) = *(--sp);
  186915. *(--dp) = *(--sp);
  186916. *(--dp) = *(--sp);
  186917. *(--dp) = hi_filler;
  186918. *(--dp) = lo_filler;
  186919. }
  186920. row_info->channels = 4;
  186921. row_info->pixel_depth = 64;
  186922. row_info->rowbytes = row_width * 8;
  186923. }
  186924. }
  186925. } /* COLOR_TYPE == RGB */
  186926. }
  186927. #endif
  186928. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186929. /* expand grayscale files to RGB, with or without alpha */
  186930. void /* PRIVATE */
  186931. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  186932. {
  186933. png_uint_32 i;
  186934. png_uint_32 row_width = row_info->width;
  186935. png_debug(1, "in png_do_gray_to_rgb\n");
  186936. if (row_info->bit_depth >= 8 &&
  186937. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186938. row != NULL && row_info != NULL &&
  186939. #endif
  186940. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  186941. {
  186942. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  186943. {
  186944. if (row_info->bit_depth == 8)
  186945. {
  186946. png_bytep sp = row + (png_size_t)row_width - 1;
  186947. png_bytep dp = sp + (png_size_t)row_width * 2;
  186948. for (i = 0; i < row_width; i++)
  186949. {
  186950. *(dp--) = *sp;
  186951. *(dp--) = *sp;
  186952. *(dp--) = *(sp--);
  186953. }
  186954. }
  186955. else
  186956. {
  186957. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  186958. png_bytep dp = sp + (png_size_t)row_width * 4;
  186959. for (i = 0; i < row_width; i++)
  186960. {
  186961. *(dp--) = *sp;
  186962. *(dp--) = *(sp - 1);
  186963. *(dp--) = *sp;
  186964. *(dp--) = *(sp - 1);
  186965. *(dp--) = *(sp--);
  186966. *(dp--) = *(sp--);
  186967. }
  186968. }
  186969. }
  186970. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  186971. {
  186972. if (row_info->bit_depth == 8)
  186973. {
  186974. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  186975. png_bytep dp = sp + (png_size_t)row_width * 2;
  186976. for (i = 0; i < row_width; i++)
  186977. {
  186978. *(dp--) = *(sp--);
  186979. *(dp--) = *sp;
  186980. *(dp--) = *sp;
  186981. *(dp--) = *(sp--);
  186982. }
  186983. }
  186984. else
  186985. {
  186986. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  186987. png_bytep dp = sp + (png_size_t)row_width * 4;
  186988. for (i = 0; i < row_width; i++)
  186989. {
  186990. *(dp--) = *(sp--);
  186991. *(dp--) = *(sp--);
  186992. *(dp--) = *sp;
  186993. *(dp--) = *(sp - 1);
  186994. *(dp--) = *sp;
  186995. *(dp--) = *(sp - 1);
  186996. *(dp--) = *(sp--);
  186997. *(dp--) = *(sp--);
  186998. }
  186999. }
  187000. }
  187001. row_info->channels += (png_byte)2;
  187002. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  187003. row_info->pixel_depth = (png_byte)(row_info->channels *
  187004. row_info->bit_depth);
  187005. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187006. }
  187007. }
  187008. #endif
  187009. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187010. /* reduce RGB files to grayscale, with or without alpha
  187011. * using the equation given in Poynton's ColorFAQ at
  187012. * <http://www.inforamp.net/~poynton/>
  187013. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  187014. *
  187015. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  187016. *
  187017. * We approximate this with
  187018. *
  187019. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  187020. *
  187021. * which can be expressed with integers as
  187022. *
  187023. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  187024. *
  187025. * The calculation is to be done in a linear colorspace.
  187026. *
  187027. * Other integer coefficents can be used via png_set_rgb_to_gray().
  187028. */
  187029. int /* PRIVATE */
  187030. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  187031. {
  187032. png_uint_32 i;
  187033. png_uint_32 row_width = row_info->width;
  187034. int rgb_error = 0;
  187035. png_debug(1, "in png_do_rgb_to_gray\n");
  187036. if (
  187037. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187038. row != NULL && row_info != NULL &&
  187039. #endif
  187040. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187041. {
  187042. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  187043. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  187044. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  187045. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187046. {
  187047. if (row_info->bit_depth == 8)
  187048. {
  187049. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187050. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187051. {
  187052. png_bytep sp = row;
  187053. png_bytep dp = row;
  187054. for (i = 0; i < row_width; i++)
  187055. {
  187056. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187057. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187058. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187059. if(red != green || red != blue)
  187060. {
  187061. rgb_error |= 1;
  187062. *(dp++) = png_ptr->gamma_from_1[
  187063. (rc*red+gc*green+bc*blue)>>15];
  187064. }
  187065. else
  187066. *(dp++) = *(sp-1);
  187067. }
  187068. }
  187069. else
  187070. #endif
  187071. {
  187072. png_bytep sp = row;
  187073. png_bytep dp = row;
  187074. for (i = 0; i < row_width; i++)
  187075. {
  187076. png_byte red = *(sp++);
  187077. png_byte green = *(sp++);
  187078. png_byte blue = *(sp++);
  187079. if(red != green || red != blue)
  187080. {
  187081. rgb_error |= 1;
  187082. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  187083. }
  187084. else
  187085. *(dp++) = *(sp-1);
  187086. }
  187087. }
  187088. }
  187089. else /* RGB bit_depth == 16 */
  187090. {
  187091. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187092. if (png_ptr->gamma_16_to_1 != NULL &&
  187093. png_ptr->gamma_16_from_1 != NULL)
  187094. {
  187095. png_bytep sp = row;
  187096. png_bytep dp = row;
  187097. for (i = 0; i < row_width; i++)
  187098. {
  187099. png_uint_16 red, green, blue, w;
  187100. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187101. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187102. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187103. if(red == green && red == blue)
  187104. w = red;
  187105. else
  187106. {
  187107. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187108. png_ptr->gamma_shift][red>>8];
  187109. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187110. png_ptr->gamma_shift][green>>8];
  187111. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187112. png_ptr->gamma_shift][blue>>8];
  187113. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  187114. + bc*blue_1)>>15);
  187115. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187116. png_ptr->gamma_shift][gray16 >> 8];
  187117. rgb_error |= 1;
  187118. }
  187119. *(dp++) = (png_byte)((w>>8) & 0xff);
  187120. *(dp++) = (png_byte)(w & 0xff);
  187121. }
  187122. }
  187123. else
  187124. #endif
  187125. {
  187126. png_bytep sp = row;
  187127. png_bytep dp = row;
  187128. for (i = 0; i < row_width; i++)
  187129. {
  187130. png_uint_16 red, green, blue, gray16;
  187131. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187132. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187133. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187134. if(red != green || red != blue)
  187135. rgb_error |= 1;
  187136. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187137. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187138. *(dp++) = (png_byte)(gray16 & 0xff);
  187139. }
  187140. }
  187141. }
  187142. }
  187143. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187144. {
  187145. if (row_info->bit_depth == 8)
  187146. {
  187147. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187148. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187149. {
  187150. png_bytep sp = row;
  187151. png_bytep dp = row;
  187152. for (i = 0; i < row_width; i++)
  187153. {
  187154. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187155. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187156. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187157. if(red != green || red != blue)
  187158. rgb_error |= 1;
  187159. *(dp++) = png_ptr->gamma_from_1
  187160. [(rc*red + gc*green + bc*blue)>>15];
  187161. *(dp++) = *(sp++); /* alpha */
  187162. }
  187163. }
  187164. else
  187165. #endif
  187166. {
  187167. png_bytep sp = row;
  187168. png_bytep dp = row;
  187169. for (i = 0; i < row_width; i++)
  187170. {
  187171. png_byte red = *(sp++);
  187172. png_byte green = *(sp++);
  187173. png_byte blue = *(sp++);
  187174. if(red != green || red != blue)
  187175. rgb_error |= 1;
  187176. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  187177. *(dp++) = *(sp++); /* alpha */
  187178. }
  187179. }
  187180. }
  187181. else /* RGBA bit_depth == 16 */
  187182. {
  187183. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187184. if (png_ptr->gamma_16_to_1 != NULL &&
  187185. png_ptr->gamma_16_from_1 != NULL)
  187186. {
  187187. png_bytep sp = row;
  187188. png_bytep dp = row;
  187189. for (i = 0; i < row_width; i++)
  187190. {
  187191. png_uint_16 red, green, blue, w;
  187192. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187193. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187194. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187195. if(red == green && red == blue)
  187196. w = red;
  187197. else
  187198. {
  187199. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187200. png_ptr->gamma_shift][red>>8];
  187201. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187202. png_ptr->gamma_shift][green>>8];
  187203. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187204. png_ptr->gamma_shift][blue>>8];
  187205. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  187206. + gc * green_1 + bc * blue_1)>>15);
  187207. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187208. png_ptr->gamma_shift][gray16 >> 8];
  187209. rgb_error |= 1;
  187210. }
  187211. *(dp++) = (png_byte)((w>>8) & 0xff);
  187212. *(dp++) = (png_byte)(w & 0xff);
  187213. *(dp++) = *(sp++); /* alpha */
  187214. *(dp++) = *(sp++);
  187215. }
  187216. }
  187217. else
  187218. #endif
  187219. {
  187220. png_bytep sp = row;
  187221. png_bytep dp = row;
  187222. for (i = 0; i < row_width; i++)
  187223. {
  187224. png_uint_16 red, green, blue, gray16;
  187225. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187226. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187227. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187228. if(red != green || red != blue)
  187229. rgb_error |= 1;
  187230. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187231. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187232. *(dp++) = (png_byte)(gray16 & 0xff);
  187233. *(dp++) = *(sp++); /* alpha */
  187234. *(dp++) = *(sp++);
  187235. }
  187236. }
  187237. }
  187238. }
  187239. row_info->channels -= (png_byte)2;
  187240. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  187241. row_info->pixel_depth = (png_byte)(row_info->channels *
  187242. row_info->bit_depth);
  187243. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187244. }
  187245. return rgb_error;
  187246. }
  187247. #endif
  187248. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  187249. * large of png_color. This lets grayscale images be treated as
  187250. * paletted. Most useful for gamma correction and simplification
  187251. * of code.
  187252. */
  187253. void PNGAPI
  187254. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  187255. {
  187256. int num_palette;
  187257. int color_inc;
  187258. int i;
  187259. int v;
  187260. png_debug(1, "in png_do_build_grayscale_palette\n");
  187261. if (palette == NULL)
  187262. return;
  187263. switch (bit_depth)
  187264. {
  187265. case 1:
  187266. num_palette = 2;
  187267. color_inc = 0xff;
  187268. break;
  187269. case 2:
  187270. num_palette = 4;
  187271. color_inc = 0x55;
  187272. break;
  187273. case 4:
  187274. num_palette = 16;
  187275. color_inc = 0x11;
  187276. break;
  187277. case 8:
  187278. num_palette = 256;
  187279. color_inc = 1;
  187280. break;
  187281. default:
  187282. num_palette = 0;
  187283. color_inc = 0;
  187284. break;
  187285. }
  187286. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  187287. {
  187288. palette[i].red = (png_byte)v;
  187289. palette[i].green = (png_byte)v;
  187290. palette[i].blue = (png_byte)v;
  187291. }
  187292. }
  187293. /* This function is currently unused. Do we really need it? */
  187294. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  187295. void /* PRIVATE */
  187296. png_correct_palette(png_structp png_ptr, png_colorp palette,
  187297. int num_palette)
  187298. {
  187299. png_debug(1, "in png_correct_palette\n");
  187300. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  187301. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187302. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  187303. {
  187304. png_color back, back_1;
  187305. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187306. {
  187307. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187308. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187309. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187310. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187311. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187312. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187313. }
  187314. else
  187315. {
  187316. double g;
  187317. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  187318. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  187319. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  187320. {
  187321. back.red = png_ptr->background.red;
  187322. back.green = png_ptr->background.green;
  187323. back.blue = png_ptr->background.blue;
  187324. }
  187325. else
  187326. {
  187327. back.red =
  187328. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187329. 255.0 + 0.5);
  187330. back.green =
  187331. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187332. 255.0 + 0.5);
  187333. back.blue =
  187334. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187335. 255.0 + 0.5);
  187336. }
  187337. g = 1.0 / png_ptr->background_gamma;
  187338. back_1.red =
  187339. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187340. 255.0 + 0.5);
  187341. back_1.green =
  187342. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187343. 255.0 + 0.5);
  187344. back_1.blue =
  187345. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187346. 255.0 + 0.5);
  187347. }
  187348. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187349. {
  187350. png_uint_32 i;
  187351. for (i = 0; i < (png_uint_32)num_palette; i++)
  187352. {
  187353. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  187354. {
  187355. palette[i] = back;
  187356. }
  187357. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  187358. {
  187359. png_byte v, w;
  187360. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  187361. png_composite(w, v, png_ptr->trans[i], back_1.red);
  187362. palette[i].red = png_ptr->gamma_from_1[w];
  187363. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  187364. png_composite(w, v, png_ptr->trans[i], back_1.green);
  187365. palette[i].green = png_ptr->gamma_from_1[w];
  187366. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  187367. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  187368. palette[i].blue = png_ptr->gamma_from_1[w];
  187369. }
  187370. else
  187371. {
  187372. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187373. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187374. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187375. }
  187376. }
  187377. }
  187378. else
  187379. {
  187380. int i;
  187381. for (i = 0; i < num_palette; i++)
  187382. {
  187383. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  187384. {
  187385. palette[i] = back;
  187386. }
  187387. else
  187388. {
  187389. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187390. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187391. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187392. }
  187393. }
  187394. }
  187395. }
  187396. else
  187397. #endif
  187398. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187399. if (png_ptr->transformations & PNG_GAMMA)
  187400. {
  187401. int i;
  187402. for (i = 0; i < num_palette; i++)
  187403. {
  187404. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187405. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187406. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187407. }
  187408. }
  187409. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187410. else
  187411. #endif
  187412. #endif
  187413. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187414. if (png_ptr->transformations & PNG_BACKGROUND)
  187415. {
  187416. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187417. {
  187418. png_color back;
  187419. back.red = (png_byte)png_ptr->background.red;
  187420. back.green = (png_byte)png_ptr->background.green;
  187421. back.blue = (png_byte)png_ptr->background.blue;
  187422. for (i = 0; i < (int)png_ptr->num_trans; i++)
  187423. {
  187424. if (png_ptr->trans[i] == 0)
  187425. {
  187426. palette[i].red = back.red;
  187427. palette[i].green = back.green;
  187428. palette[i].blue = back.blue;
  187429. }
  187430. else if (png_ptr->trans[i] != 0xff)
  187431. {
  187432. png_composite(palette[i].red, png_ptr->palette[i].red,
  187433. png_ptr->trans[i], back.red);
  187434. png_composite(palette[i].green, png_ptr->palette[i].green,
  187435. png_ptr->trans[i], back.green);
  187436. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  187437. png_ptr->trans[i], back.blue);
  187438. }
  187439. }
  187440. }
  187441. else /* assume grayscale palette (what else could it be?) */
  187442. {
  187443. int i;
  187444. for (i = 0; i < num_palette; i++)
  187445. {
  187446. if (i == (png_byte)png_ptr->trans_values.gray)
  187447. {
  187448. palette[i].red = (png_byte)png_ptr->background.red;
  187449. palette[i].green = (png_byte)png_ptr->background.green;
  187450. palette[i].blue = (png_byte)png_ptr->background.blue;
  187451. }
  187452. }
  187453. }
  187454. }
  187455. #endif
  187456. }
  187457. #endif
  187458. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187459. /* Replace any alpha or transparency with the supplied background color.
  187460. * "background" is already in the screen gamma, while "background_1" is
  187461. * at a gamma of 1.0. Paletted files have already been taken care of.
  187462. */
  187463. void /* PRIVATE */
  187464. png_do_background(png_row_infop row_info, png_bytep row,
  187465. png_color_16p trans_values, png_color_16p background
  187466. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187467. , png_color_16p background_1,
  187468. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  187469. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  187470. png_uint_16pp gamma_16_to_1, int gamma_shift
  187471. #endif
  187472. )
  187473. {
  187474. png_bytep sp, dp;
  187475. png_uint_32 i;
  187476. png_uint_32 row_width=row_info->width;
  187477. int shift;
  187478. png_debug(1, "in png_do_background\n");
  187479. if (background != NULL &&
  187480. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187481. row != NULL && row_info != NULL &&
  187482. #endif
  187483. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  187484. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  187485. {
  187486. switch (row_info->color_type)
  187487. {
  187488. case PNG_COLOR_TYPE_GRAY:
  187489. {
  187490. switch (row_info->bit_depth)
  187491. {
  187492. case 1:
  187493. {
  187494. sp = row;
  187495. shift = 7;
  187496. for (i = 0; i < row_width; i++)
  187497. {
  187498. if ((png_uint_16)((*sp >> shift) & 0x01)
  187499. == trans_values->gray)
  187500. {
  187501. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  187502. *sp |= (png_byte)(background->gray << shift);
  187503. }
  187504. if (!shift)
  187505. {
  187506. shift = 7;
  187507. sp++;
  187508. }
  187509. else
  187510. shift--;
  187511. }
  187512. break;
  187513. }
  187514. case 2:
  187515. {
  187516. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187517. if (gamma_table != NULL)
  187518. {
  187519. sp = row;
  187520. shift = 6;
  187521. for (i = 0; i < row_width; i++)
  187522. {
  187523. if ((png_uint_16)((*sp >> shift) & 0x03)
  187524. == trans_values->gray)
  187525. {
  187526. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  187527. *sp |= (png_byte)(background->gray << shift);
  187528. }
  187529. else
  187530. {
  187531. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  187532. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  187533. (p << 4) | (p << 6)] >> 6) & 0x03);
  187534. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  187535. *sp |= (png_byte)(g << shift);
  187536. }
  187537. if (!shift)
  187538. {
  187539. shift = 6;
  187540. sp++;
  187541. }
  187542. else
  187543. shift -= 2;
  187544. }
  187545. }
  187546. else
  187547. #endif
  187548. {
  187549. sp = row;
  187550. shift = 6;
  187551. for (i = 0; i < row_width; i++)
  187552. {
  187553. if ((png_uint_16)((*sp >> shift) & 0x03)
  187554. == trans_values->gray)
  187555. {
  187556. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  187557. *sp |= (png_byte)(background->gray << shift);
  187558. }
  187559. if (!shift)
  187560. {
  187561. shift = 6;
  187562. sp++;
  187563. }
  187564. else
  187565. shift -= 2;
  187566. }
  187567. }
  187568. break;
  187569. }
  187570. case 4:
  187571. {
  187572. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187573. if (gamma_table != NULL)
  187574. {
  187575. sp = row;
  187576. shift = 4;
  187577. for (i = 0; i < row_width; i++)
  187578. {
  187579. if ((png_uint_16)((*sp >> shift) & 0x0f)
  187580. == trans_values->gray)
  187581. {
  187582. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  187583. *sp |= (png_byte)(background->gray << shift);
  187584. }
  187585. else
  187586. {
  187587. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  187588. png_byte g = (png_byte)((gamma_table[p |
  187589. (p << 4)] >> 4) & 0x0f);
  187590. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  187591. *sp |= (png_byte)(g << shift);
  187592. }
  187593. if (!shift)
  187594. {
  187595. shift = 4;
  187596. sp++;
  187597. }
  187598. else
  187599. shift -= 4;
  187600. }
  187601. }
  187602. else
  187603. #endif
  187604. {
  187605. sp = row;
  187606. shift = 4;
  187607. for (i = 0; i < row_width; i++)
  187608. {
  187609. if ((png_uint_16)((*sp >> shift) & 0x0f)
  187610. == trans_values->gray)
  187611. {
  187612. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  187613. *sp |= (png_byte)(background->gray << shift);
  187614. }
  187615. if (!shift)
  187616. {
  187617. shift = 4;
  187618. sp++;
  187619. }
  187620. else
  187621. shift -= 4;
  187622. }
  187623. }
  187624. break;
  187625. }
  187626. case 8:
  187627. {
  187628. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187629. if (gamma_table != NULL)
  187630. {
  187631. sp = row;
  187632. for (i = 0; i < row_width; i++, sp++)
  187633. {
  187634. if (*sp == trans_values->gray)
  187635. {
  187636. *sp = (png_byte)background->gray;
  187637. }
  187638. else
  187639. {
  187640. *sp = gamma_table[*sp];
  187641. }
  187642. }
  187643. }
  187644. else
  187645. #endif
  187646. {
  187647. sp = row;
  187648. for (i = 0; i < row_width; i++, sp++)
  187649. {
  187650. if (*sp == trans_values->gray)
  187651. {
  187652. *sp = (png_byte)background->gray;
  187653. }
  187654. }
  187655. }
  187656. break;
  187657. }
  187658. case 16:
  187659. {
  187660. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187661. if (gamma_16 != NULL)
  187662. {
  187663. sp = row;
  187664. for (i = 0; i < row_width; i++, sp += 2)
  187665. {
  187666. png_uint_16 v;
  187667. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187668. if (v == trans_values->gray)
  187669. {
  187670. /* background is already in screen gamma */
  187671. *sp = (png_byte)((background->gray >> 8) & 0xff);
  187672. *(sp + 1) = (png_byte)(background->gray & 0xff);
  187673. }
  187674. else
  187675. {
  187676. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187677. *sp = (png_byte)((v >> 8) & 0xff);
  187678. *(sp + 1) = (png_byte)(v & 0xff);
  187679. }
  187680. }
  187681. }
  187682. else
  187683. #endif
  187684. {
  187685. sp = row;
  187686. for (i = 0; i < row_width; i++, sp += 2)
  187687. {
  187688. png_uint_16 v;
  187689. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187690. if (v == trans_values->gray)
  187691. {
  187692. *sp = (png_byte)((background->gray >> 8) & 0xff);
  187693. *(sp + 1) = (png_byte)(background->gray & 0xff);
  187694. }
  187695. }
  187696. }
  187697. break;
  187698. }
  187699. }
  187700. break;
  187701. }
  187702. case PNG_COLOR_TYPE_RGB:
  187703. {
  187704. if (row_info->bit_depth == 8)
  187705. {
  187706. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187707. if (gamma_table != NULL)
  187708. {
  187709. sp = row;
  187710. for (i = 0; i < row_width; i++, sp += 3)
  187711. {
  187712. if (*sp == trans_values->red &&
  187713. *(sp + 1) == trans_values->green &&
  187714. *(sp + 2) == trans_values->blue)
  187715. {
  187716. *sp = (png_byte)background->red;
  187717. *(sp + 1) = (png_byte)background->green;
  187718. *(sp + 2) = (png_byte)background->blue;
  187719. }
  187720. else
  187721. {
  187722. *sp = gamma_table[*sp];
  187723. *(sp + 1) = gamma_table[*(sp + 1)];
  187724. *(sp + 2) = gamma_table[*(sp + 2)];
  187725. }
  187726. }
  187727. }
  187728. else
  187729. #endif
  187730. {
  187731. sp = row;
  187732. for (i = 0; i < row_width; i++, sp += 3)
  187733. {
  187734. if (*sp == trans_values->red &&
  187735. *(sp + 1) == trans_values->green &&
  187736. *(sp + 2) == trans_values->blue)
  187737. {
  187738. *sp = (png_byte)background->red;
  187739. *(sp + 1) = (png_byte)background->green;
  187740. *(sp + 2) = (png_byte)background->blue;
  187741. }
  187742. }
  187743. }
  187744. }
  187745. else /* if (row_info->bit_depth == 16) */
  187746. {
  187747. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187748. if (gamma_16 != NULL)
  187749. {
  187750. sp = row;
  187751. for (i = 0; i < row_width; i++, sp += 6)
  187752. {
  187753. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187754. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  187755. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  187756. if (r == trans_values->red && g == trans_values->green &&
  187757. b == trans_values->blue)
  187758. {
  187759. /* background is already in screen gamma */
  187760. *sp = (png_byte)((background->red >> 8) & 0xff);
  187761. *(sp + 1) = (png_byte)(background->red & 0xff);
  187762. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187763. *(sp + 3) = (png_byte)(background->green & 0xff);
  187764. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187765. *(sp + 5) = (png_byte)(background->blue & 0xff);
  187766. }
  187767. else
  187768. {
  187769. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187770. *sp = (png_byte)((v >> 8) & 0xff);
  187771. *(sp + 1) = (png_byte)(v & 0xff);
  187772. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187773. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  187774. *(sp + 3) = (png_byte)(v & 0xff);
  187775. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187776. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  187777. *(sp + 5) = (png_byte)(v & 0xff);
  187778. }
  187779. }
  187780. }
  187781. else
  187782. #endif
  187783. {
  187784. sp = row;
  187785. for (i = 0; i < row_width; i++, sp += 6)
  187786. {
  187787. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  187788. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  187789. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  187790. if (r == trans_values->red && g == trans_values->green &&
  187791. b == trans_values->blue)
  187792. {
  187793. *sp = (png_byte)((background->red >> 8) & 0xff);
  187794. *(sp + 1) = (png_byte)(background->red & 0xff);
  187795. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187796. *(sp + 3) = (png_byte)(background->green & 0xff);
  187797. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187798. *(sp + 5) = (png_byte)(background->blue & 0xff);
  187799. }
  187800. }
  187801. }
  187802. }
  187803. break;
  187804. }
  187805. case PNG_COLOR_TYPE_GRAY_ALPHA:
  187806. {
  187807. if (row_info->bit_depth == 8)
  187808. {
  187809. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187810. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  187811. gamma_table != NULL)
  187812. {
  187813. sp = row;
  187814. dp = row;
  187815. for (i = 0; i < row_width; i++, sp += 2, dp++)
  187816. {
  187817. png_uint_16 a = *(sp + 1);
  187818. if (a == 0xff)
  187819. {
  187820. *dp = gamma_table[*sp];
  187821. }
  187822. else if (a == 0)
  187823. {
  187824. /* background is already in screen gamma */
  187825. *dp = (png_byte)background->gray;
  187826. }
  187827. else
  187828. {
  187829. png_byte v, w;
  187830. v = gamma_to_1[*sp];
  187831. png_composite(w, v, a, background_1->gray);
  187832. *dp = gamma_from_1[w];
  187833. }
  187834. }
  187835. }
  187836. else
  187837. #endif
  187838. {
  187839. sp = row;
  187840. dp = row;
  187841. for (i = 0; i < row_width; i++, sp += 2, dp++)
  187842. {
  187843. png_byte a = *(sp + 1);
  187844. if (a == 0xff)
  187845. {
  187846. *dp = *sp;
  187847. }
  187848. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187849. else if (a == 0)
  187850. {
  187851. *dp = (png_byte)background->gray;
  187852. }
  187853. else
  187854. {
  187855. png_composite(*dp, *sp, a, background_1->gray);
  187856. }
  187857. #else
  187858. *dp = (png_byte)background->gray;
  187859. #endif
  187860. }
  187861. }
  187862. }
  187863. else /* if (png_ptr->bit_depth == 16) */
  187864. {
  187865. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187866. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  187867. gamma_16_to_1 != NULL)
  187868. {
  187869. sp = row;
  187870. dp = row;
  187871. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  187872. {
  187873. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  187874. if (a == (png_uint_16)0xffff)
  187875. {
  187876. png_uint_16 v;
  187877. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187878. *dp = (png_byte)((v >> 8) & 0xff);
  187879. *(dp + 1) = (png_byte)(v & 0xff);
  187880. }
  187881. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187882. else if (a == 0)
  187883. #else
  187884. else
  187885. #endif
  187886. {
  187887. /* background is already in screen gamma */
  187888. *dp = (png_byte)((background->gray >> 8) & 0xff);
  187889. *(dp + 1) = (png_byte)(background->gray & 0xff);
  187890. }
  187891. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187892. else
  187893. {
  187894. png_uint_16 g, v, w;
  187895. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  187896. png_composite_16(v, g, a, background_1->gray);
  187897. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  187898. *dp = (png_byte)((w >> 8) & 0xff);
  187899. *(dp + 1) = (png_byte)(w & 0xff);
  187900. }
  187901. #endif
  187902. }
  187903. }
  187904. else
  187905. #endif
  187906. {
  187907. sp = row;
  187908. dp = row;
  187909. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  187910. {
  187911. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  187912. if (a == (png_uint_16)0xffff)
  187913. {
  187914. png_memcpy(dp, sp, 2);
  187915. }
  187916. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187917. else if (a == 0)
  187918. #else
  187919. else
  187920. #endif
  187921. {
  187922. *dp = (png_byte)((background->gray >> 8) & 0xff);
  187923. *(dp + 1) = (png_byte)(background->gray & 0xff);
  187924. }
  187925. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187926. else
  187927. {
  187928. png_uint_16 g, v;
  187929. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187930. png_composite_16(v, g, a, background_1->gray);
  187931. *dp = (png_byte)((v >> 8) & 0xff);
  187932. *(dp + 1) = (png_byte)(v & 0xff);
  187933. }
  187934. #endif
  187935. }
  187936. }
  187937. }
  187938. break;
  187939. }
  187940. case PNG_COLOR_TYPE_RGB_ALPHA:
  187941. {
  187942. if (row_info->bit_depth == 8)
  187943. {
  187944. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187945. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  187946. gamma_table != NULL)
  187947. {
  187948. sp = row;
  187949. dp = row;
  187950. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  187951. {
  187952. png_byte a = *(sp + 3);
  187953. if (a == 0xff)
  187954. {
  187955. *dp = gamma_table[*sp];
  187956. *(dp + 1) = gamma_table[*(sp + 1)];
  187957. *(dp + 2) = gamma_table[*(sp + 2)];
  187958. }
  187959. else if (a == 0)
  187960. {
  187961. /* background is already in screen gamma */
  187962. *dp = (png_byte)background->red;
  187963. *(dp + 1) = (png_byte)background->green;
  187964. *(dp + 2) = (png_byte)background->blue;
  187965. }
  187966. else
  187967. {
  187968. png_byte v, w;
  187969. v = gamma_to_1[*sp];
  187970. png_composite(w, v, a, background_1->red);
  187971. *dp = gamma_from_1[w];
  187972. v = gamma_to_1[*(sp + 1)];
  187973. png_composite(w, v, a, background_1->green);
  187974. *(dp + 1) = gamma_from_1[w];
  187975. v = gamma_to_1[*(sp + 2)];
  187976. png_composite(w, v, a, background_1->blue);
  187977. *(dp + 2) = gamma_from_1[w];
  187978. }
  187979. }
  187980. }
  187981. else
  187982. #endif
  187983. {
  187984. sp = row;
  187985. dp = row;
  187986. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  187987. {
  187988. png_byte a = *(sp + 3);
  187989. if (a == 0xff)
  187990. {
  187991. *dp = *sp;
  187992. *(dp + 1) = *(sp + 1);
  187993. *(dp + 2) = *(sp + 2);
  187994. }
  187995. else if (a == 0)
  187996. {
  187997. *dp = (png_byte)background->red;
  187998. *(dp + 1) = (png_byte)background->green;
  187999. *(dp + 2) = (png_byte)background->blue;
  188000. }
  188001. else
  188002. {
  188003. png_composite(*dp, *sp, a, background->red);
  188004. png_composite(*(dp + 1), *(sp + 1), a,
  188005. background->green);
  188006. png_composite(*(dp + 2), *(sp + 2), a,
  188007. background->blue);
  188008. }
  188009. }
  188010. }
  188011. }
  188012. else /* if (row_info->bit_depth == 16) */
  188013. {
  188014. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188015. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188016. gamma_16_to_1 != NULL)
  188017. {
  188018. sp = row;
  188019. dp = row;
  188020. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188021. {
  188022. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188023. << 8) + (png_uint_16)(*(sp + 7)));
  188024. if (a == (png_uint_16)0xffff)
  188025. {
  188026. png_uint_16 v;
  188027. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188028. *dp = (png_byte)((v >> 8) & 0xff);
  188029. *(dp + 1) = (png_byte)(v & 0xff);
  188030. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188031. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188032. *(dp + 3) = (png_byte)(v & 0xff);
  188033. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188034. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188035. *(dp + 5) = (png_byte)(v & 0xff);
  188036. }
  188037. else if (a == 0)
  188038. {
  188039. /* background is already in screen gamma */
  188040. *dp = (png_byte)((background->red >> 8) & 0xff);
  188041. *(dp + 1) = (png_byte)(background->red & 0xff);
  188042. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188043. *(dp + 3) = (png_byte)(background->green & 0xff);
  188044. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188045. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188046. }
  188047. else
  188048. {
  188049. png_uint_16 v, w, x;
  188050. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188051. png_composite_16(w, v, a, background_1->red);
  188052. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188053. *dp = (png_byte)((x >> 8) & 0xff);
  188054. *(dp + 1) = (png_byte)(x & 0xff);
  188055. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188056. png_composite_16(w, v, a, background_1->green);
  188057. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188058. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  188059. *(dp + 3) = (png_byte)(x & 0xff);
  188060. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188061. png_composite_16(w, v, a, background_1->blue);
  188062. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  188063. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  188064. *(dp + 5) = (png_byte)(x & 0xff);
  188065. }
  188066. }
  188067. }
  188068. else
  188069. #endif
  188070. {
  188071. sp = row;
  188072. dp = row;
  188073. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188074. {
  188075. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188076. << 8) + (png_uint_16)(*(sp + 7)));
  188077. if (a == (png_uint_16)0xffff)
  188078. {
  188079. png_memcpy(dp, sp, 6);
  188080. }
  188081. else if (a == 0)
  188082. {
  188083. *dp = (png_byte)((background->red >> 8) & 0xff);
  188084. *(dp + 1) = (png_byte)(background->red & 0xff);
  188085. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188086. *(dp + 3) = (png_byte)(background->green & 0xff);
  188087. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188088. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188089. }
  188090. else
  188091. {
  188092. png_uint_16 v;
  188093. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188094. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  188095. + *(sp + 3));
  188096. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  188097. + *(sp + 5));
  188098. png_composite_16(v, r, a, background->red);
  188099. *dp = (png_byte)((v >> 8) & 0xff);
  188100. *(dp + 1) = (png_byte)(v & 0xff);
  188101. png_composite_16(v, g, a, background->green);
  188102. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188103. *(dp + 3) = (png_byte)(v & 0xff);
  188104. png_composite_16(v, b, a, background->blue);
  188105. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188106. *(dp + 5) = (png_byte)(v & 0xff);
  188107. }
  188108. }
  188109. }
  188110. }
  188111. break;
  188112. }
  188113. }
  188114. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  188115. {
  188116. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188117. row_info->channels--;
  188118. row_info->pixel_depth = (png_byte)(row_info->channels *
  188119. row_info->bit_depth);
  188120. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188121. }
  188122. }
  188123. }
  188124. #endif
  188125. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188126. /* Gamma correct the image, avoiding the alpha channel. Make sure
  188127. * you do this after you deal with the transparency issue on grayscale
  188128. * or RGB images. If your bit depth is 8, use gamma_table, if it
  188129. * is 16, use gamma_16_table and gamma_shift. Build these with
  188130. * build_gamma_table().
  188131. */
  188132. void /* PRIVATE */
  188133. png_do_gamma(png_row_infop row_info, png_bytep row,
  188134. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  188135. int gamma_shift)
  188136. {
  188137. png_bytep sp;
  188138. png_uint_32 i;
  188139. png_uint_32 row_width=row_info->width;
  188140. png_debug(1, "in png_do_gamma\n");
  188141. if (
  188142. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188143. row != NULL && row_info != NULL &&
  188144. #endif
  188145. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  188146. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  188147. {
  188148. switch (row_info->color_type)
  188149. {
  188150. case PNG_COLOR_TYPE_RGB:
  188151. {
  188152. if (row_info->bit_depth == 8)
  188153. {
  188154. sp = row;
  188155. for (i = 0; i < row_width; i++)
  188156. {
  188157. *sp = gamma_table[*sp];
  188158. sp++;
  188159. *sp = gamma_table[*sp];
  188160. sp++;
  188161. *sp = gamma_table[*sp];
  188162. sp++;
  188163. }
  188164. }
  188165. else /* if (row_info->bit_depth == 16) */
  188166. {
  188167. sp = row;
  188168. for (i = 0; i < row_width; i++)
  188169. {
  188170. png_uint_16 v;
  188171. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188172. *sp = (png_byte)((v >> 8) & 0xff);
  188173. *(sp + 1) = (png_byte)(v & 0xff);
  188174. sp += 2;
  188175. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188176. *sp = (png_byte)((v >> 8) & 0xff);
  188177. *(sp + 1) = (png_byte)(v & 0xff);
  188178. sp += 2;
  188179. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188180. *sp = (png_byte)((v >> 8) & 0xff);
  188181. *(sp + 1) = (png_byte)(v & 0xff);
  188182. sp += 2;
  188183. }
  188184. }
  188185. break;
  188186. }
  188187. case PNG_COLOR_TYPE_RGB_ALPHA:
  188188. {
  188189. if (row_info->bit_depth == 8)
  188190. {
  188191. sp = row;
  188192. for (i = 0; i < row_width; i++)
  188193. {
  188194. *sp = gamma_table[*sp];
  188195. sp++;
  188196. *sp = gamma_table[*sp];
  188197. sp++;
  188198. *sp = gamma_table[*sp];
  188199. sp++;
  188200. sp++;
  188201. }
  188202. }
  188203. else /* if (row_info->bit_depth == 16) */
  188204. {
  188205. sp = row;
  188206. for (i = 0; i < row_width; i++)
  188207. {
  188208. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188209. *sp = (png_byte)((v >> 8) & 0xff);
  188210. *(sp + 1) = (png_byte)(v & 0xff);
  188211. sp += 2;
  188212. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188213. *sp = (png_byte)((v >> 8) & 0xff);
  188214. *(sp + 1) = (png_byte)(v & 0xff);
  188215. sp += 2;
  188216. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188217. *sp = (png_byte)((v >> 8) & 0xff);
  188218. *(sp + 1) = (png_byte)(v & 0xff);
  188219. sp += 4;
  188220. }
  188221. }
  188222. break;
  188223. }
  188224. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188225. {
  188226. if (row_info->bit_depth == 8)
  188227. {
  188228. sp = row;
  188229. for (i = 0; i < row_width; i++)
  188230. {
  188231. *sp = gamma_table[*sp];
  188232. sp += 2;
  188233. }
  188234. }
  188235. else /* if (row_info->bit_depth == 16) */
  188236. {
  188237. sp = row;
  188238. for (i = 0; i < row_width; i++)
  188239. {
  188240. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188241. *sp = (png_byte)((v >> 8) & 0xff);
  188242. *(sp + 1) = (png_byte)(v & 0xff);
  188243. sp += 4;
  188244. }
  188245. }
  188246. break;
  188247. }
  188248. case PNG_COLOR_TYPE_GRAY:
  188249. {
  188250. if (row_info->bit_depth == 2)
  188251. {
  188252. sp = row;
  188253. for (i = 0; i < row_width; i += 4)
  188254. {
  188255. int a = *sp & 0xc0;
  188256. int b = *sp & 0x30;
  188257. int c = *sp & 0x0c;
  188258. int d = *sp & 0x03;
  188259. *sp = (png_byte)(
  188260. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  188261. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  188262. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  188263. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  188264. sp++;
  188265. }
  188266. }
  188267. if (row_info->bit_depth == 4)
  188268. {
  188269. sp = row;
  188270. for (i = 0; i < row_width; i += 2)
  188271. {
  188272. int msb = *sp & 0xf0;
  188273. int lsb = *sp & 0x0f;
  188274. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  188275. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  188276. sp++;
  188277. }
  188278. }
  188279. else if (row_info->bit_depth == 8)
  188280. {
  188281. sp = row;
  188282. for (i = 0; i < row_width; i++)
  188283. {
  188284. *sp = gamma_table[*sp];
  188285. sp++;
  188286. }
  188287. }
  188288. else if (row_info->bit_depth == 16)
  188289. {
  188290. sp = row;
  188291. for (i = 0; i < row_width; i++)
  188292. {
  188293. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188294. *sp = (png_byte)((v >> 8) & 0xff);
  188295. *(sp + 1) = (png_byte)(v & 0xff);
  188296. sp += 2;
  188297. }
  188298. }
  188299. break;
  188300. }
  188301. }
  188302. }
  188303. }
  188304. #endif
  188305. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188306. /* Expands a palette row to an RGB or RGBA row depending
  188307. * upon whether you supply trans and num_trans.
  188308. */
  188309. void /* PRIVATE */
  188310. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  188311. png_colorp palette, png_bytep trans, int num_trans)
  188312. {
  188313. int shift, value;
  188314. png_bytep sp, dp;
  188315. png_uint_32 i;
  188316. png_uint_32 row_width=row_info->width;
  188317. png_debug(1, "in png_do_expand_palette\n");
  188318. if (
  188319. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188320. row != NULL && row_info != NULL &&
  188321. #endif
  188322. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  188323. {
  188324. if (row_info->bit_depth < 8)
  188325. {
  188326. switch (row_info->bit_depth)
  188327. {
  188328. case 1:
  188329. {
  188330. sp = row + (png_size_t)((row_width - 1) >> 3);
  188331. dp = row + (png_size_t)row_width - 1;
  188332. shift = 7 - (int)((row_width + 7) & 0x07);
  188333. for (i = 0; i < row_width; i++)
  188334. {
  188335. if ((*sp >> shift) & 0x01)
  188336. *dp = 1;
  188337. else
  188338. *dp = 0;
  188339. if (shift == 7)
  188340. {
  188341. shift = 0;
  188342. sp--;
  188343. }
  188344. else
  188345. shift++;
  188346. dp--;
  188347. }
  188348. break;
  188349. }
  188350. case 2:
  188351. {
  188352. sp = row + (png_size_t)((row_width - 1) >> 2);
  188353. dp = row + (png_size_t)row_width - 1;
  188354. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188355. for (i = 0; i < row_width; i++)
  188356. {
  188357. value = (*sp >> shift) & 0x03;
  188358. *dp = (png_byte)value;
  188359. if (shift == 6)
  188360. {
  188361. shift = 0;
  188362. sp--;
  188363. }
  188364. else
  188365. shift += 2;
  188366. dp--;
  188367. }
  188368. break;
  188369. }
  188370. case 4:
  188371. {
  188372. sp = row + (png_size_t)((row_width - 1) >> 1);
  188373. dp = row + (png_size_t)row_width - 1;
  188374. shift = (int)((row_width & 0x01) << 2);
  188375. for (i = 0; i < row_width; i++)
  188376. {
  188377. value = (*sp >> shift) & 0x0f;
  188378. *dp = (png_byte)value;
  188379. if (shift == 4)
  188380. {
  188381. shift = 0;
  188382. sp--;
  188383. }
  188384. else
  188385. shift += 4;
  188386. dp--;
  188387. }
  188388. break;
  188389. }
  188390. }
  188391. row_info->bit_depth = 8;
  188392. row_info->pixel_depth = 8;
  188393. row_info->rowbytes = row_width;
  188394. }
  188395. switch (row_info->bit_depth)
  188396. {
  188397. case 8:
  188398. {
  188399. if (trans != NULL)
  188400. {
  188401. sp = row + (png_size_t)row_width - 1;
  188402. dp = row + (png_size_t)(row_width << 2) - 1;
  188403. for (i = 0; i < row_width; i++)
  188404. {
  188405. if ((int)(*sp) >= num_trans)
  188406. *dp-- = 0xff;
  188407. else
  188408. *dp-- = trans[*sp];
  188409. *dp-- = palette[*sp].blue;
  188410. *dp-- = palette[*sp].green;
  188411. *dp-- = palette[*sp].red;
  188412. sp--;
  188413. }
  188414. row_info->bit_depth = 8;
  188415. row_info->pixel_depth = 32;
  188416. row_info->rowbytes = row_width * 4;
  188417. row_info->color_type = 6;
  188418. row_info->channels = 4;
  188419. }
  188420. else
  188421. {
  188422. sp = row + (png_size_t)row_width - 1;
  188423. dp = row + (png_size_t)(row_width * 3) - 1;
  188424. for (i = 0; i < row_width; i++)
  188425. {
  188426. *dp-- = palette[*sp].blue;
  188427. *dp-- = palette[*sp].green;
  188428. *dp-- = palette[*sp].red;
  188429. sp--;
  188430. }
  188431. row_info->bit_depth = 8;
  188432. row_info->pixel_depth = 24;
  188433. row_info->rowbytes = row_width * 3;
  188434. row_info->color_type = 2;
  188435. row_info->channels = 3;
  188436. }
  188437. break;
  188438. }
  188439. }
  188440. }
  188441. }
  188442. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  188443. * expanded transparency value is supplied, an alpha channel is built.
  188444. */
  188445. void /* PRIVATE */
  188446. png_do_expand(png_row_infop row_info, png_bytep row,
  188447. png_color_16p trans_value)
  188448. {
  188449. int shift, value;
  188450. png_bytep sp, dp;
  188451. png_uint_32 i;
  188452. png_uint_32 row_width=row_info->width;
  188453. png_debug(1, "in png_do_expand\n");
  188454. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188455. if (row != NULL && row_info != NULL)
  188456. #endif
  188457. {
  188458. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188459. {
  188460. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  188461. if (row_info->bit_depth < 8)
  188462. {
  188463. switch (row_info->bit_depth)
  188464. {
  188465. case 1:
  188466. {
  188467. gray = (png_uint_16)((gray&0x01)*0xff);
  188468. sp = row + (png_size_t)((row_width - 1) >> 3);
  188469. dp = row + (png_size_t)row_width - 1;
  188470. shift = 7 - (int)((row_width + 7) & 0x07);
  188471. for (i = 0; i < row_width; i++)
  188472. {
  188473. if ((*sp >> shift) & 0x01)
  188474. *dp = 0xff;
  188475. else
  188476. *dp = 0;
  188477. if (shift == 7)
  188478. {
  188479. shift = 0;
  188480. sp--;
  188481. }
  188482. else
  188483. shift++;
  188484. dp--;
  188485. }
  188486. break;
  188487. }
  188488. case 2:
  188489. {
  188490. gray = (png_uint_16)((gray&0x03)*0x55);
  188491. sp = row + (png_size_t)((row_width - 1) >> 2);
  188492. dp = row + (png_size_t)row_width - 1;
  188493. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188494. for (i = 0; i < row_width; i++)
  188495. {
  188496. value = (*sp >> shift) & 0x03;
  188497. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  188498. (value << 6));
  188499. if (shift == 6)
  188500. {
  188501. shift = 0;
  188502. sp--;
  188503. }
  188504. else
  188505. shift += 2;
  188506. dp--;
  188507. }
  188508. break;
  188509. }
  188510. case 4:
  188511. {
  188512. gray = (png_uint_16)((gray&0x0f)*0x11);
  188513. sp = row + (png_size_t)((row_width - 1) >> 1);
  188514. dp = row + (png_size_t)row_width - 1;
  188515. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  188516. for (i = 0; i < row_width; i++)
  188517. {
  188518. value = (*sp >> shift) & 0x0f;
  188519. *dp = (png_byte)(value | (value << 4));
  188520. if (shift == 4)
  188521. {
  188522. shift = 0;
  188523. sp--;
  188524. }
  188525. else
  188526. shift = 4;
  188527. dp--;
  188528. }
  188529. break;
  188530. }
  188531. }
  188532. row_info->bit_depth = 8;
  188533. row_info->pixel_depth = 8;
  188534. row_info->rowbytes = row_width;
  188535. }
  188536. if (trans_value != NULL)
  188537. {
  188538. if (row_info->bit_depth == 8)
  188539. {
  188540. gray = gray & 0xff;
  188541. sp = row + (png_size_t)row_width - 1;
  188542. dp = row + (png_size_t)(row_width << 1) - 1;
  188543. for (i = 0; i < row_width; i++)
  188544. {
  188545. if (*sp == gray)
  188546. *dp-- = 0;
  188547. else
  188548. *dp-- = 0xff;
  188549. *dp-- = *sp--;
  188550. }
  188551. }
  188552. else if (row_info->bit_depth == 16)
  188553. {
  188554. png_byte gray_high = (gray >> 8) & 0xff;
  188555. png_byte gray_low = gray & 0xff;
  188556. sp = row + row_info->rowbytes - 1;
  188557. dp = row + (row_info->rowbytes << 1) - 1;
  188558. for (i = 0; i < row_width; i++)
  188559. {
  188560. if (*(sp-1) == gray_high && *(sp) == gray_low)
  188561. {
  188562. *dp-- = 0;
  188563. *dp-- = 0;
  188564. }
  188565. else
  188566. {
  188567. *dp-- = 0xff;
  188568. *dp-- = 0xff;
  188569. }
  188570. *dp-- = *sp--;
  188571. *dp-- = *sp--;
  188572. }
  188573. }
  188574. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  188575. row_info->channels = 2;
  188576. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  188577. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  188578. row_width);
  188579. }
  188580. }
  188581. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  188582. {
  188583. if (row_info->bit_depth == 8)
  188584. {
  188585. png_byte red = trans_value->red & 0xff;
  188586. png_byte green = trans_value->green & 0xff;
  188587. png_byte blue = trans_value->blue & 0xff;
  188588. sp = row + (png_size_t)row_info->rowbytes - 1;
  188589. dp = row + (png_size_t)(row_width << 2) - 1;
  188590. for (i = 0; i < row_width; i++)
  188591. {
  188592. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  188593. *dp-- = 0;
  188594. else
  188595. *dp-- = 0xff;
  188596. *dp-- = *sp--;
  188597. *dp-- = *sp--;
  188598. *dp-- = *sp--;
  188599. }
  188600. }
  188601. else if (row_info->bit_depth == 16)
  188602. {
  188603. png_byte red_high = (trans_value->red >> 8) & 0xff;
  188604. png_byte green_high = (trans_value->green >> 8) & 0xff;
  188605. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  188606. png_byte red_low = trans_value->red & 0xff;
  188607. png_byte green_low = trans_value->green & 0xff;
  188608. png_byte blue_low = trans_value->blue & 0xff;
  188609. sp = row + row_info->rowbytes - 1;
  188610. dp = row + (png_size_t)(row_width << 3) - 1;
  188611. for (i = 0; i < row_width; i++)
  188612. {
  188613. if (*(sp - 5) == red_high &&
  188614. *(sp - 4) == red_low &&
  188615. *(sp - 3) == green_high &&
  188616. *(sp - 2) == green_low &&
  188617. *(sp - 1) == blue_high &&
  188618. *(sp ) == blue_low)
  188619. {
  188620. *dp-- = 0;
  188621. *dp-- = 0;
  188622. }
  188623. else
  188624. {
  188625. *dp-- = 0xff;
  188626. *dp-- = 0xff;
  188627. }
  188628. *dp-- = *sp--;
  188629. *dp-- = *sp--;
  188630. *dp-- = *sp--;
  188631. *dp-- = *sp--;
  188632. *dp-- = *sp--;
  188633. *dp-- = *sp--;
  188634. }
  188635. }
  188636. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  188637. row_info->channels = 4;
  188638. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  188639. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188640. }
  188641. }
  188642. }
  188643. #endif
  188644. #if defined(PNG_READ_DITHER_SUPPORTED)
  188645. void /* PRIVATE */
  188646. png_do_dither(png_row_infop row_info, png_bytep row,
  188647. png_bytep palette_lookup, png_bytep dither_lookup)
  188648. {
  188649. png_bytep sp, dp;
  188650. png_uint_32 i;
  188651. png_uint_32 row_width=row_info->width;
  188652. png_debug(1, "in png_do_dither\n");
  188653. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188654. if (row != NULL && row_info != NULL)
  188655. #endif
  188656. {
  188657. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  188658. palette_lookup && row_info->bit_depth == 8)
  188659. {
  188660. int r, g, b, p;
  188661. sp = row;
  188662. dp = row;
  188663. for (i = 0; i < row_width; i++)
  188664. {
  188665. r = *sp++;
  188666. g = *sp++;
  188667. b = *sp++;
  188668. /* this looks real messy, but the compiler will reduce
  188669. it down to a reasonable formula. For example, with
  188670. 5 bits per color, we get:
  188671. p = (((r >> 3) & 0x1f) << 10) |
  188672. (((g >> 3) & 0x1f) << 5) |
  188673. ((b >> 3) & 0x1f);
  188674. */
  188675. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  188676. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  188677. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  188678. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  188679. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  188680. (PNG_DITHER_BLUE_BITS)) |
  188681. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  188682. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  188683. *dp++ = palette_lookup[p];
  188684. }
  188685. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  188686. row_info->channels = 1;
  188687. row_info->pixel_depth = row_info->bit_depth;
  188688. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188689. }
  188690. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  188691. palette_lookup != NULL && row_info->bit_depth == 8)
  188692. {
  188693. int r, g, b, p;
  188694. sp = row;
  188695. dp = row;
  188696. for (i = 0; i < row_width; i++)
  188697. {
  188698. r = *sp++;
  188699. g = *sp++;
  188700. b = *sp++;
  188701. sp++;
  188702. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  188703. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  188704. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  188705. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  188706. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  188707. (PNG_DITHER_BLUE_BITS)) |
  188708. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  188709. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  188710. *dp++ = palette_lookup[p];
  188711. }
  188712. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  188713. row_info->channels = 1;
  188714. row_info->pixel_depth = row_info->bit_depth;
  188715. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188716. }
  188717. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  188718. dither_lookup && row_info->bit_depth == 8)
  188719. {
  188720. sp = row;
  188721. for (i = 0; i < row_width; i++, sp++)
  188722. {
  188723. *sp = dither_lookup[*sp];
  188724. }
  188725. }
  188726. }
  188727. }
  188728. #endif
  188729. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188730. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188731. static PNG_CONST int png_gamma_shift[] =
  188732. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  188733. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  188734. * tables, we don't make a full table if we are reducing to 8-bit in
  188735. * the future. Note also how the gamma_16 tables are segmented so that
  188736. * we don't need to allocate > 64K chunks for a full 16-bit table.
  188737. */
  188738. void /* PRIVATE */
  188739. png_build_gamma_table(png_structp png_ptr)
  188740. {
  188741. png_debug(1, "in png_build_gamma_table\n");
  188742. if (png_ptr->bit_depth <= 8)
  188743. {
  188744. int i;
  188745. double g;
  188746. if (png_ptr->screen_gamma > .000001)
  188747. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  188748. else
  188749. g = 1.0;
  188750. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  188751. (png_uint_32)256);
  188752. for (i = 0; i < 256; i++)
  188753. {
  188754. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  188755. g) * 255.0 + .5);
  188756. }
  188757. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  188758. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188759. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  188760. {
  188761. g = 1.0 / (png_ptr->gamma);
  188762. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  188763. (png_uint_32)256);
  188764. for (i = 0; i < 256; i++)
  188765. {
  188766. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  188767. g) * 255.0 + .5);
  188768. }
  188769. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  188770. (png_uint_32)256);
  188771. if(png_ptr->screen_gamma > 0.000001)
  188772. g = 1.0 / png_ptr->screen_gamma;
  188773. else
  188774. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  188775. for (i = 0; i < 256; i++)
  188776. {
  188777. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  188778. g) * 255.0 + .5);
  188779. }
  188780. }
  188781. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  188782. }
  188783. else
  188784. {
  188785. double g;
  188786. int i, j, shift, num;
  188787. int sig_bit;
  188788. png_uint_32 ig;
  188789. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188790. {
  188791. sig_bit = (int)png_ptr->sig_bit.red;
  188792. if ((int)png_ptr->sig_bit.green > sig_bit)
  188793. sig_bit = png_ptr->sig_bit.green;
  188794. if ((int)png_ptr->sig_bit.blue > sig_bit)
  188795. sig_bit = png_ptr->sig_bit.blue;
  188796. }
  188797. else
  188798. {
  188799. sig_bit = (int)png_ptr->sig_bit.gray;
  188800. }
  188801. if (sig_bit > 0)
  188802. shift = 16 - sig_bit;
  188803. else
  188804. shift = 0;
  188805. if (png_ptr->transformations & PNG_16_TO_8)
  188806. {
  188807. if (shift < (16 - PNG_MAX_GAMMA_8))
  188808. shift = (16 - PNG_MAX_GAMMA_8);
  188809. }
  188810. if (shift > 8)
  188811. shift = 8;
  188812. if (shift < 0)
  188813. shift = 0;
  188814. png_ptr->gamma_shift = (png_byte)shift;
  188815. num = (1 << (8 - shift));
  188816. if (png_ptr->screen_gamma > .000001)
  188817. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  188818. else
  188819. g = 1.0;
  188820. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  188821. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  188822. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  188823. {
  188824. double fin, fout;
  188825. png_uint_32 last, max;
  188826. for (i = 0; i < num; i++)
  188827. {
  188828. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  188829. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  188830. }
  188831. g = 1.0 / g;
  188832. last = 0;
  188833. for (i = 0; i < 256; i++)
  188834. {
  188835. fout = ((double)i + 0.5) / 256.0;
  188836. fin = pow(fout, g);
  188837. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  188838. while (last <= max)
  188839. {
  188840. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  188841. [(int)(last >> (8 - shift))] = (png_uint_16)(
  188842. (png_uint_16)i | ((png_uint_16)i << 8));
  188843. last++;
  188844. }
  188845. }
  188846. while (last < ((png_uint_32)num << 8))
  188847. {
  188848. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  188849. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  188850. last++;
  188851. }
  188852. }
  188853. else
  188854. {
  188855. for (i = 0; i < num; i++)
  188856. {
  188857. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  188858. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  188859. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  188860. for (j = 0; j < 256; j++)
  188861. {
  188862. png_ptr->gamma_16_table[i][j] =
  188863. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  188864. 65535.0, g) * 65535.0 + .5);
  188865. }
  188866. }
  188867. }
  188868. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  188869. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188870. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  188871. {
  188872. g = 1.0 / (png_ptr->gamma);
  188873. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  188874. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  188875. for (i = 0; i < num; i++)
  188876. {
  188877. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  188878. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  188879. ig = (((png_uint_32)i *
  188880. (png_uint_32)png_gamma_shift[shift]) >> 4);
  188881. for (j = 0; j < 256; j++)
  188882. {
  188883. png_ptr->gamma_16_to_1[i][j] =
  188884. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  188885. 65535.0, g) * 65535.0 + .5);
  188886. }
  188887. }
  188888. if(png_ptr->screen_gamma > 0.000001)
  188889. g = 1.0 / png_ptr->screen_gamma;
  188890. else
  188891. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  188892. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  188893. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  188894. for (i = 0; i < num; i++)
  188895. {
  188896. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  188897. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  188898. ig = (((png_uint_32)i *
  188899. (png_uint_32)png_gamma_shift[shift]) >> 4);
  188900. for (j = 0; j < 256; j++)
  188901. {
  188902. png_ptr->gamma_16_from_1[i][j] =
  188903. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  188904. 65535.0, g) * 65535.0 + .5);
  188905. }
  188906. }
  188907. }
  188908. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  188909. }
  188910. }
  188911. #endif
  188912. /* To do: install integer version of png_build_gamma_table here */
  188913. #endif
  188914. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  188915. /* undoes intrapixel differencing */
  188916. void /* PRIVATE */
  188917. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  188918. {
  188919. png_debug(1, "in png_do_read_intrapixel\n");
  188920. if (
  188921. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188922. row != NULL && row_info != NULL &&
  188923. #endif
  188924. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  188925. {
  188926. int bytes_per_pixel;
  188927. png_uint_32 row_width = row_info->width;
  188928. if (row_info->bit_depth == 8)
  188929. {
  188930. png_bytep rp;
  188931. png_uint_32 i;
  188932. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188933. bytes_per_pixel = 3;
  188934. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188935. bytes_per_pixel = 4;
  188936. else
  188937. return;
  188938. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  188939. {
  188940. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  188941. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  188942. }
  188943. }
  188944. else if (row_info->bit_depth == 16)
  188945. {
  188946. png_bytep rp;
  188947. png_uint_32 i;
  188948. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188949. bytes_per_pixel = 6;
  188950. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188951. bytes_per_pixel = 8;
  188952. else
  188953. return;
  188954. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  188955. {
  188956. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  188957. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  188958. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  188959. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  188960. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  188961. *(rp ) = (png_byte)((red >> 8) & 0xff);
  188962. *(rp+1) = (png_byte)(red & 0xff);
  188963. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  188964. *(rp+5) = (png_byte)(blue & 0xff);
  188965. }
  188966. }
  188967. }
  188968. }
  188969. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  188970. #endif /* PNG_READ_SUPPORTED */
  188971. /********* End of inlined file: pngrtran.c *********/
  188972. /********* Start of inlined file: pngrutil.c *********/
  188973. /* pngrutil.c - utilities to read a PNG file
  188974. *
  188975. * Last changed in libpng 1.2.21 [October 4, 2007]
  188976. * For conditions of distribution and use, see copyright notice in png.h
  188977. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188978. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188979. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188980. *
  188981. * This file contains routines that are only called from within
  188982. * libpng itself during the course of reading an image.
  188983. */
  188984. #define PNG_INTERNAL
  188985. #if defined(PNG_READ_SUPPORTED)
  188986. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  188987. # define WIN32_WCE_OLD
  188988. #endif
  188989. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188990. # if defined(WIN32_WCE_OLD)
  188991. /* strtod() function is not supported on WindowsCE */
  188992. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  188993. {
  188994. double result = 0;
  188995. int len;
  188996. wchar_t *str, *end;
  188997. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  188998. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  188999. if ( NULL != str )
  189000. {
  189001. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  189002. result = wcstod(str, &end);
  189003. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  189004. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  189005. png_free(png_ptr, str);
  189006. }
  189007. return result;
  189008. }
  189009. # else
  189010. # define png_strtod(p,a,b) strtod(a,b)
  189011. # endif
  189012. #endif
  189013. png_uint_32 PNGAPI
  189014. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  189015. {
  189016. png_uint_32 i = png_get_uint_32(buf);
  189017. if (i > PNG_UINT_31_MAX)
  189018. png_error(png_ptr, "PNG unsigned integer out of range.");
  189019. return (i);
  189020. }
  189021. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  189022. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  189023. png_uint_32 PNGAPI
  189024. png_get_uint_32(png_bytep buf)
  189025. {
  189026. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  189027. ((png_uint_32)(*(buf + 1)) << 16) +
  189028. ((png_uint_32)(*(buf + 2)) << 8) +
  189029. (png_uint_32)(*(buf + 3));
  189030. return (i);
  189031. }
  189032. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  189033. * data is stored in the PNG file in two's complement format, and it is
  189034. * assumed that the machine format for signed integers is the same. */
  189035. png_int_32 PNGAPI
  189036. png_get_int_32(png_bytep buf)
  189037. {
  189038. png_int_32 i = ((png_int_32)(*buf) << 24) +
  189039. ((png_int_32)(*(buf + 1)) << 16) +
  189040. ((png_int_32)(*(buf + 2)) << 8) +
  189041. (png_int_32)(*(buf + 3));
  189042. return (i);
  189043. }
  189044. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  189045. png_uint_16 PNGAPI
  189046. png_get_uint_16(png_bytep buf)
  189047. {
  189048. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  189049. (png_uint_16)(*(buf + 1)));
  189050. return (i);
  189051. }
  189052. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  189053. /* Read data, and (optionally) run it through the CRC. */
  189054. void /* PRIVATE */
  189055. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  189056. {
  189057. if(png_ptr == NULL) return;
  189058. png_read_data(png_ptr, buf, length);
  189059. png_calculate_crc(png_ptr, buf, length);
  189060. }
  189061. /* Optionally skip data and then check the CRC. Depending on whether we
  189062. are reading a ancillary or critical chunk, and how the program has set
  189063. things up, we may calculate the CRC on the data and print a message.
  189064. Returns '1' if there was a CRC error, '0' otherwise. */
  189065. int /* PRIVATE */
  189066. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  189067. {
  189068. png_size_t i;
  189069. png_size_t istop = png_ptr->zbuf_size;
  189070. for (i = (png_size_t)skip; i > istop; i -= istop)
  189071. {
  189072. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  189073. }
  189074. if (i)
  189075. {
  189076. png_crc_read(png_ptr, png_ptr->zbuf, i);
  189077. }
  189078. if (png_crc_error(png_ptr))
  189079. {
  189080. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  189081. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  189082. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  189083. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  189084. {
  189085. png_chunk_warning(png_ptr, "CRC error");
  189086. }
  189087. else
  189088. {
  189089. png_chunk_error(png_ptr, "CRC error");
  189090. }
  189091. return (1);
  189092. }
  189093. return (0);
  189094. }
  189095. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  189096. the data it has read thus far. */
  189097. int /* PRIVATE */
  189098. png_crc_error(png_structp png_ptr)
  189099. {
  189100. png_byte crc_bytes[4];
  189101. png_uint_32 crc;
  189102. int need_crc = 1;
  189103. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  189104. {
  189105. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  189106. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189107. need_crc = 0;
  189108. }
  189109. else /* critical */
  189110. {
  189111. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  189112. need_crc = 0;
  189113. }
  189114. png_read_data(png_ptr, crc_bytes, 4);
  189115. if (need_crc)
  189116. {
  189117. crc = png_get_uint_32(crc_bytes);
  189118. return ((int)(crc != png_ptr->crc));
  189119. }
  189120. else
  189121. return (0);
  189122. }
  189123. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  189124. defined(PNG_READ_iCCP_SUPPORTED)
  189125. /*
  189126. * Decompress trailing data in a chunk. The assumption is that chunkdata
  189127. * points at an allocated area holding the contents of a chunk with a
  189128. * trailing compressed part. What we get back is an allocated area
  189129. * holding the original prefix part and an uncompressed version of the
  189130. * trailing part (the malloc area passed in is freed).
  189131. */
  189132. png_charp /* PRIVATE */
  189133. png_decompress_chunk(png_structp png_ptr, int comp_type,
  189134. png_charp chunkdata, png_size_t chunklength,
  189135. png_size_t prefix_size, png_size_t *newlength)
  189136. {
  189137. static PNG_CONST char msg[] = "Error decoding compressed text";
  189138. png_charp text;
  189139. png_size_t text_size;
  189140. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  189141. {
  189142. int ret = Z_OK;
  189143. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  189144. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  189145. png_ptr->zstream.next_out = png_ptr->zbuf;
  189146. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189147. text_size = 0;
  189148. text = NULL;
  189149. while (png_ptr->zstream.avail_in)
  189150. {
  189151. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189152. if (ret != Z_OK && ret != Z_STREAM_END)
  189153. {
  189154. if (png_ptr->zstream.msg != NULL)
  189155. png_warning(png_ptr, png_ptr->zstream.msg);
  189156. else
  189157. png_warning(png_ptr, msg);
  189158. inflateReset(&png_ptr->zstream);
  189159. png_ptr->zstream.avail_in = 0;
  189160. if (text == NULL)
  189161. {
  189162. text_size = prefix_size + png_sizeof(msg) + 1;
  189163. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  189164. if (text == NULL)
  189165. {
  189166. png_free(png_ptr,chunkdata);
  189167. png_error(png_ptr,"Not enough memory to decompress chunk");
  189168. }
  189169. png_memcpy(text, chunkdata, prefix_size);
  189170. }
  189171. text[text_size - 1] = 0x00;
  189172. /* Copy what we can of the error message into the text chunk */
  189173. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  189174. text_size = png_sizeof(msg) > text_size ? text_size :
  189175. png_sizeof(msg);
  189176. png_memcpy(text + prefix_size, msg, text_size + 1);
  189177. break;
  189178. }
  189179. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  189180. {
  189181. if (text == NULL)
  189182. {
  189183. text_size = prefix_size +
  189184. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189185. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  189186. if (text == NULL)
  189187. {
  189188. png_free(png_ptr,chunkdata);
  189189. png_error(png_ptr,"Not enough memory to decompress chunk.");
  189190. }
  189191. png_memcpy(text + prefix_size, png_ptr->zbuf,
  189192. text_size - prefix_size);
  189193. png_memcpy(text, chunkdata, prefix_size);
  189194. *(text + text_size) = 0x00;
  189195. }
  189196. else
  189197. {
  189198. png_charp tmp;
  189199. tmp = text;
  189200. text = (png_charp)png_malloc_warn(png_ptr,
  189201. (png_uint_32)(text_size +
  189202. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  189203. if (text == NULL)
  189204. {
  189205. png_free(png_ptr, tmp);
  189206. png_free(png_ptr, chunkdata);
  189207. png_error(png_ptr,"Not enough memory to decompress chunk..");
  189208. }
  189209. png_memcpy(text, tmp, text_size);
  189210. png_free(png_ptr, tmp);
  189211. png_memcpy(text + text_size, png_ptr->zbuf,
  189212. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  189213. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189214. *(text + text_size) = 0x00;
  189215. }
  189216. if (ret == Z_STREAM_END)
  189217. break;
  189218. else
  189219. {
  189220. png_ptr->zstream.next_out = png_ptr->zbuf;
  189221. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189222. }
  189223. }
  189224. }
  189225. if (ret != Z_STREAM_END)
  189226. {
  189227. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189228. char umsg[52];
  189229. if (ret == Z_BUF_ERROR)
  189230. png_snprintf(umsg, 52,
  189231. "Buffer error in compressed datastream in %s chunk",
  189232. png_ptr->chunk_name);
  189233. else if (ret == Z_DATA_ERROR)
  189234. png_snprintf(umsg, 52,
  189235. "Data error in compressed datastream in %s chunk",
  189236. png_ptr->chunk_name);
  189237. else
  189238. png_snprintf(umsg, 52,
  189239. "Incomplete compressed datastream in %s chunk",
  189240. png_ptr->chunk_name);
  189241. png_warning(png_ptr, umsg);
  189242. #else
  189243. png_warning(png_ptr,
  189244. "Incomplete compressed datastream in chunk other than IDAT");
  189245. #endif
  189246. text_size=prefix_size;
  189247. if (text == NULL)
  189248. {
  189249. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  189250. if (text == NULL)
  189251. {
  189252. png_free(png_ptr, chunkdata);
  189253. png_error(png_ptr,"Not enough memory for text.");
  189254. }
  189255. png_memcpy(text, chunkdata, prefix_size);
  189256. }
  189257. *(text + text_size) = 0x00;
  189258. }
  189259. inflateReset(&png_ptr->zstream);
  189260. png_ptr->zstream.avail_in = 0;
  189261. png_free(png_ptr, chunkdata);
  189262. chunkdata = text;
  189263. *newlength=text_size;
  189264. }
  189265. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  189266. {
  189267. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189268. char umsg[50];
  189269. png_snprintf(umsg, 50,
  189270. "Unknown zTXt compression type %d", comp_type);
  189271. png_warning(png_ptr, umsg);
  189272. #else
  189273. png_warning(png_ptr, "Unknown zTXt compression type");
  189274. #endif
  189275. *(chunkdata + prefix_size) = 0x00;
  189276. *newlength=prefix_size;
  189277. }
  189278. return chunkdata;
  189279. }
  189280. #endif
  189281. /* read and check the IDHR chunk */
  189282. void /* PRIVATE */
  189283. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189284. {
  189285. png_byte buf[13];
  189286. png_uint_32 width, height;
  189287. int bit_depth, color_type, compression_type, filter_type;
  189288. int interlace_type;
  189289. png_debug(1, "in png_handle_IHDR\n");
  189290. if (png_ptr->mode & PNG_HAVE_IHDR)
  189291. png_error(png_ptr, "Out of place IHDR");
  189292. /* check the length */
  189293. if (length != 13)
  189294. png_error(png_ptr, "Invalid IHDR chunk");
  189295. png_ptr->mode |= PNG_HAVE_IHDR;
  189296. png_crc_read(png_ptr, buf, 13);
  189297. png_crc_finish(png_ptr, 0);
  189298. width = png_get_uint_31(png_ptr, buf);
  189299. height = png_get_uint_31(png_ptr, buf + 4);
  189300. bit_depth = buf[8];
  189301. color_type = buf[9];
  189302. compression_type = buf[10];
  189303. filter_type = buf[11];
  189304. interlace_type = buf[12];
  189305. /* set internal variables */
  189306. png_ptr->width = width;
  189307. png_ptr->height = height;
  189308. png_ptr->bit_depth = (png_byte)bit_depth;
  189309. png_ptr->interlaced = (png_byte)interlace_type;
  189310. png_ptr->color_type = (png_byte)color_type;
  189311. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189312. png_ptr->filter_type = (png_byte)filter_type;
  189313. #endif
  189314. png_ptr->compression_type = (png_byte)compression_type;
  189315. /* find number of channels */
  189316. switch (png_ptr->color_type)
  189317. {
  189318. case PNG_COLOR_TYPE_GRAY:
  189319. case PNG_COLOR_TYPE_PALETTE:
  189320. png_ptr->channels = 1;
  189321. break;
  189322. case PNG_COLOR_TYPE_RGB:
  189323. png_ptr->channels = 3;
  189324. break;
  189325. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189326. png_ptr->channels = 2;
  189327. break;
  189328. case PNG_COLOR_TYPE_RGB_ALPHA:
  189329. png_ptr->channels = 4;
  189330. break;
  189331. }
  189332. /* set up other useful info */
  189333. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  189334. png_ptr->channels);
  189335. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  189336. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  189337. png_debug1(3,"channels = %d\n", png_ptr->channels);
  189338. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  189339. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  189340. color_type, interlace_type, compression_type, filter_type);
  189341. }
  189342. /* read and check the palette */
  189343. void /* PRIVATE */
  189344. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189345. {
  189346. png_color palette[PNG_MAX_PALETTE_LENGTH];
  189347. int num, i;
  189348. #ifndef PNG_NO_POINTER_INDEXING
  189349. png_colorp pal_ptr;
  189350. #endif
  189351. png_debug(1, "in png_handle_PLTE\n");
  189352. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189353. png_error(png_ptr, "Missing IHDR before PLTE");
  189354. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189355. {
  189356. png_warning(png_ptr, "Invalid PLTE after IDAT");
  189357. png_crc_finish(png_ptr, length);
  189358. return;
  189359. }
  189360. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189361. png_error(png_ptr, "Duplicate PLTE chunk");
  189362. png_ptr->mode |= PNG_HAVE_PLTE;
  189363. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  189364. {
  189365. png_warning(png_ptr,
  189366. "Ignoring PLTE chunk in grayscale PNG");
  189367. png_crc_finish(png_ptr, length);
  189368. return;
  189369. }
  189370. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189371. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  189372. {
  189373. png_crc_finish(png_ptr, length);
  189374. return;
  189375. }
  189376. #endif
  189377. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  189378. {
  189379. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  189380. {
  189381. png_warning(png_ptr, "Invalid palette chunk");
  189382. png_crc_finish(png_ptr, length);
  189383. return;
  189384. }
  189385. else
  189386. {
  189387. png_error(png_ptr, "Invalid palette chunk");
  189388. }
  189389. }
  189390. num = (int)length / 3;
  189391. #ifndef PNG_NO_POINTER_INDEXING
  189392. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  189393. {
  189394. png_byte buf[3];
  189395. png_crc_read(png_ptr, buf, 3);
  189396. pal_ptr->red = buf[0];
  189397. pal_ptr->green = buf[1];
  189398. pal_ptr->blue = buf[2];
  189399. }
  189400. #else
  189401. for (i = 0; i < num; i++)
  189402. {
  189403. png_byte buf[3];
  189404. png_crc_read(png_ptr, buf, 3);
  189405. /* don't depend upon png_color being any order */
  189406. palette[i].red = buf[0];
  189407. palette[i].green = buf[1];
  189408. palette[i].blue = buf[2];
  189409. }
  189410. #endif
  189411. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  189412. whatever the normal CRC configuration tells us. However, if we
  189413. have an RGB image, the PLTE can be considered ancillary, so
  189414. we will act as though it is. */
  189415. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189416. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189417. #endif
  189418. {
  189419. png_crc_finish(png_ptr, 0);
  189420. }
  189421. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189422. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  189423. {
  189424. /* If we don't want to use the data from an ancillary chunk,
  189425. we have two options: an error abort, or a warning and we
  189426. ignore the data in this chunk (which should be OK, since
  189427. it's considered ancillary for a RGB or RGBA image). */
  189428. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  189429. {
  189430. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  189431. {
  189432. png_chunk_error(png_ptr, "CRC error");
  189433. }
  189434. else
  189435. {
  189436. png_chunk_warning(png_ptr, "CRC error");
  189437. return;
  189438. }
  189439. }
  189440. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  189441. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189442. {
  189443. png_chunk_warning(png_ptr, "CRC error");
  189444. }
  189445. }
  189446. #endif
  189447. png_set_PLTE(png_ptr, info_ptr, palette, num);
  189448. #if defined(PNG_READ_tRNS_SUPPORTED)
  189449. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189450. {
  189451. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  189452. {
  189453. if (png_ptr->num_trans > (png_uint_16)num)
  189454. {
  189455. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  189456. png_ptr->num_trans = (png_uint_16)num;
  189457. }
  189458. if (info_ptr->num_trans > (png_uint_16)num)
  189459. {
  189460. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  189461. info_ptr->num_trans = (png_uint_16)num;
  189462. }
  189463. }
  189464. }
  189465. #endif
  189466. }
  189467. void /* PRIVATE */
  189468. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189469. {
  189470. png_debug(1, "in png_handle_IEND\n");
  189471. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  189472. {
  189473. png_error(png_ptr, "No image in file");
  189474. }
  189475. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  189476. if (length != 0)
  189477. {
  189478. png_warning(png_ptr, "Incorrect IEND chunk length");
  189479. }
  189480. png_crc_finish(png_ptr, length);
  189481. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  189482. }
  189483. #if defined(PNG_READ_gAMA_SUPPORTED)
  189484. void /* PRIVATE */
  189485. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189486. {
  189487. png_fixed_point igamma;
  189488. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189489. float file_gamma;
  189490. #endif
  189491. png_byte buf[4];
  189492. png_debug(1, "in png_handle_gAMA\n");
  189493. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189494. png_error(png_ptr, "Missing IHDR before gAMA");
  189495. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189496. {
  189497. png_warning(png_ptr, "Invalid gAMA after IDAT");
  189498. png_crc_finish(png_ptr, length);
  189499. return;
  189500. }
  189501. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189502. /* Should be an error, but we can cope with it */
  189503. png_warning(png_ptr, "Out of place gAMA chunk");
  189504. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  189505. #if defined(PNG_READ_sRGB_SUPPORTED)
  189506. && !(info_ptr->valid & PNG_INFO_sRGB)
  189507. #endif
  189508. )
  189509. {
  189510. png_warning(png_ptr, "Duplicate gAMA chunk");
  189511. png_crc_finish(png_ptr, length);
  189512. return;
  189513. }
  189514. if (length != 4)
  189515. {
  189516. png_warning(png_ptr, "Incorrect gAMA chunk length");
  189517. png_crc_finish(png_ptr, length);
  189518. return;
  189519. }
  189520. png_crc_read(png_ptr, buf, 4);
  189521. if (png_crc_finish(png_ptr, 0))
  189522. return;
  189523. igamma = (png_fixed_point)png_get_uint_32(buf);
  189524. /* check for zero gamma */
  189525. if (igamma == 0)
  189526. {
  189527. png_warning(png_ptr,
  189528. "Ignoring gAMA chunk with gamma=0");
  189529. return;
  189530. }
  189531. #if defined(PNG_READ_sRGB_SUPPORTED)
  189532. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  189533. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  189534. {
  189535. png_warning(png_ptr,
  189536. "Ignoring incorrect gAMA value when sRGB is also present");
  189537. #ifndef PNG_NO_CONSOLE_IO
  189538. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  189539. #endif
  189540. return;
  189541. }
  189542. #endif /* PNG_READ_sRGB_SUPPORTED */
  189543. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189544. file_gamma = (float)igamma / (float)100000.0;
  189545. # ifdef PNG_READ_GAMMA_SUPPORTED
  189546. png_ptr->gamma = file_gamma;
  189547. # endif
  189548. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  189549. #endif
  189550. #ifdef PNG_FIXED_POINT_SUPPORTED
  189551. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  189552. #endif
  189553. }
  189554. #endif
  189555. #if defined(PNG_READ_sBIT_SUPPORTED)
  189556. void /* PRIVATE */
  189557. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189558. {
  189559. png_size_t truelen;
  189560. png_byte buf[4];
  189561. png_debug(1, "in png_handle_sBIT\n");
  189562. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  189563. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189564. png_error(png_ptr, "Missing IHDR before sBIT");
  189565. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189566. {
  189567. png_warning(png_ptr, "Invalid sBIT after IDAT");
  189568. png_crc_finish(png_ptr, length);
  189569. return;
  189570. }
  189571. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189572. {
  189573. /* Should be an error, but we can cope with it */
  189574. png_warning(png_ptr, "Out of place sBIT chunk");
  189575. }
  189576. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  189577. {
  189578. png_warning(png_ptr, "Duplicate sBIT chunk");
  189579. png_crc_finish(png_ptr, length);
  189580. return;
  189581. }
  189582. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189583. truelen = 3;
  189584. else
  189585. truelen = (png_size_t)png_ptr->channels;
  189586. if (length != truelen || length > 4)
  189587. {
  189588. png_warning(png_ptr, "Incorrect sBIT chunk length");
  189589. png_crc_finish(png_ptr, length);
  189590. return;
  189591. }
  189592. png_crc_read(png_ptr, buf, truelen);
  189593. if (png_crc_finish(png_ptr, 0))
  189594. return;
  189595. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189596. {
  189597. png_ptr->sig_bit.red = buf[0];
  189598. png_ptr->sig_bit.green = buf[1];
  189599. png_ptr->sig_bit.blue = buf[2];
  189600. png_ptr->sig_bit.alpha = buf[3];
  189601. }
  189602. else
  189603. {
  189604. png_ptr->sig_bit.gray = buf[0];
  189605. png_ptr->sig_bit.red = buf[0];
  189606. png_ptr->sig_bit.green = buf[0];
  189607. png_ptr->sig_bit.blue = buf[0];
  189608. png_ptr->sig_bit.alpha = buf[1];
  189609. }
  189610. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  189611. }
  189612. #endif
  189613. #if defined(PNG_READ_cHRM_SUPPORTED)
  189614. void /* PRIVATE */
  189615. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189616. {
  189617. png_byte buf[4];
  189618. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189619. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  189620. #endif
  189621. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  189622. int_y_green, int_x_blue, int_y_blue;
  189623. png_uint_32 uint_x, uint_y;
  189624. png_debug(1, "in png_handle_cHRM\n");
  189625. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189626. png_error(png_ptr, "Missing IHDR before cHRM");
  189627. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189628. {
  189629. png_warning(png_ptr, "Invalid cHRM after IDAT");
  189630. png_crc_finish(png_ptr, length);
  189631. return;
  189632. }
  189633. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189634. /* Should be an error, but we can cope with it */
  189635. png_warning(png_ptr, "Missing PLTE before cHRM");
  189636. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  189637. #if defined(PNG_READ_sRGB_SUPPORTED)
  189638. && !(info_ptr->valid & PNG_INFO_sRGB)
  189639. #endif
  189640. )
  189641. {
  189642. png_warning(png_ptr, "Duplicate cHRM chunk");
  189643. png_crc_finish(png_ptr, length);
  189644. return;
  189645. }
  189646. if (length != 32)
  189647. {
  189648. png_warning(png_ptr, "Incorrect cHRM chunk length");
  189649. png_crc_finish(png_ptr, length);
  189650. return;
  189651. }
  189652. png_crc_read(png_ptr, buf, 4);
  189653. uint_x = png_get_uint_32(buf);
  189654. png_crc_read(png_ptr, buf, 4);
  189655. uint_y = png_get_uint_32(buf);
  189656. if (uint_x > 80000L || uint_y > 80000L ||
  189657. uint_x + uint_y > 100000L)
  189658. {
  189659. png_warning(png_ptr, "Invalid cHRM white point");
  189660. png_crc_finish(png_ptr, 24);
  189661. return;
  189662. }
  189663. int_x_white = (png_fixed_point)uint_x;
  189664. int_y_white = (png_fixed_point)uint_y;
  189665. png_crc_read(png_ptr, buf, 4);
  189666. uint_x = png_get_uint_32(buf);
  189667. png_crc_read(png_ptr, buf, 4);
  189668. uint_y = png_get_uint_32(buf);
  189669. if (uint_x + uint_y > 100000L)
  189670. {
  189671. png_warning(png_ptr, "Invalid cHRM red point");
  189672. png_crc_finish(png_ptr, 16);
  189673. return;
  189674. }
  189675. int_x_red = (png_fixed_point)uint_x;
  189676. int_y_red = (png_fixed_point)uint_y;
  189677. png_crc_read(png_ptr, buf, 4);
  189678. uint_x = png_get_uint_32(buf);
  189679. png_crc_read(png_ptr, buf, 4);
  189680. uint_y = png_get_uint_32(buf);
  189681. if (uint_x + uint_y > 100000L)
  189682. {
  189683. png_warning(png_ptr, "Invalid cHRM green point");
  189684. png_crc_finish(png_ptr, 8);
  189685. return;
  189686. }
  189687. int_x_green = (png_fixed_point)uint_x;
  189688. int_y_green = (png_fixed_point)uint_y;
  189689. png_crc_read(png_ptr, buf, 4);
  189690. uint_x = png_get_uint_32(buf);
  189691. png_crc_read(png_ptr, buf, 4);
  189692. uint_y = png_get_uint_32(buf);
  189693. if (uint_x + uint_y > 100000L)
  189694. {
  189695. png_warning(png_ptr, "Invalid cHRM blue point");
  189696. png_crc_finish(png_ptr, 0);
  189697. return;
  189698. }
  189699. int_x_blue = (png_fixed_point)uint_x;
  189700. int_y_blue = (png_fixed_point)uint_y;
  189701. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189702. white_x = (float)int_x_white / (float)100000.0;
  189703. white_y = (float)int_y_white / (float)100000.0;
  189704. red_x = (float)int_x_red / (float)100000.0;
  189705. red_y = (float)int_y_red / (float)100000.0;
  189706. green_x = (float)int_x_green / (float)100000.0;
  189707. green_y = (float)int_y_green / (float)100000.0;
  189708. blue_x = (float)int_x_blue / (float)100000.0;
  189709. blue_y = (float)int_y_blue / (float)100000.0;
  189710. #endif
  189711. #if defined(PNG_READ_sRGB_SUPPORTED)
  189712. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  189713. {
  189714. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  189715. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  189716. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  189717. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  189718. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  189719. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  189720. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  189721. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  189722. {
  189723. png_warning(png_ptr,
  189724. "Ignoring incorrect cHRM value when sRGB is also present");
  189725. #ifndef PNG_NO_CONSOLE_IO
  189726. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189727. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  189728. white_x, white_y, red_x, red_y);
  189729. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  189730. green_x, green_y, blue_x, blue_y);
  189731. #else
  189732. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  189733. int_x_white, int_y_white, int_x_red, int_y_red);
  189734. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  189735. int_x_green, int_y_green, int_x_blue, int_y_blue);
  189736. #endif
  189737. #endif /* PNG_NO_CONSOLE_IO */
  189738. }
  189739. png_crc_finish(png_ptr, 0);
  189740. return;
  189741. }
  189742. #endif /* PNG_READ_sRGB_SUPPORTED */
  189743. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189744. png_set_cHRM(png_ptr, info_ptr,
  189745. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  189746. #endif
  189747. #ifdef PNG_FIXED_POINT_SUPPORTED
  189748. png_set_cHRM_fixed(png_ptr, info_ptr,
  189749. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  189750. int_y_green, int_x_blue, int_y_blue);
  189751. #endif
  189752. if (png_crc_finish(png_ptr, 0))
  189753. return;
  189754. }
  189755. #endif
  189756. #if defined(PNG_READ_sRGB_SUPPORTED)
  189757. void /* PRIVATE */
  189758. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189759. {
  189760. int intent;
  189761. png_byte buf[1];
  189762. png_debug(1, "in png_handle_sRGB\n");
  189763. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189764. png_error(png_ptr, "Missing IHDR before sRGB");
  189765. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189766. {
  189767. png_warning(png_ptr, "Invalid sRGB after IDAT");
  189768. png_crc_finish(png_ptr, length);
  189769. return;
  189770. }
  189771. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189772. /* Should be an error, but we can cope with it */
  189773. png_warning(png_ptr, "Out of place sRGB chunk");
  189774. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  189775. {
  189776. png_warning(png_ptr, "Duplicate sRGB chunk");
  189777. png_crc_finish(png_ptr, length);
  189778. return;
  189779. }
  189780. if (length != 1)
  189781. {
  189782. png_warning(png_ptr, "Incorrect sRGB chunk length");
  189783. png_crc_finish(png_ptr, length);
  189784. return;
  189785. }
  189786. png_crc_read(png_ptr, buf, 1);
  189787. if (png_crc_finish(png_ptr, 0))
  189788. return;
  189789. intent = buf[0];
  189790. /* check for bad intent */
  189791. if (intent >= PNG_sRGB_INTENT_LAST)
  189792. {
  189793. png_warning(png_ptr, "Unknown sRGB intent");
  189794. return;
  189795. }
  189796. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  189797. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  189798. {
  189799. png_fixed_point igamma;
  189800. #ifdef PNG_FIXED_POINT_SUPPORTED
  189801. igamma=info_ptr->int_gamma;
  189802. #else
  189803. # ifdef PNG_FLOATING_POINT_SUPPORTED
  189804. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  189805. # endif
  189806. #endif
  189807. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  189808. {
  189809. png_warning(png_ptr,
  189810. "Ignoring incorrect gAMA value when sRGB is also present");
  189811. #ifndef PNG_NO_CONSOLE_IO
  189812. # ifdef PNG_FIXED_POINT_SUPPORTED
  189813. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  189814. # else
  189815. # ifdef PNG_FLOATING_POINT_SUPPORTED
  189816. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  189817. # endif
  189818. # endif
  189819. #endif
  189820. }
  189821. }
  189822. #endif /* PNG_READ_gAMA_SUPPORTED */
  189823. #ifdef PNG_READ_cHRM_SUPPORTED
  189824. #ifdef PNG_FIXED_POINT_SUPPORTED
  189825. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  189826. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  189827. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  189828. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  189829. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  189830. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  189831. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  189832. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  189833. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  189834. {
  189835. png_warning(png_ptr,
  189836. "Ignoring incorrect cHRM value when sRGB is also present");
  189837. }
  189838. #endif /* PNG_FIXED_POINT_SUPPORTED */
  189839. #endif /* PNG_READ_cHRM_SUPPORTED */
  189840. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  189841. }
  189842. #endif /* PNG_READ_sRGB_SUPPORTED */
  189843. #if defined(PNG_READ_iCCP_SUPPORTED)
  189844. void /* PRIVATE */
  189845. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189846. /* Note: this does not properly handle chunks that are > 64K under DOS */
  189847. {
  189848. png_charp chunkdata;
  189849. png_byte compression_type;
  189850. png_bytep pC;
  189851. png_charp profile;
  189852. png_uint_32 skip = 0;
  189853. png_uint_32 profile_size, profile_length;
  189854. png_size_t slength, prefix_length, data_length;
  189855. png_debug(1, "in png_handle_iCCP\n");
  189856. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189857. png_error(png_ptr, "Missing IHDR before iCCP");
  189858. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189859. {
  189860. png_warning(png_ptr, "Invalid iCCP after IDAT");
  189861. png_crc_finish(png_ptr, length);
  189862. return;
  189863. }
  189864. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189865. /* Should be an error, but we can cope with it */
  189866. png_warning(png_ptr, "Out of place iCCP chunk");
  189867. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  189868. {
  189869. png_warning(png_ptr, "Duplicate iCCP chunk");
  189870. png_crc_finish(png_ptr, length);
  189871. return;
  189872. }
  189873. #ifdef PNG_MAX_MALLOC_64K
  189874. if (length > (png_uint_32)65535L)
  189875. {
  189876. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  189877. skip = length - (png_uint_32)65535L;
  189878. length = (png_uint_32)65535L;
  189879. }
  189880. #endif
  189881. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  189882. slength = (png_size_t)length;
  189883. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189884. if (png_crc_finish(png_ptr, skip))
  189885. {
  189886. png_free(png_ptr, chunkdata);
  189887. return;
  189888. }
  189889. chunkdata[slength] = 0x00;
  189890. for (profile = chunkdata; *profile; profile++)
  189891. /* empty loop to find end of name */ ;
  189892. ++profile;
  189893. /* there should be at least one zero (the compression type byte)
  189894. following the separator, and we should be on it */
  189895. if ( profile >= chunkdata + slength - 1)
  189896. {
  189897. png_free(png_ptr, chunkdata);
  189898. png_warning(png_ptr, "Malformed iCCP chunk");
  189899. return;
  189900. }
  189901. /* compression_type should always be zero */
  189902. compression_type = *profile++;
  189903. if (compression_type)
  189904. {
  189905. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  189906. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  189907. wrote nonzero) */
  189908. }
  189909. prefix_length = profile - chunkdata;
  189910. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  189911. slength, prefix_length, &data_length);
  189912. profile_length = data_length - prefix_length;
  189913. if ( prefix_length > data_length || profile_length < 4)
  189914. {
  189915. png_free(png_ptr, chunkdata);
  189916. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  189917. return;
  189918. }
  189919. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  189920. pC = (png_bytep)(chunkdata+prefix_length);
  189921. profile_size = ((*(pC ))<<24) |
  189922. ((*(pC+1))<<16) |
  189923. ((*(pC+2))<< 8) |
  189924. ((*(pC+3)) );
  189925. if(profile_size < profile_length)
  189926. profile_length = profile_size;
  189927. if(profile_size > profile_length)
  189928. {
  189929. png_free(png_ptr, chunkdata);
  189930. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  189931. return;
  189932. }
  189933. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  189934. chunkdata + prefix_length, profile_length);
  189935. png_free(png_ptr, chunkdata);
  189936. }
  189937. #endif /* PNG_READ_iCCP_SUPPORTED */
  189938. #if defined(PNG_READ_sPLT_SUPPORTED)
  189939. void /* PRIVATE */
  189940. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189941. /* Note: this does not properly handle chunks that are > 64K under DOS */
  189942. {
  189943. png_bytep chunkdata;
  189944. png_bytep entry_start;
  189945. png_sPLT_t new_palette;
  189946. #ifdef PNG_NO_POINTER_INDEXING
  189947. png_sPLT_entryp pp;
  189948. #endif
  189949. int data_length, entry_size, i;
  189950. png_uint_32 skip = 0;
  189951. png_size_t slength;
  189952. png_debug(1, "in png_handle_sPLT\n");
  189953. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189954. png_error(png_ptr, "Missing IHDR before sPLT");
  189955. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189956. {
  189957. png_warning(png_ptr, "Invalid sPLT after IDAT");
  189958. png_crc_finish(png_ptr, length);
  189959. return;
  189960. }
  189961. #ifdef PNG_MAX_MALLOC_64K
  189962. if (length > (png_uint_32)65535L)
  189963. {
  189964. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  189965. skip = length - (png_uint_32)65535L;
  189966. length = (png_uint_32)65535L;
  189967. }
  189968. #endif
  189969. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  189970. slength = (png_size_t)length;
  189971. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189972. if (png_crc_finish(png_ptr, skip))
  189973. {
  189974. png_free(png_ptr, chunkdata);
  189975. return;
  189976. }
  189977. chunkdata[slength] = 0x00;
  189978. for (entry_start = chunkdata; *entry_start; entry_start++)
  189979. /* empty loop to find end of name */ ;
  189980. ++entry_start;
  189981. /* a sample depth should follow the separator, and we should be on it */
  189982. if (entry_start > chunkdata + slength - 2)
  189983. {
  189984. png_free(png_ptr, chunkdata);
  189985. png_warning(png_ptr, "malformed sPLT chunk");
  189986. return;
  189987. }
  189988. new_palette.depth = *entry_start++;
  189989. entry_size = (new_palette.depth == 8 ? 6 : 10);
  189990. data_length = (slength - (entry_start - chunkdata));
  189991. /* integrity-check the data length */
  189992. if (data_length % entry_size)
  189993. {
  189994. png_free(png_ptr, chunkdata);
  189995. png_warning(png_ptr, "sPLT chunk has bad length");
  189996. return;
  189997. }
  189998. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  189999. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  190000. png_sizeof(png_sPLT_entry)))
  190001. {
  190002. png_warning(png_ptr, "sPLT chunk too long");
  190003. return;
  190004. }
  190005. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  190006. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  190007. if (new_palette.entries == NULL)
  190008. {
  190009. png_warning(png_ptr, "sPLT chunk requires too much memory");
  190010. return;
  190011. }
  190012. #ifndef PNG_NO_POINTER_INDEXING
  190013. for (i = 0; i < new_palette.nentries; i++)
  190014. {
  190015. png_sPLT_entryp pp = new_palette.entries + i;
  190016. if (new_palette.depth == 8)
  190017. {
  190018. pp->red = *entry_start++;
  190019. pp->green = *entry_start++;
  190020. pp->blue = *entry_start++;
  190021. pp->alpha = *entry_start++;
  190022. }
  190023. else
  190024. {
  190025. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  190026. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  190027. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  190028. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  190029. }
  190030. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190031. }
  190032. #else
  190033. pp = new_palette.entries;
  190034. for (i = 0; i < new_palette.nentries; i++)
  190035. {
  190036. if (new_palette.depth == 8)
  190037. {
  190038. pp[i].red = *entry_start++;
  190039. pp[i].green = *entry_start++;
  190040. pp[i].blue = *entry_start++;
  190041. pp[i].alpha = *entry_start++;
  190042. }
  190043. else
  190044. {
  190045. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  190046. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  190047. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  190048. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  190049. }
  190050. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190051. }
  190052. #endif
  190053. /* discard all chunk data except the name and stash that */
  190054. new_palette.name = (png_charp)chunkdata;
  190055. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  190056. png_free(png_ptr, chunkdata);
  190057. png_free(png_ptr, new_palette.entries);
  190058. }
  190059. #endif /* PNG_READ_sPLT_SUPPORTED */
  190060. #if defined(PNG_READ_tRNS_SUPPORTED)
  190061. void /* PRIVATE */
  190062. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190063. {
  190064. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  190065. int bit_mask;
  190066. png_debug(1, "in png_handle_tRNS\n");
  190067. /* For non-indexed color, mask off any bits in the tRNS value that
  190068. * exceed the bit depth. Some creators were writing extra bits there.
  190069. * This is not needed for indexed color. */
  190070. bit_mask = (1 << png_ptr->bit_depth) - 1;
  190071. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190072. png_error(png_ptr, "Missing IHDR before tRNS");
  190073. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190074. {
  190075. png_warning(png_ptr, "Invalid tRNS after IDAT");
  190076. png_crc_finish(png_ptr, length);
  190077. return;
  190078. }
  190079. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190080. {
  190081. png_warning(png_ptr, "Duplicate tRNS chunk");
  190082. png_crc_finish(png_ptr, length);
  190083. return;
  190084. }
  190085. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190086. {
  190087. png_byte buf[2];
  190088. if (length != 2)
  190089. {
  190090. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190091. png_crc_finish(png_ptr, length);
  190092. return;
  190093. }
  190094. png_crc_read(png_ptr, buf, 2);
  190095. png_ptr->num_trans = 1;
  190096. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  190097. }
  190098. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190099. {
  190100. png_byte buf[6];
  190101. if (length != 6)
  190102. {
  190103. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190104. png_crc_finish(png_ptr, length);
  190105. return;
  190106. }
  190107. png_crc_read(png_ptr, buf, (png_size_t)length);
  190108. png_ptr->num_trans = 1;
  190109. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  190110. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  190111. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  190112. }
  190113. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190114. {
  190115. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190116. {
  190117. /* Should be an error, but we can cope with it. */
  190118. png_warning(png_ptr, "Missing PLTE before tRNS");
  190119. }
  190120. if (length > (png_uint_32)png_ptr->num_palette ||
  190121. length > PNG_MAX_PALETTE_LENGTH)
  190122. {
  190123. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190124. png_crc_finish(png_ptr, length);
  190125. return;
  190126. }
  190127. if (length == 0)
  190128. {
  190129. png_warning(png_ptr, "Zero length tRNS chunk");
  190130. png_crc_finish(png_ptr, length);
  190131. return;
  190132. }
  190133. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  190134. png_ptr->num_trans = (png_uint_16)length;
  190135. }
  190136. else
  190137. {
  190138. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  190139. png_crc_finish(png_ptr, length);
  190140. return;
  190141. }
  190142. if (png_crc_finish(png_ptr, 0))
  190143. {
  190144. png_ptr->num_trans = 0;
  190145. return;
  190146. }
  190147. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  190148. &(png_ptr->trans_values));
  190149. }
  190150. #endif
  190151. #if defined(PNG_READ_bKGD_SUPPORTED)
  190152. void /* PRIVATE */
  190153. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190154. {
  190155. png_size_t truelen;
  190156. png_byte buf[6];
  190157. png_debug(1, "in png_handle_bKGD\n");
  190158. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190159. png_error(png_ptr, "Missing IHDR before bKGD");
  190160. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190161. {
  190162. png_warning(png_ptr, "Invalid bKGD after IDAT");
  190163. png_crc_finish(png_ptr, length);
  190164. return;
  190165. }
  190166. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  190167. !(png_ptr->mode & PNG_HAVE_PLTE))
  190168. {
  190169. png_warning(png_ptr, "Missing PLTE before bKGD");
  190170. png_crc_finish(png_ptr, length);
  190171. return;
  190172. }
  190173. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  190174. {
  190175. png_warning(png_ptr, "Duplicate bKGD chunk");
  190176. png_crc_finish(png_ptr, length);
  190177. return;
  190178. }
  190179. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190180. truelen = 1;
  190181. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190182. truelen = 6;
  190183. else
  190184. truelen = 2;
  190185. if (length != truelen)
  190186. {
  190187. png_warning(png_ptr, "Incorrect bKGD chunk length");
  190188. png_crc_finish(png_ptr, length);
  190189. return;
  190190. }
  190191. png_crc_read(png_ptr, buf, truelen);
  190192. if (png_crc_finish(png_ptr, 0))
  190193. return;
  190194. /* We convert the index value into RGB components so that we can allow
  190195. * arbitrary RGB values for background when we have transparency, and
  190196. * so it is easy to determine the RGB values of the background color
  190197. * from the info_ptr struct. */
  190198. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190199. {
  190200. png_ptr->background.index = buf[0];
  190201. if(info_ptr->num_palette)
  190202. {
  190203. if(buf[0] > info_ptr->num_palette)
  190204. {
  190205. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  190206. return;
  190207. }
  190208. png_ptr->background.red =
  190209. (png_uint_16)png_ptr->palette[buf[0]].red;
  190210. png_ptr->background.green =
  190211. (png_uint_16)png_ptr->palette[buf[0]].green;
  190212. png_ptr->background.blue =
  190213. (png_uint_16)png_ptr->palette[buf[0]].blue;
  190214. }
  190215. }
  190216. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  190217. {
  190218. png_ptr->background.red =
  190219. png_ptr->background.green =
  190220. png_ptr->background.blue =
  190221. png_ptr->background.gray = png_get_uint_16(buf);
  190222. }
  190223. else
  190224. {
  190225. png_ptr->background.red = png_get_uint_16(buf);
  190226. png_ptr->background.green = png_get_uint_16(buf + 2);
  190227. png_ptr->background.blue = png_get_uint_16(buf + 4);
  190228. }
  190229. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  190230. }
  190231. #endif
  190232. #if defined(PNG_READ_hIST_SUPPORTED)
  190233. void /* PRIVATE */
  190234. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190235. {
  190236. unsigned int num, i;
  190237. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  190238. png_debug(1, "in png_handle_hIST\n");
  190239. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190240. png_error(png_ptr, "Missing IHDR before hIST");
  190241. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190242. {
  190243. png_warning(png_ptr, "Invalid hIST after IDAT");
  190244. png_crc_finish(png_ptr, length);
  190245. return;
  190246. }
  190247. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190248. {
  190249. png_warning(png_ptr, "Missing PLTE before hIST");
  190250. png_crc_finish(png_ptr, length);
  190251. return;
  190252. }
  190253. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  190254. {
  190255. png_warning(png_ptr, "Duplicate hIST chunk");
  190256. png_crc_finish(png_ptr, length);
  190257. return;
  190258. }
  190259. num = length / 2 ;
  190260. if (num != (unsigned int) png_ptr->num_palette || num >
  190261. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  190262. {
  190263. png_warning(png_ptr, "Incorrect hIST chunk length");
  190264. png_crc_finish(png_ptr, length);
  190265. return;
  190266. }
  190267. for (i = 0; i < num; i++)
  190268. {
  190269. png_byte buf[2];
  190270. png_crc_read(png_ptr, buf, 2);
  190271. readbuf[i] = png_get_uint_16(buf);
  190272. }
  190273. if (png_crc_finish(png_ptr, 0))
  190274. return;
  190275. png_set_hIST(png_ptr, info_ptr, readbuf);
  190276. }
  190277. #endif
  190278. #if defined(PNG_READ_pHYs_SUPPORTED)
  190279. void /* PRIVATE */
  190280. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190281. {
  190282. png_byte buf[9];
  190283. png_uint_32 res_x, res_y;
  190284. int unit_type;
  190285. png_debug(1, "in png_handle_pHYs\n");
  190286. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190287. png_error(png_ptr, "Missing IHDR before pHYs");
  190288. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190289. {
  190290. png_warning(png_ptr, "Invalid pHYs after IDAT");
  190291. png_crc_finish(png_ptr, length);
  190292. return;
  190293. }
  190294. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  190295. {
  190296. png_warning(png_ptr, "Duplicate pHYs chunk");
  190297. png_crc_finish(png_ptr, length);
  190298. return;
  190299. }
  190300. if (length != 9)
  190301. {
  190302. png_warning(png_ptr, "Incorrect pHYs chunk length");
  190303. png_crc_finish(png_ptr, length);
  190304. return;
  190305. }
  190306. png_crc_read(png_ptr, buf, 9);
  190307. if (png_crc_finish(png_ptr, 0))
  190308. return;
  190309. res_x = png_get_uint_32(buf);
  190310. res_y = png_get_uint_32(buf + 4);
  190311. unit_type = buf[8];
  190312. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  190313. }
  190314. #endif
  190315. #if defined(PNG_READ_oFFs_SUPPORTED)
  190316. void /* PRIVATE */
  190317. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190318. {
  190319. png_byte buf[9];
  190320. png_int_32 offset_x, offset_y;
  190321. int unit_type;
  190322. png_debug(1, "in png_handle_oFFs\n");
  190323. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190324. png_error(png_ptr, "Missing IHDR before oFFs");
  190325. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190326. {
  190327. png_warning(png_ptr, "Invalid oFFs after IDAT");
  190328. png_crc_finish(png_ptr, length);
  190329. return;
  190330. }
  190331. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  190332. {
  190333. png_warning(png_ptr, "Duplicate oFFs chunk");
  190334. png_crc_finish(png_ptr, length);
  190335. return;
  190336. }
  190337. if (length != 9)
  190338. {
  190339. png_warning(png_ptr, "Incorrect oFFs chunk length");
  190340. png_crc_finish(png_ptr, length);
  190341. return;
  190342. }
  190343. png_crc_read(png_ptr, buf, 9);
  190344. if (png_crc_finish(png_ptr, 0))
  190345. return;
  190346. offset_x = png_get_int_32(buf);
  190347. offset_y = png_get_int_32(buf + 4);
  190348. unit_type = buf[8];
  190349. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  190350. }
  190351. #endif
  190352. #if defined(PNG_READ_pCAL_SUPPORTED)
  190353. /* read the pCAL chunk (described in the PNG Extensions document) */
  190354. void /* PRIVATE */
  190355. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190356. {
  190357. png_charp purpose;
  190358. png_int_32 X0, X1;
  190359. png_byte type, nparams;
  190360. png_charp buf, units, endptr;
  190361. png_charpp params;
  190362. png_size_t slength;
  190363. int i;
  190364. png_debug(1, "in png_handle_pCAL\n");
  190365. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190366. png_error(png_ptr, "Missing IHDR before pCAL");
  190367. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190368. {
  190369. png_warning(png_ptr, "Invalid pCAL after IDAT");
  190370. png_crc_finish(png_ptr, length);
  190371. return;
  190372. }
  190373. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  190374. {
  190375. png_warning(png_ptr, "Duplicate pCAL chunk");
  190376. png_crc_finish(png_ptr, length);
  190377. return;
  190378. }
  190379. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  190380. length + 1);
  190381. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190382. if (purpose == NULL)
  190383. {
  190384. png_warning(png_ptr, "No memory for pCAL purpose.");
  190385. return;
  190386. }
  190387. slength = (png_size_t)length;
  190388. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  190389. if (png_crc_finish(png_ptr, 0))
  190390. {
  190391. png_free(png_ptr, purpose);
  190392. return;
  190393. }
  190394. purpose[slength] = 0x00; /* null terminate the last string */
  190395. png_debug(3, "Finding end of pCAL purpose string\n");
  190396. for (buf = purpose; *buf; buf++)
  190397. /* empty loop */ ;
  190398. endptr = purpose + slength;
  190399. /* We need to have at least 12 bytes after the purpose string
  190400. in order to get the parameter information. */
  190401. if (endptr <= buf + 12)
  190402. {
  190403. png_warning(png_ptr, "Invalid pCAL data");
  190404. png_free(png_ptr, purpose);
  190405. return;
  190406. }
  190407. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  190408. X0 = png_get_int_32((png_bytep)buf+1);
  190409. X1 = png_get_int_32((png_bytep)buf+5);
  190410. type = buf[9];
  190411. nparams = buf[10];
  190412. units = buf + 11;
  190413. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  190414. /* Check that we have the right number of parameters for known
  190415. equation types. */
  190416. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  190417. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  190418. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  190419. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  190420. {
  190421. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  190422. png_free(png_ptr, purpose);
  190423. return;
  190424. }
  190425. else if (type >= PNG_EQUATION_LAST)
  190426. {
  190427. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  190428. }
  190429. for (buf = units; *buf; buf++)
  190430. /* Empty loop to move past the units string. */ ;
  190431. png_debug(3, "Allocating pCAL parameters array\n");
  190432. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  190433. *png_sizeof(png_charp))) ;
  190434. if (params == NULL)
  190435. {
  190436. png_free(png_ptr, purpose);
  190437. png_warning(png_ptr, "No memory for pCAL params.");
  190438. return;
  190439. }
  190440. /* Get pointers to the start of each parameter string. */
  190441. for (i = 0; i < (int)nparams; i++)
  190442. {
  190443. buf++; /* Skip the null string terminator from previous parameter. */
  190444. png_debug1(3, "Reading pCAL parameter %d\n", i);
  190445. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  190446. /* Empty loop to move past each parameter string */ ;
  190447. /* Make sure we haven't run out of data yet */
  190448. if (buf > endptr)
  190449. {
  190450. png_warning(png_ptr, "Invalid pCAL data");
  190451. png_free(png_ptr, purpose);
  190452. png_free(png_ptr, params);
  190453. return;
  190454. }
  190455. }
  190456. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  190457. units, params);
  190458. png_free(png_ptr, purpose);
  190459. png_free(png_ptr, params);
  190460. }
  190461. #endif
  190462. #if defined(PNG_READ_sCAL_SUPPORTED)
  190463. /* read the sCAL chunk */
  190464. void /* PRIVATE */
  190465. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190466. {
  190467. png_charp buffer, ep;
  190468. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190469. double width, height;
  190470. png_charp vp;
  190471. #else
  190472. #ifdef PNG_FIXED_POINT_SUPPORTED
  190473. png_charp swidth, sheight;
  190474. #endif
  190475. #endif
  190476. png_size_t slength;
  190477. png_debug(1, "in png_handle_sCAL\n");
  190478. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190479. png_error(png_ptr, "Missing IHDR before sCAL");
  190480. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190481. {
  190482. png_warning(png_ptr, "Invalid sCAL after IDAT");
  190483. png_crc_finish(png_ptr, length);
  190484. return;
  190485. }
  190486. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  190487. {
  190488. png_warning(png_ptr, "Duplicate sCAL chunk");
  190489. png_crc_finish(png_ptr, length);
  190490. return;
  190491. }
  190492. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  190493. length + 1);
  190494. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190495. if (buffer == NULL)
  190496. {
  190497. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  190498. return;
  190499. }
  190500. slength = (png_size_t)length;
  190501. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  190502. if (png_crc_finish(png_ptr, 0))
  190503. {
  190504. png_free(png_ptr, buffer);
  190505. return;
  190506. }
  190507. buffer[slength] = 0x00; /* null terminate the last string */
  190508. ep = buffer + 1; /* skip unit byte */
  190509. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190510. width = png_strtod(png_ptr, ep, &vp);
  190511. if (*vp)
  190512. {
  190513. png_warning(png_ptr, "malformed width string in sCAL chunk");
  190514. return;
  190515. }
  190516. #else
  190517. #ifdef PNG_FIXED_POINT_SUPPORTED
  190518. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  190519. if (swidth == NULL)
  190520. {
  190521. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  190522. return;
  190523. }
  190524. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  190525. #endif
  190526. #endif
  190527. for (ep = buffer; *ep; ep++)
  190528. /* empty loop */ ;
  190529. ep++;
  190530. if (buffer + slength < ep)
  190531. {
  190532. png_warning(png_ptr, "Truncated sCAL chunk");
  190533. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  190534. !defined(PNG_FLOATING_POINT_SUPPORTED)
  190535. png_free(png_ptr, swidth);
  190536. #endif
  190537. png_free(png_ptr, buffer);
  190538. return;
  190539. }
  190540. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190541. height = png_strtod(png_ptr, ep, &vp);
  190542. if (*vp)
  190543. {
  190544. png_warning(png_ptr, "malformed height string in sCAL chunk");
  190545. return;
  190546. }
  190547. #else
  190548. #ifdef PNG_FIXED_POINT_SUPPORTED
  190549. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  190550. if (swidth == NULL)
  190551. {
  190552. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  190553. return;
  190554. }
  190555. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  190556. #endif
  190557. #endif
  190558. if (buffer + slength < ep
  190559. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190560. || width <= 0. || height <= 0.
  190561. #endif
  190562. )
  190563. {
  190564. png_warning(png_ptr, "Invalid sCAL data");
  190565. png_free(png_ptr, buffer);
  190566. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  190567. png_free(png_ptr, swidth);
  190568. png_free(png_ptr, sheight);
  190569. #endif
  190570. return;
  190571. }
  190572. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190573. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  190574. #else
  190575. #ifdef PNG_FIXED_POINT_SUPPORTED
  190576. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  190577. #endif
  190578. #endif
  190579. png_free(png_ptr, buffer);
  190580. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  190581. png_free(png_ptr, swidth);
  190582. png_free(png_ptr, sheight);
  190583. #endif
  190584. }
  190585. #endif
  190586. #if defined(PNG_READ_tIME_SUPPORTED)
  190587. void /* PRIVATE */
  190588. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190589. {
  190590. png_byte buf[7];
  190591. png_time mod_time;
  190592. png_debug(1, "in png_handle_tIME\n");
  190593. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190594. png_error(png_ptr, "Out of place tIME chunk");
  190595. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  190596. {
  190597. png_warning(png_ptr, "Duplicate tIME chunk");
  190598. png_crc_finish(png_ptr, length);
  190599. return;
  190600. }
  190601. if (png_ptr->mode & PNG_HAVE_IDAT)
  190602. png_ptr->mode |= PNG_AFTER_IDAT;
  190603. if (length != 7)
  190604. {
  190605. png_warning(png_ptr, "Incorrect tIME chunk length");
  190606. png_crc_finish(png_ptr, length);
  190607. return;
  190608. }
  190609. png_crc_read(png_ptr, buf, 7);
  190610. if (png_crc_finish(png_ptr, 0))
  190611. return;
  190612. mod_time.second = buf[6];
  190613. mod_time.minute = buf[5];
  190614. mod_time.hour = buf[4];
  190615. mod_time.day = buf[3];
  190616. mod_time.month = buf[2];
  190617. mod_time.year = png_get_uint_16(buf);
  190618. png_set_tIME(png_ptr, info_ptr, &mod_time);
  190619. }
  190620. #endif
  190621. #if defined(PNG_READ_tEXt_SUPPORTED)
  190622. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190623. void /* PRIVATE */
  190624. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190625. {
  190626. png_textp text_ptr;
  190627. png_charp key;
  190628. png_charp text;
  190629. png_uint_32 skip = 0;
  190630. png_size_t slength;
  190631. int ret;
  190632. png_debug(1, "in png_handle_tEXt\n");
  190633. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190634. png_error(png_ptr, "Missing IHDR before tEXt");
  190635. if (png_ptr->mode & PNG_HAVE_IDAT)
  190636. png_ptr->mode |= PNG_AFTER_IDAT;
  190637. #ifdef PNG_MAX_MALLOC_64K
  190638. if (length > (png_uint_32)65535L)
  190639. {
  190640. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  190641. skip = length - (png_uint_32)65535L;
  190642. length = (png_uint_32)65535L;
  190643. }
  190644. #endif
  190645. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190646. if (key == NULL)
  190647. {
  190648. png_warning(png_ptr, "No memory to process text chunk.");
  190649. return;
  190650. }
  190651. slength = (png_size_t)length;
  190652. png_crc_read(png_ptr, (png_bytep)key, slength);
  190653. if (png_crc_finish(png_ptr, skip))
  190654. {
  190655. png_free(png_ptr, key);
  190656. return;
  190657. }
  190658. key[slength] = 0x00;
  190659. for (text = key; *text; text++)
  190660. /* empty loop to find end of key */ ;
  190661. if (text != key + slength)
  190662. text++;
  190663. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  190664. (png_uint_32)png_sizeof(png_text));
  190665. if (text_ptr == NULL)
  190666. {
  190667. png_warning(png_ptr, "Not enough memory to process text chunk.");
  190668. png_free(png_ptr, key);
  190669. return;
  190670. }
  190671. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  190672. text_ptr->key = key;
  190673. #ifdef PNG_iTXt_SUPPORTED
  190674. text_ptr->lang = NULL;
  190675. text_ptr->lang_key = NULL;
  190676. text_ptr->itxt_length = 0;
  190677. #endif
  190678. text_ptr->text = text;
  190679. text_ptr->text_length = png_strlen(text);
  190680. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190681. png_free(png_ptr, key);
  190682. png_free(png_ptr, text_ptr);
  190683. if (ret)
  190684. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  190685. }
  190686. #endif
  190687. #if defined(PNG_READ_zTXt_SUPPORTED)
  190688. /* note: this does not correctly handle chunks that are > 64K under DOS */
  190689. void /* PRIVATE */
  190690. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190691. {
  190692. png_textp text_ptr;
  190693. png_charp chunkdata;
  190694. png_charp text;
  190695. int comp_type;
  190696. int ret;
  190697. png_size_t slength, prefix_len, data_len;
  190698. png_debug(1, "in png_handle_zTXt\n");
  190699. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190700. png_error(png_ptr, "Missing IHDR before zTXt");
  190701. if (png_ptr->mode & PNG_HAVE_IDAT)
  190702. png_ptr->mode |= PNG_AFTER_IDAT;
  190703. #ifdef PNG_MAX_MALLOC_64K
  190704. /* We will no doubt have problems with chunks even half this size, but
  190705. there is no hard and fast rule to tell us where to stop. */
  190706. if (length > (png_uint_32)65535L)
  190707. {
  190708. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  190709. png_crc_finish(png_ptr, length);
  190710. return;
  190711. }
  190712. #endif
  190713. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190714. if (chunkdata == NULL)
  190715. {
  190716. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  190717. return;
  190718. }
  190719. slength = (png_size_t)length;
  190720. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190721. if (png_crc_finish(png_ptr, 0))
  190722. {
  190723. png_free(png_ptr, chunkdata);
  190724. return;
  190725. }
  190726. chunkdata[slength] = 0x00;
  190727. for (text = chunkdata; *text; text++)
  190728. /* empty loop */ ;
  190729. /* zTXt must have some text after the chunkdataword */
  190730. if (text >= chunkdata + slength - 2)
  190731. {
  190732. png_warning(png_ptr, "Truncated zTXt chunk");
  190733. png_free(png_ptr, chunkdata);
  190734. return;
  190735. }
  190736. else
  190737. {
  190738. comp_type = *(++text);
  190739. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  190740. {
  190741. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  190742. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  190743. }
  190744. text++; /* skip the compression_method byte */
  190745. }
  190746. prefix_len = text - chunkdata;
  190747. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  190748. (png_size_t)length, prefix_len, &data_len);
  190749. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  190750. (png_uint_32)png_sizeof(png_text));
  190751. if (text_ptr == NULL)
  190752. {
  190753. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  190754. png_free(png_ptr, chunkdata);
  190755. return;
  190756. }
  190757. text_ptr->compression = comp_type;
  190758. text_ptr->key = chunkdata;
  190759. #ifdef PNG_iTXt_SUPPORTED
  190760. text_ptr->lang = NULL;
  190761. text_ptr->lang_key = NULL;
  190762. text_ptr->itxt_length = 0;
  190763. #endif
  190764. text_ptr->text = chunkdata + prefix_len;
  190765. text_ptr->text_length = data_len;
  190766. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190767. png_free(png_ptr, text_ptr);
  190768. png_free(png_ptr, chunkdata);
  190769. if (ret)
  190770. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  190771. }
  190772. #endif
  190773. #if defined(PNG_READ_iTXt_SUPPORTED)
  190774. /* note: this does not correctly handle chunks that are > 64K under DOS */
  190775. void /* PRIVATE */
  190776. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190777. {
  190778. png_textp text_ptr;
  190779. png_charp chunkdata;
  190780. png_charp key, lang, text, lang_key;
  190781. int comp_flag;
  190782. int comp_type = 0;
  190783. int ret;
  190784. png_size_t slength, prefix_len, data_len;
  190785. png_debug(1, "in png_handle_iTXt\n");
  190786. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190787. png_error(png_ptr, "Missing IHDR before iTXt");
  190788. if (png_ptr->mode & PNG_HAVE_IDAT)
  190789. png_ptr->mode |= PNG_AFTER_IDAT;
  190790. #ifdef PNG_MAX_MALLOC_64K
  190791. /* We will no doubt have problems with chunks even half this size, but
  190792. there is no hard and fast rule to tell us where to stop. */
  190793. if (length > (png_uint_32)65535L)
  190794. {
  190795. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  190796. png_crc_finish(png_ptr, length);
  190797. return;
  190798. }
  190799. #endif
  190800. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190801. if (chunkdata == NULL)
  190802. {
  190803. png_warning(png_ptr, "No memory to process iTXt chunk.");
  190804. return;
  190805. }
  190806. slength = (png_size_t)length;
  190807. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190808. if (png_crc_finish(png_ptr, 0))
  190809. {
  190810. png_free(png_ptr, chunkdata);
  190811. return;
  190812. }
  190813. chunkdata[slength] = 0x00;
  190814. for (lang = chunkdata; *lang; lang++)
  190815. /* empty loop */ ;
  190816. lang++; /* skip NUL separator */
  190817. /* iTXt must have a language tag (possibly empty), two compression bytes,
  190818. translated keyword (possibly empty), and possibly some text after the
  190819. keyword */
  190820. if (lang >= chunkdata + slength - 3)
  190821. {
  190822. png_warning(png_ptr, "Truncated iTXt chunk");
  190823. png_free(png_ptr, chunkdata);
  190824. return;
  190825. }
  190826. else
  190827. {
  190828. comp_flag = *lang++;
  190829. comp_type = *lang++;
  190830. }
  190831. for (lang_key = lang; *lang_key; lang_key++)
  190832. /* empty loop */ ;
  190833. lang_key++; /* skip NUL separator */
  190834. if (lang_key >= chunkdata + slength)
  190835. {
  190836. png_warning(png_ptr, "Truncated iTXt chunk");
  190837. png_free(png_ptr, chunkdata);
  190838. return;
  190839. }
  190840. for (text = lang_key; *text; text++)
  190841. /* empty loop */ ;
  190842. text++; /* skip NUL separator */
  190843. if (text >= chunkdata + slength)
  190844. {
  190845. png_warning(png_ptr, "Malformed iTXt chunk");
  190846. png_free(png_ptr, chunkdata);
  190847. return;
  190848. }
  190849. prefix_len = text - chunkdata;
  190850. key=chunkdata;
  190851. if (comp_flag)
  190852. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  190853. (size_t)length, prefix_len, &data_len);
  190854. else
  190855. data_len=png_strlen(chunkdata + prefix_len);
  190856. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  190857. (png_uint_32)png_sizeof(png_text));
  190858. if (text_ptr == NULL)
  190859. {
  190860. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  190861. png_free(png_ptr, chunkdata);
  190862. return;
  190863. }
  190864. text_ptr->compression = (int)comp_flag + 1;
  190865. text_ptr->lang_key = chunkdata+(lang_key-key);
  190866. text_ptr->lang = chunkdata+(lang-key);
  190867. text_ptr->itxt_length = data_len;
  190868. text_ptr->text_length = 0;
  190869. text_ptr->key = chunkdata;
  190870. text_ptr->text = chunkdata + prefix_len;
  190871. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190872. png_free(png_ptr, text_ptr);
  190873. png_free(png_ptr, chunkdata);
  190874. if (ret)
  190875. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  190876. }
  190877. #endif
  190878. /* This function is called when we haven't found a handler for a
  190879. chunk. If there isn't a problem with the chunk itself (ie bad
  190880. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  190881. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  190882. case it will be saved away to be written out later. */
  190883. void /* PRIVATE */
  190884. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190885. {
  190886. png_uint_32 skip = 0;
  190887. png_debug(1, "in png_handle_unknown\n");
  190888. if (png_ptr->mode & PNG_HAVE_IDAT)
  190889. {
  190890. #ifdef PNG_USE_LOCAL_ARRAYS
  190891. PNG_CONST PNG_IDAT;
  190892. #endif
  190893. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  190894. png_ptr->mode |= PNG_AFTER_IDAT;
  190895. }
  190896. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  190897. if (!(png_ptr->chunk_name[0] & 0x20))
  190898. {
  190899. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  190900. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  190901. PNG_HANDLE_CHUNK_ALWAYS
  190902. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190903. && png_ptr->read_user_chunk_fn == NULL
  190904. #endif
  190905. )
  190906. #endif
  190907. png_chunk_error(png_ptr, "unknown critical chunk");
  190908. }
  190909. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  190910. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  190911. (png_ptr->read_user_chunk_fn != NULL))
  190912. {
  190913. #ifdef PNG_MAX_MALLOC_64K
  190914. if (length > (png_uint_32)65535L)
  190915. {
  190916. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  190917. skip = length - (png_uint_32)65535L;
  190918. length = (png_uint_32)65535L;
  190919. }
  190920. #endif
  190921. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  190922. (png_charp)png_ptr->chunk_name, 5);
  190923. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  190924. png_ptr->unknown_chunk.size = (png_size_t)length;
  190925. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  190926. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190927. if(png_ptr->read_user_chunk_fn != NULL)
  190928. {
  190929. /* callback to user unknown chunk handler */
  190930. int ret;
  190931. ret = (*(png_ptr->read_user_chunk_fn))
  190932. (png_ptr, &png_ptr->unknown_chunk);
  190933. if (ret < 0)
  190934. png_chunk_error(png_ptr, "error in user chunk");
  190935. if (ret == 0)
  190936. {
  190937. if (!(png_ptr->chunk_name[0] & 0x20))
  190938. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  190939. PNG_HANDLE_CHUNK_ALWAYS)
  190940. png_chunk_error(png_ptr, "unknown critical chunk");
  190941. png_set_unknown_chunks(png_ptr, info_ptr,
  190942. &png_ptr->unknown_chunk, 1);
  190943. }
  190944. }
  190945. #else
  190946. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  190947. #endif
  190948. png_free(png_ptr, png_ptr->unknown_chunk.data);
  190949. png_ptr->unknown_chunk.data = NULL;
  190950. }
  190951. else
  190952. #endif
  190953. skip = length;
  190954. png_crc_finish(png_ptr, skip);
  190955. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190956. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  190957. #endif
  190958. }
  190959. /* This function is called to verify that a chunk name is valid.
  190960. This function can't have the "critical chunk check" incorporated
  190961. into it, since in the future we will need to be able to call user
  190962. functions to handle unknown critical chunks after we check that
  190963. the chunk name itself is valid. */
  190964. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  190965. void /* PRIVATE */
  190966. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  190967. {
  190968. png_debug(1, "in png_check_chunk_name\n");
  190969. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  190970. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  190971. {
  190972. png_chunk_error(png_ptr, "invalid chunk type");
  190973. }
  190974. }
  190975. /* Combines the row recently read in with the existing pixels in the
  190976. row. This routine takes care of alpha and transparency if requested.
  190977. This routine also handles the two methods of progressive display
  190978. of interlaced images, depending on the mask value.
  190979. The mask value describes which pixels are to be combined with
  190980. the row. The pattern always repeats every 8 pixels, so just 8
  190981. bits are needed. A one indicates the pixel is to be combined,
  190982. a zero indicates the pixel is to be skipped. This is in addition
  190983. to any alpha or transparency value associated with the pixel. If
  190984. you want all pixels to be combined, pass 0xff (255) in mask. */
  190985. void /* PRIVATE */
  190986. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  190987. {
  190988. png_debug(1,"in png_combine_row\n");
  190989. if (mask == 0xff)
  190990. {
  190991. png_memcpy(row, png_ptr->row_buf + 1,
  190992. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  190993. }
  190994. else
  190995. {
  190996. switch (png_ptr->row_info.pixel_depth)
  190997. {
  190998. case 1:
  190999. {
  191000. png_bytep sp = png_ptr->row_buf + 1;
  191001. png_bytep dp = row;
  191002. int s_inc, s_start, s_end;
  191003. int m = 0x80;
  191004. int shift;
  191005. png_uint_32 i;
  191006. png_uint_32 row_width = png_ptr->width;
  191007. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191008. if (png_ptr->transformations & PNG_PACKSWAP)
  191009. {
  191010. s_start = 0;
  191011. s_end = 7;
  191012. s_inc = 1;
  191013. }
  191014. else
  191015. #endif
  191016. {
  191017. s_start = 7;
  191018. s_end = 0;
  191019. s_inc = -1;
  191020. }
  191021. shift = s_start;
  191022. for (i = 0; i < row_width; i++)
  191023. {
  191024. if (m & mask)
  191025. {
  191026. int value;
  191027. value = (*sp >> shift) & 0x01;
  191028. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191029. *dp |= (png_byte)(value << shift);
  191030. }
  191031. if (shift == s_end)
  191032. {
  191033. shift = s_start;
  191034. sp++;
  191035. dp++;
  191036. }
  191037. else
  191038. shift += s_inc;
  191039. if (m == 1)
  191040. m = 0x80;
  191041. else
  191042. m >>= 1;
  191043. }
  191044. break;
  191045. }
  191046. case 2:
  191047. {
  191048. png_bytep sp = png_ptr->row_buf + 1;
  191049. png_bytep dp = row;
  191050. int s_start, s_end, s_inc;
  191051. int m = 0x80;
  191052. int shift;
  191053. png_uint_32 i;
  191054. png_uint_32 row_width = png_ptr->width;
  191055. int value;
  191056. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191057. if (png_ptr->transformations & PNG_PACKSWAP)
  191058. {
  191059. s_start = 0;
  191060. s_end = 6;
  191061. s_inc = 2;
  191062. }
  191063. else
  191064. #endif
  191065. {
  191066. s_start = 6;
  191067. s_end = 0;
  191068. s_inc = -2;
  191069. }
  191070. shift = s_start;
  191071. for (i = 0; i < row_width; i++)
  191072. {
  191073. if (m & mask)
  191074. {
  191075. value = (*sp >> shift) & 0x03;
  191076. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191077. *dp |= (png_byte)(value << shift);
  191078. }
  191079. if (shift == s_end)
  191080. {
  191081. shift = s_start;
  191082. sp++;
  191083. dp++;
  191084. }
  191085. else
  191086. shift += s_inc;
  191087. if (m == 1)
  191088. m = 0x80;
  191089. else
  191090. m >>= 1;
  191091. }
  191092. break;
  191093. }
  191094. case 4:
  191095. {
  191096. png_bytep sp = png_ptr->row_buf + 1;
  191097. png_bytep dp = row;
  191098. int s_start, s_end, s_inc;
  191099. int m = 0x80;
  191100. int shift;
  191101. png_uint_32 i;
  191102. png_uint_32 row_width = png_ptr->width;
  191103. int value;
  191104. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191105. if (png_ptr->transformations & PNG_PACKSWAP)
  191106. {
  191107. s_start = 0;
  191108. s_end = 4;
  191109. s_inc = 4;
  191110. }
  191111. else
  191112. #endif
  191113. {
  191114. s_start = 4;
  191115. s_end = 0;
  191116. s_inc = -4;
  191117. }
  191118. shift = s_start;
  191119. for (i = 0; i < row_width; i++)
  191120. {
  191121. if (m & mask)
  191122. {
  191123. value = (*sp >> shift) & 0xf;
  191124. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191125. *dp |= (png_byte)(value << shift);
  191126. }
  191127. if (shift == s_end)
  191128. {
  191129. shift = s_start;
  191130. sp++;
  191131. dp++;
  191132. }
  191133. else
  191134. shift += s_inc;
  191135. if (m == 1)
  191136. m = 0x80;
  191137. else
  191138. m >>= 1;
  191139. }
  191140. break;
  191141. }
  191142. default:
  191143. {
  191144. png_bytep sp = png_ptr->row_buf + 1;
  191145. png_bytep dp = row;
  191146. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  191147. png_uint_32 i;
  191148. png_uint_32 row_width = png_ptr->width;
  191149. png_byte m = 0x80;
  191150. for (i = 0; i < row_width; i++)
  191151. {
  191152. if (m & mask)
  191153. {
  191154. png_memcpy(dp, sp, pixel_bytes);
  191155. }
  191156. sp += pixel_bytes;
  191157. dp += pixel_bytes;
  191158. if (m == 1)
  191159. m = 0x80;
  191160. else
  191161. m >>= 1;
  191162. }
  191163. break;
  191164. }
  191165. }
  191166. }
  191167. }
  191168. #ifdef PNG_READ_INTERLACING_SUPPORTED
  191169. /* OLD pre-1.0.9 interface:
  191170. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  191171. png_uint_32 transformations)
  191172. */
  191173. void /* PRIVATE */
  191174. png_do_read_interlace(png_structp png_ptr)
  191175. {
  191176. png_row_infop row_info = &(png_ptr->row_info);
  191177. png_bytep row = png_ptr->row_buf + 1;
  191178. int pass = png_ptr->pass;
  191179. png_uint_32 transformations = png_ptr->transformations;
  191180. #ifdef PNG_USE_LOCAL_ARRAYS
  191181. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191182. /* offset to next interlace block */
  191183. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191184. #endif
  191185. png_debug(1,"in png_do_read_interlace\n");
  191186. if (row != NULL && row_info != NULL)
  191187. {
  191188. png_uint_32 final_width;
  191189. final_width = row_info->width * png_pass_inc[pass];
  191190. switch (row_info->pixel_depth)
  191191. {
  191192. case 1:
  191193. {
  191194. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  191195. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  191196. int sshift, dshift;
  191197. int s_start, s_end, s_inc;
  191198. int jstop = png_pass_inc[pass];
  191199. png_byte v;
  191200. png_uint_32 i;
  191201. int j;
  191202. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191203. if (transformations & PNG_PACKSWAP)
  191204. {
  191205. sshift = (int)((row_info->width + 7) & 0x07);
  191206. dshift = (int)((final_width + 7) & 0x07);
  191207. s_start = 7;
  191208. s_end = 0;
  191209. s_inc = -1;
  191210. }
  191211. else
  191212. #endif
  191213. {
  191214. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  191215. dshift = 7 - (int)((final_width + 7) & 0x07);
  191216. s_start = 0;
  191217. s_end = 7;
  191218. s_inc = 1;
  191219. }
  191220. for (i = 0; i < row_info->width; i++)
  191221. {
  191222. v = (png_byte)((*sp >> sshift) & 0x01);
  191223. for (j = 0; j < jstop; j++)
  191224. {
  191225. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  191226. *dp |= (png_byte)(v << dshift);
  191227. if (dshift == s_end)
  191228. {
  191229. dshift = s_start;
  191230. dp--;
  191231. }
  191232. else
  191233. dshift += s_inc;
  191234. }
  191235. if (sshift == s_end)
  191236. {
  191237. sshift = s_start;
  191238. sp--;
  191239. }
  191240. else
  191241. sshift += s_inc;
  191242. }
  191243. break;
  191244. }
  191245. case 2:
  191246. {
  191247. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  191248. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  191249. int sshift, dshift;
  191250. int s_start, s_end, s_inc;
  191251. int jstop = png_pass_inc[pass];
  191252. png_uint_32 i;
  191253. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191254. if (transformations & PNG_PACKSWAP)
  191255. {
  191256. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  191257. dshift = (int)(((final_width + 3) & 0x03) << 1);
  191258. s_start = 6;
  191259. s_end = 0;
  191260. s_inc = -2;
  191261. }
  191262. else
  191263. #endif
  191264. {
  191265. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  191266. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  191267. s_start = 0;
  191268. s_end = 6;
  191269. s_inc = 2;
  191270. }
  191271. for (i = 0; i < row_info->width; i++)
  191272. {
  191273. png_byte v;
  191274. int j;
  191275. v = (png_byte)((*sp >> sshift) & 0x03);
  191276. for (j = 0; j < jstop; j++)
  191277. {
  191278. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  191279. *dp |= (png_byte)(v << dshift);
  191280. if (dshift == s_end)
  191281. {
  191282. dshift = s_start;
  191283. dp--;
  191284. }
  191285. else
  191286. dshift += s_inc;
  191287. }
  191288. if (sshift == s_end)
  191289. {
  191290. sshift = s_start;
  191291. sp--;
  191292. }
  191293. else
  191294. sshift += s_inc;
  191295. }
  191296. break;
  191297. }
  191298. case 4:
  191299. {
  191300. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  191301. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  191302. int sshift, dshift;
  191303. int s_start, s_end, s_inc;
  191304. png_uint_32 i;
  191305. int jstop = png_pass_inc[pass];
  191306. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191307. if (transformations & PNG_PACKSWAP)
  191308. {
  191309. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  191310. dshift = (int)(((final_width + 1) & 0x01) << 2);
  191311. s_start = 4;
  191312. s_end = 0;
  191313. s_inc = -4;
  191314. }
  191315. else
  191316. #endif
  191317. {
  191318. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  191319. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  191320. s_start = 0;
  191321. s_end = 4;
  191322. s_inc = 4;
  191323. }
  191324. for (i = 0; i < row_info->width; i++)
  191325. {
  191326. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  191327. int j;
  191328. for (j = 0; j < jstop; j++)
  191329. {
  191330. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  191331. *dp |= (png_byte)(v << dshift);
  191332. if (dshift == s_end)
  191333. {
  191334. dshift = s_start;
  191335. dp--;
  191336. }
  191337. else
  191338. dshift += s_inc;
  191339. }
  191340. if (sshift == s_end)
  191341. {
  191342. sshift = s_start;
  191343. sp--;
  191344. }
  191345. else
  191346. sshift += s_inc;
  191347. }
  191348. break;
  191349. }
  191350. default:
  191351. {
  191352. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  191353. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  191354. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  191355. int jstop = png_pass_inc[pass];
  191356. png_uint_32 i;
  191357. for (i = 0; i < row_info->width; i++)
  191358. {
  191359. png_byte v[8];
  191360. int j;
  191361. png_memcpy(v, sp, pixel_bytes);
  191362. for (j = 0; j < jstop; j++)
  191363. {
  191364. png_memcpy(dp, v, pixel_bytes);
  191365. dp -= pixel_bytes;
  191366. }
  191367. sp -= pixel_bytes;
  191368. }
  191369. break;
  191370. }
  191371. }
  191372. row_info->width = final_width;
  191373. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  191374. }
  191375. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  191376. transformations = transformations; /* silence compiler warning */
  191377. #endif
  191378. }
  191379. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  191380. void /* PRIVATE */
  191381. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  191382. png_bytep prev_row, int filter)
  191383. {
  191384. png_debug(1, "in png_read_filter_row\n");
  191385. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  191386. switch (filter)
  191387. {
  191388. case PNG_FILTER_VALUE_NONE:
  191389. break;
  191390. case PNG_FILTER_VALUE_SUB:
  191391. {
  191392. png_uint_32 i;
  191393. png_uint_32 istop = row_info->rowbytes;
  191394. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191395. png_bytep rp = row + bpp;
  191396. png_bytep lp = row;
  191397. for (i = bpp; i < istop; i++)
  191398. {
  191399. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  191400. rp++;
  191401. }
  191402. break;
  191403. }
  191404. case PNG_FILTER_VALUE_UP:
  191405. {
  191406. png_uint_32 i;
  191407. png_uint_32 istop = row_info->rowbytes;
  191408. png_bytep rp = row;
  191409. png_bytep pp = prev_row;
  191410. for (i = 0; i < istop; i++)
  191411. {
  191412. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  191413. rp++;
  191414. }
  191415. break;
  191416. }
  191417. case PNG_FILTER_VALUE_AVG:
  191418. {
  191419. png_uint_32 i;
  191420. png_bytep rp = row;
  191421. png_bytep pp = prev_row;
  191422. png_bytep lp = row;
  191423. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191424. png_uint_32 istop = row_info->rowbytes - bpp;
  191425. for (i = 0; i < bpp; i++)
  191426. {
  191427. *rp = (png_byte)(((int)(*rp) +
  191428. ((int)(*pp++) / 2 )) & 0xff);
  191429. rp++;
  191430. }
  191431. for (i = 0; i < istop; i++)
  191432. {
  191433. *rp = (png_byte)(((int)(*rp) +
  191434. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  191435. rp++;
  191436. }
  191437. break;
  191438. }
  191439. case PNG_FILTER_VALUE_PAETH:
  191440. {
  191441. png_uint_32 i;
  191442. png_bytep rp = row;
  191443. png_bytep pp = prev_row;
  191444. png_bytep lp = row;
  191445. png_bytep cp = prev_row;
  191446. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191447. png_uint_32 istop=row_info->rowbytes - bpp;
  191448. for (i = 0; i < bpp; i++)
  191449. {
  191450. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  191451. rp++;
  191452. }
  191453. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  191454. {
  191455. int a, b, c, pa, pb, pc, p;
  191456. a = *lp++;
  191457. b = *pp++;
  191458. c = *cp++;
  191459. p = b - c;
  191460. pc = a - c;
  191461. #ifdef PNG_USE_ABS
  191462. pa = abs(p);
  191463. pb = abs(pc);
  191464. pc = abs(p + pc);
  191465. #else
  191466. pa = p < 0 ? -p : p;
  191467. pb = pc < 0 ? -pc : pc;
  191468. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  191469. #endif
  191470. /*
  191471. if (pa <= pb && pa <= pc)
  191472. p = a;
  191473. else if (pb <= pc)
  191474. p = b;
  191475. else
  191476. p = c;
  191477. */
  191478. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  191479. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  191480. rp++;
  191481. }
  191482. break;
  191483. }
  191484. default:
  191485. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  191486. *row=0;
  191487. break;
  191488. }
  191489. }
  191490. void /* PRIVATE */
  191491. png_read_finish_row(png_structp png_ptr)
  191492. {
  191493. #ifdef PNG_USE_LOCAL_ARRAYS
  191494. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191495. /* start of interlace block */
  191496. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  191497. /* offset to next interlace block */
  191498. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191499. /* start of interlace block in the y direction */
  191500. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  191501. /* offset to next interlace block in the y direction */
  191502. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  191503. #endif
  191504. png_debug(1, "in png_read_finish_row\n");
  191505. png_ptr->row_number++;
  191506. if (png_ptr->row_number < png_ptr->num_rows)
  191507. return;
  191508. if (png_ptr->interlaced)
  191509. {
  191510. png_ptr->row_number = 0;
  191511. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  191512. png_ptr->rowbytes + 1);
  191513. do
  191514. {
  191515. png_ptr->pass++;
  191516. if (png_ptr->pass >= 7)
  191517. break;
  191518. png_ptr->iwidth = (png_ptr->width +
  191519. png_pass_inc[png_ptr->pass] - 1 -
  191520. png_pass_start[png_ptr->pass]) /
  191521. png_pass_inc[png_ptr->pass];
  191522. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  191523. png_ptr->iwidth) + 1;
  191524. if (!(png_ptr->transformations & PNG_INTERLACE))
  191525. {
  191526. png_ptr->num_rows = (png_ptr->height +
  191527. png_pass_yinc[png_ptr->pass] - 1 -
  191528. png_pass_ystart[png_ptr->pass]) /
  191529. png_pass_yinc[png_ptr->pass];
  191530. if (!(png_ptr->num_rows))
  191531. continue;
  191532. }
  191533. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  191534. break;
  191535. } while (png_ptr->iwidth == 0);
  191536. if (png_ptr->pass < 7)
  191537. return;
  191538. }
  191539. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  191540. {
  191541. #ifdef PNG_USE_LOCAL_ARRAYS
  191542. PNG_CONST PNG_IDAT;
  191543. #endif
  191544. char extra;
  191545. int ret;
  191546. png_ptr->zstream.next_out = (Bytef *)&extra;
  191547. png_ptr->zstream.avail_out = (uInt)1;
  191548. for(;;)
  191549. {
  191550. if (!(png_ptr->zstream.avail_in))
  191551. {
  191552. while (!png_ptr->idat_size)
  191553. {
  191554. png_byte chunk_length[4];
  191555. png_crc_finish(png_ptr, 0);
  191556. png_read_data(png_ptr, chunk_length, 4);
  191557. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  191558. png_reset_crc(png_ptr);
  191559. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  191560. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  191561. png_error(png_ptr, "Not enough image data");
  191562. }
  191563. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  191564. png_ptr->zstream.next_in = png_ptr->zbuf;
  191565. if (png_ptr->zbuf_size > png_ptr->idat_size)
  191566. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  191567. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  191568. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  191569. }
  191570. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  191571. if (ret == Z_STREAM_END)
  191572. {
  191573. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  191574. png_ptr->idat_size)
  191575. png_warning(png_ptr, "Extra compressed data");
  191576. png_ptr->mode |= PNG_AFTER_IDAT;
  191577. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  191578. break;
  191579. }
  191580. if (ret != Z_OK)
  191581. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  191582. "Decompression Error");
  191583. if (!(png_ptr->zstream.avail_out))
  191584. {
  191585. png_warning(png_ptr, "Extra compressed data.");
  191586. png_ptr->mode |= PNG_AFTER_IDAT;
  191587. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  191588. break;
  191589. }
  191590. }
  191591. png_ptr->zstream.avail_out = 0;
  191592. }
  191593. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  191594. png_warning(png_ptr, "Extra compression data");
  191595. inflateReset(&png_ptr->zstream);
  191596. png_ptr->mode |= PNG_AFTER_IDAT;
  191597. }
  191598. void /* PRIVATE */
  191599. png_read_start_row(png_structp png_ptr)
  191600. {
  191601. #ifdef PNG_USE_LOCAL_ARRAYS
  191602. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191603. /* start of interlace block */
  191604. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  191605. /* offset to next interlace block */
  191606. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191607. /* start of interlace block in the y direction */
  191608. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  191609. /* offset to next interlace block in the y direction */
  191610. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  191611. #endif
  191612. int max_pixel_depth;
  191613. png_uint_32 row_bytes;
  191614. png_debug(1, "in png_read_start_row\n");
  191615. png_ptr->zstream.avail_in = 0;
  191616. png_init_read_transformations(png_ptr);
  191617. if (png_ptr->interlaced)
  191618. {
  191619. if (!(png_ptr->transformations & PNG_INTERLACE))
  191620. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  191621. png_pass_ystart[0]) / png_pass_yinc[0];
  191622. else
  191623. png_ptr->num_rows = png_ptr->height;
  191624. png_ptr->iwidth = (png_ptr->width +
  191625. png_pass_inc[png_ptr->pass] - 1 -
  191626. png_pass_start[png_ptr->pass]) /
  191627. png_pass_inc[png_ptr->pass];
  191628. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  191629. png_ptr->irowbytes = (png_size_t)row_bytes;
  191630. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  191631. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  191632. }
  191633. else
  191634. {
  191635. png_ptr->num_rows = png_ptr->height;
  191636. png_ptr->iwidth = png_ptr->width;
  191637. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  191638. }
  191639. max_pixel_depth = png_ptr->pixel_depth;
  191640. #if defined(PNG_READ_PACK_SUPPORTED)
  191641. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  191642. max_pixel_depth = 8;
  191643. #endif
  191644. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191645. if (png_ptr->transformations & PNG_EXPAND)
  191646. {
  191647. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191648. {
  191649. if (png_ptr->num_trans)
  191650. max_pixel_depth = 32;
  191651. else
  191652. max_pixel_depth = 24;
  191653. }
  191654. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  191655. {
  191656. if (max_pixel_depth < 8)
  191657. max_pixel_depth = 8;
  191658. if (png_ptr->num_trans)
  191659. max_pixel_depth *= 2;
  191660. }
  191661. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191662. {
  191663. if (png_ptr->num_trans)
  191664. {
  191665. max_pixel_depth *= 4;
  191666. max_pixel_depth /= 3;
  191667. }
  191668. }
  191669. }
  191670. #endif
  191671. #if defined(PNG_READ_FILLER_SUPPORTED)
  191672. if (png_ptr->transformations & (PNG_FILLER))
  191673. {
  191674. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191675. max_pixel_depth = 32;
  191676. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  191677. {
  191678. if (max_pixel_depth <= 8)
  191679. max_pixel_depth = 16;
  191680. else
  191681. max_pixel_depth = 32;
  191682. }
  191683. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191684. {
  191685. if (max_pixel_depth <= 32)
  191686. max_pixel_depth = 32;
  191687. else
  191688. max_pixel_depth = 64;
  191689. }
  191690. }
  191691. #endif
  191692. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191693. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191694. {
  191695. if (
  191696. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191697. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  191698. #endif
  191699. #if defined(PNG_READ_FILLER_SUPPORTED)
  191700. (png_ptr->transformations & (PNG_FILLER)) ||
  191701. #endif
  191702. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191703. {
  191704. if (max_pixel_depth <= 16)
  191705. max_pixel_depth = 32;
  191706. else
  191707. max_pixel_depth = 64;
  191708. }
  191709. else
  191710. {
  191711. if (max_pixel_depth <= 8)
  191712. {
  191713. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191714. max_pixel_depth = 32;
  191715. else
  191716. max_pixel_depth = 24;
  191717. }
  191718. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191719. max_pixel_depth = 64;
  191720. else
  191721. max_pixel_depth = 48;
  191722. }
  191723. }
  191724. #endif
  191725. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  191726. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191727. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191728. {
  191729. int user_pixel_depth=png_ptr->user_transform_depth*
  191730. png_ptr->user_transform_channels;
  191731. if(user_pixel_depth > max_pixel_depth)
  191732. max_pixel_depth=user_pixel_depth;
  191733. }
  191734. #endif
  191735. /* align the width on the next larger 8 pixels. Mainly used
  191736. for interlacing */
  191737. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  191738. /* calculate the maximum bytes needed, adding a byte and a pixel
  191739. for safety's sake */
  191740. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  191741. 1 + ((max_pixel_depth + 7) >> 3);
  191742. #ifdef PNG_MAX_MALLOC_64K
  191743. if (row_bytes > (png_uint_32)65536L)
  191744. png_error(png_ptr, "This image requires a row greater than 64KB");
  191745. #endif
  191746. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  191747. png_ptr->row_buf = png_ptr->big_row_buf+32;
  191748. #ifdef PNG_MAX_MALLOC_64K
  191749. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  191750. png_error(png_ptr, "This image requires a row greater than 64KB");
  191751. #endif
  191752. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  191753. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  191754. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  191755. png_ptr->rowbytes + 1));
  191756. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  191757. png_debug1(3, "width = %lu,\n", png_ptr->width);
  191758. png_debug1(3, "height = %lu,\n", png_ptr->height);
  191759. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  191760. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  191761. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  191762. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  191763. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  191764. }
  191765. #endif /* PNG_READ_SUPPORTED */
  191766. /********* End of inlined file: pngrutil.c *********/
  191767. /********* Start of inlined file: pngset.c *********/
  191768. /* pngset.c - storage of image information into info struct
  191769. *
  191770. * Last changed in libpng 1.2.21 [October 4, 2007]
  191771. * For conditions of distribution and use, see copyright notice in png.h
  191772. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191773. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191774. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191775. *
  191776. * The functions here are used during reads to store data from the file
  191777. * into the info struct, and during writes to store application data
  191778. * into the info struct for writing into the file. This abstracts the
  191779. * info struct and allows us to change the structure in the future.
  191780. */
  191781. #define PNG_INTERNAL
  191782. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  191783. #if defined(PNG_bKGD_SUPPORTED)
  191784. void PNGAPI
  191785. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  191786. {
  191787. png_debug1(1, "in %s storage function\n", "bKGD");
  191788. if (png_ptr == NULL || info_ptr == NULL)
  191789. return;
  191790. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  191791. info_ptr->valid |= PNG_INFO_bKGD;
  191792. }
  191793. #endif
  191794. #if defined(PNG_cHRM_SUPPORTED)
  191795. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191796. void PNGAPI
  191797. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  191798. double white_x, double white_y, double red_x, double red_y,
  191799. double green_x, double green_y, double blue_x, double blue_y)
  191800. {
  191801. png_debug1(1, "in %s storage function\n", "cHRM");
  191802. if (png_ptr == NULL || info_ptr == NULL)
  191803. return;
  191804. if (white_x < 0.0 || white_y < 0.0 ||
  191805. red_x < 0.0 || red_y < 0.0 ||
  191806. green_x < 0.0 || green_y < 0.0 ||
  191807. blue_x < 0.0 || blue_y < 0.0)
  191808. {
  191809. png_warning(png_ptr,
  191810. "Ignoring attempt to set negative chromaticity value");
  191811. return;
  191812. }
  191813. if (white_x > 21474.83 || white_y > 21474.83 ||
  191814. red_x > 21474.83 || red_y > 21474.83 ||
  191815. green_x > 21474.83 || green_y > 21474.83 ||
  191816. blue_x > 21474.83 || blue_y > 21474.83)
  191817. {
  191818. png_warning(png_ptr,
  191819. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  191820. return;
  191821. }
  191822. info_ptr->x_white = (float)white_x;
  191823. info_ptr->y_white = (float)white_y;
  191824. info_ptr->x_red = (float)red_x;
  191825. info_ptr->y_red = (float)red_y;
  191826. info_ptr->x_green = (float)green_x;
  191827. info_ptr->y_green = (float)green_y;
  191828. info_ptr->x_blue = (float)blue_x;
  191829. info_ptr->y_blue = (float)blue_y;
  191830. #ifdef PNG_FIXED_POINT_SUPPORTED
  191831. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  191832. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  191833. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  191834. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  191835. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  191836. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  191837. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  191838. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  191839. #endif
  191840. info_ptr->valid |= PNG_INFO_cHRM;
  191841. }
  191842. #endif
  191843. #ifdef PNG_FIXED_POINT_SUPPORTED
  191844. void PNGAPI
  191845. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  191846. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  191847. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  191848. png_fixed_point blue_x, png_fixed_point blue_y)
  191849. {
  191850. png_debug1(1, "in %s storage function\n", "cHRM");
  191851. if (png_ptr == NULL || info_ptr == NULL)
  191852. return;
  191853. if (white_x < 0 || white_y < 0 ||
  191854. red_x < 0 || red_y < 0 ||
  191855. green_x < 0 || green_y < 0 ||
  191856. blue_x < 0 || blue_y < 0)
  191857. {
  191858. png_warning(png_ptr,
  191859. "Ignoring attempt to set negative chromaticity value");
  191860. return;
  191861. }
  191862. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191863. if (white_x > (double) PNG_UINT_31_MAX ||
  191864. white_y > (double) PNG_UINT_31_MAX ||
  191865. red_x > (double) PNG_UINT_31_MAX ||
  191866. red_y > (double) PNG_UINT_31_MAX ||
  191867. green_x > (double) PNG_UINT_31_MAX ||
  191868. green_y > (double) PNG_UINT_31_MAX ||
  191869. blue_x > (double) PNG_UINT_31_MAX ||
  191870. blue_y > (double) PNG_UINT_31_MAX)
  191871. #else
  191872. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191873. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191874. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191875. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191876. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191877. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191878. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191879. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  191880. #endif
  191881. {
  191882. png_warning(png_ptr,
  191883. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  191884. return;
  191885. }
  191886. info_ptr->int_x_white = white_x;
  191887. info_ptr->int_y_white = white_y;
  191888. info_ptr->int_x_red = red_x;
  191889. info_ptr->int_y_red = red_y;
  191890. info_ptr->int_x_green = green_x;
  191891. info_ptr->int_y_green = green_y;
  191892. info_ptr->int_x_blue = blue_x;
  191893. info_ptr->int_y_blue = blue_y;
  191894. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191895. info_ptr->x_white = (float)(white_x/100000.);
  191896. info_ptr->y_white = (float)(white_y/100000.);
  191897. info_ptr->x_red = (float)( red_x/100000.);
  191898. info_ptr->y_red = (float)( red_y/100000.);
  191899. info_ptr->x_green = (float)(green_x/100000.);
  191900. info_ptr->y_green = (float)(green_y/100000.);
  191901. info_ptr->x_blue = (float)( blue_x/100000.);
  191902. info_ptr->y_blue = (float)( blue_y/100000.);
  191903. #endif
  191904. info_ptr->valid |= PNG_INFO_cHRM;
  191905. }
  191906. #endif
  191907. #endif
  191908. #if defined(PNG_gAMA_SUPPORTED)
  191909. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191910. void PNGAPI
  191911. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  191912. {
  191913. double gamma;
  191914. png_debug1(1, "in %s storage function\n", "gAMA");
  191915. if (png_ptr == NULL || info_ptr == NULL)
  191916. return;
  191917. /* Check for overflow */
  191918. if (file_gamma > 21474.83)
  191919. {
  191920. png_warning(png_ptr, "Limiting gamma to 21474.83");
  191921. gamma=21474.83;
  191922. }
  191923. else
  191924. gamma=file_gamma;
  191925. info_ptr->gamma = (float)gamma;
  191926. #ifdef PNG_FIXED_POINT_SUPPORTED
  191927. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  191928. #endif
  191929. info_ptr->valid |= PNG_INFO_gAMA;
  191930. if(gamma == 0.0)
  191931. png_warning(png_ptr, "Setting gamma=0");
  191932. }
  191933. #endif
  191934. void PNGAPI
  191935. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  191936. int_gamma)
  191937. {
  191938. png_fixed_point gamma;
  191939. png_debug1(1, "in %s storage function\n", "gAMA");
  191940. if (png_ptr == NULL || info_ptr == NULL)
  191941. return;
  191942. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  191943. {
  191944. png_warning(png_ptr, "Limiting gamma to 21474.83");
  191945. gamma=PNG_UINT_31_MAX;
  191946. }
  191947. else
  191948. {
  191949. if (int_gamma < 0)
  191950. {
  191951. png_warning(png_ptr, "Setting negative gamma to zero");
  191952. gamma=0;
  191953. }
  191954. else
  191955. gamma=int_gamma;
  191956. }
  191957. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191958. info_ptr->gamma = (float)(gamma/100000.);
  191959. #endif
  191960. #ifdef PNG_FIXED_POINT_SUPPORTED
  191961. info_ptr->int_gamma = gamma;
  191962. #endif
  191963. info_ptr->valid |= PNG_INFO_gAMA;
  191964. if(gamma == 0)
  191965. png_warning(png_ptr, "Setting gamma=0");
  191966. }
  191967. #endif
  191968. #if defined(PNG_hIST_SUPPORTED)
  191969. void PNGAPI
  191970. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  191971. {
  191972. int i;
  191973. png_debug1(1, "in %s storage function\n", "hIST");
  191974. if (png_ptr == NULL || info_ptr == NULL)
  191975. return;
  191976. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  191977. > PNG_MAX_PALETTE_LENGTH)
  191978. {
  191979. png_warning(png_ptr,
  191980. "Invalid palette size, hIST allocation skipped.");
  191981. return;
  191982. }
  191983. #ifdef PNG_FREE_ME_SUPPORTED
  191984. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  191985. #endif
  191986. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  191987. 1.2.1 */
  191988. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  191989. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  191990. if (png_ptr->hist == NULL)
  191991. {
  191992. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  191993. return;
  191994. }
  191995. for (i = 0; i < info_ptr->num_palette; i++)
  191996. png_ptr->hist[i] = hist[i];
  191997. info_ptr->hist = png_ptr->hist;
  191998. info_ptr->valid |= PNG_INFO_hIST;
  191999. #ifdef PNG_FREE_ME_SUPPORTED
  192000. info_ptr->free_me |= PNG_FREE_HIST;
  192001. #else
  192002. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  192003. #endif
  192004. }
  192005. #endif
  192006. void PNGAPI
  192007. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  192008. png_uint_32 width, png_uint_32 height, int bit_depth,
  192009. int color_type, int interlace_type, int compression_type,
  192010. int filter_type)
  192011. {
  192012. png_debug1(1, "in %s storage function\n", "IHDR");
  192013. if (png_ptr == NULL || info_ptr == NULL)
  192014. return;
  192015. /* check for width and height valid values */
  192016. if (width == 0 || height == 0)
  192017. png_error(png_ptr, "Image width or height is zero in IHDR");
  192018. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192019. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  192020. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192021. #else
  192022. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  192023. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192024. #endif
  192025. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  192026. png_error(png_ptr, "Invalid image size in IHDR");
  192027. if ( width > (PNG_UINT_32_MAX
  192028. >> 3) /* 8-byte RGBA pixels */
  192029. - 64 /* bigrowbuf hack */
  192030. - 1 /* filter byte */
  192031. - 7*8 /* rounding of width to multiple of 8 pixels */
  192032. - 8) /* extra max_pixel_depth pad */
  192033. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  192034. /* check other values */
  192035. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  192036. bit_depth != 8 && bit_depth != 16)
  192037. png_error(png_ptr, "Invalid bit depth in IHDR");
  192038. if (color_type < 0 || color_type == 1 ||
  192039. color_type == 5 || color_type > 6)
  192040. png_error(png_ptr, "Invalid color type in IHDR");
  192041. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  192042. ((color_type == PNG_COLOR_TYPE_RGB ||
  192043. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  192044. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  192045. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  192046. if (interlace_type >= PNG_INTERLACE_LAST)
  192047. png_error(png_ptr, "Unknown interlace method in IHDR");
  192048. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  192049. png_error(png_ptr, "Unknown compression method in IHDR");
  192050. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192051. /* Accept filter_method 64 (intrapixel differencing) only if
  192052. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  192053. * 2. Libpng did not read a PNG signature (this filter_method is only
  192054. * used in PNG datastreams that are embedded in MNG datastreams) and
  192055. * 3. The application called png_permit_mng_features with a mask that
  192056. * included PNG_FLAG_MNG_FILTER_64 and
  192057. * 4. The filter_method is 64 and
  192058. * 5. The color_type is RGB or RGBA
  192059. */
  192060. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  192061. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192062. if(filter_type != PNG_FILTER_TYPE_BASE)
  192063. {
  192064. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  192065. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  192066. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  192067. (color_type == PNG_COLOR_TYPE_RGB ||
  192068. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  192069. png_error(png_ptr, "Unknown filter method in IHDR");
  192070. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  192071. png_warning(png_ptr, "Invalid filter method in IHDR");
  192072. }
  192073. #else
  192074. if(filter_type != PNG_FILTER_TYPE_BASE)
  192075. png_error(png_ptr, "Unknown filter method in IHDR");
  192076. #endif
  192077. info_ptr->width = width;
  192078. info_ptr->height = height;
  192079. info_ptr->bit_depth = (png_byte)bit_depth;
  192080. info_ptr->color_type =(png_byte) color_type;
  192081. info_ptr->compression_type = (png_byte)compression_type;
  192082. info_ptr->filter_type = (png_byte)filter_type;
  192083. info_ptr->interlace_type = (png_byte)interlace_type;
  192084. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192085. info_ptr->channels = 1;
  192086. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192087. info_ptr->channels = 3;
  192088. else
  192089. info_ptr->channels = 1;
  192090. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  192091. info_ptr->channels++;
  192092. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  192093. /* check for potential overflow */
  192094. if (width > (PNG_UINT_32_MAX
  192095. >> 3) /* 8-byte RGBA pixels */
  192096. - 64 /* bigrowbuf hack */
  192097. - 1 /* filter byte */
  192098. - 7*8 /* rounding of width to multiple of 8 pixels */
  192099. - 8) /* extra max_pixel_depth pad */
  192100. info_ptr->rowbytes = (png_size_t)0;
  192101. else
  192102. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  192103. }
  192104. #if defined(PNG_oFFs_SUPPORTED)
  192105. void PNGAPI
  192106. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  192107. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  192108. {
  192109. png_debug1(1, "in %s storage function\n", "oFFs");
  192110. if (png_ptr == NULL || info_ptr == NULL)
  192111. return;
  192112. info_ptr->x_offset = offset_x;
  192113. info_ptr->y_offset = offset_y;
  192114. info_ptr->offset_unit_type = (png_byte)unit_type;
  192115. info_ptr->valid |= PNG_INFO_oFFs;
  192116. }
  192117. #endif
  192118. #if defined(PNG_pCAL_SUPPORTED)
  192119. void PNGAPI
  192120. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  192121. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  192122. png_charp units, png_charpp params)
  192123. {
  192124. png_uint_32 length;
  192125. int i;
  192126. png_debug1(1, "in %s storage function\n", "pCAL");
  192127. if (png_ptr == NULL || info_ptr == NULL)
  192128. return;
  192129. length = png_strlen(purpose) + 1;
  192130. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  192131. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  192132. if (info_ptr->pcal_purpose == NULL)
  192133. {
  192134. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  192135. return;
  192136. }
  192137. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  192138. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  192139. info_ptr->pcal_X0 = X0;
  192140. info_ptr->pcal_X1 = X1;
  192141. info_ptr->pcal_type = (png_byte)type;
  192142. info_ptr->pcal_nparams = (png_byte)nparams;
  192143. length = png_strlen(units) + 1;
  192144. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  192145. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  192146. if (info_ptr->pcal_units == NULL)
  192147. {
  192148. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  192149. return;
  192150. }
  192151. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  192152. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  192153. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  192154. if (info_ptr->pcal_params == NULL)
  192155. {
  192156. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  192157. return;
  192158. }
  192159. info_ptr->pcal_params[nparams] = NULL;
  192160. for (i = 0; i < nparams; i++)
  192161. {
  192162. length = png_strlen(params[i]) + 1;
  192163. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  192164. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  192165. if (info_ptr->pcal_params[i] == NULL)
  192166. {
  192167. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  192168. return;
  192169. }
  192170. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  192171. }
  192172. info_ptr->valid |= PNG_INFO_pCAL;
  192173. #ifdef PNG_FREE_ME_SUPPORTED
  192174. info_ptr->free_me |= PNG_FREE_PCAL;
  192175. #endif
  192176. }
  192177. #endif
  192178. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  192179. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192180. void PNGAPI
  192181. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  192182. int unit, double width, double height)
  192183. {
  192184. png_debug1(1, "in %s storage function\n", "sCAL");
  192185. if (png_ptr == NULL || info_ptr == NULL)
  192186. return;
  192187. info_ptr->scal_unit = (png_byte)unit;
  192188. info_ptr->scal_pixel_width = width;
  192189. info_ptr->scal_pixel_height = height;
  192190. info_ptr->valid |= PNG_INFO_sCAL;
  192191. }
  192192. #else
  192193. #ifdef PNG_FIXED_POINT_SUPPORTED
  192194. void PNGAPI
  192195. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  192196. int unit, png_charp swidth, png_charp sheight)
  192197. {
  192198. png_uint_32 length;
  192199. png_debug1(1, "in %s storage function\n", "sCAL");
  192200. if (png_ptr == NULL || info_ptr == NULL)
  192201. return;
  192202. info_ptr->scal_unit = (png_byte)unit;
  192203. length = png_strlen(swidth) + 1;
  192204. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192205. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  192206. if (info_ptr->scal_s_width == NULL)
  192207. {
  192208. png_warning(png_ptr,
  192209. "Memory allocation failed while processing sCAL.");
  192210. }
  192211. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  192212. length = png_strlen(sheight) + 1;
  192213. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192214. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  192215. if (info_ptr->scal_s_height == NULL)
  192216. {
  192217. png_free (png_ptr, info_ptr->scal_s_width);
  192218. png_warning(png_ptr,
  192219. "Memory allocation failed while processing sCAL.");
  192220. }
  192221. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  192222. info_ptr->valid |= PNG_INFO_sCAL;
  192223. #ifdef PNG_FREE_ME_SUPPORTED
  192224. info_ptr->free_me |= PNG_FREE_SCAL;
  192225. #endif
  192226. }
  192227. #endif
  192228. #endif
  192229. #endif
  192230. #if defined(PNG_pHYs_SUPPORTED)
  192231. void PNGAPI
  192232. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  192233. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  192234. {
  192235. png_debug1(1, "in %s storage function\n", "pHYs");
  192236. if (png_ptr == NULL || info_ptr == NULL)
  192237. return;
  192238. info_ptr->x_pixels_per_unit = res_x;
  192239. info_ptr->y_pixels_per_unit = res_y;
  192240. info_ptr->phys_unit_type = (png_byte)unit_type;
  192241. info_ptr->valid |= PNG_INFO_pHYs;
  192242. }
  192243. #endif
  192244. void PNGAPI
  192245. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  192246. png_colorp palette, int num_palette)
  192247. {
  192248. png_debug1(1, "in %s storage function\n", "PLTE");
  192249. if (png_ptr == NULL || info_ptr == NULL)
  192250. return;
  192251. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  192252. {
  192253. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192254. png_error(png_ptr, "Invalid palette length");
  192255. else
  192256. {
  192257. png_warning(png_ptr, "Invalid palette length");
  192258. return;
  192259. }
  192260. }
  192261. /*
  192262. * It may not actually be necessary to set png_ptr->palette here;
  192263. * we do it for backward compatibility with the way the png_handle_tRNS
  192264. * function used to do the allocation.
  192265. */
  192266. #ifdef PNG_FREE_ME_SUPPORTED
  192267. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  192268. #endif
  192269. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  192270. of num_palette entries,
  192271. in case of an invalid PNG file that has too-large sample values. */
  192272. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  192273. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  192274. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  192275. png_sizeof(png_color));
  192276. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  192277. info_ptr->palette = png_ptr->palette;
  192278. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  192279. #ifdef PNG_FREE_ME_SUPPORTED
  192280. info_ptr->free_me |= PNG_FREE_PLTE;
  192281. #else
  192282. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  192283. #endif
  192284. info_ptr->valid |= PNG_INFO_PLTE;
  192285. }
  192286. #if defined(PNG_sBIT_SUPPORTED)
  192287. void PNGAPI
  192288. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  192289. png_color_8p sig_bit)
  192290. {
  192291. png_debug1(1, "in %s storage function\n", "sBIT");
  192292. if (png_ptr == NULL || info_ptr == NULL)
  192293. return;
  192294. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  192295. info_ptr->valid |= PNG_INFO_sBIT;
  192296. }
  192297. #endif
  192298. #if defined(PNG_sRGB_SUPPORTED)
  192299. void PNGAPI
  192300. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  192301. {
  192302. png_debug1(1, "in %s storage function\n", "sRGB");
  192303. if (png_ptr == NULL || info_ptr == NULL)
  192304. return;
  192305. info_ptr->srgb_intent = (png_byte)intent;
  192306. info_ptr->valid |= PNG_INFO_sRGB;
  192307. }
  192308. void PNGAPI
  192309. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  192310. int intent)
  192311. {
  192312. #if defined(PNG_gAMA_SUPPORTED)
  192313. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192314. float file_gamma;
  192315. #endif
  192316. #ifdef PNG_FIXED_POINT_SUPPORTED
  192317. png_fixed_point int_file_gamma;
  192318. #endif
  192319. #endif
  192320. #if defined(PNG_cHRM_SUPPORTED)
  192321. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192322. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  192323. #endif
  192324. #ifdef PNG_FIXED_POINT_SUPPORTED
  192325. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  192326. int_green_y, int_blue_x, int_blue_y;
  192327. #endif
  192328. #endif
  192329. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  192330. if (png_ptr == NULL || info_ptr == NULL)
  192331. return;
  192332. png_set_sRGB(png_ptr, info_ptr, intent);
  192333. #if defined(PNG_gAMA_SUPPORTED)
  192334. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192335. file_gamma = (float).45455;
  192336. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  192337. #endif
  192338. #ifdef PNG_FIXED_POINT_SUPPORTED
  192339. int_file_gamma = 45455L;
  192340. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  192341. #endif
  192342. #endif
  192343. #if defined(PNG_cHRM_SUPPORTED)
  192344. #ifdef PNG_FIXED_POINT_SUPPORTED
  192345. int_white_x = 31270L;
  192346. int_white_y = 32900L;
  192347. int_red_x = 64000L;
  192348. int_red_y = 33000L;
  192349. int_green_x = 30000L;
  192350. int_green_y = 60000L;
  192351. int_blue_x = 15000L;
  192352. int_blue_y = 6000L;
  192353. png_set_cHRM_fixed(png_ptr, info_ptr,
  192354. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  192355. int_blue_x, int_blue_y);
  192356. #endif
  192357. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192358. white_x = (float).3127;
  192359. white_y = (float).3290;
  192360. red_x = (float).64;
  192361. red_y = (float).33;
  192362. green_x = (float).30;
  192363. green_y = (float).60;
  192364. blue_x = (float).15;
  192365. blue_y = (float).06;
  192366. png_set_cHRM(png_ptr, info_ptr,
  192367. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  192368. #endif
  192369. #endif
  192370. }
  192371. #endif
  192372. #if defined(PNG_iCCP_SUPPORTED)
  192373. void PNGAPI
  192374. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  192375. png_charp name, int compression_type,
  192376. png_charp profile, png_uint_32 proflen)
  192377. {
  192378. png_charp new_iccp_name;
  192379. png_charp new_iccp_profile;
  192380. png_debug1(1, "in %s storage function\n", "iCCP");
  192381. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  192382. return;
  192383. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  192384. if (new_iccp_name == NULL)
  192385. {
  192386. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  192387. return;
  192388. }
  192389. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  192390. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  192391. if (new_iccp_profile == NULL)
  192392. {
  192393. png_free (png_ptr, new_iccp_name);
  192394. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  192395. return;
  192396. }
  192397. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  192398. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  192399. info_ptr->iccp_proflen = proflen;
  192400. info_ptr->iccp_name = new_iccp_name;
  192401. info_ptr->iccp_profile = new_iccp_profile;
  192402. /* Compression is always zero but is here so the API and info structure
  192403. * does not have to change if we introduce multiple compression types */
  192404. info_ptr->iccp_compression = (png_byte)compression_type;
  192405. #ifdef PNG_FREE_ME_SUPPORTED
  192406. info_ptr->free_me |= PNG_FREE_ICCP;
  192407. #endif
  192408. info_ptr->valid |= PNG_INFO_iCCP;
  192409. }
  192410. #endif
  192411. #if defined(PNG_TEXT_SUPPORTED)
  192412. void PNGAPI
  192413. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  192414. int num_text)
  192415. {
  192416. int ret;
  192417. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  192418. if (ret)
  192419. png_error(png_ptr, "Insufficient memory to store text");
  192420. }
  192421. int /* PRIVATE */
  192422. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  192423. int num_text)
  192424. {
  192425. int i;
  192426. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  192427. "text" : (png_const_charp)png_ptr->chunk_name));
  192428. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  192429. return(0);
  192430. /* Make sure we have enough space in the "text" array in info_struct
  192431. * to hold all of the incoming text_ptr objects.
  192432. */
  192433. if (info_ptr->num_text + num_text > info_ptr->max_text)
  192434. {
  192435. if (info_ptr->text != NULL)
  192436. {
  192437. png_textp old_text;
  192438. int old_max;
  192439. old_max = info_ptr->max_text;
  192440. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  192441. old_text = info_ptr->text;
  192442. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  192443. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  192444. if (info_ptr->text == NULL)
  192445. {
  192446. png_free(png_ptr, old_text);
  192447. return(1);
  192448. }
  192449. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  192450. png_sizeof(png_text)));
  192451. png_free(png_ptr, old_text);
  192452. }
  192453. else
  192454. {
  192455. info_ptr->max_text = num_text + 8;
  192456. info_ptr->num_text = 0;
  192457. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  192458. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  192459. if (info_ptr->text == NULL)
  192460. return(1);
  192461. #ifdef PNG_FREE_ME_SUPPORTED
  192462. info_ptr->free_me |= PNG_FREE_TEXT;
  192463. #endif
  192464. }
  192465. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  192466. info_ptr->max_text);
  192467. }
  192468. for (i = 0; i < num_text; i++)
  192469. {
  192470. png_size_t text_length,key_len;
  192471. png_size_t lang_len,lang_key_len;
  192472. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  192473. if (text_ptr[i].key == NULL)
  192474. continue;
  192475. key_len = png_strlen(text_ptr[i].key);
  192476. if(text_ptr[i].compression <= 0)
  192477. {
  192478. lang_len = 0;
  192479. lang_key_len = 0;
  192480. }
  192481. else
  192482. #ifdef PNG_iTXt_SUPPORTED
  192483. {
  192484. /* set iTXt data */
  192485. if (text_ptr[i].lang != NULL)
  192486. lang_len = png_strlen(text_ptr[i].lang);
  192487. else
  192488. lang_len = 0;
  192489. if (text_ptr[i].lang_key != NULL)
  192490. lang_key_len = png_strlen(text_ptr[i].lang_key);
  192491. else
  192492. lang_key_len = 0;
  192493. }
  192494. #else
  192495. {
  192496. png_warning(png_ptr, "iTXt chunk not supported.");
  192497. continue;
  192498. }
  192499. #endif
  192500. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  192501. {
  192502. text_length = 0;
  192503. #ifdef PNG_iTXt_SUPPORTED
  192504. if(text_ptr[i].compression > 0)
  192505. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  192506. else
  192507. #endif
  192508. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  192509. }
  192510. else
  192511. {
  192512. text_length = png_strlen(text_ptr[i].text);
  192513. textp->compression = text_ptr[i].compression;
  192514. }
  192515. textp->key = (png_charp)png_malloc_warn(png_ptr,
  192516. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  192517. if (textp->key == NULL)
  192518. return(1);
  192519. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  192520. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  192521. (int)textp->key);
  192522. png_memcpy(textp->key, text_ptr[i].key,
  192523. (png_size_t)(key_len));
  192524. *(textp->key+key_len) = '\0';
  192525. #ifdef PNG_iTXt_SUPPORTED
  192526. if (text_ptr[i].compression > 0)
  192527. {
  192528. textp->lang=textp->key + key_len + 1;
  192529. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  192530. *(textp->lang+lang_len) = '\0';
  192531. textp->lang_key=textp->lang + lang_len + 1;
  192532. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  192533. *(textp->lang_key+lang_key_len) = '\0';
  192534. textp->text=textp->lang_key + lang_key_len + 1;
  192535. }
  192536. else
  192537. #endif
  192538. {
  192539. #ifdef PNG_iTXt_SUPPORTED
  192540. textp->lang=NULL;
  192541. textp->lang_key=NULL;
  192542. #endif
  192543. textp->text=textp->key + key_len + 1;
  192544. }
  192545. if(text_length)
  192546. png_memcpy(textp->text, text_ptr[i].text,
  192547. (png_size_t)(text_length));
  192548. *(textp->text+text_length) = '\0';
  192549. #ifdef PNG_iTXt_SUPPORTED
  192550. if(textp->compression > 0)
  192551. {
  192552. textp->text_length = 0;
  192553. textp->itxt_length = text_length;
  192554. }
  192555. else
  192556. #endif
  192557. {
  192558. textp->text_length = text_length;
  192559. #ifdef PNG_iTXt_SUPPORTED
  192560. textp->itxt_length = 0;
  192561. #endif
  192562. }
  192563. info_ptr->num_text++;
  192564. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  192565. }
  192566. return(0);
  192567. }
  192568. #endif
  192569. #if defined(PNG_tIME_SUPPORTED)
  192570. void PNGAPI
  192571. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  192572. {
  192573. png_debug1(1, "in %s storage function\n", "tIME");
  192574. if (png_ptr == NULL || info_ptr == NULL ||
  192575. (png_ptr->mode & PNG_WROTE_tIME))
  192576. return;
  192577. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  192578. info_ptr->valid |= PNG_INFO_tIME;
  192579. }
  192580. #endif
  192581. #if defined(PNG_tRNS_SUPPORTED)
  192582. void PNGAPI
  192583. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  192584. png_bytep trans, int num_trans, png_color_16p trans_values)
  192585. {
  192586. png_debug1(1, "in %s storage function\n", "tRNS");
  192587. if (png_ptr == NULL || info_ptr == NULL)
  192588. return;
  192589. if (trans != NULL)
  192590. {
  192591. /*
  192592. * It may not actually be necessary to set png_ptr->trans here;
  192593. * we do it for backward compatibility with the way the png_handle_tRNS
  192594. * function used to do the allocation.
  192595. */
  192596. #ifdef PNG_FREE_ME_SUPPORTED
  192597. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  192598. #endif
  192599. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  192600. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  192601. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  192602. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  192603. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  192604. #ifdef PNG_FREE_ME_SUPPORTED
  192605. info_ptr->free_me |= PNG_FREE_TRNS;
  192606. #else
  192607. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  192608. #endif
  192609. }
  192610. if (trans_values != NULL)
  192611. {
  192612. png_memcpy(&(info_ptr->trans_values), trans_values,
  192613. png_sizeof(png_color_16));
  192614. if (num_trans == 0)
  192615. num_trans = 1;
  192616. }
  192617. info_ptr->num_trans = (png_uint_16)num_trans;
  192618. info_ptr->valid |= PNG_INFO_tRNS;
  192619. }
  192620. #endif
  192621. #if defined(PNG_sPLT_SUPPORTED)
  192622. void PNGAPI
  192623. png_set_sPLT(png_structp png_ptr,
  192624. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  192625. {
  192626. png_sPLT_tp np;
  192627. int i;
  192628. if (png_ptr == NULL || info_ptr == NULL)
  192629. return;
  192630. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  192631. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  192632. if (np == NULL)
  192633. {
  192634. png_warning(png_ptr, "No memory for sPLT palettes.");
  192635. return;
  192636. }
  192637. png_memcpy(np, info_ptr->splt_palettes,
  192638. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  192639. png_free(png_ptr, info_ptr->splt_palettes);
  192640. info_ptr->splt_palettes=NULL;
  192641. for (i = 0; i < nentries; i++)
  192642. {
  192643. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  192644. png_sPLT_tp from = entries + i;
  192645. to->name = (png_charp)png_malloc_warn(png_ptr,
  192646. png_strlen(from->name) + 1);
  192647. if (to->name == NULL)
  192648. {
  192649. png_warning(png_ptr,
  192650. "Out of memory while processing sPLT chunk");
  192651. }
  192652. /* TODO: use png_malloc_warn */
  192653. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  192654. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  192655. from->nentries * png_sizeof(png_sPLT_entry));
  192656. /* TODO: use png_malloc_warn */
  192657. png_memcpy(to->entries, from->entries,
  192658. from->nentries * png_sizeof(png_sPLT_entry));
  192659. if (to->entries == NULL)
  192660. {
  192661. png_warning(png_ptr,
  192662. "Out of memory while processing sPLT chunk");
  192663. png_free(png_ptr,to->name);
  192664. to->name = NULL;
  192665. }
  192666. to->nentries = from->nentries;
  192667. to->depth = from->depth;
  192668. }
  192669. info_ptr->splt_palettes = np;
  192670. info_ptr->splt_palettes_num += nentries;
  192671. info_ptr->valid |= PNG_INFO_sPLT;
  192672. #ifdef PNG_FREE_ME_SUPPORTED
  192673. info_ptr->free_me |= PNG_FREE_SPLT;
  192674. #endif
  192675. }
  192676. #endif /* PNG_sPLT_SUPPORTED */
  192677. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  192678. void PNGAPI
  192679. png_set_unknown_chunks(png_structp png_ptr,
  192680. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  192681. {
  192682. png_unknown_chunkp np;
  192683. int i;
  192684. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  192685. return;
  192686. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  192687. (info_ptr->unknown_chunks_num + num_unknowns) *
  192688. png_sizeof(png_unknown_chunk));
  192689. if (np == NULL)
  192690. {
  192691. png_warning(png_ptr,
  192692. "Out of memory while processing unknown chunk.");
  192693. return;
  192694. }
  192695. png_memcpy(np, info_ptr->unknown_chunks,
  192696. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  192697. png_free(png_ptr, info_ptr->unknown_chunks);
  192698. info_ptr->unknown_chunks=NULL;
  192699. for (i = 0; i < num_unknowns; i++)
  192700. {
  192701. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  192702. png_unknown_chunkp from = unknowns + i;
  192703. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  192704. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  192705. if (to->data == NULL)
  192706. {
  192707. png_warning(png_ptr,
  192708. "Out of memory while processing unknown chunk.");
  192709. }
  192710. else
  192711. {
  192712. png_memcpy(to->data, from->data, from->size);
  192713. to->size = from->size;
  192714. /* note our location in the read or write sequence */
  192715. to->location = (png_byte)(png_ptr->mode & 0xff);
  192716. }
  192717. }
  192718. info_ptr->unknown_chunks = np;
  192719. info_ptr->unknown_chunks_num += num_unknowns;
  192720. #ifdef PNG_FREE_ME_SUPPORTED
  192721. info_ptr->free_me |= PNG_FREE_UNKN;
  192722. #endif
  192723. }
  192724. void PNGAPI
  192725. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  192726. int chunk, int location)
  192727. {
  192728. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  192729. (int)info_ptr->unknown_chunks_num)
  192730. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  192731. }
  192732. #endif
  192733. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  192734. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  192735. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  192736. void PNGAPI
  192737. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  192738. {
  192739. /* This function is deprecated in favor of png_permit_mng_features()
  192740. and will be removed from libpng-1.3.0 */
  192741. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  192742. if (png_ptr == NULL)
  192743. return;
  192744. png_ptr->mng_features_permitted = (png_byte)
  192745. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  192746. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  192747. }
  192748. #endif
  192749. #endif
  192750. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192751. png_uint_32 PNGAPI
  192752. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  192753. {
  192754. png_debug(1, "in png_permit_mng_features\n");
  192755. if (png_ptr == NULL)
  192756. return (png_uint_32)0;
  192757. png_ptr->mng_features_permitted =
  192758. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  192759. return (png_uint_32)png_ptr->mng_features_permitted;
  192760. }
  192761. #endif
  192762. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  192763. void PNGAPI
  192764. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  192765. chunk_list, int num_chunks)
  192766. {
  192767. png_bytep new_list, p;
  192768. int i, old_num_chunks;
  192769. if (png_ptr == NULL)
  192770. return;
  192771. if (num_chunks == 0)
  192772. {
  192773. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  192774. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  192775. else
  192776. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  192777. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  192778. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  192779. else
  192780. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  192781. return;
  192782. }
  192783. if (chunk_list == NULL)
  192784. return;
  192785. old_num_chunks=png_ptr->num_chunk_list;
  192786. new_list=(png_bytep)png_malloc(png_ptr,
  192787. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  192788. if(png_ptr->chunk_list != NULL)
  192789. {
  192790. png_memcpy(new_list, png_ptr->chunk_list,
  192791. (png_size_t)(5*old_num_chunks));
  192792. png_free(png_ptr, png_ptr->chunk_list);
  192793. png_ptr->chunk_list=NULL;
  192794. }
  192795. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  192796. (png_size_t)(5*num_chunks));
  192797. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  192798. *p=(png_byte)keep;
  192799. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  192800. png_ptr->chunk_list=new_list;
  192801. #ifdef PNG_FREE_ME_SUPPORTED
  192802. png_ptr->free_me |= PNG_FREE_LIST;
  192803. #endif
  192804. }
  192805. #endif
  192806. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192807. void PNGAPI
  192808. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  192809. png_user_chunk_ptr read_user_chunk_fn)
  192810. {
  192811. png_debug(1, "in png_set_read_user_chunk_fn\n");
  192812. if (png_ptr == NULL)
  192813. return;
  192814. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  192815. png_ptr->user_chunk_ptr = user_chunk_ptr;
  192816. }
  192817. #endif
  192818. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  192819. void PNGAPI
  192820. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  192821. {
  192822. png_debug1(1, "in %s storage function\n", "rows");
  192823. if (png_ptr == NULL || info_ptr == NULL)
  192824. return;
  192825. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  192826. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  192827. info_ptr->row_pointers = row_pointers;
  192828. if(row_pointers)
  192829. info_ptr->valid |= PNG_INFO_IDAT;
  192830. }
  192831. #endif
  192832. #ifdef PNG_WRITE_SUPPORTED
  192833. void PNGAPI
  192834. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  192835. {
  192836. if (png_ptr == NULL)
  192837. return;
  192838. if(png_ptr->zbuf)
  192839. png_free(png_ptr, png_ptr->zbuf);
  192840. png_ptr->zbuf_size = (png_size_t)size;
  192841. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  192842. png_ptr->zstream.next_out = png_ptr->zbuf;
  192843. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  192844. }
  192845. #endif
  192846. void PNGAPI
  192847. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  192848. {
  192849. if (png_ptr && info_ptr)
  192850. info_ptr->valid &= ~(mask);
  192851. }
  192852. #ifndef PNG_1_0_X
  192853. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  192854. /* function was added to libpng 1.2.0 and should always exist by default */
  192855. void PNGAPI
  192856. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  192857. {
  192858. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  192859. if (png_ptr != NULL)
  192860. png_ptr->asm_flags = 0;
  192861. }
  192862. /* this function was added to libpng 1.2.0 */
  192863. void PNGAPI
  192864. png_set_mmx_thresholds (png_structp png_ptr,
  192865. png_byte mmx_bitdepth_threshold,
  192866. png_uint_32 mmx_rowbytes_threshold)
  192867. {
  192868. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  192869. if (png_ptr == NULL)
  192870. return;
  192871. }
  192872. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  192873. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192874. /* this function was added to libpng 1.2.6 */
  192875. void PNGAPI
  192876. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  192877. png_uint_32 user_height_max)
  192878. {
  192879. /* Images with dimensions larger than these limits will be
  192880. * rejected by png_set_IHDR(). To accept any PNG datastream
  192881. * regardless of dimensions, set both limits to 0x7ffffffL.
  192882. */
  192883. if(png_ptr == NULL) return;
  192884. png_ptr->user_width_max = user_width_max;
  192885. png_ptr->user_height_max = user_height_max;
  192886. }
  192887. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  192888. #endif /* ?PNG_1_0_X */
  192889. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  192890. /********* End of inlined file: pngset.c *********/
  192891. /********* Start of inlined file: pngtrans.c *********/
  192892. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  192893. *
  192894. * Last changed in libpng 1.2.17 May 15, 2007
  192895. * For conditions of distribution and use, see copyright notice in png.h
  192896. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192897. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192898. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192899. */
  192900. #define PNG_INTERNAL
  192901. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  192902. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  192903. /* turn on BGR-to-RGB mapping */
  192904. void PNGAPI
  192905. png_set_bgr(png_structp png_ptr)
  192906. {
  192907. png_debug(1, "in png_set_bgr\n");
  192908. if(png_ptr == NULL) return;
  192909. png_ptr->transformations |= PNG_BGR;
  192910. }
  192911. #endif
  192912. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  192913. /* turn on 16 bit byte swapping */
  192914. void PNGAPI
  192915. png_set_swap(png_structp png_ptr)
  192916. {
  192917. png_debug(1, "in png_set_swap\n");
  192918. if(png_ptr == NULL) return;
  192919. if (png_ptr->bit_depth == 16)
  192920. png_ptr->transformations |= PNG_SWAP_BYTES;
  192921. }
  192922. #endif
  192923. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  192924. /* turn on pixel packing */
  192925. void PNGAPI
  192926. png_set_packing(png_structp png_ptr)
  192927. {
  192928. png_debug(1, "in png_set_packing\n");
  192929. if(png_ptr == NULL) return;
  192930. if (png_ptr->bit_depth < 8)
  192931. {
  192932. png_ptr->transformations |= PNG_PACK;
  192933. png_ptr->usr_bit_depth = 8;
  192934. }
  192935. }
  192936. #endif
  192937. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  192938. /* turn on packed pixel swapping */
  192939. void PNGAPI
  192940. png_set_packswap(png_structp png_ptr)
  192941. {
  192942. png_debug(1, "in png_set_packswap\n");
  192943. if(png_ptr == NULL) return;
  192944. if (png_ptr->bit_depth < 8)
  192945. png_ptr->transformations |= PNG_PACKSWAP;
  192946. }
  192947. #endif
  192948. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  192949. void PNGAPI
  192950. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  192951. {
  192952. png_debug(1, "in png_set_shift\n");
  192953. if(png_ptr == NULL) return;
  192954. png_ptr->transformations |= PNG_SHIFT;
  192955. png_ptr->shift = *true_bits;
  192956. }
  192957. #endif
  192958. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  192959. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192960. int PNGAPI
  192961. png_set_interlace_handling(png_structp png_ptr)
  192962. {
  192963. png_debug(1, "in png_set_interlace handling\n");
  192964. if (png_ptr && png_ptr->interlaced)
  192965. {
  192966. png_ptr->transformations |= PNG_INTERLACE;
  192967. return (7);
  192968. }
  192969. return (1);
  192970. }
  192971. #endif
  192972. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  192973. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  192974. * The filler type has changed in v0.95 to allow future 2-byte fillers
  192975. * for 48-bit input data, as well as to avoid problems with some compilers
  192976. * that don't like bytes as parameters.
  192977. */
  192978. void PNGAPI
  192979. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  192980. {
  192981. png_debug(1, "in png_set_filler\n");
  192982. if(png_ptr == NULL) return;
  192983. png_ptr->transformations |= PNG_FILLER;
  192984. png_ptr->filler = (png_byte)filler;
  192985. if (filler_loc == PNG_FILLER_AFTER)
  192986. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  192987. else
  192988. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  192989. /* This should probably go in the "do_read_filler" routine.
  192990. * I attempted to do that in libpng-1.0.1a but that caused problems
  192991. * so I restored it in libpng-1.0.2a
  192992. */
  192993. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192994. {
  192995. png_ptr->usr_channels = 4;
  192996. }
  192997. /* Also I added this in libpng-1.0.2a (what happens when we expand
  192998. * a less-than-8-bit grayscale to GA? */
  192999. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  193000. {
  193001. png_ptr->usr_channels = 2;
  193002. }
  193003. }
  193004. #if !defined(PNG_1_0_X)
  193005. /* Added to libpng-1.2.7 */
  193006. void PNGAPI
  193007. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193008. {
  193009. png_debug(1, "in png_set_add_alpha\n");
  193010. if(png_ptr == NULL) return;
  193011. png_set_filler(png_ptr, filler, filler_loc);
  193012. png_ptr->transformations |= PNG_ADD_ALPHA;
  193013. }
  193014. #endif
  193015. #endif
  193016. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  193017. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193018. void PNGAPI
  193019. png_set_swap_alpha(png_structp png_ptr)
  193020. {
  193021. png_debug(1, "in png_set_swap_alpha\n");
  193022. if(png_ptr == NULL) return;
  193023. png_ptr->transformations |= PNG_SWAP_ALPHA;
  193024. }
  193025. #endif
  193026. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  193027. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193028. void PNGAPI
  193029. png_set_invert_alpha(png_structp png_ptr)
  193030. {
  193031. png_debug(1, "in png_set_invert_alpha\n");
  193032. if(png_ptr == NULL) return;
  193033. png_ptr->transformations |= PNG_INVERT_ALPHA;
  193034. }
  193035. #endif
  193036. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  193037. void PNGAPI
  193038. png_set_invert_mono(png_structp png_ptr)
  193039. {
  193040. png_debug(1, "in png_set_invert_mono\n");
  193041. if(png_ptr == NULL) return;
  193042. png_ptr->transformations |= PNG_INVERT_MONO;
  193043. }
  193044. /* invert monochrome grayscale data */
  193045. void /* PRIVATE */
  193046. png_do_invert(png_row_infop row_info, png_bytep row)
  193047. {
  193048. png_debug(1, "in png_do_invert\n");
  193049. /* This test removed from libpng version 1.0.13 and 1.2.0:
  193050. * if (row_info->bit_depth == 1 &&
  193051. */
  193052. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193053. if (row == NULL || row_info == NULL)
  193054. return;
  193055. #endif
  193056. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193057. {
  193058. png_bytep rp = row;
  193059. png_uint_32 i;
  193060. png_uint_32 istop = row_info->rowbytes;
  193061. for (i = 0; i < istop; i++)
  193062. {
  193063. *rp = (png_byte)(~(*rp));
  193064. rp++;
  193065. }
  193066. }
  193067. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193068. row_info->bit_depth == 8)
  193069. {
  193070. png_bytep rp = row;
  193071. png_uint_32 i;
  193072. png_uint_32 istop = row_info->rowbytes;
  193073. for (i = 0; i < istop; i+=2)
  193074. {
  193075. *rp = (png_byte)(~(*rp));
  193076. rp+=2;
  193077. }
  193078. }
  193079. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193080. row_info->bit_depth == 16)
  193081. {
  193082. png_bytep rp = row;
  193083. png_uint_32 i;
  193084. png_uint_32 istop = row_info->rowbytes;
  193085. for (i = 0; i < istop; i+=4)
  193086. {
  193087. *rp = (png_byte)(~(*rp));
  193088. *(rp+1) = (png_byte)(~(*(rp+1)));
  193089. rp+=4;
  193090. }
  193091. }
  193092. }
  193093. #endif
  193094. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193095. /* swaps byte order on 16 bit depth images */
  193096. void /* PRIVATE */
  193097. png_do_swap(png_row_infop row_info, png_bytep row)
  193098. {
  193099. png_debug(1, "in png_do_swap\n");
  193100. if (
  193101. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193102. row != NULL && row_info != NULL &&
  193103. #endif
  193104. row_info->bit_depth == 16)
  193105. {
  193106. png_bytep rp = row;
  193107. png_uint_32 i;
  193108. png_uint_32 istop= row_info->width * row_info->channels;
  193109. for (i = 0; i < istop; i++, rp += 2)
  193110. {
  193111. png_byte t = *rp;
  193112. *rp = *(rp + 1);
  193113. *(rp + 1) = t;
  193114. }
  193115. }
  193116. }
  193117. #endif
  193118. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193119. static PNG_CONST png_byte onebppswaptable[256] = {
  193120. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  193121. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  193122. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  193123. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  193124. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  193125. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  193126. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  193127. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  193128. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  193129. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  193130. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  193131. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  193132. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  193133. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  193134. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  193135. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  193136. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  193137. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  193138. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  193139. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  193140. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  193141. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  193142. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  193143. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  193144. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  193145. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  193146. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  193147. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  193148. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  193149. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  193150. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  193151. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  193152. };
  193153. static PNG_CONST png_byte twobppswaptable[256] = {
  193154. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  193155. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  193156. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  193157. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  193158. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  193159. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  193160. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  193161. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  193162. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  193163. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  193164. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  193165. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  193166. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  193167. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  193168. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  193169. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  193170. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  193171. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  193172. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  193173. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  193174. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  193175. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  193176. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  193177. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  193178. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  193179. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  193180. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  193181. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  193182. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  193183. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  193184. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  193185. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  193186. };
  193187. static PNG_CONST png_byte fourbppswaptable[256] = {
  193188. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  193189. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  193190. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  193191. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  193192. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  193193. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  193194. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  193195. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  193196. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  193197. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  193198. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  193199. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  193200. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  193201. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  193202. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  193203. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  193204. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  193205. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  193206. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  193207. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  193208. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  193209. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  193210. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  193211. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  193212. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  193213. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  193214. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  193215. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  193216. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  193217. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  193218. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  193219. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  193220. };
  193221. /* swaps pixel packing order within bytes */
  193222. void /* PRIVATE */
  193223. png_do_packswap(png_row_infop row_info, png_bytep row)
  193224. {
  193225. png_debug(1, "in png_do_packswap\n");
  193226. if (
  193227. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193228. row != NULL && row_info != NULL &&
  193229. #endif
  193230. row_info->bit_depth < 8)
  193231. {
  193232. png_bytep rp, end, table;
  193233. end = row + row_info->rowbytes;
  193234. if (row_info->bit_depth == 1)
  193235. table = (png_bytep)onebppswaptable;
  193236. else if (row_info->bit_depth == 2)
  193237. table = (png_bytep)twobppswaptable;
  193238. else if (row_info->bit_depth == 4)
  193239. table = (png_bytep)fourbppswaptable;
  193240. else
  193241. return;
  193242. for (rp = row; rp < end; rp++)
  193243. *rp = table[*rp];
  193244. }
  193245. }
  193246. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  193247. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  193248. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  193249. /* remove filler or alpha byte(s) */
  193250. void /* PRIVATE */
  193251. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  193252. {
  193253. png_debug(1, "in png_do_strip_filler\n");
  193254. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193255. if (row != NULL && row_info != NULL)
  193256. #endif
  193257. {
  193258. png_bytep sp=row;
  193259. png_bytep dp=row;
  193260. png_uint_32 row_width=row_info->width;
  193261. png_uint_32 i;
  193262. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  193263. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193264. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193265. row_info->channels == 4)
  193266. {
  193267. if (row_info->bit_depth == 8)
  193268. {
  193269. /* This converts from RGBX or RGBA to RGB */
  193270. if (flags & PNG_FLAG_FILLER_AFTER)
  193271. {
  193272. dp+=3; sp+=4;
  193273. for (i = 1; i < row_width; i++)
  193274. {
  193275. *dp++ = *sp++;
  193276. *dp++ = *sp++;
  193277. *dp++ = *sp++;
  193278. sp++;
  193279. }
  193280. }
  193281. /* This converts from XRGB or ARGB to RGB */
  193282. else
  193283. {
  193284. for (i = 0; i < row_width; i++)
  193285. {
  193286. sp++;
  193287. *dp++ = *sp++;
  193288. *dp++ = *sp++;
  193289. *dp++ = *sp++;
  193290. }
  193291. }
  193292. row_info->pixel_depth = 24;
  193293. row_info->rowbytes = row_width * 3;
  193294. }
  193295. else /* if (row_info->bit_depth == 16) */
  193296. {
  193297. if (flags & PNG_FLAG_FILLER_AFTER)
  193298. {
  193299. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  193300. sp += 8; dp += 6;
  193301. for (i = 1; i < row_width; i++)
  193302. {
  193303. /* This could be (although png_memcpy is probably slower):
  193304. png_memcpy(dp, sp, 6);
  193305. sp += 8;
  193306. dp += 6;
  193307. */
  193308. *dp++ = *sp++;
  193309. *dp++ = *sp++;
  193310. *dp++ = *sp++;
  193311. *dp++ = *sp++;
  193312. *dp++ = *sp++;
  193313. *dp++ = *sp++;
  193314. sp += 2;
  193315. }
  193316. }
  193317. else
  193318. {
  193319. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  193320. for (i = 0; i < row_width; i++)
  193321. {
  193322. /* This could be (although png_memcpy is probably slower):
  193323. png_memcpy(dp, sp, 6);
  193324. sp += 8;
  193325. dp += 6;
  193326. */
  193327. sp+=2;
  193328. *dp++ = *sp++;
  193329. *dp++ = *sp++;
  193330. *dp++ = *sp++;
  193331. *dp++ = *sp++;
  193332. *dp++ = *sp++;
  193333. *dp++ = *sp++;
  193334. }
  193335. }
  193336. row_info->pixel_depth = 48;
  193337. row_info->rowbytes = row_width * 6;
  193338. }
  193339. row_info->channels = 3;
  193340. }
  193341. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  193342. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193343. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193344. row_info->channels == 2)
  193345. {
  193346. if (row_info->bit_depth == 8)
  193347. {
  193348. /* This converts from GX or GA to G */
  193349. if (flags & PNG_FLAG_FILLER_AFTER)
  193350. {
  193351. for (i = 0; i < row_width; i++)
  193352. {
  193353. *dp++ = *sp++;
  193354. sp++;
  193355. }
  193356. }
  193357. /* This converts from XG or AG to G */
  193358. else
  193359. {
  193360. for (i = 0; i < row_width; i++)
  193361. {
  193362. sp++;
  193363. *dp++ = *sp++;
  193364. }
  193365. }
  193366. row_info->pixel_depth = 8;
  193367. row_info->rowbytes = row_width;
  193368. }
  193369. else /* if (row_info->bit_depth == 16) */
  193370. {
  193371. if (flags & PNG_FLAG_FILLER_AFTER)
  193372. {
  193373. /* This converts from GGXX or GGAA to GG */
  193374. sp += 4; dp += 2;
  193375. for (i = 1; i < row_width; i++)
  193376. {
  193377. *dp++ = *sp++;
  193378. *dp++ = *sp++;
  193379. sp += 2;
  193380. }
  193381. }
  193382. else
  193383. {
  193384. /* This converts from XXGG or AAGG to GG */
  193385. for (i = 0; i < row_width; i++)
  193386. {
  193387. sp += 2;
  193388. *dp++ = *sp++;
  193389. *dp++ = *sp++;
  193390. }
  193391. }
  193392. row_info->pixel_depth = 16;
  193393. row_info->rowbytes = row_width * 2;
  193394. }
  193395. row_info->channels = 1;
  193396. }
  193397. if (flags & PNG_FLAG_STRIP_ALPHA)
  193398. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193399. }
  193400. }
  193401. #endif
  193402. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  193403. /* swaps red and blue bytes within a pixel */
  193404. void /* PRIVATE */
  193405. png_do_bgr(png_row_infop row_info, png_bytep row)
  193406. {
  193407. png_debug(1, "in png_do_bgr\n");
  193408. if (
  193409. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193410. row != NULL && row_info != NULL &&
  193411. #endif
  193412. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193413. {
  193414. png_uint_32 row_width = row_info->width;
  193415. if (row_info->bit_depth == 8)
  193416. {
  193417. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193418. {
  193419. png_bytep rp;
  193420. png_uint_32 i;
  193421. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  193422. {
  193423. png_byte save = *rp;
  193424. *rp = *(rp + 2);
  193425. *(rp + 2) = save;
  193426. }
  193427. }
  193428. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193429. {
  193430. png_bytep rp;
  193431. png_uint_32 i;
  193432. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  193433. {
  193434. png_byte save = *rp;
  193435. *rp = *(rp + 2);
  193436. *(rp + 2) = save;
  193437. }
  193438. }
  193439. }
  193440. else if (row_info->bit_depth == 16)
  193441. {
  193442. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193443. {
  193444. png_bytep rp;
  193445. png_uint_32 i;
  193446. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  193447. {
  193448. png_byte save = *rp;
  193449. *rp = *(rp + 4);
  193450. *(rp + 4) = save;
  193451. save = *(rp + 1);
  193452. *(rp + 1) = *(rp + 5);
  193453. *(rp + 5) = save;
  193454. }
  193455. }
  193456. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193457. {
  193458. png_bytep rp;
  193459. png_uint_32 i;
  193460. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  193461. {
  193462. png_byte save = *rp;
  193463. *rp = *(rp + 4);
  193464. *(rp + 4) = save;
  193465. save = *(rp + 1);
  193466. *(rp + 1) = *(rp + 5);
  193467. *(rp + 5) = save;
  193468. }
  193469. }
  193470. }
  193471. }
  193472. }
  193473. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  193474. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  193475. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  193476. defined(PNG_LEGACY_SUPPORTED)
  193477. void PNGAPI
  193478. png_set_user_transform_info(png_structp png_ptr, png_voidp
  193479. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  193480. {
  193481. png_debug(1, "in png_set_user_transform_info\n");
  193482. if(png_ptr == NULL) return;
  193483. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193484. png_ptr->user_transform_ptr = user_transform_ptr;
  193485. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  193486. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  193487. #else
  193488. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  193489. png_warning(png_ptr,
  193490. "This version of libpng does not support user transform info");
  193491. #endif
  193492. }
  193493. #endif
  193494. /* This function returns a pointer to the user_transform_ptr associated with
  193495. * the user transform functions. The application should free any memory
  193496. * associated with this pointer before png_write_destroy and png_read_destroy
  193497. * are called.
  193498. */
  193499. png_voidp PNGAPI
  193500. png_get_user_transform_ptr(png_structp png_ptr)
  193501. {
  193502. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193503. if (png_ptr == NULL) return (NULL);
  193504. return ((png_voidp)png_ptr->user_transform_ptr);
  193505. #else
  193506. return (NULL);
  193507. #endif
  193508. }
  193509. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  193510. /********* End of inlined file: pngtrans.c *********/
  193511. /********* Start of inlined file: pngwio.c *********/
  193512. /* pngwio.c - functions for data output
  193513. *
  193514. * Last changed in libpng 1.2.13 November 13, 2006
  193515. * For conditions of distribution and use, see copyright notice in png.h
  193516. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  193517. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193518. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193519. *
  193520. * This file provides a location for all output. Users who need
  193521. * special handling are expected to write functions that have the same
  193522. * arguments as these and perform similar functions, but that possibly
  193523. * use different output methods. Note that you shouldn't change these
  193524. * functions, but rather write replacement functions and then change
  193525. * them at run time with png_set_write_fn(...).
  193526. */
  193527. #define PNG_INTERNAL
  193528. #ifdef PNG_WRITE_SUPPORTED
  193529. /* Write the data to whatever output you are using. The default routine
  193530. writes to a file pointer. Note that this routine sometimes gets called
  193531. with very small lengths, so you should implement some kind of simple
  193532. buffering if you are using unbuffered writes. This should never be asked
  193533. to write more than 64K on a 16 bit machine. */
  193534. void /* PRIVATE */
  193535. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  193536. {
  193537. if (png_ptr->write_data_fn != NULL )
  193538. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  193539. else
  193540. png_error(png_ptr, "Call to NULL write function");
  193541. }
  193542. #if !defined(PNG_NO_STDIO)
  193543. /* This is the function that does the actual writing of data. If you are
  193544. not writing to a standard C stream, you should create a replacement
  193545. write_data function and use it at run time with png_set_write_fn(), rather
  193546. than changing the library. */
  193547. #ifndef USE_FAR_KEYWORD
  193548. void PNGAPI
  193549. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  193550. {
  193551. png_uint_32 check;
  193552. if(png_ptr == NULL) return;
  193553. #if defined(_WIN32_WCE)
  193554. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  193555. check = 0;
  193556. #else
  193557. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  193558. #endif
  193559. if (check != length)
  193560. png_error(png_ptr, "Write Error");
  193561. }
  193562. #else
  193563. /* this is the model-independent version. Since the standard I/O library
  193564. can't handle far buffers in the medium and small models, we have to copy
  193565. the data.
  193566. */
  193567. #define NEAR_BUF_SIZE 1024
  193568. #define MIN(a,b) (a <= b ? a : b)
  193569. void PNGAPI
  193570. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  193571. {
  193572. png_uint_32 check;
  193573. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  193574. png_FILE_p io_ptr;
  193575. if(png_ptr == NULL) return;
  193576. /* Check if data really is near. If so, use usual code. */
  193577. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  193578. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  193579. if ((png_bytep)near_data == data)
  193580. {
  193581. #if defined(_WIN32_WCE)
  193582. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  193583. check = 0;
  193584. #else
  193585. check = fwrite(near_data, 1, length, io_ptr);
  193586. #endif
  193587. }
  193588. else
  193589. {
  193590. png_byte buf[NEAR_BUF_SIZE];
  193591. png_size_t written, remaining, err;
  193592. check = 0;
  193593. remaining = length;
  193594. do
  193595. {
  193596. written = MIN(NEAR_BUF_SIZE, remaining);
  193597. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  193598. #if defined(_WIN32_WCE)
  193599. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  193600. err = 0;
  193601. #else
  193602. err = fwrite(buf, 1, written, io_ptr);
  193603. #endif
  193604. if (err != written)
  193605. break;
  193606. else
  193607. check += err;
  193608. data += written;
  193609. remaining -= written;
  193610. }
  193611. while (remaining != 0);
  193612. }
  193613. if (check != length)
  193614. png_error(png_ptr, "Write Error");
  193615. }
  193616. #endif
  193617. #endif
  193618. /* This function is called to output any data pending writing (normally
  193619. to disk). After png_flush is called, there should be no data pending
  193620. writing in any buffers. */
  193621. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  193622. void /* PRIVATE */
  193623. png_flush(png_structp png_ptr)
  193624. {
  193625. if (png_ptr->output_flush_fn != NULL)
  193626. (*(png_ptr->output_flush_fn))(png_ptr);
  193627. }
  193628. #if !defined(PNG_NO_STDIO)
  193629. void PNGAPI
  193630. png_default_flush(png_structp png_ptr)
  193631. {
  193632. #if !defined(_WIN32_WCE)
  193633. png_FILE_p io_ptr;
  193634. #endif
  193635. if(png_ptr == NULL) return;
  193636. #if !defined(_WIN32_WCE)
  193637. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  193638. if (io_ptr != NULL)
  193639. fflush(io_ptr);
  193640. #endif
  193641. }
  193642. #endif
  193643. #endif
  193644. /* This function allows the application to supply new output functions for
  193645. libpng if standard C streams aren't being used.
  193646. This function takes as its arguments:
  193647. png_ptr - pointer to a png output data structure
  193648. io_ptr - pointer to user supplied structure containing info about
  193649. the output functions. May be NULL.
  193650. write_data_fn - pointer to a new output function that takes as its
  193651. arguments a pointer to a png_struct, a pointer to
  193652. data to be written, and a 32-bit unsigned int that is
  193653. the number of bytes to be written. The new write
  193654. function should call png_error(png_ptr, "Error msg")
  193655. to exit and output any fatal error messages.
  193656. flush_data_fn - pointer to a new flush function that takes as its
  193657. arguments a pointer to a png_struct. After a call to
  193658. the flush function, there should be no data in any buffers
  193659. or pending transmission. If the output method doesn't do
  193660. any buffering of ouput, a function prototype must still be
  193661. supplied although it doesn't have to do anything. If
  193662. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  193663. time, output_flush_fn will be ignored, although it must be
  193664. supplied for compatibility. */
  193665. void PNGAPI
  193666. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  193667. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  193668. {
  193669. if(png_ptr == NULL) return;
  193670. png_ptr->io_ptr = io_ptr;
  193671. #if !defined(PNG_NO_STDIO)
  193672. if (write_data_fn != NULL)
  193673. png_ptr->write_data_fn = write_data_fn;
  193674. else
  193675. png_ptr->write_data_fn = png_default_write_data;
  193676. #else
  193677. png_ptr->write_data_fn = write_data_fn;
  193678. #endif
  193679. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  193680. #if !defined(PNG_NO_STDIO)
  193681. if (output_flush_fn != NULL)
  193682. png_ptr->output_flush_fn = output_flush_fn;
  193683. else
  193684. png_ptr->output_flush_fn = png_default_flush;
  193685. #else
  193686. png_ptr->output_flush_fn = output_flush_fn;
  193687. #endif
  193688. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  193689. /* It is an error to read while writing a png file */
  193690. if (png_ptr->read_data_fn != NULL)
  193691. {
  193692. png_ptr->read_data_fn = NULL;
  193693. png_warning(png_ptr,
  193694. "Attempted to set both read_data_fn and write_data_fn in");
  193695. png_warning(png_ptr,
  193696. "the same structure. Resetting read_data_fn to NULL.");
  193697. }
  193698. }
  193699. #if defined(USE_FAR_KEYWORD)
  193700. #if defined(_MSC_VER)
  193701. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  193702. {
  193703. void *near_ptr;
  193704. void FAR *far_ptr;
  193705. FP_OFF(near_ptr) = FP_OFF(ptr);
  193706. far_ptr = (void FAR *)near_ptr;
  193707. if(check != 0)
  193708. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  193709. png_error(png_ptr,"segment lost in conversion");
  193710. return(near_ptr);
  193711. }
  193712. # else
  193713. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  193714. {
  193715. void *near_ptr;
  193716. void FAR *far_ptr;
  193717. near_ptr = (void FAR *)ptr;
  193718. far_ptr = (void FAR *)near_ptr;
  193719. if(check != 0)
  193720. if(far_ptr != ptr)
  193721. png_error(png_ptr,"segment lost in conversion");
  193722. return(near_ptr);
  193723. }
  193724. # endif
  193725. # endif
  193726. #endif /* PNG_WRITE_SUPPORTED */
  193727. /********* End of inlined file: pngwio.c *********/
  193728. /********* Start of inlined file: pngwrite.c *********/
  193729. /* pngwrite.c - general routines to write a PNG file
  193730. *
  193731. * Last changed in libpng 1.2.15 January 5, 2007
  193732. * For conditions of distribution and use, see copyright notice in png.h
  193733. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193734. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193735. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193736. */
  193737. /* get internal access to png.h */
  193738. #define PNG_INTERNAL
  193739. #ifdef PNG_WRITE_SUPPORTED
  193740. /* Writes all the PNG information. This is the suggested way to use the
  193741. * library. If you have a new chunk to add, make a function to write it,
  193742. * and put it in the correct location here. If you want the chunk written
  193743. * after the image data, put it in png_write_end(). I strongly encourage
  193744. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  193745. * the chunk, as that will keep the code from breaking if you want to just
  193746. * write a plain PNG file. If you have long comments, I suggest writing
  193747. * them in png_write_end(), and compressing them.
  193748. */
  193749. void PNGAPI
  193750. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  193751. {
  193752. png_debug(1, "in png_write_info_before_PLTE\n");
  193753. if (png_ptr == NULL || info_ptr == NULL)
  193754. return;
  193755. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  193756. {
  193757. png_write_sig(png_ptr); /* write PNG signature */
  193758. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193759. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  193760. {
  193761. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  193762. png_ptr->mng_features_permitted=0;
  193763. }
  193764. #endif
  193765. /* write IHDR information. */
  193766. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  193767. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  193768. info_ptr->filter_type,
  193769. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193770. info_ptr->interlace_type);
  193771. #else
  193772. 0);
  193773. #endif
  193774. /* the rest of these check to see if the valid field has the appropriate
  193775. flag set, and if it does, writes the chunk. */
  193776. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  193777. if (info_ptr->valid & PNG_INFO_gAMA)
  193778. {
  193779. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193780. png_write_gAMA(png_ptr, info_ptr->gamma);
  193781. #else
  193782. #ifdef PNG_FIXED_POINT_SUPPORTED
  193783. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  193784. # endif
  193785. #endif
  193786. }
  193787. #endif
  193788. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  193789. if (info_ptr->valid & PNG_INFO_sRGB)
  193790. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  193791. #endif
  193792. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  193793. if (info_ptr->valid & PNG_INFO_iCCP)
  193794. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  193795. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  193796. #endif
  193797. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  193798. if (info_ptr->valid & PNG_INFO_sBIT)
  193799. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  193800. #endif
  193801. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  193802. if (info_ptr->valid & PNG_INFO_cHRM)
  193803. {
  193804. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193805. png_write_cHRM(png_ptr,
  193806. info_ptr->x_white, info_ptr->y_white,
  193807. info_ptr->x_red, info_ptr->y_red,
  193808. info_ptr->x_green, info_ptr->y_green,
  193809. info_ptr->x_blue, info_ptr->y_blue);
  193810. #else
  193811. # ifdef PNG_FIXED_POINT_SUPPORTED
  193812. png_write_cHRM_fixed(png_ptr,
  193813. info_ptr->int_x_white, info_ptr->int_y_white,
  193814. info_ptr->int_x_red, info_ptr->int_y_red,
  193815. info_ptr->int_x_green, info_ptr->int_y_green,
  193816. info_ptr->int_x_blue, info_ptr->int_y_blue);
  193817. # endif
  193818. #endif
  193819. }
  193820. #endif
  193821. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193822. if (info_ptr->unknown_chunks_num)
  193823. {
  193824. png_unknown_chunk *up;
  193825. png_debug(5, "writing extra chunks\n");
  193826. for (up = info_ptr->unknown_chunks;
  193827. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193828. up++)
  193829. {
  193830. int keep=png_handle_as_unknown(png_ptr, up->name);
  193831. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193832. up->location && !(up->location & PNG_HAVE_PLTE) &&
  193833. !(up->location & PNG_HAVE_IDAT) &&
  193834. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193835. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193836. {
  193837. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193838. }
  193839. }
  193840. }
  193841. #endif
  193842. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  193843. }
  193844. }
  193845. void PNGAPI
  193846. png_write_info(png_structp png_ptr, png_infop info_ptr)
  193847. {
  193848. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  193849. int i;
  193850. #endif
  193851. png_debug(1, "in png_write_info\n");
  193852. if (png_ptr == NULL || info_ptr == NULL)
  193853. return;
  193854. png_write_info_before_PLTE(png_ptr, info_ptr);
  193855. if (info_ptr->valid & PNG_INFO_PLTE)
  193856. png_write_PLTE(png_ptr, info_ptr->palette,
  193857. (png_uint_32)info_ptr->num_palette);
  193858. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193859. png_error(png_ptr, "Valid palette required for paletted images");
  193860. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  193861. if (info_ptr->valid & PNG_INFO_tRNS)
  193862. {
  193863. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193864. /* invert the alpha channel (in tRNS) */
  193865. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  193866. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193867. {
  193868. int j;
  193869. for (j=0; j<(int)info_ptr->num_trans; j++)
  193870. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  193871. }
  193872. #endif
  193873. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  193874. info_ptr->num_trans, info_ptr->color_type);
  193875. }
  193876. #endif
  193877. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  193878. if (info_ptr->valid & PNG_INFO_bKGD)
  193879. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  193880. #endif
  193881. #if defined(PNG_WRITE_hIST_SUPPORTED)
  193882. if (info_ptr->valid & PNG_INFO_hIST)
  193883. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  193884. #endif
  193885. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  193886. if (info_ptr->valid & PNG_INFO_oFFs)
  193887. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  193888. info_ptr->offset_unit_type);
  193889. #endif
  193890. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  193891. if (info_ptr->valid & PNG_INFO_pCAL)
  193892. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  193893. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  193894. info_ptr->pcal_units, info_ptr->pcal_params);
  193895. #endif
  193896. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  193897. if (info_ptr->valid & PNG_INFO_sCAL)
  193898. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  193899. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  193900. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  193901. #else
  193902. #ifdef PNG_FIXED_POINT_SUPPORTED
  193903. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  193904. info_ptr->scal_s_width, info_ptr->scal_s_height);
  193905. #else
  193906. png_warning(png_ptr,
  193907. "png_write_sCAL not supported; sCAL chunk not written.");
  193908. #endif
  193909. #endif
  193910. #endif
  193911. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  193912. if (info_ptr->valid & PNG_INFO_pHYs)
  193913. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  193914. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  193915. #endif
  193916. #if defined(PNG_WRITE_tIME_SUPPORTED)
  193917. if (info_ptr->valid & PNG_INFO_tIME)
  193918. {
  193919. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  193920. png_ptr->mode |= PNG_WROTE_tIME;
  193921. }
  193922. #endif
  193923. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  193924. if (info_ptr->valid & PNG_INFO_sPLT)
  193925. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  193926. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  193927. #endif
  193928. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  193929. /* Check to see if we need to write text chunks */
  193930. for (i = 0; i < info_ptr->num_text; i++)
  193931. {
  193932. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  193933. info_ptr->text[i].compression);
  193934. /* an internationalized chunk? */
  193935. if (info_ptr->text[i].compression > 0)
  193936. {
  193937. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  193938. /* write international chunk */
  193939. png_write_iTXt(png_ptr,
  193940. info_ptr->text[i].compression,
  193941. info_ptr->text[i].key,
  193942. info_ptr->text[i].lang,
  193943. info_ptr->text[i].lang_key,
  193944. info_ptr->text[i].text);
  193945. #else
  193946. png_warning(png_ptr, "Unable to write international text");
  193947. #endif
  193948. /* Mark this chunk as written */
  193949. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193950. }
  193951. /* If we want a compressed text chunk */
  193952. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  193953. {
  193954. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  193955. /* write compressed chunk */
  193956. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  193957. info_ptr->text[i].text, 0,
  193958. info_ptr->text[i].compression);
  193959. #else
  193960. png_warning(png_ptr, "Unable to write compressed text");
  193961. #endif
  193962. /* Mark this chunk as written */
  193963. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  193964. }
  193965. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  193966. {
  193967. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  193968. /* write uncompressed chunk */
  193969. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  193970. info_ptr->text[i].text,
  193971. 0);
  193972. #else
  193973. png_warning(png_ptr, "Unable to write uncompressed text");
  193974. #endif
  193975. /* Mark this chunk as written */
  193976. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193977. }
  193978. }
  193979. #endif
  193980. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193981. if (info_ptr->unknown_chunks_num)
  193982. {
  193983. png_unknown_chunk *up;
  193984. png_debug(5, "writing extra chunks\n");
  193985. for (up = info_ptr->unknown_chunks;
  193986. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193987. up++)
  193988. {
  193989. int keep=png_handle_as_unknown(png_ptr, up->name);
  193990. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193991. up->location && (up->location & PNG_HAVE_PLTE) &&
  193992. !(up->location & PNG_HAVE_IDAT) &&
  193993. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193994. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193995. {
  193996. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193997. }
  193998. }
  193999. }
  194000. #endif
  194001. }
  194002. /* Writes the end of the PNG file. If you don't want to write comments or
  194003. * time information, you can pass NULL for info. If you already wrote these
  194004. * in png_write_info(), do not write them again here. If you have long
  194005. * comments, I suggest writing them here, and compressing them.
  194006. */
  194007. void PNGAPI
  194008. png_write_end(png_structp png_ptr, png_infop info_ptr)
  194009. {
  194010. png_debug(1, "in png_write_end\n");
  194011. if (png_ptr == NULL)
  194012. return;
  194013. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  194014. png_error(png_ptr, "No IDATs written into file");
  194015. /* see if user wants us to write information chunks */
  194016. if (info_ptr != NULL)
  194017. {
  194018. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194019. int i; /* local index variable */
  194020. #endif
  194021. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194022. /* check to see if user has supplied a time chunk */
  194023. if ((info_ptr->valid & PNG_INFO_tIME) &&
  194024. !(png_ptr->mode & PNG_WROTE_tIME))
  194025. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194026. #endif
  194027. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194028. /* loop through comment chunks */
  194029. for (i = 0; i < info_ptr->num_text; i++)
  194030. {
  194031. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  194032. info_ptr->text[i].compression);
  194033. /* an internationalized chunk? */
  194034. if (info_ptr->text[i].compression > 0)
  194035. {
  194036. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194037. /* write international chunk */
  194038. png_write_iTXt(png_ptr,
  194039. info_ptr->text[i].compression,
  194040. info_ptr->text[i].key,
  194041. info_ptr->text[i].lang,
  194042. info_ptr->text[i].lang_key,
  194043. info_ptr->text[i].text);
  194044. #else
  194045. png_warning(png_ptr, "Unable to write international text");
  194046. #endif
  194047. /* Mark this chunk as written */
  194048. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194049. }
  194050. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  194051. {
  194052. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194053. /* write compressed chunk */
  194054. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194055. info_ptr->text[i].text, 0,
  194056. info_ptr->text[i].compression);
  194057. #else
  194058. png_warning(png_ptr, "Unable to write compressed text");
  194059. #endif
  194060. /* Mark this chunk as written */
  194061. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194062. }
  194063. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194064. {
  194065. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194066. /* write uncompressed chunk */
  194067. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194068. info_ptr->text[i].text, 0);
  194069. #else
  194070. png_warning(png_ptr, "Unable to write uncompressed text");
  194071. #endif
  194072. /* Mark this chunk as written */
  194073. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194074. }
  194075. }
  194076. #endif
  194077. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194078. if (info_ptr->unknown_chunks_num)
  194079. {
  194080. png_unknown_chunk *up;
  194081. png_debug(5, "writing extra chunks\n");
  194082. for (up = info_ptr->unknown_chunks;
  194083. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194084. up++)
  194085. {
  194086. int keep=png_handle_as_unknown(png_ptr, up->name);
  194087. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194088. up->location && (up->location & PNG_AFTER_IDAT) &&
  194089. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194090. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194091. {
  194092. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194093. }
  194094. }
  194095. }
  194096. #endif
  194097. }
  194098. png_ptr->mode |= PNG_AFTER_IDAT;
  194099. /* write end of PNG file */
  194100. png_write_IEND(png_ptr);
  194101. }
  194102. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194103. #if !defined(_WIN32_WCE)
  194104. /* "time.h" functions are not supported on WindowsCE */
  194105. void PNGAPI
  194106. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  194107. {
  194108. png_debug(1, "in png_convert_from_struct_tm\n");
  194109. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  194110. ptime->month = (png_byte)(ttime->tm_mon + 1);
  194111. ptime->day = (png_byte)ttime->tm_mday;
  194112. ptime->hour = (png_byte)ttime->tm_hour;
  194113. ptime->minute = (png_byte)ttime->tm_min;
  194114. ptime->second = (png_byte)ttime->tm_sec;
  194115. }
  194116. void PNGAPI
  194117. png_convert_from_time_t(png_timep ptime, time_t ttime)
  194118. {
  194119. struct tm *tbuf;
  194120. png_debug(1, "in png_convert_from_time_t\n");
  194121. tbuf = gmtime(&ttime);
  194122. png_convert_from_struct_tm(ptime, tbuf);
  194123. }
  194124. #endif
  194125. #endif
  194126. /* Initialize png_ptr structure, and allocate any memory needed */
  194127. png_structp PNGAPI
  194128. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  194129. png_error_ptr error_fn, png_error_ptr warn_fn)
  194130. {
  194131. #ifdef PNG_USER_MEM_SUPPORTED
  194132. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  194133. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  194134. }
  194135. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  194136. png_structp PNGAPI
  194137. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  194138. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  194139. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  194140. {
  194141. #endif /* PNG_USER_MEM_SUPPORTED */
  194142. png_structp png_ptr;
  194143. #ifdef PNG_SETJMP_SUPPORTED
  194144. #ifdef USE_FAR_KEYWORD
  194145. jmp_buf jmpbuf;
  194146. #endif
  194147. #endif
  194148. int i;
  194149. png_debug(1, "in png_create_write_struct\n");
  194150. #ifdef PNG_USER_MEM_SUPPORTED
  194151. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  194152. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  194153. #else
  194154. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194155. #endif /* PNG_USER_MEM_SUPPORTED */
  194156. if (png_ptr == NULL)
  194157. return (NULL);
  194158. /* added at libpng-1.2.6 */
  194159. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194160. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194161. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194162. #endif
  194163. #ifdef PNG_SETJMP_SUPPORTED
  194164. #ifdef USE_FAR_KEYWORD
  194165. if (setjmp(jmpbuf))
  194166. #else
  194167. if (setjmp(png_ptr->jmpbuf))
  194168. #endif
  194169. {
  194170. png_free(png_ptr, png_ptr->zbuf);
  194171. png_ptr->zbuf=NULL;
  194172. png_destroy_struct(png_ptr);
  194173. return (NULL);
  194174. }
  194175. #ifdef USE_FAR_KEYWORD
  194176. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194177. #endif
  194178. #endif
  194179. #ifdef PNG_USER_MEM_SUPPORTED
  194180. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  194181. #endif /* PNG_USER_MEM_SUPPORTED */
  194182. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  194183. i=0;
  194184. do
  194185. {
  194186. if(user_png_ver[i] != png_libpng_ver[i])
  194187. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194188. } while (png_libpng_ver[i++]);
  194189. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  194190. {
  194191. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  194192. * we must recompile any applications that use any older library version.
  194193. * For versions after libpng 1.0, we will be compatible, so we need
  194194. * only check the first digit.
  194195. */
  194196. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  194197. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  194198. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  194199. {
  194200. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194201. char msg[80];
  194202. if (user_png_ver)
  194203. {
  194204. png_snprintf(msg, 80,
  194205. "Application was compiled with png.h from libpng-%.20s",
  194206. user_png_ver);
  194207. png_warning(png_ptr, msg);
  194208. }
  194209. png_snprintf(msg, 80,
  194210. "Application is running with png.c from libpng-%.20s",
  194211. png_libpng_ver);
  194212. png_warning(png_ptr, msg);
  194213. #endif
  194214. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194215. png_ptr->flags=0;
  194216. #endif
  194217. png_error(png_ptr,
  194218. "Incompatible libpng version in application and library");
  194219. }
  194220. }
  194221. /* initialize zbuf - compression buffer */
  194222. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194223. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194224. (png_uint_32)png_ptr->zbuf_size);
  194225. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194226. png_flush_ptr_NULL);
  194227. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194228. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194229. 1, png_doublep_NULL, png_doublep_NULL);
  194230. #endif
  194231. #ifdef PNG_SETJMP_SUPPORTED
  194232. /* Applications that neglect to set up their own setjmp() and then encounter
  194233. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  194234. abort instead of returning. */
  194235. #ifdef USE_FAR_KEYWORD
  194236. if (setjmp(jmpbuf))
  194237. PNG_ABORT();
  194238. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194239. #else
  194240. if (setjmp(png_ptr->jmpbuf))
  194241. PNG_ABORT();
  194242. #endif
  194243. #endif
  194244. return (png_ptr);
  194245. }
  194246. /* Initialize png_ptr structure, and allocate any memory needed */
  194247. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194248. /* Deprecated. */
  194249. #undef png_write_init
  194250. void PNGAPI
  194251. png_write_init(png_structp png_ptr)
  194252. {
  194253. /* We only come here via pre-1.0.7-compiled applications */
  194254. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  194255. }
  194256. void PNGAPI
  194257. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  194258. png_size_t png_struct_size, png_size_t png_info_size)
  194259. {
  194260. /* We only come here via pre-1.0.12-compiled applications */
  194261. if(png_ptr == NULL) return;
  194262. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194263. if(png_sizeof(png_struct) > png_struct_size ||
  194264. png_sizeof(png_info) > png_info_size)
  194265. {
  194266. char msg[80];
  194267. png_ptr->warning_fn=NULL;
  194268. if (user_png_ver)
  194269. {
  194270. png_snprintf(msg, 80,
  194271. "Application was compiled with png.h from libpng-%.20s",
  194272. user_png_ver);
  194273. png_warning(png_ptr, msg);
  194274. }
  194275. png_snprintf(msg, 80,
  194276. "Application is running with png.c from libpng-%.20s",
  194277. png_libpng_ver);
  194278. png_warning(png_ptr, msg);
  194279. }
  194280. #endif
  194281. if(png_sizeof(png_struct) > png_struct_size)
  194282. {
  194283. png_ptr->error_fn=NULL;
  194284. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194285. png_ptr->flags=0;
  194286. #endif
  194287. png_error(png_ptr,
  194288. "The png struct allocated by the application for writing is too small.");
  194289. }
  194290. if(png_sizeof(png_info) > png_info_size)
  194291. {
  194292. png_ptr->error_fn=NULL;
  194293. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194294. png_ptr->flags=0;
  194295. #endif
  194296. png_error(png_ptr,
  194297. "The info struct allocated by the application for writing is too small.");
  194298. }
  194299. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  194300. }
  194301. #endif /* PNG_1_0_X || PNG_1_2_X */
  194302. void PNGAPI
  194303. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  194304. png_size_t png_struct_size)
  194305. {
  194306. png_structp png_ptr=*ptr_ptr;
  194307. #ifdef PNG_SETJMP_SUPPORTED
  194308. jmp_buf tmp_jmp; /* to save current jump buffer */
  194309. #endif
  194310. int i = 0;
  194311. if (png_ptr == NULL)
  194312. return;
  194313. do
  194314. {
  194315. if (user_png_ver[i] != png_libpng_ver[i])
  194316. {
  194317. #ifdef PNG_LEGACY_SUPPORTED
  194318. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194319. #else
  194320. png_ptr->warning_fn=NULL;
  194321. png_warning(png_ptr,
  194322. "Application uses deprecated png_write_init() and should be recompiled.");
  194323. break;
  194324. #endif
  194325. }
  194326. } while (png_libpng_ver[i++]);
  194327. png_debug(1, "in png_write_init_3\n");
  194328. #ifdef PNG_SETJMP_SUPPORTED
  194329. /* save jump buffer and error functions */
  194330. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  194331. #endif
  194332. if (png_sizeof(png_struct) > png_struct_size)
  194333. {
  194334. png_destroy_struct(png_ptr);
  194335. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194336. *ptr_ptr = png_ptr;
  194337. }
  194338. /* reset all variables to 0 */
  194339. png_memset(png_ptr, 0, png_sizeof (png_struct));
  194340. /* added at libpng-1.2.6 */
  194341. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194342. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194343. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194344. #endif
  194345. #ifdef PNG_SETJMP_SUPPORTED
  194346. /* restore jump buffer */
  194347. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  194348. #endif
  194349. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194350. png_flush_ptr_NULL);
  194351. /* initialize zbuf - compression buffer */
  194352. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194353. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194354. (png_uint_32)png_ptr->zbuf_size);
  194355. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194356. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194357. 1, png_doublep_NULL, png_doublep_NULL);
  194358. #endif
  194359. }
  194360. /* Write a few rows of image data. If the image is interlaced,
  194361. * either you will have to write the 7 sub images, or, if you
  194362. * have called png_set_interlace_handling(), you will have to
  194363. * "write" the image seven times.
  194364. */
  194365. void PNGAPI
  194366. png_write_rows(png_structp png_ptr, png_bytepp row,
  194367. png_uint_32 num_rows)
  194368. {
  194369. png_uint_32 i; /* row counter */
  194370. png_bytepp rp; /* row pointer */
  194371. png_debug(1, "in png_write_rows\n");
  194372. if (png_ptr == NULL)
  194373. return;
  194374. /* loop through the rows */
  194375. for (i = 0, rp = row; i < num_rows; i++, rp++)
  194376. {
  194377. png_write_row(png_ptr, *rp);
  194378. }
  194379. }
  194380. /* Write the image. You only need to call this function once, even
  194381. * if you are writing an interlaced image.
  194382. */
  194383. void PNGAPI
  194384. png_write_image(png_structp png_ptr, png_bytepp image)
  194385. {
  194386. png_uint_32 i; /* row index */
  194387. int pass, num_pass; /* pass variables */
  194388. png_bytepp rp; /* points to current row */
  194389. if (png_ptr == NULL)
  194390. return;
  194391. png_debug(1, "in png_write_image\n");
  194392. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194393. /* intialize interlace handling. If image is not interlaced,
  194394. this will set pass to 1 */
  194395. num_pass = png_set_interlace_handling(png_ptr);
  194396. #else
  194397. num_pass = 1;
  194398. #endif
  194399. /* loop through passes */
  194400. for (pass = 0; pass < num_pass; pass++)
  194401. {
  194402. /* loop through image */
  194403. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  194404. {
  194405. png_write_row(png_ptr, *rp);
  194406. }
  194407. }
  194408. }
  194409. /* called by user to write a row of image data */
  194410. void PNGAPI
  194411. png_write_row(png_structp png_ptr, png_bytep row)
  194412. {
  194413. if (png_ptr == NULL)
  194414. return;
  194415. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  194416. png_ptr->row_number, png_ptr->pass);
  194417. /* initialize transformations and other stuff if first time */
  194418. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  194419. {
  194420. /* make sure we wrote the header info */
  194421. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  194422. png_error(png_ptr,
  194423. "png_write_info was never called before png_write_row.");
  194424. /* check for transforms that have been set but were defined out */
  194425. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  194426. if (png_ptr->transformations & PNG_INVERT_MONO)
  194427. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  194428. #endif
  194429. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  194430. if (png_ptr->transformations & PNG_FILLER)
  194431. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  194432. #endif
  194433. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  194434. if (png_ptr->transformations & PNG_PACKSWAP)
  194435. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  194436. #endif
  194437. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  194438. if (png_ptr->transformations & PNG_PACK)
  194439. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  194440. #endif
  194441. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  194442. if (png_ptr->transformations & PNG_SHIFT)
  194443. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  194444. #endif
  194445. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  194446. if (png_ptr->transformations & PNG_BGR)
  194447. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  194448. #endif
  194449. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  194450. if (png_ptr->transformations & PNG_SWAP_BYTES)
  194451. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  194452. #endif
  194453. png_write_start_row(png_ptr);
  194454. }
  194455. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194456. /* if interlaced and not interested in row, return */
  194457. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  194458. {
  194459. switch (png_ptr->pass)
  194460. {
  194461. case 0:
  194462. if (png_ptr->row_number & 0x07)
  194463. {
  194464. png_write_finish_row(png_ptr);
  194465. return;
  194466. }
  194467. break;
  194468. case 1:
  194469. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  194470. {
  194471. png_write_finish_row(png_ptr);
  194472. return;
  194473. }
  194474. break;
  194475. case 2:
  194476. if ((png_ptr->row_number & 0x07) != 4)
  194477. {
  194478. png_write_finish_row(png_ptr);
  194479. return;
  194480. }
  194481. break;
  194482. case 3:
  194483. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  194484. {
  194485. png_write_finish_row(png_ptr);
  194486. return;
  194487. }
  194488. break;
  194489. case 4:
  194490. if ((png_ptr->row_number & 0x03) != 2)
  194491. {
  194492. png_write_finish_row(png_ptr);
  194493. return;
  194494. }
  194495. break;
  194496. case 5:
  194497. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  194498. {
  194499. png_write_finish_row(png_ptr);
  194500. return;
  194501. }
  194502. break;
  194503. case 6:
  194504. if (!(png_ptr->row_number & 0x01))
  194505. {
  194506. png_write_finish_row(png_ptr);
  194507. return;
  194508. }
  194509. break;
  194510. }
  194511. }
  194512. #endif
  194513. /* set up row info for transformations */
  194514. png_ptr->row_info.color_type = png_ptr->color_type;
  194515. png_ptr->row_info.width = png_ptr->usr_width;
  194516. png_ptr->row_info.channels = png_ptr->usr_channels;
  194517. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  194518. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  194519. png_ptr->row_info.channels);
  194520. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  194521. png_ptr->row_info.width);
  194522. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  194523. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  194524. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  194525. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  194526. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  194527. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  194528. /* Copy user's row into buffer, leaving room for filter byte. */
  194529. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  194530. png_ptr->row_info.rowbytes);
  194531. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194532. /* handle interlacing */
  194533. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  194534. (png_ptr->transformations & PNG_INTERLACE))
  194535. {
  194536. png_do_write_interlace(&(png_ptr->row_info),
  194537. png_ptr->row_buf + 1, png_ptr->pass);
  194538. /* this should always get caught above, but still ... */
  194539. if (!(png_ptr->row_info.width))
  194540. {
  194541. png_write_finish_row(png_ptr);
  194542. return;
  194543. }
  194544. }
  194545. #endif
  194546. /* handle other transformations */
  194547. if (png_ptr->transformations)
  194548. png_do_write_transformations(png_ptr);
  194549. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194550. /* Write filter_method 64 (intrapixel differencing) only if
  194551. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  194552. * 2. Libpng did not write a PNG signature (this filter_method is only
  194553. * used in PNG datastreams that are embedded in MNG datastreams) and
  194554. * 3. The application called png_permit_mng_features with a mask that
  194555. * included PNG_FLAG_MNG_FILTER_64 and
  194556. * 4. The filter_method is 64 and
  194557. * 5. The color_type is RGB or RGBA
  194558. */
  194559. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194560. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  194561. {
  194562. /* Intrapixel differencing */
  194563. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194564. }
  194565. #endif
  194566. /* Find a filter if necessary, filter the row and write it out. */
  194567. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  194568. if (png_ptr->write_row_fn != NULL)
  194569. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  194570. }
  194571. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194572. /* Set the automatic flush interval or 0 to turn flushing off */
  194573. void PNGAPI
  194574. png_set_flush(png_structp png_ptr, int nrows)
  194575. {
  194576. png_debug(1, "in png_set_flush\n");
  194577. if (png_ptr == NULL)
  194578. return;
  194579. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  194580. }
  194581. /* flush the current output buffers now */
  194582. void PNGAPI
  194583. png_write_flush(png_structp png_ptr)
  194584. {
  194585. int wrote_IDAT;
  194586. png_debug(1, "in png_write_flush\n");
  194587. if (png_ptr == NULL)
  194588. return;
  194589. /* We have already written out all of the data */
  194590. if (png_ptr->row_number >= png_ptr->num_rows)
  194591. return;
  194592. do
  194593. {
  194594. int ret;
  194595. /* compress the data */
  194596. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  194597. wrote_IDAT = 0;
  194598. /* check for compression errors */
  194599. if (ret != Z_OK)
  194600. {
  194601. if (png_ptr->zstream.msg != NULL)
  194602. png_error(png_ptr, png_ptr->zstream.msg);
  194603. else
  194604. png_error(png_ptr, "zlib error");
  194605. }
  194606. if (!(png_ptr->zstream.avail_out))
  194607. {
  194608. /* write the IDAT and reset the zlib output buffer */
  194609. png_write_IDAT(png_ptr, png_ptr->zbuf,
  194610. png_ptr->zbuf_size);
  194611. png_ptr->zstream.next_out = png_ptr->zbuf;
  194612. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194613. wrote_IDAT = 1;
  194614. }
  194615. } while(wrote_IDAT == 1);
  194616. /* If there is any data left to be output, write it into a new IDAT */
  194617. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  194618. {
  194619. /* write the IDAT and reset the zlib output buffer */
  194620. png_write_IDAT(png_ptr, png_ptr->zbuf,
  194621. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  194622. png_ptr->zstream.next_out = png_ptr->zbuf;
  194623. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194624. }
  194625. png_ptr->flush_rows = 0;
  194626. png_flush(png_ptr);
  194627. }
  194628. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  194629. /* free all memory used by the write */
  194630. void PNGAPI
  194631. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  194632. {
  194633. png_structp png_ptr = NULL;
  194634. png_infop info_ptr = NULL;
  194635. #ifdef PNG_USER_MEM_SUPPORTED
  194636. png_free_ptr free_fn = NULL;
  194637. png_voidp mem_ptr = NULL;
  194638. #endif
  194639. png_debug(1, "in png_destroy_write_struct\n");
  194640. if (png_ptr_ptr != NULL)
  194641. {
  194642. png_ptr = *png_ptr_ptr;
  194643. #ifdef PNG_USER_MEM_SUPPORTED
  194644. free_fn = png_ptr->free_fn;
  194645. mem_ptr = png_ptr->mem_ptr;
  194646. #endif
  194647. }
  194648. if (info_ptr_ptr != NULL)
  194649. info_ptr = *info_ptr_ptr;
  194650. if (info_ptr != NULL)
  194651. {
  194652. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  194653. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194654. if (png_ptr->num_chunk_list)
  194655. {
  194656. png_free(png_ptr, png_ptr->chunk_list);
  194657. png_ptr->chunk_list=NULL;
  194658. png_ptr->num_chunk_list=0;
  194659. }
  194660. #endif
  194661. #ifdef PNG_USER_MEM_SUPPORTED
  194662. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  194663. (png_voidp)mem_ptr);
  194664. #else
  194665. png_destroy_struct((png_voidp)info_ptr);
  194666. #endif
  194667. *info_ptr_ptr = NULL;
  194668. }
  194669. if (png_ptr != NULL)
  194670. {
  194671. png_write_destroy(png_ptr);
  194672. #ifdef PNG_USER_MEM_SUPPORTED
  194673. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  194674. (png_voidp)mem_ptr);
  194675. #else
  194676. png_destroy_struct((png_voidp)png_ptr);
  194677. #endif
  194678. *png_ptr_ptr = NULL;
  194679. }
  194680. }
  194681. /* Free any memory used in png_ptr struct (old method) */
  194682. void /* PRIVATE */
  194683. png_write_destroy(png_structp png_ptr)
  194684. {
  194685. #ifdef PNG_SETJMP_SUPPORTED
  194686. jmp_buf tmp_jmp; /* save jump buffer */
  194687. #endif
  194688. png_error_ptr error_fn;
  194689. png_error_ptr warning_fn;
  194690. png_voidp error_ptr;
  194691. #ifdef PNG_USER_MEM_SUPPORTED
  194692. png_free_ptr free_fn;
  194693. #endif
  194694. png_debug(1, "in png_write_destroy\n");
  194695. /* free any memory zlib uses */
  194696. deflateEnd(&png_ptr->zstream);
  194697. /* free our memory. png_free checks NULL for us. */
  194698. png_free(png_ptr, png_ptr->zbuf);
  194699. png_free(png_ptr, png_ptr->row_buf);
  194700. png_free(png_ptr, png_ptr->prev_row);
  194701. png_free(png_ptr, png_ptr->sub_row);
  194702. png_free(png_ptr, png_ptr->up_row);
  194703. png_free(png_ptr, png_ptr->avg_row);
  194704. png_free(png_ptr, png_ptr->paeth_row);
  194705. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  194706. png_free(png_ptr, png_ptr->time_buffer);
  194707. #endif
  194708. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194709. png_free(png_ptr, png_ptr->prev_filters);
  194710. png_free(png_ptr, png_ptr->filter_weights);
  194711. png_free(png_ptr, png_ptr->inv_filter_weights);
  194712. png_free(png_ptr, png_ptr->filter_costs);
  194713. png_free(png_ptr, png_ptr->inv_filter_costs);
  194714. #endif
  194715. #ifdef PNG_SETJMP_SUPPORTED
  194716. /* reset structure */
  194717. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  194718. #endif
  194719. error_fn = png_ptr->error_fn;
  194720. warning_fn = png_ptr->warning_fn;
  194721. error_ptr = png_ptr->error_ptr;
  194722. #ifdef PNG_USER_MEM_SUPPORTED
  194723. free_fn = png_ptr->free_fn;
  194724. #endif
  194725. png_memset(png_ptr, 0, png_sizeof (png_struct));
  194726. png_ptr->error_fn = error_fn;
  194727. png_ptr->warning_fn = warning_fn;
  194728. png_ptr->error_ptr = error_ptr;
  194729. #ifdef PNG_USER_MEM_SUPPORTED
  194730. png_ptr->free_fn = free_fn;
  194731. #endif
  194732. #ifdef PNG_SETJMP_SUPPORTED
  194733. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  194734. #endif
  194735. }
  194736. /* Allow the application to select one or more row filters to use. */
  194737. void PNGAPI
  194738. png_set_filter(png_structp png_ptr, int method, int filters)
  194739. {
  194740. png_debug(1, "in png_set_filter\n");
  194741. if (png_ptr == NULL)
  194742. return;
  194743. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194744. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194745. (method == PNG_INTRAPIXEL_DIFFERENCING))
  194746. method = PNG_FILTER_TYPE_BASE;
  194747. #endif
  194748. if (method == PNG_FILTER_TYPE_BASE)
  194749. {
  194750. switch (filters & (PNG_ALL_FILTERS | 0x07))
  194751. {
  194752. #ifndef PNG_NO_WRITE_FILTER
  194753. case 5:
  194754. case 6:
  194755. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  194756. #endif /* PNG_NO_WRITE_FILTER */
  194757. case PNG_FILTER_VALUE_NONE:
  194758. png_ptr->do_filter=PNG_FILTER_NONE; break;
  194759. #ifndef PNG_NO_WRITE_FILTER
  194760. case PNG_FILTER_VALUE_SUB:
  194761. png_ptr->do_filter=PNG_FILTER_SUB; break;
  194762. case PNG_FILTER_VALUE_UP:
  194763. png_ptr->do_filter=PNG_FILTER_UP; break;
  194764. case PNG_FILTER_VALUE_AVG:
  194765. png_ptr->do_filter=PNG_FILTER_AVG; break;
  194766. case PNG_FILTER_VALUE_PAETH:
  194767. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  194768. default: png_ptr->do_filter = (png_byte)filters; break;
  194769. #else
  194770. default: png_warning(png_ptr, "Unknown row filter for method 0");
  194771. #endif /* PNG_NO_WRITE_FILTER */
  194772. }
  194773. /* If we have allocated the row_buf, this means we have already started
  194774. * with the image and we should have allocated all of the filter buffers
  194775. * that have been selected. If prev_row isn't already allocated, then
  194776. * it is too late to start using the filters that need it, since we
  194777. * will be missing the data in the previous row. If an application
  194778. * wants to start and stop using particular filters during compression,
  194779. * it should start out with all of the filters, and then add and
  194780. * remove them after the start of compression.
  194781. */
  194782. if (png_ptr->row_buf != NULL)
  194783. {
  194784. #ifndef PNG_NO_WRITE_FILTER
  194785. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  194786. {
  194787. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  194788. (png_ptr->rowbytes + 1));
  194789. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  194790. }
  194791. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  194792. {
  194793. if (png_ptr->prev_row == NULL)
  194794. {
  194795. png_warning(png_ptr, "Can't add Up filter after starting");
  194796. png_ptr->do_filter &= ~PNG_FILTER_UP;
  194797. }
  194798. else
  194799. {
  194800. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  194801. (png_ptr->rowbytes + 1));
  194802. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  194803. }
  194804. }
  194805. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  194806. {
  194807. if (png_ptr->prev_row == NULL)
  194808. {
  194809. png_warning(png_ptr, "Can't add Average filter after starting");
  194810. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  194811. }
  194812. else
  194813. {
  194814. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  194815. (png_ptr->rowbytes + 1));
  194816. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  194817. }
  194818. }
  194819. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  194820. png_ptr->paeth_row == NULL)
  194821. {
  194822. if (png_ptr->prev_row == NULL)
  194823. {
  194824. png_warning(png_ptr, "Can't add Paeth filter after starting");
  194825. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  194826. }
  194827. else
  194828. {
  194829. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  194830. (png_ptr->rowbytes + 1));
  194831. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  194832. }
  194833. }
  194834. if (png_ptr->do_filter == PNG_NO_FILTERS)
  194835. #endif /* PNG_NO_WRITE_FILTER */
  194836. png_ptr->do_filter = PNG_FILTER_NONE;
  194837. }
  194838. }
  194839. else
  194840. png_error(png_ptr, "Unknown custom filter method");
  194841. }
  194842. /* This allows us to influence the way in which libpng chooses the "best"
  194843. * filter for the current scanline. While the "minimum-sum-of-absolute-
  194844. * differences metric is relatively fast and effective, there is some
  194845. * question as to whether it can be improved upon by trying to keep the
  194846. * filtered data going to zlib more consistent, hopefully resulting in
  194847. * better compression.
  194848. */
  194849. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  194850. void PNGAPI
  194851. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  194852. int num_weights, png_doublep filter_weights,
  194853. png_doublep filter_costs)
  194854. {
  194855. int i;
  194856. png_debug(1, "in png_set_filter_heuristics\n");
  194857. if (png_ptr == NULL)
  194858. return;
  194859. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  194860. {
  194861. png_warning(png_ptr, "Unknown filter heuristic method");
  194862. return;
  194863. }
  194864. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  194865. {
  194866. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  194867. }
  194868. if (num_weights < 0 || filter_weights == NULL ||
  194869. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  194870. {
  194871. num_weights = 0;
  194872. }
  194873. png_ptr->num_prev_filters = (png_byte)num_weights;
  194874. png_ptr->heuristic_method = (png_byte)heuristic_method;
  194875. if (num_weights > 0)
  194876. {
  194877. if (png_ptr->prev_filters == NULL)
  194878. {
  194879. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  194880. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  194881. /* To make sure that the weighting starts out fairly */
  194882. for (i = 0; i < num_weights; i++)
  194883. {
  194884. png_ptr->prev_filters[i] = 255;
  194885. }
  194886. }
  194887. if (png_ptr->filter_weights == NULL)
  194888. {
  194889. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  194890. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  194891. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  194892. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  194893. for (i = 0; i < num_weights; i++)
  194894. {
  194895. png_ptr->inv_filter_weights[i] =
  194896. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  194897. }
  194898. }
  194899. for (i = 0; i < num_weights; i++)
  194900. {
  194901. if (filter_weights[i] < 0.0)
  194902. {
  194903. png_ptr->inv_filter_weights[i] =
  194904. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  194905. }
  194906. else
  194907. {
  194908. png_ptr->inv_filter_weights[i] =
  194909. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  194910. png_ptr->filter_weights[i] =
  194911. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  194912. }
  194913. }
  194914. }
  194915. /* If, in the future, there are other filter methods, this would
  194916. * need to be based on png_ptr->filter.
  194917. */
  194918. if (png_ptr->filter_costs == NULL)
  194919. {
  194920. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  194921. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  194922. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  194923. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  194924. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  194925. {
  194926. png_ptr->inv_filter_costs[i] =
  194927. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  194928. }
  194929. }
  194930. /* Here is where we set the relative costs of the different filters. We
  194931. * should take the desired compression level into account when setting
  194932. * the costs, so that Paeth, for instance, has a high relative cost at low
  194933. * compression levels, while it has a lower relative cost at higher
  194934. * compression settings. The filter types are in order of increasing
  194935. * relative cost, so it would be possible to do this with an algorithm.
  194936. */
  194937. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  194938. {
  194939. if (filter_costs == NULL || filter_costs[i] < 0.0)
  194940. {
  194941. png_ptr->inv_filter_costs[i] =
  194942. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  194943. }
  194944. else if (filter_costs[i] >= 1.0)
  194945. {
  194946. png_ptr->inv_filter_costs[i] =
  194947. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  194948. png_ptr->filter_costs[i] =
  194949. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  194950. }
  194951. }
  194952. }
  194953. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  194954. void PNGAPI
  194955. png_set_compression_level(png_structp png_ptr, int level)
  194956. {
  194957. png_debug(1, "in png_set_compression_level\n");
  194958. if (png_ptr == NULL)
  194959. return;
  194960. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  194961. png_ptr->zlib_level = level;
  194962. }
  194963. void PNGAPI
  194964. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  194965. {
  194966. png_debug(1, "in png_set_compression_mem_level\n");
  194967. if (png_ptr == NULL)
  194968. return;
  194969. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  194970. png_ptr->zlib_mem_level = mem_level;
  194971. }
  194972. void PNGAPI
  194973. png_set_compression_strategy(png_structp png_ptr, int strategy)
  194974. {
  194975. png_debug(1, "in png_set_compression_strategy\n");
  194976. if (png_ptr == NULL)
  194977. return;
  194978. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  194979. png_ptr->zlib_strategy = strategy;
  194980. }
  194981. void PNGAPI
  194982. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  194983. {
  194984. if (png_ptr == NULL)
  194985. return;
  194986. if (window_bits > 15)
  194987. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  194988. else if (window_bits < 8)
  194989. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  194990. #ifndef WBITS_8_OK
  194991. /* avoid libpng bug with 256-byte windows */
  194992. if (window_bits == 8)
  194993. {
  194994. png_warning(png_ptr, "Compression window is being reset to 512");
  194995. window_bits=9;
  194996. }
  194997. #endif
  194998. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  194999. png_ptr->zlib_window_bits = window_bits;
  195000. }
  195001. void PNGAPI
  195002. png_set_compression_method(png_structp png_ptr, int method)
  195003. {
  195004. png_debug(1, "in png_set_compression_method\n");
  195005. if (png_ptr == NULL)
  195006. return;
  195007. if (method != 8)
  195008. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  195009. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  195010. png_ptr->zlib_method = method;
  195011. }
  195012. void PNGAPI
  195013. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  195014. {
  195015. if (png_ptr == NULL)
  195016. return;
  195017. png_ptr->write_row_fn = write_row_fn;
  195018. }
  195019. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195020. void PNGAPI
  195021. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  195022. write_user_transform_fn)
  195023. {
  195024. png_debug(1, "in png_set_write_user_transform_fn\n");
  195025. if (png_ptr == NULL)
  195026. return;
  195027. png_ptr->transformations |= PNG_USER_TRANSFORM;
  195028. png_ptr->write_user_transform_fn = write_user_transform_fn;
  195029. }
  195030. #endif
  195031. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  195032. void PNGAPI
  195033. png_write_png(png_structp png_ptr, png_infop info_ptr,
  195034. int transforms, voidp params)
  195035. {
  195036. if (png_ptr == NULL || info_ptr == NULL)
  195037. return;
  195038. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195039. /* invert the alpha channel from opacity to transparency */
  195040. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  195041. png_set_invert_alpha(png_ptr);
  195042. #endif
  195043. /* Write the file header information. */
  195044. png_write_info(png_ptr, info_ptr);
  195045. /* ------ these transformations don't touch the info structure ------- */
  195046. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195047. /* invert monochrome pixels */
  195048. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  195049. png_set_invert_mono(png_ptr);
  195050. #endif
  195051. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195052. /* Shift the pixels up to a legal bit depth and fill in
  195053. * as appropriate to correctly scale the image.
  195054. */
  195055. if ((transforms & PNG_TRANSFORM_SHIFT)
  195056. && (info_ptr->valid & PNG_INFO_sBIT))
  195057. png_set_shift(png_ptr, &info_ptr->sig_bit);
  195058. #endif
  195059. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195060. /* pack pixels into bytes */
  195061. if (transforms & PNG_TRANSFORM_PACKING)
  195062. png_set_packing(png_ptr);
  195063. #endif
  195064. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195065. /* swap location of alpha bytes from ARGB to RGBA */
  195066. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  195067. png_set_swap_alpha(png_ptr);
  195068. #endif
  195069. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195070. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  195071. * RGB (4 channels -> 3 channels). The second parameter is not used.
  195072. */
  195073. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  195074. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  195075. #endif
  195076. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195077. /* flip BGR pixels to RGB */
  195078. if (transforms & PNG_TRANSFORM_BGR)
  195079. png_set_bgr(png_ptr);
  195080. #endif
  195081. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195082. /* swap bytes of 16-bit files to most significant byte first */
  195083. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  195084. png_set_swap(png_ptr);
  195085. #endif
  195086. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195087. /* swap bits of 1, 2, 4 bit packed pixel formats */
  195088. if (transforms & PNG_TRANSFORM_PACKSWAP)
  195089. png_set_packswap(png_ptr);
  195090. #endif
  195091. /* ----------------------- end of transformations ------------------- */
  195092. /* write the bits */
  195093. if (info_ptr->valid & PNG_INFO_IDAT)
  195094. png_write_image(png_ptr, info_ptr->row_pointers);
  195095. /* It is REQUIRED to call this to finish writing the rest of the file */
  195096. png_write_end(png_ptr, info_ptr);
  195097. transforms = transforms; /* quiet compiler warnings */
  195098. params = params;
  195099. }
  195100. #endif
  195101. #endif /* PNG_WRITE_SUPPORTED */
  195102. /********* End of inlined file: pngwrite.c *********/
  195103. /********* Start of inlined file: pngwtran.c *********/
  195104. /* pngwtran.c - transforms the data in a row for PNG writers
  195105. *
  195106. * Last changed in libpng 1.2.9 April 14, 2006
  195107. * For conditions of distribution and use, see copyright notice in png.h
  195108. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  195109. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195110. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195111. */
  195112. #define PNG_INTERNAL
  195113. #ifdef PNG_WRITE_SUPPORTED
  195114. /* Transform the data according to the user's wishes. The order of
  195115. * transformations is significant.
  195116. */
  195117. void /* PRIVATE */
  195118. png_do_write_transformations(png_structp png_ptr)
  195119. {
  195120. png_debug(1, "in png_do_write_transformations\n");
  195121. if (png_ptr == NULL)
  195122. return;
  195123. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195124. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  195125. if(png_ptr->write_user_transform_fn != NULL)
  195126. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  195127. (png_ptr, /* png_ptr */
  195128. &(png_ptr->row_info), /* row_info: */
  195129. /* png_uint_32 width; width of row */
  195130. /* png_uint_32 rowbytes; number of bytes in row */
  195131. /* png_byte color_type; color type of pixels */
  195132. /* png_byte bit_depth; bit depth of samples */
  195133. /* png_byte channels; number of channels (1-4) */
  195134. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  195135. png_ptr->row_buf + 1); /* start of pixel data for row */
  195136. #endif
  195137. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195138. if (png_ptr->transformations & PNG_FILLER)
  195139. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195140. png_ptr->flags);
  195141. #endif
  195142. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195143. if (png_ptr->transformations & PNG_PACKSWAP)
  195144. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195145. #endif
  195146. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195147. if (png_ptr->transformations & PNG_PACK)
  195148. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195149. (png_uint_32)png_ptr->bit_depth);
  195150. #endif
  195151. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195152. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195153. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195154. #endif
  195155. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195156. if (png_ptr->transformations & PNG_SHIFT)
  195157. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195158. &(png_ptr->shift));
  195159. #endif
  195160. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195161. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  195162. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195163. #endif
  195164. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195165. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  195166. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195167. #endif
  195168. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195169. if (png_ptr->transformations & PNG_BGR)
  195170. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195171. #endif
  195172. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195173. if (png_ptr->transformations & PNG_INVERT_MONO)
  195174. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195175. #endif
  195176. }
  195177. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195178. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  195179. * row_info bit depth should be 8 (one pixel per byte). The channels
  195180. * should be 1 (this only happens on grayscale and paletted images).
  195181. */
  195182. void /* PRIVATE */
  195183. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  195184. {
  195185. png_debug(1, "in png_do_pack\n");
  195186. if (row_info->bit_depth == 8 &&
  195187. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195188. row != NULL && row_info != NULL &&
  195189. #endif
  195190. row_info->channels == 1)
  195191. {
  195192. switch ((int)bit_depth)
  195193. {
  195194. case 1:
  195195. {
  195196. png_bytep sp, dp;
  195197. int mask, v;
  195198. png_uint_32 i;
  195199. png_uint_32 row_width = row_info->width;
  195200. sp = row;
  195201. dp = row;
  195202. mask = 0x80;
  195203. v = 0;
  195204. for (i = 0; i < row_width; i++)
  195205. {
  195206. if (*sp != 0)
  195207. v |= mask;
  195208. sp++;
  195209. if (mask > 1)
  195210. mask >>= 1;
  195211. else
  195212. {
  195213. mask = 0x80;
  195214. *dp = (png_byte)v;
  195215. dp++;
  195216. v = 0;
  195217. }
  195218. }
  195219. if (mask != 0x80)
  195220. *dp = (png_byte)v;
  195221. break;
  195222. }
  195223. case 2:
  195224. {
  195225. png_bytep sp, dp;
  195226. int shift, v;
  195227. png_uint_32 i;
  195228. png_uint_32 row_width = row_info->width;
  195229. sp = row;
  195230. dp = row;
  195231. shift = 6;
  195232. v = 0;
  195233. for (i = 0; i < row_width; i++)
  195234. {
  195235. png_byte value;
  195236. value = (png_byte)(*sp & 0x03);
  195237. v |= (value << shift);
  195238. if (shift == 0)
  195239. {
  195240. shift = 6;
  195241. *dp = (png_byte)v;
  195242. dp++;
  195243. v = 0;
  195244. }
  195245. else
  195246. shift -= 2;
  195247. sp++;
  195248. }
  195249. if (shift != 6)
  195250. *dp = (png_byte)v;
  195251. break;
  195252. }
  195253. case 4:
  195254. {
  195255. png_bytep sp, dp;
  195256. int shift, v;
  195257. png_uint_32 i;
  195258. png_uint_32 row_width = row_info->width;
  195259. sp = row;
  195260. dp = row;
  195261. shift = 4;
  195262. v = 0;
  195263. for (i = 0; i < row_width; i++)
  195264. {
  195265. png_byte value;
  195266. value = (png_byte)(*sp & 0x0f);
  195267. v |= (value << shift);
  195268. if (shift == 0)
  195269. {
  195270. shift = 4;
  195271. *dp = (png_byte)v;
  195272. dp++;
  195273. v = 0;
  195274. }
  195275. else
  195276. shift -= 4;
  195277. sp++;
  195278. }
  195279. if (shift != 4)
  195280. *dp = (png_byte)v;
  195281. break;
  195282. }
  195283. }
  195284. row_info->bit_depth = (png_byte)bit_depth;
  195285. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  195286. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  195287. row_info->width);
  195288. }
  195289. }
  195290. #endif
  195291. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195292. /* Shift pixel values to take advantage of whole range. Pass the
  195293. * true number of bits in bit_depth. The row should be packed
  195294. * according to row_info->bit_depth. Thus, if you had a row of
  195295. * bit depth 4, but the pixels only had values from 0 to 7, you
  195296. * would pass 3 as bit_depth, and this routine would translate the
  195297. * data to 0 to 15.
  195298. */
  195299. void /* PRIVATE */
  195300. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  195301. {
  195302. png_debug(1, "in png_do_shift\n");
  195303. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195304. if (row != NULL && row_info != NULL &&
  195305. #else
  195306. if (
  195307. #endif
  195308. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  195309. {
  195310. int shift_start[4], shift_dec[4];
  195311. int channels = 0;
  195312. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  195313. {
  195314. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  195315. shift_dec[channels] = bit_depth->red;
  195316. channels++;
  195317. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  195318. shift_dec[channels] = bit_depth->green;
  195319. channels++;
  195320. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  195321. shift_dec[channels] = bit_depth->blue;
  195322. channels++;
  195323. }
  195324. else
  195325. {
  195326. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  195327. shift_dec[channels] = bit_depth->gray;
  195328. channels++;
  195329. }
  195330. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  195331. {
  195332. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  195333. shift_dec[channels] = bit_depth->alpha;
  195334. channels++;
  195335. }
  195336. /* with low row depths, could only be grayscale, so one channel */
  195337. if (row_info->bit_depth < 8)
  195338. {
  195339. png_bytep bp = row;
  195340. png_uint_32 i;
  195341. png_byte mask;
  195342. png_uint_32 row_bytes = row_info->rowbytes;
  195343. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  195344. mask = 0x55;
  195345. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  195346. mask = 0x11;
  195347. else
  195348. mask = 0xff;
  195349. for (i = 0; i < row_bytes; i++, bp++)
  195350. {
  195351. png_uint_16 v;
  195352. int j;
  195353. v = *bp;
  195354. *bp = 0;
  195355. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  195356. {
  195357. if (j > 0)
  195358. *bp |= (png_byte)((v << j) & 0xff);
  195359. else
  195360. *bp |= (png_byte)((v >> (-j)) & mask);
  195361. }
  195362. }
  195363. }
  195364. else if (row_info->bit_depth == 8)
  195365. {
  195366. png_bytep bp = row;
  195367. png_uint_32 i;
  195368. png_uint_32 istop = channels * row_info->width;
  195369. for (i = 0; i < istop; i++, bp++)
  195370. {
  195371. png_uint_16 v;
  195372. int j;
  195373. int c = (int)(i%channels);
  195374. v = *bp;
  195375. *bp = 0;
  195376. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  195377. {
  195378. if (j > 0)
  195379. *bp |= (png_byte)((v << j) & 0xff);
  195380. else
  195381. *bp |= (png_byte)((v >> (-j)) & 0xff);
  195382. }
  195383. }
  195384. }
  195385. else
  195386. {
  195387. png_bytep bp;
  195388. png_uint_32 i;
  195389. png_uint_32 istop = channels * row_info->width;
  195390. for (bp = row, i = 0; i < istop; i++)
  195391. {
  195392. int c = (int)(i%channels);
  195393. png_uint_16 value, v;
  195394. int j;
  195395. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  195396. value = 0;
  195397. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  195398. {
  195399. if (j > 0)
  195400. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  195401. else
  195402. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  195403. }
  195404. *bp++ = (png_byte)(value >> 8);
  195405. *bp++ = (png_byte)(value & 0xff);
  195406. }
  195407. }
  195408. }
  195409. }
  195410. #endif
  195411. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195412. void /* PRIVATE */
  195413. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  195414. {
  195415. png_debug(1, "in png_do_write_swap_alpha\n");
  195416. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195417. if (row != NULL && row_info != NULL)
  195418. #endif
  195419. {
  195420. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195421. {
  195422. /* This converts from ARGB to RGBA */
  195423. if (row_info->bit_depth == 8)
  195424. {
  195425. png_bytep sp, dp;
  195426. png_uint_32 i;
  195427. png_uint_32 row_width = row_info->width;
  195428. for (i = 0, sp = dp = row; i < row_width; i++)
  195429. {
  195430. png_byte save = *(sp++);
  195431. *(dp++) = *(sp++);
  195432. *(dp++) = *(sp++);
  195433. *(dp++) = *(sp++);
  195434. *(dp++) = save;
  195435. }
  195436. }
  195437. /* This converts from AARRGGBB to RRGGBBAA */
  195438. else
  195439. {
  195440. png_bytep sp, dp;
  195441. png_uint_32 i;
  195442. png_uint_32 row_width = row_info->width;
  195443. for (i = 0, sp = dp = row; i < row_width; i++)
  195444. {
  195445. png_byte save[2];
  195446. save[0] = *(sp++);
  195447. save[1] = *(sp++);
  195448. *(dp++) = *(sp++);
  195449. *(dp++) = *(sp++);
  195450. *(dp++) = *(sp++);
  195451. *(dp++) = *(sp++);
  195452. *(dp++) = *(sp++);
  195453. *(dp++) = *(sp++);
  195454. *(dp++) = save[0];
  195455. *(dp++) = save[1];
  195456. }
  195457. }
  195458. }
  195459. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195460. {
  195461. /* This converts from AG to GA */
  195462. if (row_info->bit_depth == 8)
  195463. {
  195464. png_bytep sp, dp;
  195465. png_uint_32 i;
  195466. png_uint_32 row_width = row_info->width;
  195467. for (i = 0, sp = dp = row; i < row_width; i++)
  195468. {
  195469. png_byte save = *(sp++);
  195470. *(dp++) = *(sp++);
  195471. *(dp++) = save;
  195472. }
  195473. }
  195474. /* This converts from AAGG to GGAA */
  195475. else
  195476. {
  195477. png_bytep sp, dp;
  195478. png_uint_32 i;
  195479. png_uint_32 row_width = row_info->width;
  195480. for (i = 0, sp = dp = row; i < row_width; i++)
  195481. {
  195482. png_byte save[2];
  195483. save[0] = *(sp++);
  195484. save[1] = *(sp++);
  195485. *(dp++) = *(sp++);
  195486. *(dp++) = *(sp++);
  195487. *(dp++) = save[0];
  195488. *(dp++) = save[1];
  195489. }
  195490. }
  195491. }
  195492. }
  195493. }
  195494. #endif
  195495. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195496. void /* PRIVATE */
  195497. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  195498. {
  195499. png_debug(1, "in png_do_write_invert_alpha\n");
  195500. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195501. if (row != NULL && row_info != NULL)
  195502. #endif
  195503. {
  195504. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195505. {
  195506. /* This inverts the alpha channel in RGBA */
  195507. if (row_info->bit_depth == 8)
  195508. {
  195509. png_bytep sp, dp;
  195510. png_uint_32 i;
  195511. png_uint_32 row_width = row_info->width;
  195512. for (i = 0, sp = dp = row; i < row_width; i++)
  195513. {
  195514. /* does nothing
  195515. *(dp++) = *(sp++);
  195516. *(dp++) = *(sp++);
  195517. *(dp++) = *(sp++);
  195518. */
  195519. sp+=3; dp = sp;
  195520. *(dp++) = (png_byte)(255 - *(sp++));
  195521. }
  195522. }
  195523. /* This inverts the alpha channel in RRGGBBAA */
  195524. else
  195525. {
  195526. png_bytep sp, dp;
  195527. png_uint_32 i;
  195528. png_uint_32 row_width = row_info->width;
  195529. for (i = 0, sp = dp = row; i < row_width; i++)
  195530. {
  195531. /* does nothing
  195532. *(dp++) = *(sp++);
  195533. *(dp++) = *(sp++);
  195534. *(dp++) = *(sp++);
  195535. *(dp++) = *(sp++);
  195536. *(dp++) = *(sp++);
  195537. *(dp++) = *(sp++);
  195538. */
  195539. sp+=6; dp = sp;
  195540. *(dp++) = (png_byte)(255 - *(sp++));
  195541. *(dp++) = (png_byte)(255 - *(sp++));
  195542. }
  195543. }
  195544. }
  195545. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195546. {
  195547. /* This inverts the alpha channel in GA */
  195548. if (row_info->bit_depth == 8)
  195549. {
  195550. png_bytep sp, dp;
  195551. png_uint_32 i;
  195552. png_uint_32 row_width = row_info->width;
  195553. for (i = 0, sp = dp = row; i < row_width; i++)
  195554. {
  195555. *(dp++) = *(sp++);
  195556. *(dp++) = (png_byte)(255 - *(sp++));
  195557. }
  195558. }
  195559. /* This inverts the alpha channel in GGAA */
  195560. else
  195561. {
  195562. png_bytep sp, dp;
  195563. png_uint_32 i;
  195564. png_uint_32 row_width = row_info->width;
  195565. for (i = 0, sp = dp = row; i < row_width; i++)
  195566. {
  195567. /* does nothing
  195568. *(dp++) = *(sp++);
  195569. *(dp++) = *(sp++);
  195570. */
  195571. sp+=2; dp = sp;
  195572. *(dp++) = (png_byte)(255 - *(sp++));
  195573. *(dp++) = (png_byte)(255 - *(sp++));
  195574. }
  195575. }
  195576. }
  195577. }
  195578. }
  195579. #endif
  195580. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195581. /* undoes intrapixel differencing */
  195582. void /* PRIVATE */
  195583. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  195584. {
  195585. png_debug(1, "in png_do_write_intrapixel\n");
  195586. if (
  195587. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195588. row != NULL && row_info != NULL &&
  195589. #endif
  195590. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  195591. {
  195592. int bytes_per_pixel;
  195593. png_uint_32 row_width = row_info->width;
  195594. if (row_info->bit_depth == 8)
  195595. {
  195596. png_bytep rp;
  195597. png_uint_32 i;
  195598. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  195599. bytes_per_pixel = 3;
  195600. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195601. bytes_per_pixel = 4;
  195602. else
  195603. return;
  195604. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  195605. {
  195606. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  195607. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  195608. }
  195609. }
  195610. else if (row_info->bit_depth == 16)
  195611. {
  195612. png_bytep rp;
  195613. png_uint_32 i;
  195614. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  195615. bytes_per_pixel = 6;
  195616. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195617. bytes_per_pixel = 8;
  195618. else
  195619. return;
  195620. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  195621. {
  195622. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  195623. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  195624. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  195625. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  195626. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  195627. *(rp ) = (png_byte)((red >> 8) & 0xff);
  195628. *(rp+1) = (png_byte)(red & 0xff);
  195629. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  195630. *(rp+5) = (png_byte)(blue & 0xff);
  195631. }
  195632. }
  195633. }
  195634. }
  195635. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  195636. #endif /* PNG_WRITE_SUPPORTED */
  195637. /********* End of inlined file: pngwtran.c *********/
  195638. /********* Start of inlined file: pngwutil.c *********/
  195639. /* pngwutil.c - utilities to write a PNG file
  195640. *
  195641. * Last changed in libpng 1.2.20 Septhember 3, 2007
  195642. * For conditions of distribution and use, see copyright notice in png.h
  195643. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195644. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195645. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195646. */
  195647. #define PNG_INTERNAL
  195648. #ifdef PNG_WRITE_SUPPORTED
  195649. /* Place a 32-bit number into a buffer in PNG byte order. We work
  195650. * with unsigned numbers for convenience, although one supported
  195651. * ancillary chunk uses signed (two's complement) numbers.
  195652. */
  195653. void PNGAPI
  195654. png_save_uint_32(png_bytep buf, png_uint_32 i)
  195655. {
  195656. buf[0] = (png_byte)((i >> 24) & 0xff);
  195657. buf[1] = (png_byte)((i >> 16) & 0xff);
  195658. buf[2] = (png_byte)((i >> 8) & 0xff);
  195659. buf[3] = (png_byte)(i & 0xff);
  195660. }
  195661. /* The png_save_int_32 function assumes integers are stored in two's
  195662. * complement format. If this isn't the case, then this routine needs to
  195663. * be modified to write data in two's complement format.
  195664. */
  195665. void PNGAPI
  195666. png_save_int_32(png_bytep buf, png_int_32 i)
  195667. {
  195668. buf[0] = (png_byte)((i >> 24) & 0xff);
  195669. buf[1] = (png_byte)((i >> 16) & 0xff);
  195670. buf[2] = (png_byte)((i >> 8) & 0xff);
  195671. buf[3] = (png_byte)(i & 0xff);
  195672. }
  195673. /* Place a 16-bit number into a buffer in PNG byte order.
  195674. * The parameter is declared unsigned int, not png_uint_16,
  195675. * just to avoid potential problems on pre-ANSI C compilers.
  195676. */
  195677. void PNGAPI
  195678. png_save_uint_16(png_bytep buf, unsigned int i)
  195679. {
  195680. buf[0] = (png_byte)((i >> 8) & 0xff);
  195681. buf[1] = (png_byte)(i & 0xff);
  195682. }
  195683. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  195684. * representing the chunk name. The array must be at least 4 bytes in
  195685. * length, and does not need to be null terminated. To be safe, pass the
  195686. * pre-defined chunk names here, and if you need a new one, define it
  195687. * where the others are defined. The length is the length of the data.
  195688. * All the data must be present. If that is not possible, use the
  195689. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  195690. * functions instead.
  195691. */
  195692. void PNGAPI
  195693. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  195694. png_bytep data, png_size_t length)
  195695. {
  195696. if(png_ptr == NULL) return;
  195697. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  195698. png_write_chunk_data(png_ptr, data, length);
  195699. png_write_chunk_end(png_ptr);
  195700. }
  195701. /* Write the start of a PNG chunk. The type is the chunk type.
  195702. * The total_length is the sum of the lengths of all the data you will be
  195703. * passing in png_write_chunk_data().
  195704. */
  195705. void PNGAPI
  195706. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  195707. png_uint_32 length)
  195708. {
  195709. png_byte buf[4];
  195710. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  195711. if(png_ptr == NULL) return;
  195712. /* write the length */
  195713. png_save_uint_32(buf, length);
  195714. png_write_data(png_ptr, buf, (png_size_t)4);
  195715. /* write the chunk name */
  195716. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  195717. /* reset the crc and run it over the chunk name */
  195718. png_reset_crc(png_ptr);
  195719. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  195720. }
  195721. /* Write the data of a PNG chunk started with png_write_chunk_start().
  195722. * Note that multiple calls to this function are allowed, and that the
  195723. * sum of the lengths from these calls *must* add up to the total_length
  195724. * given to png_write_chunk_start().
  195725. */
  195726. void PNGAPI
  195727. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195728. {
  195729. /* write the data, and run the CRC over it */
  195730. if(png_ptr == NULL) return;
  195731. if (data != NULL && length > 0)
  195732. {
  195733. png_calculate_crc(png_ptr, data, length);
  195734. png_write_data(png_ptr, data, length);
  195735. }
  195736. }
  195737. /* Finish a chunk started with png_write_chunk_start(). */
  195738. void PNGAPI
  195739. png_write_chunk_end(png_structp png_ptr)
  195740. {
  195741. png_byte buf[4];
  195742. if(png_ptr == NULL) return;
  195743. /* write the crc */
  195744. png_save_uint_32(buf, png_ptr->crc);
  195745. png_write_data(png_ptr, buf, (png_size_t)4);
  195746. }
  195747. /* Simple function to write the signature. If we have already written
  195748. * the magic bytes of the signature, or more likely, the PNG stream is
  195749. * being embedded into another stream and doesn't need its own signature,
  195750. * we should call png_set_sig_bytes() to tell libpng how many of the
  195751. * bytes have already been written.
  195752. */
  195753. void /* PRIVATE */
  195754. png_write_sig(png_structp png_ptr)
  195755. {
  195756. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  195757. /* write the rest of the 8 byte signature */
  195758. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  195759. (png_size_t)8 - png_ptr->sig_bytes);
  195760. if(png_ptr->sig_bytes < 3)
  195761. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  195762. }
  195763. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  195764. /*
  195765. * This pair of functions encapsulates the operation of (a) compressing a
  195766. * text string, and (b) issuing it later as a series of chunk data writes.
  195767. * The compression_state structure is shared context for these functions
  195768. * set up by the caller in order to make the whole mess thread-safe.
  195769. */
  195770. typedef struct
  195771. {
  195772. char *input; /* the uncompressed input data */
  195773. int input_len; /* its length */
  195774. int num_output_ptr; /* number of output pointers used */
  195775. int max_output_ptr; /* size of output_ptr */
  195776. png_charpp output_ptr; /* array of pointers to output */
  195777. } compression_state;
  195778. /* compress given text into storage in the png_ptr structure */
  195779. static int /* PRIVATE */
  195780. png_text_compress(png_structp png_ptr,
  195781. png_charp text, png_size_t text_len, int compression,
  195782. compression_state *comp)
  195783. {
  195784. int ret;
  195785. comp->num_output_ptr = 0;
  195786. comp->max_output_ptr = 0;
  195787. comp->output_ptr = NULL;
  195788. comp->input = NULL;
  195789. comp->input_len = 0;
  195790. /* we may just want to pass the text right through */
  195791. if (compression == PNG_TEXT_COMPRESSION_NONE)
  195792. {
  195793. comp->input = text;
  195794. comp->input_len = text_len;
  195795. return((int)text_len);
  195796. }
  195797. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  195798. {
  195799. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195800. char msg[50];
  195801. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  195802. png_warning(png_ptr, msg);
  195803. #else
  195804. png_warning(png_ptr, "Unknown compression type");
  195805. #endif
  195806. }
  195807. /* We can't write the chunk until we find out how much data we have,
  195808. * which means we need to run the compressor first and save the
  195809. * output. This shouldn't be a problem, as the vast majority of
  195810. * comments should be reasonable, but we will set up an array of
  195811. * malloc'd pointers to be sure.
  195812. *
  195813. * If we knew the application was well behaved, we could simplify this
  195814. * greatly by assuming we can always malloc an output buffer large
  195815. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  195816. * and malloc this directly. The only time this would be a bad idea is
  195817. * if we can't malloc more than 64K and we have 64K of random input
  195818. * data, or if the input string is incredibly large (although this
  195819. * wouldn't cause a failure, just a slowdown due to swapping).
  195820. */
  195821. /* set up the compression buffers */
  195822. png_ptr->zstream.avail_in = (uInt)text_len;
  195823. png_ptr->zstream.next_in = (Bytef *)text;
  195824. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195825. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  195826. /* this is the same compression loop as in png_write_row() */
  195827. do
  195828. {
  195829. /* compress the data */
  195830. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  195831. if (ret != Z_OK)
  195832. {
  195833. /* error */
  195834. if (png_ptr->zstream.msg != NULL)
  195835. png_error(png_ptr, png_ptr->zstream.msg);
  195836. else
  195837. png_error(png_ptr, "zlib error");
  195838. }
  195839. /* check to see if we need more room */
  195840. if (!(png_ptr->zstream.avail_out))
  195841. {
  195842. /* make sure the output array has room */
  195843. if (comp->num_output_ptr >= comp->max_output_ptr)
  195844. {
  195845. int old_max;
  195846. old_max = comp->max_output_ptr;
  195847. comp->max_output_ptr = comp->num_output_ptr + 4;
  195848. if (comp->output_ptr != NULL)
  195849. {
  195850. png_charpp old_ptr;
  195851. old_ptr = comp->output_ptr;
  195852. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  195853. (png_uint_32)(comp->max_output_ptr *
  195854. png_sizeof (png_charpp)));
  195855. png_memcpy(comp->output_ptr, old_ptr, old_max
  195856. * png_sizeof (png_charp));
  195857. png_free(png_ptr, old_ptr);
  195858. }
  195859. else
  195860. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  195861. (png_uint_32)(comp->max_output_ptr *
  195862. png_sizeof (png_charp)));
  195863. }
  195864. /* save the data */
  195865. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  195866. (png_uint_32)png_ptr->zbuf_size);
  195867. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  195868. png_ptr->zbuf_size);
  195869. comp->num_output_ptr++;
  195870. /* and reset the buffer */
  195871. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195872. png_ptr->zstream.next_out = png_ptr->zbuf;
  195873. }
  195874. /* continue until we don't have any more to compress */
  195875. } while (png_ptr->zstream.avail_in);
  195876. /* finish the compression */
  195877. do
  195878. {
  195879. /* tell zlib we are finished */
  195880. ret = deflate(&png_ptr->zstream, Z_FINISH);
  195881. if (ret == Z_OK)
  195882. {
  195883. /* check to see if we need more room */
  195884. if (!(png_ptr->zstream.avail_out))
  195885. {
  195886. /* check to make sure our output array has room */
  195887. if (comp->num_output_ptr >= comp->max_output_ptr)
  195888. {
  195889. int old_max;
  195890. old_max = comp->max_output_ptr;
  195891. comp->max_output_ptr = comp->num_output_ptr + 4;
  195892. if (comp->output_ptr != NULL)
  195893. {
  195894. png_charpp old_ptr;
  195895. old_ptr = comp->output_ptr;
  195896. /* This could be optimized to realloc() */
  195897. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  195898. (png_uint_32)(comp->max_output_ptr *
  195899. png_sizeof (png_charpp)));
  195900. png_memcpy(comp->output_ptr, old_ptr,
  195901. old_max * png_sizeof (png_charp));
  195902. png_free(png_ptr, old_ptr);
  195903. }
  195904. else
  195905. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  195906. (png_uint_32)(comp->max_output_ptr *
  195907. png_sizeof (png_charp)));
  195908. }
  195909. /* save off the data */
  195910. comp->output_ptr[comp->num_output_ptr] =
  195911. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  195912. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  195913. png_ptr->zbuf_size);
  195914. comp->num_output_ptr++;
  195915. /* and reset the buffer pointers */
  195916. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195917. png_ptr->zstream.next_out = png_ptr->zbuf;
  195918. }
  195919. }
  195920. else if (ret != Z_STREAM_END)
  195921. {
  195922. /* we got an error */
  195923. if (png_ptr->zstream.msg != NULL)
  195924. png_error(png_ptr, png_ptr->zstream.msg);
  195925. else
  195926. png_error(png_ptr, "zlib error");
  195927. }
  195928. } while (ret != Z_STREAM_END);
  195929. /* text length is number of buffers plus last buffer */
  195930. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  195931. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  195932. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  195933. return((int)text_len);
  195934. }
  195935. /* ship the compressed text out via chunk writes */
  195936. static void /* PRIVATE */
  195937. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  195938. {
  195939. int i;
  195940. /* handle the no-compression case */
  195941. if (comp->input)
  195942. {
  195943. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  195944. (png_size_t)comp->input_len);
  195945. return;
  195946. }
  195947. /* write saved output buffers, if any */
  195948. for (i = 0; i < comp->num_output_ptr; i++)
  195949. {
  195950. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  195951. png_ptr->zbuf_size);
  195952. png_free(png_ptr, comp->output_ptr[i]);
  195953. comp->output_ptr[i]=NULL;
  195954. }
  195955. if (comp->max_output_ptr != 0)
  195956. png_free(png_ptr, comp->output_ptr);
  195957. comp->output_ptr=NULL;
  195958. /* write anything left in zbuf */
  195959. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  195960. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  195961. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  195962. /* reset zlib for another zTXt/iTXt or image data */
  195963. deflateReset(&png_ptr->zstream);
  195964. png_ptr->zstream.data_type = Z_BINARY;
  195965. }
  195966. #endif
  195967. /* Write the IHDR chunk, and update the png_struct with the necessary
  195968. * information. Note that the rest of this code depends upon this
  195969. * information being correct.
  195970. */
  195971. void /* PRIVATE */
  195972. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  195973. int bit_depth, int color_type, int compression_type, int filter_type,
  195974. int interlace_type)
  195975. {
  195976. #ifdef PNG_USE_LOCAL_ARRAYS
  195977. PNG_IHDR;
  195978. #endif
  195979. png_byte buf[13]; /* buffer to store the IHDR info */
  195980. png_debug(1, "in png_write_IHDR\n");
  195981. /* Check that we have valid input data from the application info */
  195982. switch (color_type)
  195983. {
  195984. case PNG_COLOR_TYPE_GRAY:
  195985. switch (bit_depth)
  195986. {
  195987. case 1:
  195988. case 2:
  195989. case 4:
  195990. case 8:
  195991. case 16: png_ptr->channels = 1; break;
  195992. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  195993. }
  195994. break;
  195995. case PNG_COLOR_TYPE_RGB:
  195996. if (bit_depth != 8 && bit_depth != 16)
  195997. png_error(png_ptr, "Invalid bit depth for RGB image");
  195998. png_ptr->channels = 3;
  195999. break;
  196000. case PNG_COLOR_TYPE_PALETTE:
  196001. switch (bit_depth)
  196002. {
  196003. case 1:
  196004. case 2:
  196005. case 4:
  196006. case 8: png_ptr->channels = 1; break;
  196007. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  196008. }
  196009. break;
  196010. case PNG_COLOR_TYPE_GRAY_ALPHA:
  196011. if (bit_depth != 8 && bit_depth != 16)
  196012. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  196013. png_ptr->channels = 2;
  196014. break;
  196015. case PNG_COLOR_TYPE_RGB_ALPHA:
  196016. if (bit_depth != 8 && bit_depth != 16)
  196017. png_error(png_ptr, "Invalid bit depth for RGBA image");
  196018. png_ptr->channels = 4;
  196019. break;
  196020. default:
  196021. png_error(png_ptr, "Invalid image color type specified");
  196022. }
  196023. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196024. {
  196025. png_warning(png_ptr, "Invalid compression type specified");
  196026. compression_type = PNG_COMPRESSION_TYPE_BASE;
  196027. }
  196028. /* Write filter_method 64 (intrapixel differencing) only if
  196029. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196030. * 2. Libpng did not write a PNG signature (this filter_method is only
  196031. * used in PNG datastreams that are embedded in MNG datastreams) and
  196032. * 3. The application called png_permit_mng_features with a mask that
  196033. * included PNG_FLAG_MNG_FILTER_64 and
  196034. * 4. The filter_method is 64 and
  196035. * 5. The color_type is RGB or RGBA
  196036. */
  196037. if (
  196038. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196039. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196040. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196041. (color_type == PNG_COLOR_TYPE_RGB ||
  196042. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  196043. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  196044. #endif
  196045. filter_type != PNG_FILTER_TYPE_BASE)
  196046. {
  196047. png_warning(png_ptr, "Invalid filter type specified");
  196048. filter_type = PNG_FILTER_TYPE_BASE;
  196049. }
  196050. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196051. if (interlace_type != PNG_INTERLACE_NONE &&
  196052. interlace_type != PNG_INTERLACE_ADAM7)
  196053. {
  196054. png_warning(png_ptr, "Invalid interlace type specified");
  196055. interlace_type = PNG_INTERLACE_ADAM7;
  196056. }
  196057. #else
  196058. interlace_type=PNG_INTERLACE_NONE;
  196059. #endif
  196060. /* save off the relevent information */
  196061. png_ptr->bit_depth = (png_byte)bit_depth;
  196062. png_ptr->color_type = (png_byte)color_type;
  196063. png_ptr->interlaced = (png_byte)interlace_type;
  196064. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196065. png_ptr->filter_type = (png_byte)filter_type;
  196066. #endif
  196067. png_ptr->compression_type = (png_byte)compression_type;
  196068. png_ptr->width = width;
  196069. png_ptr->height = height;
  196070. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  196071. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  196072. /* set the usr info, so any transformations can modify it */
  196073. png_ptr->usr_width = png_ptr->width;
  196074. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  196075. png_ptr->usr_channels = png_ptr->channels;
  196076. /* pack the header information into the buffer */
  196077. png_save_uint_32(buf, width);
  196078. png_save_uint_32(buf + 4, height);
  196079. buf[8] = (png_byte)bit_depth;
  196080. buf[9] = (png_byte)color_type;
  196081. buf[10] = (png_byte)compression_type;
  196082. buf[11] = (png_byte)filter_type;
  196083. buf[12] = (png_byte)interlace_type;
  196084. /* write the chunk */
  196085. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  196086. /* initialize zlib with PNG info */
  196087. png_ptr->zstream.zalloc = png_zalloc;
  196088. png_ptr->zstream.zfree = png_zfree;
  196089. png_ptr->zstream.opaque = (voidpf)png_ptr;
  196090. if (!(png_ptr->do_filter))
  196091. {
  196092. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  196093. png_ptr->bit_depth < 8)
  196094. png_ptr->do_filter = PNG_FILTER_NONE;
  196095. else
  196096. png_ptr->do_filter = PNG_ALL_FILTERS;
  196097. }
  196098. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  196099. {
  196100. if (png_ptr->do_filter != PNG_FILTER_NONE)
  196101. png_ptr->zlib_strategy = Z_FILTERED;
  196102. else
  196103. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  196104. }
  196105. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  196106. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  196107. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  196108. png_ptr->zlib_mem_level = 8;
  196109. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  196110. png_ptr->zlib_window_bits = 15;
  196111. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  196112. png_ptr->zlib_method = 8;
  196113. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  196114. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  196115. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  196116. png_error(png_ptr, "zlib failed to initialize compressor");
  196117. png_ptr->zstream.next_out = png_ptr->zbuf;
  196118. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196119. /* libpng is not interested in zstream.data_type */
  196120. /* set it to a predefined value, to avoid its evaluation inside zlib */
  196121. png_ptr->zstream.data_type = Z_BINARY;
  196122. png_ptr->mode = PNG_HAVE_IHDR;
  196123. }
  196124. /* write the palette. We are careful not to trust png_color to be in the
  196125. * correct order for PNG, so people can redefine it to any convenient
  196126. * structure.
  196127. */
  196128. void /* PRIVATE */
  196129. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  196130. {
  196131. #ifdef PNG_USE_LOCAL_ARRAYS
  196132. PNG_PLTE;
  196133. #endif
  196134. png_uint_32 i;
  196135. png_colorp pal_ptr;
  196136. png_byte buf[3];
  196137. png_debug(1, "in png_write_PLTE\n");
  196138. if ((
  196139. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196140. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  196141. #endif
  196142. num_pal == 0) || num_pal > 256)
  196143. {
  196144. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196145. {
  196146. png_error(png_ptr, "Invalid number of colors in palette");
  196147. }
  196148. else
  196149. {
  196150. png_warning(png_ptr, "Invalid number of colors in palette");
  196151. return;
  196152. }
  196153. }
  196154. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  196155. {
  196156. png_warning(png_ptr,
  196157. "Ignoring request to write a PLTE chunk in grayscale PNG");
  196158. return;
  196159. }
  196160. png_ptr->num_palette = (png_uint_16)num_pal;
  196161. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  196162. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  196163. #ifndef PNG_NO_POINTER_INDEXING
  196164. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  196165. {
  196166. buf[0] = pal_ptr->red;
  196167. buf[1] = pal_ptr->green;
  196168. buf[2] = pal_ptr->blue;
  196169. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196170. }
  196171. #else
  196172. /* This is a little slower but some buggy compilers need to do this instead */
  196173. pal_ptr=palette;
  196174. for (i = 0; i < num_pal; i++)
  196175. {
  196176. buf[0] = pal_ptr[i].red;
  196177. buf[1] = pal_ptr[i].green;
  196178. buf[2] = pal_ptr[i].blue;
  196179. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196180. }
  196181. #endif
  196182. png_write_chunk_end(png_ptr);
  196183. png_ptr->mode |= PNG_HAVE_PLTE;
  196184. }
  196185. /* write an IDAT chunk */
  196186. void /* PRIVATE */
  196187. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  196188. {
  196189. #ifdef PNG_USE_LOCAL_ARRAYS
  196190. PNG_IDAT;
  196191. #endif
  196192. png_debug(1, "in png_write_IDAT\n");
  196193. /* Optimize the CMF field in the zlib stream. */
  196194. /* This hack of the zlib stream is compliant to the stream specification. */
  196195. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  196196. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  196197. {
  196198. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  196199. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  196200. {
  196201. /* Avoid memory underflows and multiplication overflows. */
  196202. /* The conditions below are practically always satisfied;
  196203. however, they still must be checked. */
  196204. if (length >= 2 &&
  196205. png_ptr->height < 16384 && png_ptr->width < 16384)
  196206. {
  196207. png_uint_32 uncompressed_idat_size = png_ptr->height *
  196208. ((png_ptr->width *
  196209. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  196210. unsigned int z_cinfo = z_cmf >> 4;
  196211. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  196212. while (uncompressed_idat_size <= half_z_window_size &&
  196213. half_z_window_size >= 256)
  196214. {
  196215. z_cinfo--;
  196216. half_z_window_size >>= 1;
  196217. }
  196218. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  196219. if (data[0] != (png_byte)z_cmf)
  196220. {
  196221. data[0] = (png_byte)z_cmf;
  196222. data[1] &= 0xe0;
  196223. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  196224. }
  196225. }
  196226. }
  196227. else
  196228. png_error(png_ptr,
  196229. "Invalid zlib compression method or flags in IDAT");
  196230. }
  196231. png_write_chunk(png_ptr, png_IDAT, data, length);
  196232. png_ptr->mode |= PNG_HAVE_IDAT;
  196233. }
  196234. /* write an IEND chunk */
  196235. void /* PRIVATE */
  196236. png_write_IEND(png_structp png_ptr)
  196237. {
  196238. #ifdef PNG_USE_LOCAL_ARRAYS
  196239. PNG_IEND;
  196240. #endif
  196241. png_debug(1, "in png_write_IEND\n");
  196242. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  196243. (png_size_t)0);
  196244. png_ptr->mode |= PNG_HAVE_IEND;
  196245. }
  196246. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  196247. /* write a gAMA chunk */
  196248. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196249. void /* PRIVATE */
  196250. png_write_gAMA(png_structp png_ptr, double file_gamma)
  196251. {
  196252. #ifdef PNG_USE_LOCAL_ARRAYS
  196253. PNG_gAMA;
  196254. #endif
  196255. png_uint_32 igamma;
  196256. png_byte buf[4];
  196257. png_debug(1, "in png_write_gAMA\n");
  196258. /* file_gamma is saved in 1/100,000ths */
  196259. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  196260. png_save_uint_32(buf, igamma);
  196261. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196262. }
  196263. #endif
  196264. #ifdef PNG_FIXED_POINT_SUPPORTED
  196265. void /* PRIVATE */
  196266. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  196267. {
  196268. #ifdef PNG_USE_LOCAL_ARRAYS
  196269. PNG_gAMA;
  196270. #endif
  196271. png_byte buf[4];
  196272. png_debug(1, "in png_write_gAMA\n");
  196273. /* file_gamma is saved in 1/100,000ths */
  196274. png_save_uint_32(buf, (png_uint_32)file_gamma);
  196275. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196276. }
  196277. #endif
  196278. #endif
  196279. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  196280. /* write a sRGB chunk */
  196281. void /* PRIVATE */
  196282. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  196283. {
  196284. #ifdef PNG_USE_LOCAL_ARRAYS
  196285. PNG_sRGB;
  196286. #endif
  196287. png_byte buf[1];
  196288. png_debug(1, "in png_write_sRGB\n");
  196289. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  196290. png_warning(png_ptr,
  196291. "Invalid sRGB rendering intent specified");
  196292. buf[0]=(png_byte)srgb_intent;
  196293. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  196294. }
  196295. #endif
  196296. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  196297. /* write an iCCP chunk */
  196298. void /* PRIVATE */
  196299. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  196300. png_charp profile, int profile_len)
  196301. {
  196302. #ifdef PNG_USE_LOCAL_ARRAYS
  196303. PNG_iCCP;
  196304. #endif
  196305. png_size_t name_len;
  196306. png_charp new_name;
  196307. compression_state comp;
  196308. int embedded_profile_len = 0;
  196309. png_debug(1, "in png_write_iCCP\n");
  196310. comp.num_output_ptr = 0;
  196311. comp.max_output_ptr = 0;
  196312. comp.output_ptr = NULL;
  196313. comp.input = NULL;
  196314. comp.input_len = 0;
  196315. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  196316. &new_name)) == 0)
  196317. {
  196318. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  196319. return;
  196320. }
  196321. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196322. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  196323. if (profile == NULL)
  196324. profile_len = 0;
  196325. if (profile_len > 3)
  196326. embedded_profile_len =
  196327. ((*( (png_bytep)profile ))<<24) |
  196328. ((*( (png_bytep)profile+1))<<16) |
  196329. ((*( (png_bytep)profile+2))<< 8) |
  196330. ((*( (png_bytep)profile+3)) );
  196331. if (profile_len < embedded_profile_len)
  196332. {
  196333. png_warning(png_ptr,
  196334. "Embedded profile length too large in iCCP chunk");
  196335. return;
  196336. }
  196337. if (profile_len > embedded_profile_len)
  196338. {
  196339. png_warning(png_ptr,
  196340. "Truncating profile to actual length in iCCP chunk");
  196341. profile_len = embedded_profile_len;
  196342. }
  196343. if (profile_len)
  196344. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  196345. PNG_COMPRESSION_TYPE_BASE, &comp);
  196346. /* make sure we include the NULL after the name and the compression type */
  196347. png_write_chunk_start(png_ptr, png_iCCP,
  196348. (png_uint_32)name_len+profile_len+2);
  196349. new_name[name_len+1]=0x00;
  196350. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  196351. if (profile_len)
  196352. png_write_compressed_data_out(png_ptr, &comp);
  196353. png_write_chunk_end(png_ptr);
  196354. png_free(png_ptr, new_name);
  196355. }
  196356. #endif
  196357. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  196358. /* write a sPLT chunk */
  196359. void /* PRIVATE */
  196360. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  196361. {
  196362. #ifdef PNG_USE_LOCAL_ARRAYS
  196363. PNG_sPLT;
  196364. #endif
  196365. png_size_t name_len;
  196366. png_charp new_name;
  196367. png_byte entrybuf[10];
  196368. int entry_size = (spalette->depth == 8 ? 6 : 10);
  196369. int palette_size = entry_size * spalette->nentries;
  196370. png_sPLT_entryp ep;
  196371. #ifdef PNG_NO_POINTER_INDEXING
  196372. int i;
  196373. #endif
  196374. png_debug(1, "in png_write_sPLT\n");
  196375. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  196376. spalette->name, &new_name))==0)
  196377. {
  196378. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  196379. return;
  196380. }
  196381. /* make sure we include the NULL after the name */
  196382. png_write_chunk_start(png_ptr, png_sPLT,
  196383. (png_uint_32)(name_len + 2 + palette_size));
  196384. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  196385. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  196386. /* loop through each palette entry, writing appropriately */
  196387. #ifndef PNG_NO_POINTER_INDEXING
  196388. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  196389. {
  196390. if (spalette->depth == 8)
  196391. {
  196392. entrybuf[0] = (png_byte)ep->red;
  196393. entrybuf[1] = (png_byte)ep->green;
  196394. entrybuf[2] = (png_byte)ep->blue;
  196395. entrybuf[3] = (png_byte)ep->alpha;
  196396. png_save_uint_16(entrybuf + 4, ep->frequency);
  196397. }
  196398. else
  196399. {
  196400. png_save_uint_16(entrybuf + 0, ep->red);
  196401. png_save_uint_16(entrybuf + 2, ep->green);
  196402. png_save_uint_16(entrybuf + 4, ep->blue);
  196403. png_save_uint_16(entrybuf + 6, ep->alpha);
  196404. png_save_uint_16(entrybuf + 8, ep->frequency);
  196405. }
  196406. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  196407. }
  196408. #else
  196409. ep=spalette->entries;
  196410. for (i=0; i>spalette->nentries; i++)
  196411. {
  196412. if (spalette->depth == 8)
  196413. {
  196414. entrybuf[0] = (png_byte)ep[i].red;
  196415. entrybuf[1] = (png_byte)ep[i].green;
  196416. entrybuf[2] = (png_byte)ep[i].blue;
  196417. entrybuf[3] = (png_byte)ep[i].alpha;
  196418. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  196419. }
  196420. else
  196421. {
  196422. png_save_uint_16(entrybuf + 0, ep[i].red);
  196423. png_save_uint_16(entrybuf + 2, ep[i].green);
  196424. png_save_uint_16(entrybuf + 4, ep[i].blue);
  196425. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  196426. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  196427. }
  196428. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  196429. }
  196430. #endif
  196431. png_write_chunk_end(png_ptr);
  196432. png_free(png_ptr, new_name);
  196433. }
  196434. #endif
  196435. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  196436. /* write the sBIT chunk */
  196437. void /* PRIVATE */
  196438. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  196439. {
  196440. #ifdef PNG_USE_LOCAL_ARRAYS
  196441. PNG_sBIT;
  196442. #endif
  196443. png_byte buf[4];
  196444. png_size_t size;
  196445. png_debug(1, "in png_write_sBIT\n");
  196446. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  196447. if (color_type & PNG_COLOR_MASK_COLOR)
  196448. {
  196449. png_byte maxbits;
  196450. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  196451. png_ptr->usr_bit_depth);
  196452. if (sbit->red == 0 || sbit->red > maxbits ||
  196453. sbit->green == 0 || sbit->green > maxbits ||
  196454. sbit->blue == 0 || sbit->blue > maxbits)
  196455. {
  196456. png_warning(png_ptr, "Invalid sBIT depth specified");
  196457. return;
  196458. }
  196459. buf[0] = sbit->red;
  196460. buf[1] = sbit->green;
  196461. buf[2] = sbit->blue;
  196462. size = 3;
  196463. }
  196464. else
  196465. {
  196466. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  196467. {
  196468. png_warning(png_ptr, "Invalid sBIT depth specified");
  196469. return;
  196470. }
  196471. buf[0] = sbit->gray;
  196472. size = 1;
  196473. }
  196474. if (color_type & PNG_COLOR_MASK_ALPHA)
  196475. {
  196476. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  196477. {
  196478. png_warning(png_ptr, "Invalid sBIT depth specified");
  196479. return;
  196480. }
  196481. buf[size++] = sbit->alpha;
  196482. }
  196483. png_write_chunk(png_ptr, png_sBIT, buf, size);
  196484. }
  196485. #endif
  196486. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  196487. /* write the cHRM chunk */
  196488. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196489. void /* PRIVATE */
  196490. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  196491. double red_x, double red_y, double green_x, double green_y,
  196492. double blue_x, double blue_y)
  196493. {
  196494. #ifdef PNG_USE_LOCAL_ARRAYS
  196495. PNG_cHRM;
  196496. #endif
  196497. png_byte buf[32];
  196498. png_uint_32 itemp;
  196499. png_debug(1, "in png_write_cHRM\n");
  196500. /* each value is saved in 1/100,000ths */
  196501. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  196502. white_x + white_y > 1.0)
  196503. {
  196504. png_warning(png_ptr, "Invalid cHRM white point specified");
  196505. #if !defined(PNG_NO_CONSOLE_IO)
  196506. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  196507. #endif
  196508. return;
  196509. }
  196510. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  196511. png_save_uint_32(buf, itemp);
  196512. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  196513. png_save_uint_32(buf + 4, itemp);
  196514. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  196515. {
  196516. png_warning(png_ptr, "Invalid cHRM red point specified");
  196517. return;
  196518. }
  196519. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  196520. png_save_uint_32(buf + 8, itemp);
  196521. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  196522. png_save_uint_32(buf + 12, itemp);
  196523. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  196524. {
  196525. png_warning(png_ptr, "Invalid cHRM green point specified");
  196526. return;
  196527. }
  196528. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  196529. png_save_uint_32(buf + 16, itemp);
  196530. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  196531. png_save_uint_32(buf + 20, itemp);
  196532. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  196533. {
  196534. png_warning(png_ptr, "Invalid cHRM blue point specified");
  196535. return;
  196536. }
  196537. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  196538. png_save_uint_32(buf + 24, itemp);
  196539. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  196540. png_save_uint_32(buf + 28, itemp);
  196541. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  196542. }
  196543. #endif
  196544. #ifdef PNG_FIXED_POINT_SUPPORTED
  196545. void /* PRIVATE */
  196546. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  196547. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  196548. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  196549. png_fixed_point blue_y)
  196550. {
  196551. #ifdef PNG_USE_LOCAL_ARRAYS
  196552. PNG_cHRM;
  196553. #endif
  196554. png_byte buf[32];
  196555. png_debug(1, "in png_write_cHRM\n");
  196556. /* each value is saved in 1/100,000ths */
  196557. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  196558. {
  196559. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  196560. #if !defined(PNG_NO_CONSOLE_IO)
  196561. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  196562. #endif
  196563. return;
  196564. }
  196565. png_save_uint_32(buf, (png_uint_32)white_x);
  196566. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  196567. if (red_x + red_y > 100000L)
  196568. {
  196569. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  196570. return;
  196571. }
  196572. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  196573. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  196574. if (green_x + green_y > 100000L)
  196575. {
  196576. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  196577. return;
  196578. }
  196579. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  196580. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  196581. if (blue_x + blue_y > 100000L)
  196582. {
  196583. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  196584. return;
  196585. }
  196586. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  196587. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  196588. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  196589. }
  196590. #endif
  196591. #endif
  196592. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  196593. /* write the tRNS chunk */
  196594. void /* PRIVATE */
  196595. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  196596. int num_trans, int color_type)
  196597. {
  196598. #ifdef PNG_USE_LOCAL_ARRAYS
  196599. PNG_tRNS;
  196600. #endif
  196601. png_byte buf[6];
  196602. png_debug(1, "in png_write_tRNS\n");
  196603. if (color_type == PNG_COLOR_TYPE_PALETTE)
  196604. {
  196605. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  196606. {
  196607. png_warning(png_ptr,"Invalid number of transparent colors specified");
  196608. return;
  196609. }
  196610. /* write the chunk out as it is */
  196611. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  196612. }
  196613. else if (color_type == PNG_COLOR_TYPE_GRAY)
  196614. {
  196615. /* one 16 bit value */
  196616. if(tran->gray >= (1 << png_ptr->bit_depth))
  196617. {
  196618. png_warning(png_ptr,
  196619. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  196620. return;
  196621. }
  196622. png_save_uint_16(buf, tran->gray);
  196623. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  196624. }
  196625. else if (color_type == PNG_COLOR_TYPE_RGB)
  196626. {
  196627. /* three 16 bit values */
  196628. png_save_uint_16(buf, tran->red);
  196629. png_save_uint_16(buf + 2, tran->green);
  196630. png_save_uint_16(buf + 4, tran->blue);
  196631. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  196632. {
  196633. png_warning(png_ptr,
  196634. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  196635. return;
  196636. }
  196637. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  196638. }
  196639. else
  196640. {
  196641. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  196642. }
  196643. }
  196644. #endif
  196645. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  196646. /* write the background chunk */
  196647. void /* PRIVATE */
  196648. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  196649. {
  196650. #ifdef PNG_USE_LOCAL_ARRAYS
  196651. PNG_bKGD;
  196652. #endif
  196653. png_byte buf[6];
  196654. png_debug(1, "in png_write_bKGD\n");
  196655. if (color_type == PNG_COLOR_TYPE_PALETTE)
  196656. {
  196657. if (
  196658. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196659. (png_ptr->num_palette ||
  196660. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  196661. #endif
  196662. back->index > png_ptr->num_palette)
  196663. {
  196664. png_warning(png_ptr, "Invalid background palette index");
  196665. return;
  196666. }
  196667. buf[0] = back->index;
  196668. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  196669. }
  196670. else if (color_type & PNG_COLOR_MASK_COLOR)
  196671. {
  196672. png_save_uint_16(buf, back->red);
  196673. png_save_uint_16(buf + 2, back->green);
  196674. png_save_uint_16(buf + 4, back->blue);
  196675. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  196676. {
  196677. png_warning(png_ptr,
  196678. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  196679. return;
  196680. }
  196681. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  196682. }
  196683. else
  196684. {
  196685. if(back->gray >= (1 << png_ptr->bit_depth))
  196686. {
  196687. png_warning(png_ptr,
  196688. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  196689. return;
  196690. }
  196691. png_save_uint_16(buf, back->gray);
  196692. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  196693. }
  196694. }
  196695. #endif
  196696. #if defined(PNG_WRITE_hIST_SUPPORTED)
  196697. /* write the histogram */
  196698. void /* PRIVATE */
  196699. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  196700. {
  196701. #ifdef PNG_USE_LOCAL_ARRAYS
  196702. PNG_hIST;
  196703. #endif
  196704. int i;
  196705. png_byte buf[3];
  196706. png_debug(1, "in png_write_hIST\n");
  196707. if (num_hist > (int)png_ptr->num_palette)
  196708. {
  196709. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  196710. png_ptr->num_palette);
  196711. png_warning(png_ptr, "Invalid number of histogram entries specified");
  196712. return;
  196713. }
  196714. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  196715. for (i = 0; i < num_hist; i++)
  196716. {
  196717. png_save_uint_16(buf, hist[i]);
  196718. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  196719. }
  196720. png_write_chunk_end(png_ptr);
  196721. }
  196722. #endif
  196723. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  196724. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  196725. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  196726. * and if invalid, correct the keyword rather than discarding the entire
  196727. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  196728. * length, forbids leading or trailing whitespace, multiple internal spaces,
  196729. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  196730. *
  196731. * The new_key is allocated to hold the corrected keyword and must be freed
  196732. * by the calling routine. This avoids problems with trying to write to
  196733. * static keywords without having to have duplicate copies of the strings.
  196734. */
  196735. png_size_t /* PRIVATE */
  196736. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  196737. {
  196738. png_size_t key_len;
  196739. png_charp kp, dp;
  196740. int kflag;
  196741. int kwarn=0;
  196742. png_debug(1, "in png_check_keyword\n");
  196743. *new_key = NULL;
  196744. if (key == NULL || (key_len = png_strlen(key)) == 0)
  196745. {
  196746. png_warning(png_ptr, "zero length keyword");
  196747. return ((png_size_t)0);
  196748. }
  196749. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  196750. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  196751. if (*new_key == NULL)
  196752. {
  196753. png_warning(png_ptr, "Out of memory while procesing keyword");
  196754. return ((png_size_t)0);
  196755. }
  196756. /* Replace non-printing characters with a blank and print a warning */
  196757. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  196758. {
  196759. if ((png_byte)*kp < 0x20 ||
  196760. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  196761. {
  196762. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196763. char msg[40];
  196764. png_snprintf(msg, 40,
  196765. "invalid keyword character 0x%02X", (png_byte)*kp);
  196766. png_warning(png_ptr, msg);
  196767. #else
  196768. png_warning(png_ptr, "invalid character in keyword");
  196769. #endif
  196770. *dp = ' ';
  196771. }
  196772. else
  196773. {
  196774. *dp = *kp;
  196775. }
  196776. }
  196777. *dp = '\0';
  196778. /* Remove any trailing white space. */
  196779. kp = *new_key + key_len - 1;
  196780. if (*kp == ' ')
  196781. {
  196782. png_warning(png_ptr, "trailing spaces removed from keyword");
  196783. while (*kp == ' ')
  196784. {
  196785. *(kp--) = '\0';
  196786. key_len--;
  196787. }
  196788. }
  196789. /* Remove any leading white space. */
  196790. kp = *new_key;
  196791. if (*kp == ' ')
  196792. {
  196793. png_warning(png_ptr, "leading spaces removed from keyword");
  196794. while (*kp == ' ')
  196795. {
  196796. kp++;
  196797. key_len--;
  196798. }
  196799. }
  196800. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  196801. /* Remove multiple internal spaces. */
  196802. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  196803. {
  196804. if (*kp == ' ' && kflag == 0)
  196805. {
  196806. *(dp++) = *kp;
  196807. kflag = 1;
  196808. }
  196809. else if (*kp == ' ')
  196810. {
  196811. key_len--;
  196812. kwarn=1;
  196813. }
  196814. else
  196815. {
  196816. *(dp++) = *kp;
  196817. kflag = 0;
  196818. }
  196819. }
  196820. *dp = '\0';
  196821. if(kwarn)
  196822. png_warning(png_ptr, "extra interior spaces removed from keyword");
  196823. if (key_len == 0)
  196824. {
  196825. png_free(png_ptr, *new_key);
  196826. *new_key=NULL;
  196827. png_warning(png_ptr, "Zero length keyword");
  196828. }
  196829. if (key_len > 79)
  196830. {
  196831. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  196832. new_key[79] = '\0';
  196833. key_len = 79;
  196834. }
  196835. return (key_len);
  196836. }
  196837. #endif
  196838. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  196839. /* write a tEXt chunk */
  196840. void /* PRIVATE */
  196841. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  196842. png_size_t text_len)
  196843. {
  196844. #ifdef PNG_USE_LOCAL_ARRAYS
  196845. PNG_tEXt;
  196846. #endif
  196847. png_size_t key_len;
  196848. png_charp new_key;
  196849. png_debug(1, "in png_write_tEXt\n");
  196850. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  196851. {
  196852. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  196853. return;
  196854. }
  196855. if (text == NULL || *text == '\0')
  196856. text_len = 0;
  196857. else
  196858. text_len = png_strlen(text);
  196859. /* make sure we include the 0 after the key */
  196860. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  196861. /*
  196862. * We leave it to the application to meet PNG-1.0 requirements on the
  196863. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  196864. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  196865. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  196866. */
  196867. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  196868. if (text_len)
  196869. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  196870. png_write_chunk_end(png_ptr);
  196871. png_free(png_ptr, new_key);
  196872. }
  196873. #endif
  196874. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  196875. /* write a compressed text chunk */
  196876. void /* PRIVATE */
  196877. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  196878. png_size_t text_len, int compression)
  196879. {
  196880. #ifdef PNG_USE_LOCAL_ARRAYS
  196881. PNG_zTXt;
  196882. #endif
  196883. png_size_t key_len;
  196884. char buf[1];
  196885. png_charp new_key;
  196886. compression_state comp;
  196887. png_debug(1, "in png_write_zTXt\n");
  196888. comp.num_output_ptr = 0;
  196889. comp.max_output_ptr = 0;
  196890. comp.output_ptr = NULL;
  196891. comp.input = NULL;
  196892. comp.input_len = 0;
  196893. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  196894. {
  196895. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  196896. return;
  196897. }
  196898. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  196899. {
  196900. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  196901. png_free(png_ptr, new_key);
  196902. return;
  196903. }
  196904. text_len = png_strlen(text);
  196905. /* compute the compressed data; do it now for the length */
  196906. text_len = png_text_compress(png_ptr, text, text_len, compression,
  196907. &comp);
  196908. /* write start of chunk */
  196909. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  196910. (key_len+text_len+2));
  196911. /* write key */
  196912. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  196913. png_free(png_ptr, new_key);
  196914. buf[0] = (png_byte)compression;
  196915. /* write compression */
  196916. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  196917. /* write the compressed data */
  196918. png_write_compressed_data_out(png_ptr, &comp);
  196919. /* close the chunk */
  196920. png_write_chunk_end(png_ptr);
  196921. }
  196922. #endif
  196923. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  196924. /* write an iTXt chunk */
  196925. void /* PRIVATE */
  196926. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  196927. png_charp lang, png_charp lang_key, png_charp text)
  196928. {
  196929. #ifdef PNG_USE_LOCAL_ARRAYS
  196930. PNG_iTXt;
  196931. #endif
  196932. png_size_t lang_len, key_len, lang_key_len, text_len;
  196933. png_charp new_lang, new_key;
  196934. png_byte cbuf[2];
  196935. compression_state comp;
  196936. png_debug(1, "in png_write_iTXt\n");
  196937. comp.num_output_ptr = 0;
  196938. comp.max_output_ptr = 0;
  196939. comp.output_ptr = NULL;
  196940. comp.input = NULL;
  196941. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  196942. {
  196943. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  196944. return;
  196945. }
  196946. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  196947. {
  196948. png_warning(png_ptr, "Empty language field in iTXt chunk");
  196949. new_lang = NULL;
  196950. lang_len = 0;
  196951. }
  196952. if (lang_key == NULL)
  196953. lang_key_len = 0;
  196954. else
  196955. lang_key_len = png_strlen(lang_key);
  196956. if (text == NULL)
  196957. text_len = 0;
  196958. else
  196959. text_len = png_strlen(text);
  196960. /* compute the compressed data; do it now for the length */
  196961. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  196962. &comp);
  196963. /* make sure we include the compression flag, the compression byte,
  196964. * and the NULs after the key, lang, and lang_key parts */
  196965. png_write_chunk_start(png_ptr, png_iTXt,
  196966. (png_uint_32)(
  196967. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  196968. + key_len
  196969. + lang_len
  196970. + lang_key_len
  196971. + text_len));
  196972. /*
  196973. * We leave it to the application to meet PNG-1.0 requirements on the
  196974. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  196975. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  196976. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  196977. */
  196978. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  196979. /* set the compression flag */
  196980. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  196981. compression == PNG_TEXT_COMPRESSION_NONE)
  196982. cbuf[0] = 0;
  196983. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  196984. cbuf[0] = 1;
  196985. /* set the compression method */
  196986. cbuf[1] = 0;
  196987. png_write_chunk_data(png_ptr, cbuf, 2);
  196988. cbuf[0] = 0;
  196989. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  196990. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  196991. png_write_compressed_data_out(png_ptr, &comp);
  196992. png_write_chunk_end(png_ptr);
  196993. png_free(png_ptr, new_key);
  196994. if (new_lang)
  196995. png_free(png_ptr, new_lang);
  196996. }
  196997. #endif
  196998. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  196999. /* write the oFFs chunk */
  197000. void /* PRIVATE */
  197001. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  197002. int unit_type)
  197003. {
  197004. #ifdef PNG_USE_LOCAL_ARRAYS
  197005. PNG_oFFs;
  197006. #endif
  197007. png_byte buf[9];
  197008. png_debug(1, "in png_write_oFFs\n");
  197009. if (unit_type >= PNG_OFFSET_LAST)
  197010. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  197011. png_save_int_32(buf, x_offset);
  197012. png_save_int_32(buf + 4, y_offset);
  197013. buf[8] = (png_byte)unit_type;
  197014. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  197015. }
  197016. #endif
  197017. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  197018. /* write the pCAL chunk (described in the PNG extensions document) */
  197019. void /* PRIVATE */
  197020. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  197021. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  197022. {
  197023. #ifdef PNG_USE_LOCAL_ARRAYS
  197024. PNG_pCAL;
  197025. #endif
  197026. png_size_t purpose_len, units_len, total_len;
  197027. png_uint_32p params_len;
  197028. png_byte buf[10];
  197029. png_charp new_purpose;
  197030. int i;
  197031. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  197032. if (type >= PNG_EQUATION_LAST)
  197033. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  197034. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  197035. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  197036. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  197037. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  197038. total_len = purpose_len + units_len + 10;
  197039. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  197040. *png_sizeof(png_uint_32)));
  197041. /* Find the length of each parameter, making sure we don't count the
  197042. null terminator for the last parameter. */
  197043. for (i = 0; i < nparams; i++)
  197044. {
  197045. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  197046. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  197047. total_len += (png_size_t)params_len[i];
  197048. }
  197049. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  197050. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  197051. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  197052. png_save_int_32(buf, X0);
  197053. png_save_int_32(buf + 4, X1);
  197054. buf[8] = (png_byte)type;
  197055. buf[9] = (png_byte)nparams;
  197056. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  197057. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  197058. png_free(png_ptr, new_purpose);
  197059. for (i = 0; i < nparams; i++)
  197060. {
  197061. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  197062. (png_size_t)params_len[i]);
  197063. }
  197064. png_free(png_ptr, params_len);
  197065. png_write_chunk_end(png_ptr);
  197066. }
  197067. #endif
  197068. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  197069. /* write the sCAL chunk */
  197070. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  197071. void /* PRIVATE */
  197072. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  197073. {
  197074. #ifdef PNG_USE_LOCAL_ARRAYS
  197075. PNG_sCAL;
  197076. #endif
  197077. char buf[64];
  197078. png_size_t total_len;
  197079. png_debug(1, "in png_write_sCAL\n");
  197080. buf[0] = (char)unit;
  197081. #if defined(_WIN32_WCE)
  197082. /* sprintf() function is not supported on WindowsCE */
  197083. {
  197084. wchar_t wc_buf[32];
  197085. size_t wc_len;
  197086. swprintf(wc_buf, TEXT("%12.12e"), width);
  197087. wc_len = wcslen(wc_buf);
  197088. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  197089. total_len = wc_len + 2;
  197090. swprintf(wc_buf, TEXT("%12.12e"), height);
  197091. wc_len = wcslen(wc_buf);
  197092. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  197093. NULL, NULL);
  197094. total_len += wc_len;
  197095. }
  197096. #else
  197097. png_snprintf(buf + 1, 63, "%12.12e", width);
  197098. total_len = 1 + png_strlen(buf + 1) + 1;
  197099. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  197100. total_len += png_strlen(buf + total_len);
  197101. #endif
  197102. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197103. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  197104. }
  197105. #else
  197106. #ifdef PNG_FIXED_POINT_SUPPORTED
  197107. void /* PRIVATE */
  197108. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  197109. png_charp height)
  197110. {
  197111. #ifdef PNG_USE_LOCAL_ARRAYS
  197112. PNG_sCAL;
  197113. #endif
  197114. png_byte buf[64];
  197115. png_size_t wlen, hlen, total_len;
  197116. png_debug(1, "in png_write_sCAL_s\n");
  197117. wlen = png_strlen(width);
  197118. hlen = png_strlen(height);
  197119. total_len = wlen + hlen + 2;
  197120. if (total_len > 64)
  197121. {
  197122. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  197123. return;
  197124. }
  197125. buf[0] = (png_byte)unit;
  197126. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  197127. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  197128. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197129. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  197130. }
  197131. #endif
  197132. #endif
  197133. #endif
  197134. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  197135. /* write the pHYs chunk */
  197136. void /* PRIVATE */
  197137. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  197138. png_uint_32 y_pixels_per_unit,
  197139. int unit_type)
  197140. {
  197141. #ifdef PNG_USE_LOCAL_ARRAYS
  197142. PNG_pHYs;
  197143. #endif
  197144. png_byte buf[9];
  197145. png_debug(1, "in png_write_pHYs\n");
  197146. if (unit_type >= PNG_RESOLUTION_LAST)
  197147. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  197148. png_save_uint_32(buf, x_pixels_per_unit);
  197149. png_save_uint_32(buf + 4, y_pixels_per_unit);
  197150. buf[8] = (png_byte)unit_type;
  197151. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  197152. }
  197153. #endif
  197154. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197155. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  197156. * or png_convert_from_time_t(), or fill in the structure yourself.
  197157. */
  197158. void /* PRIVATE */
  197159. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  197160. {
  197161. #ifdef PNG_USE_LOCAL_ARRAYS
  197162. PNG_tIME;
  197163. #endif
  197164. png_byte buf[7];
  197165. png_debug(1, "in png_write_tIME\n");
  197166. if (mod_time->month > 12 || mod_time->month < 1 ||
  197167. mod_time->day > 31 || mod_time->day < 1 ||
  197168. mod_time->hour > 23 || mod_time->second > 60)
  197169. {
  197170. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  197171. return;
  197172. }
  197173. png_save_uint_16(buf, mod_time->year);
  197174. buf[2] = mod_time->month;
  197175. buf[3] = mod_time->day;
  197176. buf[4] = mod_time->hour;
  197177. buf[5] = mod_time->minute;
  197178. buf[6] = mod_time->second;
  197179. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  197180. }
  197181. #endif
  197182. /* initializes the row writing capability of libpng */
  197183. void /* PRIVATE */
  197184. png_write_start_row(png_structp png_ptr)
  197185. {
  197186. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197187. #ifdef PNG_USE_LOCAL_ARRAYS
  197188. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197189. /* start of interlace block */
  197190. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197191. /* offset to next interlace block */
  197192. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197193. /* start of interlace block in the y direction */
  197194. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197195. /* offset to next interlace block in the y direction */
  197196. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197197. #endif
  197198. #endif
  197199. png_size_t buf_size;
  197200. png_debug(1, "in png_write_start_row\n");
  197201. buf_size = (png_size_t)(PNG_ROWBYTES(
  197202. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  197203. /* set up row buffer */
  197204. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197205. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  197206. #ifndef PNG_NO_WRITE_FILTERING
  197207. /* set up filtering buffer, if using this filter */
  197208. if (png_ptr->do_filter & PNG_FILTER_SUB)
  197209. {
  197210. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  197211. (png_ptr->rowbytes + 1));
  197212. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  197213. }
  197214. /* We only need to keep the previous row if we are using one of these. */
  197215. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  197216. {
  197217. /* set up previous row buffer */
  197218. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197219. png_memset(png_ptr->prev_row, 0, buf_size);
  197220. if (png_ptr->do_filter & PNG_FILTER_UP)
  197221. {
  197222. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  197223. (png_ptr->rowbytes + 1));
  197224. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  197225. }
  197226. if (png_ptr->do_filter & PNG_FILTER_AVG)
  197227. {
  197228. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  197229. (png_ptr->rowbytes + 1));
  197230. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  197231. }
  197232. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  197233. {
  197234. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  197235. (png_ptr->rowbytes + 1));
  197236. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  197237. }
  197238. #endif /* PNG_NO_WRITE_FILTERING */
  197239. }
  197240. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197241. /* if interlaced, we need to set up width and height of pass */
  197242. if (png_ptr->interlaced)
  197243. {
  197244. if (!(png_ptr->transformations & PNG_INTERLACE))
  197245. {
  197246. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  197247. png_pass_ystart[0]) / png_pass_yinc[0];
  197248. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  197249. png_pass_start[0]) / png_pass_inc[0];
  197250. }
  197251. else
  197252. {
  197253. png_ptr->num_rows = png_ptr->height;
  197254. png_ptr->usr_width = png_ptr->width;
  197255. }
  197256. }
  197257. else
  197258. #endif
  197259. {
  197260. png_ptr->num_rows = png_ptr->height;
  197261. png_ptr->usr_width = png_ptr->width;
  197262. }
  197263. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197264. png_ptr->zstream.next_out = png_ptr->zbuf;
  197265. }
  197266. /* Internal use only. Called when finished processing a row of data. */
  197267. void /* PRIVATE */
  197268. png_write_finish_row(png_structp png_ptr)
  197269. {
  197270. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197271. #ifdef PNG_USE_LOCAL_ARRAYS
  197272. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197273. /* start of interlace block */
  197274. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197275. /* offset to next interlace block */
  197276. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197277. /* start of interlace block in the y direction */
  197278. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197279. /* offset to next interlace block in the y direction */
  197280. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197281. #endif
  197282. #endif
  197283. int ret;
  197284. png_debug(1, "in png_write_finish_row\n");
  197285. /* next row */
  197286. png_ptr->row_number++;
  197287. /* see if we are done */
  197288. if (png_ptr->row_number < png_ptr->num_rows)
  197289. return;
  197290. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197291. /* if interlaced, go to next pass */
  197292. if (png_ptr->interlaced)
  197293. {
  197294. png_ptr->row_number = 0;
  197295. if (png_ptr->transformations & PNG_INTERLACE)
  197296. {
  197297. png_ptr->pass++;
  197298. }
  197299. else
  197300. {
  197301. /* loop until we find a non-zero width or height pass */
  197302. do
  197303. {
  197304. png_ptr->pass++;
  197305. if (png_ptr->pass >= 7)
  197306. break;
  197307. png_ptr->usr_width = (png_ptr->width +
  197308. png_pass_inc[png_ptr->pass] - 1 -
  197309. png_pass_start[png_ptr->pass]) /
  197310. png_pass_inc[png_ptr->pass];
  197311. png_ptr->num_rows = (png_ptr->height +
  197312. png_pass_yinc[png_ptr->pass] - 1 -
  197313. png_pass_ystart[png_ptr->pass]) /
  197314. png_pass_yinc[png_ptr->pass];
  197315. if (png_ptr->transformations & PNG_INTERLACE)
  197316. break;
  197317. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  197318. }
  197319. /* reset the row above the image for the next pass */
  197320. if (png_ptr->pass < 7)
  197321. {
  197322. if (png_ptr->prev_row != NULL)
  197323. png_memset(png_ptr->prev_row, 0,
  197324. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  197325. png_ptr->usr_bit_depth,png_ptr->width))+1);
  197326. return;
  197327. }
  197328. }
  197329. #endif
  197330. /* if we get here, we've just written the last row, so we need
  197331. to flush the compressor */
  197332. do
  197333. {
  197334. /* tell the compressor we are done */
  197335. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197336. /* check for an error */
  197337. if (ret == Z_OK)
  197338. {
  197339. /* check to see if we need more room */
  197340. if (!(png_ptr->zstream.avail_out))
  197341. {
  197342. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197343. png_ptr->zstream.next_out = png_ptr->zbuf;
  197344. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197345. }
  197346. }
  197347. else if (ret != Z_STREAM_END)
  197348. {
  197349. if (png_ptr->zstream.msg != NULL)
  197350. png_error(png_ptr, png_ptr->zstream.msg);
  197351. else
  197352. png_error(png_ptr, "zlib error");
  197353. }
  197354. } while (ret != Z_STREAM_END);
  197355. /* write any extra space */
  197356. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  197357. {
  197358. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  197359. png_ptr->zstream.avail_out);
  197360. }
  197361. deflateReset(&png_ptr->zstream);
  197362. png_ptr->zstream.data_type = Z_BINARY;
  197363. }
  197364. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197365. /* Pick out the correct pixels for the interlace pass.
  197366. * The basic idea here is to go through the row with a source
  197367. * pointer and a destination pointer (sp and dp), and copy the
  197368. * correct pixels for the pass. As the row gets compacted,
  197369. * sp will always be >= dp, so we should never overwrite anything.
  197370. * See the default: case for the easiest code to understand.
  197371. */
  197372. void /* PRIVATE */
  197373. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  197374. {
  197375. #ifdef PNG_USE_LOCAL_ARRAYS
  197376. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197377. /* start of interlace block */
  197378. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197379. /* offset to next interlace block */
  197380. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197381. #endif
  197382. png_debug(1, "in png_do_write_interlace\n");
  197383. /* we don't have to do anything on the last pass (6) */
  197384. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197385. if (row != NULL && row_info != NULL && pass < 6)
  197386. #else
  197387. if (pass < 6)
  197388. #endif
  197389. {
  197390. /* each pixel depth is handled separately */
  197391. switch (row_info->pixel_depth)
  197392. {
  197393. case 1:
  197394. {
  197395. png_bytep sp;
  197396. png_bytep dp;
  197397. int shift;
  197398. int d;
  197399. int value;
  197400. png_uint_32 i;
  197401. png_uint_32 row_width = row_info->width;
  197402. dp = row;
  197403. d = 0;
  197404. shift = 7;
  197405. for (i = png_pass_start[pass]; i < row_width;
  197406. i += png_pass_inc[pass])
  197407. {
  197408. sp = row + (png_size_t)(i >> 3);
  197409. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  197410. d |= (value << shift);
  197411. if (shift == 0)
  197412. {
  197413. shift = 7;
  197414. *dp++ = (png_byte)d;
  197415. d = 0;
  197416. }
  197417. else
  197418. shift--;
  197419. }
  197420. if (shift != 7)
  197421. *dp = (png_byte)d;
  197422. break;
  197423. }
  197424. case 2:
  197425. {
  197426. png_bytep sp;
  197427. png_bytep dp;
  197428. int shift;
  197429. int d;
  197430. int value;
  197431. png_uint_32 i;
  197432. png_uint_32 row_width = row_info->width;
  197433. dp = row;
  197434. shift = 6;
  197435. d = 0;
  197436. for (i = png_pass_start[pass]; i < row_width;
  197437. i += png_pass_inc[pass])
  197438. {
  197439. sp = row + (png_size_t)(i >> 2);
  197440. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  197441. d |= (value << shift);
  197442. if (shift == 0)
  197443. {
  197444. shift = 6;
  197445. *dp++ = (png_byte)d;
  197446. d = 0;
  197447. }
  197448. else
  197449. shift -= 2;
  197450. }
  197451. if (shift != 6)
  197452. *dp = (png_byte)d;
  197453. break;
  197454. }
  197455. case 4:
  197456. {
  197457. png_bytep sp;
  197458. png_bytep dp;
  197459. int shift;
  197460. int d;
  197461. int value;
  197462. png_uint_32 i;
  197463. png_uint_32 row_width = row_info->width;
  197464. dp = row;
  197465. shift = 4;
  197466. d = 0;
  197467. for (i = png_pass_start[pass]; i < row_width;
  197468. i += png_pass_inc[pass])
  197469. {
  197470. sp = row + (png_size_t)(i >> 1);
  197471. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  197472. d |= (value << shift);
  197473. if (shift == 0)
  197474. {
  197475. shift = 4;
  197476. *dp++ = (png_byte)d;
  197477. d = 0;
  197478. }
  197479. else
  197480. shift -= 4;
  197481. }
  197482. if (shift != 4)
  197483. *dp = (png_byte)d;
  197484. break;
  197485. }
  197486. default:
  197487. {
  197488. png_bytep sp;
  197489. png_bytep dp;
  197490. png_uint_32 i;
  197491. png_uint_32 row_width = row_info->width;
  197492. png_size_t pixel_bytes;
  197493. /* start at the beginning */
  197494. dp = row;
  197495. /* find out how many bytes each pixel takes up */
  197496. pixel_bytes = (row_info->pixel_depth >> 3);
  197497. /* loop through the row, only looking at the pixels that
  197498. matter */
  197499. for (i = png_pass_start[pass]; i < row_width;
  197500. i += png_pass_inc[pass])
  197501. {
  197502. /* find out where the original pixel is */
  197503. sp = row + (png_size_t)i * pixel_bytes;
  197504. /* move the pixel */
  197505. if (dp != sp)
  197506. png_memcpy(dp, sp, pixel_bytes);
  197507. /* next pixel */
  197508. dp += pixel_bytes;
  197509. }
  197510. break;
  197511. }
  197512. }
  197513. /* set new row width */
  197514. row_info->width = (row_info->width +
  197515. png_pass_inc[pass] - 1 -
  197516. png_pass_start[pass]) /
  197517. png_pass_inc[pass];
  197518. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  197519. row_info->width);
  197520. }
  197521. }
  197522. #endif
  197523. /* This filters the row, chooses which filter to use, if it has not already
  197524. * been specified by the application, and then writes the row out with the
  197525. * chosen filter.
  197526. */
  197527. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  197528. #define PNG_HISHIFT 10
  197529. #define PNG_LOMASK ((png_uint_32)0xffffL)
  197530. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  197531. void /* PRIVATE */
  197532. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  197533. {
  197534. png_bytep best_row;
  197535. #ifndef PNG_NO_WRITE_FILTER
  197536. png_bytep prev_row, row_buf;
  197537. png_uint_32 mins, bpp;
  197538. png_byte filter_to_do = png_ptr->do_filter;
  197539. png_uint_32 row_bytes = row_info->rowbytes;
  197540. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197541. int num_p_filters = (int)png_ptr->num_prev_filters;
  197542. #endif
  197543. png_debug(1, "in png_write_find_filter\n");
  197544. /* find out how many bytes offset each pixel is */
  197545. bpp = (row_info->pixel_depth + 7) >> 3;
  197546. prev_row = png_ptr->prev_row;
  197547. #endif
  197548. best_row = png_ptr->row_buf;
  197549. #ifndef PNG_NO_WRITE_FILTER
  197550. row_buf = best_row;
  197551. mins = PNG_MAXSUM;
  197552. /* The prediction method we use is to find which method provides the
  197553. * smallest value when summing the absolute values of the distances
  197554. * from zero, using anything >= 128 as negative numbers. This is known
  197555. * as the "minimum sum of absolute differences" heuristic. Other
  197556. * heuristics are the "weighted minimum sum of absolute differences"
  197557. * (experimental and can in theory improve compression), and the "zlib
  197558. * predictive" method (not implemented yet), which does test compressions
  197559. * of lines using different filter methods, and then chooses the
  197560. * (series of) filter(s) that give minimum compressed data size (VERY
  197561. * computationally expensive).
  197562. *
  197563. * GRR 980525: consider also
  197564. * (1) minimum sum of absolute differences from running average (i.e.,
  197565. * keep running sum of non-absolute differences & count of bytes)
  197566. * [track dispersion, too? restart average if dispersion too large?]
  197567. * (1b) minimum sum of absolute differences from sliding average, probably
  197568. * with window size <= deflate window (usually 32K)
  197569. * (2) minimum sum of squared differences from zero or running average
  197570. * (i.e., ~ root-mean-square approach)
  197571. */
  197572. /* We don't need to test the 'no filter' case if this is the only filter
  197573. * that has been chosen, as it doesn't actually do anything to the data.
  197574. */
  197575. if ((filter_to_do & PNG_FILTER_NONE) &&
  197576. filter_to_do != PNG_FILTER_NONE)
  197577. {
  197578. png_bytep rp;
  197579. png_uint_32 sum = 0;
  197580. png_uint_32 i;
  197581. int v;
  197582. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  197583. {
  197584. v = *rp;
  197585. sum += (v < 128) ? v : 256 - v;
  197586. }
  197587. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197588. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197589. {
  197590. png_uint_32 sumhi, sumlo;
  197591. int j;
  197592. sumlo = sum & PNG_LOMASK;
  197593. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  197594. /* Reduce the sum if we match any of the previous rows */
  197595. for (j = 0; j < num_p_filters; j++)
  197596. {
  197597. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  197598. {
  197599. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197600. PNG_WEIGHT_SHIFT;
  197601. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197602. PNG_WEIGHT_SHIFT;
  197603. }
  197604. }
  197605. /* Factor in the cost of this filter (this is here for completeness,
  197606. * but it makes no sense to have a "cost" for the NONE filter, as
  197607. * it has the minimum possible computational cost - none).
  197608. */
  197609. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  197610. PNG_COST_SHIFT;
  197611. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  197612. PNG_COST_SHIFT;
  197613. if (sumhi > PNG_HIMASK)
  197614. sum = PNG_MAXSUM;
  197615. else
  197616. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197617. }
  197618. #endif
  197619. mins = sum;
  197620. }
  197621. /* sub filter */
  197622. if (filter_to_do == PNG_FILTER_SUB)
  197623. /* it's the only filter so no testing is needed */
  197624. {
  197625. png_bytep rp, lp, dp;
  197626. png_uint_32 i;
  197627. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  197628. i++, rp++, dp++)
  197629. {
  197630. *dp = *rp;
  197631. }
  197632. for (lp = row_buf + 1; i < row_bytes;
  197633. i++, rp++, lp++, dp++)
  197634. {
  197635. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  197636. }
  197637. best_row = png_ptr->sub_row;
  197638. }
  197639. else if (filter_to_do & PNG_FILTER_SUB)
  197640. {
  197641. png_bytep rp, dp, lp;
  197642. png_uint_32 sum = 0, lmins = mins;
  197643. png_uint_32 i;
  197644. int v;
  197645. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197646. /* We temporarily increase the "minimum sum" by the factor we
  197647. * would reduce the sum of this filter, so that we can do the
  197648. * early exit comparison without scaling the sum each time.
  197649. */
  197650. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197651. {
  197652. int j;
  197653. png_uint_32 lmhi, lmlo;
  197654. lmlo = lmins & PNG_LOMASK;
  197655. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197656. for (j = 0; j < num_p_filters; j++)
  197657. {
  197658. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  197659. {
  197660. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197661. PNG_WEIGHT_SHIFT;
  197662. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197663. PNG_WEIGHT_SHIFT;
  197664. }
  197665. }
  197666. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  197667. PNG_COST_SHIFT;
  197668. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  197669. PNG_COST_SHIFT;
  197670. if (lmhi > PNG_HIMASK)
  197671. lmins = PNG_MAXSUM;
  197672. else
  197673. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197674. }
  197675. #endif
  197676. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  197677. i++, rp++, dp++)
  197678. {
  197679. v = *dp = *rp;
  197680. sum += (v < 128) ? v : 256 - v;
  197681. }
  197682. for (lp = row_buf + 1; i < row_bytes;
  197683. i++, rp++, lp++, dp++)
  197684. {
  197685. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  197686. sum += (v < 128) ? v : 256 - v;
  197687. if (sum > lmins) /* We are already worse, don't continue. */
  197688. break;
  197689. }
  197690. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197691. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197692. {
  197693. int j;
  197694. png_uint_32 sumhi, sumlo;
  197695. sumlo = sum & PNG_LOMASK;
  197696. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  197697. for (j = 0; j < num_p_filters; j++)
  197698. {
  197699. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  197700. {
  197701. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  197702. PNG_WEIGHT_SHIFT;
  197703. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  197704. PNG_WEIGHT_SHIFT;
  197705. }
  197706. }
  197707. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  197708. PNG_COST_SHIFT;
  197709. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  197710. PNG_COST_SHIFT;
  197711. if (sumhi > PNG_HIMASK)
  197712. sum = PNG_MAXSUM;
  197713. else
  197714. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197715. }
  197716. #endif
  197717. if (sum < mins)
  197718. {
  197719. mins = sum;
  197720. best_row = png_ptr->sub_row;
  197721. }
  197722. }
  197723. /* up filter */
  197724. if (filter_to_do == PNG_FILTER_UP)
  197725. {
  197726. png_bytep rp, dp, pp;
  197727. png_uint_32 i;
  197728. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  197729. pp = prev_row + 1; i < row_bytes;
  197730. i++, rp++, pp++, dp++)
  197731. {
  197732. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  197733. }
  197734. best_row = png_ptr->up_row;
  197735. }
  197736. else if (filter_to_do & PNG_FILTER_UP)
  197737. {
  197738. png_bytep rp, dp, pp;
  197739. png_uint_32 sum = 0, lmins = mins;
  197740. png_uint_32 i;
  197741. int v;
  197742. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197743. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197744. {
  197745. int j;
  197746. png_uint_32 lmhi, lmlo;
  197747. lmlo = lmins & PNG_LOMASK;
  197748. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197749. for (j = 0; j < num_p_filters; j++)
  197750. {
  197751. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  197752. {
  197753. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197754. PNG_WEIGHT_SHIFT;
  197755. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197756. PNG_WEIGHT_SHIFT;
  197757. }
  197758. }
  197759. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  197760. PNG_COST_SHIFT;
  197761. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  197762. PNG_COST_SHIFT;
  197763. if (lmhi > PNG_HIMASK)
  197764. lmins = PNG_MAXSUM;
  197765. else
  197766. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197767. }
  197768. #endif
  197769. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  197770. pp = prev_row + 1; i < row_bytes; i++)
  197771. {
  197772. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  197773. sum += (v < 128) ? v : 256 - v;
  197774. if (sum > lmins) /* We are already worse, don't continue. */
  197775. break;
  197776. }
  197777. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197778. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197779. {
  197780. int j;
  197781. png_uint_32 sumhi, sumlo;
  197782. sumlo = sum & PNG_LOMASK;
  197783. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  197784. for (j = 0; j < num_p_filters; j++)
  197785. {
  197786. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  197787. {
  197788. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197789. PNG_WEIGHT_SHIFT;
  197790. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197791. PNG_WEIGHT_SHIFT;
  197792. }
  197793. }
  197794. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  197795. PNG_COST_SHIFT;
  197796. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  197797. PNG_COST_SHIFT;
  197798. if (sumhi > PNG_HIMASK)
  197799. sum = PNG_MAXSUM;
  197800. else
  197801. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197802. }
  197803. #endif
  197804. if (sum < mins)
  197805. {
  197806. mins = sum;
  197807. best_row = png_ptr->up_row;
  197808. }
  197809. }
  197810. /* avg filter */
  197811. if (filter_to_do == PNG_FILTER_AVG)
  197812. {
  197813. png_bytep rp, dp, pp, lp;
  197814. png_uint_32 i;
  197815. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  197816. pp = prev_row + 1; i < bpp; i++)
  197817. {
  197818. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  197819. }
  197820. for (lp = row_buf + 1; i < row_bytes; i++)
  197821. {
  197822. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  197823. & 0xff);
  197824. }
  197825. best_row = png_ptr->avg_row;
  197826. }
  197827. else if (filter_to_do & PNG_FILTER_AVG)
  197828. {
  197829. png_bytep rp, dp, pp, lp;
  197830. png_uint_32 sum = 0, lmins = mins;
  197831. png_uint_32 i;
  197832. int v;
  197833. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197834. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197835. {
  197836. int j;
  197837. png_uint_32 lmhi, lmlo;
  197838. lmlo = lmins & PNG_LOMASK;
  197839. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197840. for (j = 0; j < num_p_filters; j++)
  197841. {
  197842. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  197843. {
  197844. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197845. PNG_WEIGHT_SHIFT;
  197846. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197847. PNG_WEIGHT_SHIFT;
  197848. }
  197849. }
  197850. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  197851. PNG_COST_SHIFT;
  197852. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  197853. PNG_COST_SHIFT;
  197854. if (lmhi > PNG_HIMASK)
  197855. lmins = PNG_MAXSUM;
  197856. else
  197857. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197858. }
  197859. #endif
  197860. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  197861. pp = prev_row + 1; i < bpp; i++)
  197862. {
  197863. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  197864. sum += (v < 128) ? v : 256 - v;
  197865. }
  197866. for (lp = row_buf + 1; i < row_bytes; i++)
  197867. {
  197868. v = *dp++ =
  197869. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  197870. sum += (v < 128) ? v : 256 - v;
  197871. if (sum > lmins) /* We are already worse, don't continue. */
  197872. break;
  197873. }
  197874. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197875. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197876. {
  197877. int j;
  197878. png_uint_32 sumhi, sumlo;
  197879. sumlo = sum & PNG_LOMASK;
  197880. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  197881. for (j = 0; j < num_p_filters; j++)
  197882. {
  197883. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  197884. {
  197885. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197886. PNG_WEIGHT_SHIFT;
  197887. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197888. PNG_WEIGHT_SHIFT;
  197889. }
  197890. }
  197891. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  197892. PNG_COST_SHIFT;
  197893. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  197894. PNG_COST_SHIFT;
  197895. if (sumhi > PNG_HIMASK)
  197896. sum = PNG_MAXSUM;
  197897. else
  197898. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197899. }
  197900. #endif
  197901. if (sum < mins)
  197902. {
  197903. mins = sum;
  197904. best_row = png_ptr->avg_row;
  197905. }
  197906. }
  197907. /* Paeth filter */
  197908. if (filter_to_do == PNG_FILTER_PAETH)
  197909. {
  197910. png_bytep rp, dp, pp, cp, lp;
  197911. png_uint_32 i;
  197912. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  197913. pp = prev_row + 1; i < bpp; i++)
  197914. {
  197915. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  197916. }
  197917. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  197918. {
  197919. int a, b, c, pa, pb, pc, p;
  197920. b = *pp++;
  197921. c = *cp++;
  197922. a = *lp++;
  197923. p = b - c;
  197924. pc = a - c;
  197925. #ifdef PNG_USE_ABS
  197926. pa = abs(p);
  197927. pb = abs(pc);
  197928. pc = abs(p + pc);
  197929. #else
  197930. pa = p < 0 ? -p : p;
  197931. pb = pc < 0 ? -pc : pc;
  197932. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  197933. #endif
  197934. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  197935. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  197936. }
  197937. best_row = png_ptr->paeth_row;
  197938. }
  197939. else if (filter_to_do & PNG_FILTER_PAETH)
  197940. {
  197941. png_bytep rp, dp, pp, cp, lp;
  197942. png_uint_32 sum = 0, lmins = mins;
  197943. png_uint_32 i;
  197944. int v;
  197945. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197946. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197947. {
  197948. int j;
  197949. png_uint_32 lmhi, lmlo;
  197950. lmlo = lmins & PNG_LOMASK;
  197951. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197952. for (j = 0; j < num_p_filters; j++)
  197953. {
  197954. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  197955. {
  197956. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197957. PNG_WEIGHT_SHIFT;
  197958. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197959. PNG_WEIGHT_SHIFT;
  197960. }
  197961. }
  197962. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197963. PNG_COST_SHIFT;
  197964. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197965. PNG_COST_SHIFT;
  197966. if (lmhi > PNG_HIMASK)
  197967. lmins = PNG_MAXSUM;
  197968. else
  197969. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197970. }
  197971. #endif
  197972. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  197973. pp = prev_row + 1; i < bpp; i++)
  197974. {
  197975. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  197976. sum += (v < 128) ? v : 256 - v;
  197977. }
  197978. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  197979. {
  197980. int a, b, c, pa, pb, pc, p;
  197981. b = *pp++;
  197982. c = *cp++;
  197983. a = *lp++;
  197984. #ifndef PNG_SLOW_PAETH
  197985. p = b - c;
  197986. pc = a - c;
  197987. #ifdef PNG_USE_ABS
  197988. pa = abs(p);
  197989. pb = abs(pc);
  197990. pc = abs(p + pc);
  197991. #else
  197992. pa = p < 0 ? -p : p;
  197993. pb = pc < 0 ? -pc : pc;
  197994. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  197995. #endif
  197996. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  197997. #else /* PNG_SLOW_PAETH */
  197998. p = a + b - c;
  197999. pa = abs(p - a);
  198000. pb = abs(p - b);
  198001. pc = abs(p - c);
  198002. if (pa <= pb && pa <= pc)
  198003. p = a;
  198004. else if (pb <= pc)
  198005. p = b;
  198006. else
  198007. p = c;
  198008. #endif /* PNG_SLOW_PAETH */
  198009. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198010. sum += (v < 128) ? v : 256 - v;
  198011. if (sum > lmins) /* We are already worse, don't continue. */
  198012. break;
  198013. }
  198014. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198015. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198016. {
  198017. int j;
  198018. png_uint_32 sumhi, sumlo;
  198019. sumlo = sum & PNG_LOMASK;
  198020. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198021. for (j = 0; j < num_p_filters; j++)
  198022. {
  198023. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198024. {
  198025. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198026. PNG_WEIGHT_SHIFT;
  198027. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198028. PNG_WEIGHT_SHIFT;
  198029. }
  198030. }
  198031. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198032. PNG_COST_SHIFT;
  198033. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198034. PNG_COST_SHIFT;
  198035. if (sumhi > PNG_HIMASK)
  198036. sum = PNG_MAXSUM;
  198037. else
  198038. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198039. }
  198040. #endif
  198041. if (sum < mins)
  198042. {
  198043. best_row = png_ptr->paeth_row;
  198044. }
  198045. }
  198046. #endif /* PNG_NO_WRITE_FILTER */
  198047. /* Do the actual writing of the filtered row data from the chosen filter. */
  198048. png_write_filtered_row(png_ptr, best_row);
  198049. #ifndef PNG_NO_WRITE_FILTER
  198050. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198051. /* Save the type of filter we picked this time for future calculations */
  198052. if (png_ptr->num_prev_filters > 0)
  198053. {
  198054. int j;
  198055. for (j = 1; j < num_p_filters; j++)
  198056. {
  198057. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  198058. }
  198059. png_ptr->prev_filters[j] = best_row[0];
  198060. }
  198061. #endif
  198062. #endif /* PNG_NO_WRITE_FILTER */
  198063. }
  198064. /* Do the actual writing of a previously filtered row. */
  198065. void /* PRIVATE */
  198066. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  198067. {
  198068. png_debug(1, "in png_write_filtered_row\n");
  198069. png_debug1(2, "filter = %d\n", filtered_row[0]);
  198070. /* set up the zlib input buffer */
  198071. png_ptr->zstream.next_in = filtered_row;
  198072. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  198073. /* repeat until we have compressed all the data */
  198074. do
  198075. {
  198076. int ret; /* return of zlib */
  198077. /* compress the data */
  198078. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  198079. /* check for compression errors */
  198080. if (ret != Z_OK)
  198081. {
  198082. if (png_ptr->zstream.msg != NULL)
  198083. png_error(png_ptr, png_ptr->zstream.msg);
  198084. else
  198085. png_error(png_ptr, "zlib error");
  198086. }
  198087. /* see if it is time to write another IDAT */
  198088. if (!(png_ptr->zstream.avail_out))
  198089. {
  198090. /* write the IDAT and reset the zlib output buffer */
  198091. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  198092. png_ptr->zstream.next_out = png_ptr->zbuf;
  198093. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198094. }
  198095. /* repeat until all data has been compressed */
  198096. } while (png_ptr->zstream.avail_in);
  198097. /* swap the current and previous rows */
  198098. if (png_ptr->prev_row != NULL)
  198099. {
  198100. png_bytep tptr;
  198101. tptr = png_ptr->prev_row;
  198102. png_ptr->prev_row = png_ptr->row_buf;
  198103. png_ptr->row_buf = tptr;
  198104. }
  198105. /* finish row - updates counters and flushes zlib if last row */
  198106. png_write_finish_row(png_ptr);
  198107. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198108. png_ptr->flush_rows++;
  198109. if (png_ptr->flush_dist > 0 &&
  198110. png_ptr->flush_rows >= png_ptr->flush_dist)
  198111. {
  198112. png_write_flush(png_ptr);
  198113. }
  198114. #endif
  198115. }
  198116. #endif /* PNG_WRITE_SUPPORTED */
  198117. /********* End of inlined file: pngwutil.c *********/
  198118. }
  198119. #else
  198120. #define PNG_INTERNAL
  198121. #define PNG_SETJMP_NOT_SUPPORTED
  198122. #include <png.h>
  198123. #include <pngconf.h>
  198124. #endif
  198125. }
  198126. #ifdef _MSC_VER
  198127. #pragma warning (pop)
  198128. #endif
  198129. BEGIN_JUCE_NAMESPACE
  198130. using namespace pnglibNamespace;
  198131. using ::calloc;
  198132. using ::malloc;
  198133. using ::free;
  198134. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  198135. {
  198136. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  198137. in->read (data, (int) length);
  198138. }
  198139. struct PNGErrorStruct {};
  198140. static void pngErrorCallback (png_structp, png_const_charp)
  198141. {
  198142. throw PNGErrorStruct();
  198143. }
  198144. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  198145. {
  198146. Image* image = 0;
  198147. png_structp pngReadStruct;
  198148. png_infop pngInfoStruct;
  198149. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198150. if (pngReadStruct != 0)
  198151. {
  198152. pngInfoStruct = png_create_info_struct (pngReadStruct);
  198153. if (pngInfoStruct == 0)
  198154. {
  198155. png_destroy_read_struct (&pngReadStruct, 0, 0);
  198156. return 0;
  198157. }
  198158. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  198159. // read the header..
  198160. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  198161. png_uint_32 width, height;
  198162. int bitDepth, colorType, interlaceType;
  198163. png_read_info (pngReadStruct, pngInfoStruct);
  198164. png_get_IHDR (pngReadStruct, pngInfoStruct,
  198165. &width, &height,
  198166. &bitDepth, &colorType,
  198167. &interlaceType, 0, 0);
  198168. if (bitDepth == 16)
  198169. png_set_strip_16 (pngReadStruct);
  198170. if (colorType == PNG_COLOR_TYPE_PALETTE)
  198171. png_set_expand (pngReadStruct);
  198172. if (bitDepth < 8)
  198173. png_set_expand (pngReadStruct);
  198174. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  198175. png_set_expand (pngReadStruct);
  198176. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  198177. png_set_gray_to_rgb (pngReadStruct);
  198178. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  198179. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  198180. || pngInfoStruct->num_trans > 0;
  198181. // Load the image into a temp buffer in the pnglib format..
  198182. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  198183. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  198184. int y;
  198185. for (y = (int) height; --y >= 0;)
  198186. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  198187. png_read_image (pngReadStruct, rows);
  198188. png_read_end (pngReadStruct, pngInfoStruct);
  198189. juce_free (rows);
  198190. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  198191. // now convert the data to a juce image format..
  198192. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  198193. width, height, hasAlphaChan);
  198194. int stride, pixelStride;
  198195. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  198196. uint8* srcRow = tempBuffer;
  198197. uint8* destRow = pixels;
  198198. for (y = 0; y < (int) height; ++y)
  198199. {
  198200. const uint8* src = srcRow;
  198201. srcRow += (width << 2);
  198202. uint8* dest = destRow;
  198203. destRow += stride;
  198204. if (hasAlphaChan)
  198205. {
  198206. for (int i = width; --i >= 0;)
  198207. {
  198208. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  198209. ((PixelARGB*) dest)->premultiply();
  198210. dest += pixelStride;
  198211. src += 4;
  198212. }
  198213. }
  198214. else
  198215. {
  198216. for (int i = width; --i >= 0;)
  198217. {
  198218. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  198219. dest += pixelStride;
  198220. src += 4;
  198221. }
  198222. }
  198223. }
  198224. image->releasePixelDataReadWrite (pixels);
  198225. juce_free (tempBuffer);
  198226. }
  198227. return image;
  198228. }
  198229. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  198230. {
  198231. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  198232. const bool ok = out->write (data, length);
  198233. (void) ok;
  198234. jassert (ok);
  198235. }
  198236. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  198237. {
  198238. const int width = image.getWidth();
  198239. const int height = image.getHeight();
  198240. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198241. if (pngWriteStruct == 0)
  198242. return false;
  198243. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  198244. if (pngInfoStruct == 0)
  198245. {
  198246. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  198247. return false;
  198248. }
  198249. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  198250. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  198251. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  198252. : PNG_COLOR_TYPE_RGB,
  198253. PNG_INTERLACE_NONE,
  198254. PNG_COMPRESSION_TYPE_BASE,
  198255. PNG_FILTER_TYPE_BASE);
  198256. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  198257. png_color_8 sig_bit;
  198258. sig_bit.red = 8;
  198259. sig_bit.green = 8;
  198260. sig_bit.blue = 8;
  198261. sig_bit.alpha = 8;
  198262. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  198263. png_write_info (pngWriteStruct, pngInfoStruct);
  198264. png_set_shift (pngWriteStruct, &sig_bit);
  198265. png_set_packing (pngWriteStruct);
  198266. for (int y = 0; y < height; ++y)
  198267. {
  198268. uint8* dst = (uint8*) rowData;
  198269. int stride, pixelStride;
  198270. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  198271. const uint8* src = pixels;
  198272. if (image.hasAlphaChannel())
  198273. {
  198274. for (int i = width; --i >= 0;)
  198275. {
  198276. PixelARGB p (*(const PixelARGB*) src);
  198277. p.unpremultiply();
  198278. *dst++ = p.getRed();
  198279. *dst++ = p.getGreen();
  198280. *dst++ = p.getBlue();
  198281. *dst++ = p.getAlpha();
  198282. src += pixelStride;
  198283. }
  198284. }
  198285. else
  198286. {
  198287. for (int i = width; --i >= 0;)
  198288. {
  198289. *dst++ = ((const PixelRGB*) src)->getRed();
  198290. *dst++ = ((const PixelRGB*) src)->getGreen();
  198291. *dst++ = ((const PixelRGB*) src)->getBlue();
  198292. src += pixelStride;
  198293. }
  198294. }
  198295. png_write_rows (pngWriteStruct, &rowData, 1);
  198296. image.releasePixelDataReadOnly (pixels);
  198297. }
  198298. juce_free (rowData);
  198299. png_write_end (pngWriteStruct, pngInfoStruct);
  198300. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  198301. out.flush();
  198302. return true;
  198303. }
  198304. END_JUCE_NAMESPACE
  198305. /********* End of inlined file: juce_PNGLoader.cpp *********/
  198306. #endif
  198307. //==============================================================================
  198308. #if JUCE_WIN32
  198309. /********* Start of inlined file: juce_win32_NativeCode.cpp *********/
  198310. /*
  198311. This file wraps together all the win32-specific code, so that
  198312. we can include all the native headers just once, and compile all our
  198313. platform-specific stuff in one big lump, keeping it out of the way of
  198314. the rest of the codebase.
  198315. */
  198316. BEGIN_JUCE_NAMESPACE
  198317. #define JUCE_INCLUDED_FILE 1
  198318. // Now include the actual code files..
  198319. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198320. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198321. // compiled on its own).
  198322. #if JUCE_INCLUDED_FILE
  198323. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198324. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198325. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198326. #ifndef DOXYGEN
  198327. // use with DynamicLibraryLoader to simplify importing functions
  198328. //
  198329. // functionName: function to import
  198330. // localFunctionName: name you want to use to actually call it (must be different)
  198331. // returnType: the return type
  198332. // object: the DynamicLibraryLoader to use
  198333. // params: list of params (bracketed)
  198334. //
  198335. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  198336. typedef returnType (WINAPI *type##localFunctionName) params; \
  198337. type##localFunctionName localFunctionName \
  198338. = (type##localFunctionName)object.findProcAddress (#functionName);
  198339. // loads and unloads a DLL automatically
  198340. class JUCE_API DynamicLibraryLoader
  198341. {
  198342. public:
  198343. DynamicLibraryLoader (const String& name);
  198344. ~DynamicLibraryLoader();
  198345. void* findProcAddress (const String& functionName);
  198346. private:
  198347. void* libHandle;
  198348. };
  198349. #endif
  198350. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198351. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198352. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  198353. {
  198354. libHandle = LoadLibrary (name);
  198355. }
  198356. DynamicLibraryLoader::~DynamicLibraryLoader()
  198357. {
  198358. FreeLibrary ((HMODULE) libHandle);
  198359. }
  198360. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  198361. {
  198362. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  198363. }
  198364. #endif
  198365. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198366. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  198367. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198368. // compiled on its own).
  198369. #if JUCE_INCLUDED_FILE
  198370. extern void juce_updateMultiMonitorInfo() throw();
  198371. extern void juce_initialiseThreadEvents() throw();
  198372. void Logger::outputDebugString (const String& text) throw()
  198373. {
  198374. OutputDebugString (text + T("\n"));
  198375. }
  198376. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  198377. {
  198378. String text;
  198379. va_list args;
  198380. va_start (args, format);
  198381. text.vprintf(format, args);
  198382. outputDebugString (text);
  198383. }
  198384. static int64 hiResTicksPerSecond;
  198385. static double hiResTicksScaleFactor;
  198386. #if JUCE_USE_INTRINSICS
  198387. // CPU info functions using intrinsics...
  198388. #pragma intrinsic (__cpuid)
  198389. #pragma intrinsic (__rdtsc)
  198390. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  198391. {
  198392. int info [4];
  198393. __cpuid (info, 1);
  198394. if (familyModel != 0)
  198395. *familyModel = info [0];
  198396. if (extFeatures != 0)
  198397. *extFeatures = info[1];
  198398. return info[3];
  198399. }*/
  198400. const String SystemStats::getCpuVendor() throw()
  198401. {
  198402. int info [4];
  198403. __cpuid (info, 0);
  198404. char v [12];
  198405. memcpy (v, info + 1, 4);
  198406. memcpy (v + 4, info + 3, 4);
  198407. memcpy (v + 8, info + 2, 4);
  198408. return String (v, 12);
  198409. }
  198410. #else
  198411. // CPU info functions using old fashioned inline asm...
  198412. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  198413. {
  198414. unsigned int cpu = 0;
  198415. unsigned int ext = 0;
  198416. unsigned int family = 0;
  198417. #if JUCE_GCC
  198418. unsigned int dummy = 0;
  198419. #endif
  198420. #ifndef __MINGW32__
  198421. __try
  198422. #endif
  198423. {
  198424. #if JUCE_GCC
  198425. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  198426. #else
  198427. __asm
  198428. {
  198429. mov eax, 1
  198430. cpuid
  198431. mov cpu, edx
  198432. mov family, eax
  198433. mov ext, ebx
  198434. }
  198435. #endif
  198436. }
  198437. #ifndef __MINGW32__
  198438. __except (EXCEPTION_EXECUTE_HANDLER)
  198439. {
  198440. return 0;
  198441. }
  198442. #endif
  198443. if (familyModel != 0)
  198444. *familyModel = family;
  198445. if (extFeatures != 0)
  198446. *extFeatures = ext;
  198447. return cpu;
  198448. }*/
  198449. static void juce_getCpuVendor (char* const v)
  198450. {
  198451. int vendor[4];
  198452. zeromem (vendor, 16);
  198453. #ifdef JUCE_64BIT
  198454. #else
  198455. #ifndef __MINGW32__
  198456. __try
  198457. #endif
  198458. {
  198459. #if JUCE_GCC
  198460. unsigned int dummy = 0;
  198461. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  198462. #else
  198463. __asm
  198464. {
  198465. mov eax, 0
  198466. cpuid
  198467. mov [vendor], ebx
  198468. mov [vendor + 4], edx
  198469. mov [vendor + 8], ecx
  198470. }
  198471. #endif
  198472. }
  198473. #ifndef __MINGW32__
  198474. __except (EXCEPTION_EXECUTE_HANDLER)
  198475. {
  198476. *v = 0;
  198477. }
  198478. #endif
  198479. #endif
  198480. memcpy (v, vendor, 16);
  198481. }
  198482. const String SystemStats::getCpuVendor() throw()
  198483. {
  198484. char v [16];
  198485. juce_getCpuVendor (v);
  198486. return String (v, 16);
  198487. }
  198488. #endif
  198489. struct CPUFlags
  198490. {
  198491. bool hasMMX : 1;
  198492. bool hasSSE : 1;
  198493. bool hasSSE2 : 1;
  198494. bool has3DNow : 1;
  198495. };
  198496. static CPUFlags cpuFlags;
  198497. bool SystemStats::hasMMX() throw()
  198498. {
  198499. return cpuFlags.hasMMX;
  198500. }
  198501. bool SystemStats::hasSSE() throw()
  198502. {
  198503. return cpuFlags.hasSSE;
  198504. }
  198505. bool SystemStats::hasSSE2() throw()
  198506. {
  198507. return cpuFlags.hasSSE2;
  198508. }
  198509. bool SystemStats::has3DNow() throw()
  198510. {
  198511. return cpuFlags.has3DNow;
  198512. }
  198513. void SystemStats::initialiseStats() throw()
  198514. {
  198515. juce_initialiseThreadEvents();
  198516. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  198517. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  198518. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  198519. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  198520. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  198521. #else
  198522. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  198523. #endif
  198524. LARGE_INTEGER f;
  198525. QueryPerformanceFrequency (&f);
  198526. hiResTicksPerSecond = f.QuadPart;
  198527. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  198528. String s (SystemStats::getJUCEVersion());
  198529. #ifdef JUCE_DEBUG
  198530. const MMRESULT res = timeBeginPeriod (1);
  198531. jassert (res == TIMERR_NOERROR);
  198532. #else
  198533. timeBeginPeriod (1);
  198534. #endif
  198535. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198536. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  198537. #endif
  198538. }
  198539. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  198540. {
  198541. OSVERSIONINFO info;
  198542. info.dwOSVersionInfoSize = sizeof (info);
  198543. GetVersionEx (&info);
  198544. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  198545. {
  198546. switch (info.dwMajorVersion)
  198547. {
  198548. case 5:
  198549. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  198550. case 6:
  198551. return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  198552. default:
  198553. jassertfalse // !! not a supported OS!
  198554. break;
  198555. }
  198556. }
  198557. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  198558. {
  198559. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  198560. return Win98;
  198561. }
  198562. return UnknownOS;
  198563. }
  198564. const String SystemStats::getOperatingSystemName() throw()
  198565. {
  198566. const char* name = "Unknown OS";
  198567. switch (getOperatingSystemType())
  198568. {
  198569. case WinVista:
  198570. name = "Windows Vista";
  198571. break;
  198572. case WinXP:
  198573. name = "Windows XP";
  198574. break;
  198575. case Win2000:
  198576. name = "Windows 2000";
  198577. break;
  198578. case Win98:
  198579. name = "Windows 98";
  198580. break;
  198581. default:
  198582. jassertfalse // !! new type of OS?
  198583. break;
  198584. }
  198585. return name;
  198586. }
  198587. bool SystemStats::isOperatingSystem64Bit() throw()
  198588. {
  198589. #ifdef _WIN64
  198590. return true;
  198591. #else
  198592. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  198593. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  198594. BOOL isWow64 = FALSE;
  198595. return (fnIsWow64Process != 0)
  198596. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  198597. && (isWow64 != FALSE);
  198598. #endif
  198599. }
  198600. int SystemStats::getMemorySizeInMegabytes() throw()
  198601. {
  198602. MEMORYSTATUS mem;
  198603. GlobalMemoryStatus (&mem);
  198604. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  198605. }
  198606. int SystemStats::getNumCpus() throw()
  198607. {
  198608. SYSTEM_INFO systemInfo;
  198609. GetSystemInfo (&systemInfo);
  198610. return systemInfo.dwNumberOfProcessors;
  198611. }
  198612. uint32 juce_millisecondsSinceStartup() throw()
  198613. {
  198614. return (uint32) GetTickCount();
  198615. }
  198616. int64 Time::getHighResolutionTicks() throw()
  198617. {
  198618. LARGE_INTEGER ticks;
  198619. QueryPerformanceCounter (&ticks);
  198620. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  198621. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  198622. // fix for a very obscure PCI hardware bug that can make the counter
  198623. // sometimes jump forwards by a few seconds..
  198624. static int64 hiResTicksOffset = 0;
  198625. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  198626. if (offsetDrift > (hiResTicksPerSecond >> 1))
  198627. hiResTicksOffset = newOffset;
  198628. return ticks.QuadPart + hiResTicksOffset;
  198629. }
  198630. double Time::getMillisecondCounterHiRes() throw()
  198631. {
  198632. return getHighResolutionTicks() * hiResTicksScaleFactor;
  198633. }
  198634. int64 Time::getHighResolutionTicksPerSecond() throw()
  198635. {
  198636. return hiResTicksPerSecond;
  198637. }
  198638. int64 SystemStats::getClockCycleCounter() throw()
  198639. {
  198640. #if JUCE_USE_INTRINSICS
  198641. // MS intrinsics version...
  198642. return __rdtsc();
  198643. #elif JUCE_GCC
  198644. // GNU inline asm version...
  198645. unsigned int hi = 0, lo = 0;
  198646. __asm__ __volatile__ (
  198647. "xor %%eax, %%eax \n\
  198648. xor %%edx, %%edx \n\
  198649. rdtsc \n\
  198650. movl %%eax, %[lo] \n\
  198651. movl %%edx, %[hi]"
  198652. :
  198653. : [hi] "m" (hi),
  198654. [lo] "m" (lo)
  198655. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  198656. return (int64) ((((uint64) hi) << 32) | lo);
  198657. #else
  198658. // MSVC inline asm version...
  198659. unsigned int hi = 0, lo = 0;
  198660. __asm
  198661. {
  198662. xor eax, eax
  198663. xor edx, edx
  198664. rdtsc
  198665. mov lo, eax
  198666. mov hi, edx
  198667. }
  198668. return (int64) ((((uint64) hi) << 32) | lo);
  198669. #endif
  198670. }
  198671. int SystemStats::getCpuSpeedInMegaherz() throw()
  198672. {
  198673. const int64 cycles = SystemStats::getClockCycleCounter();
  198674. const uint32 millis = Time::getMillisecondCounter();
  198675. int lastResult = 0;
  198676. for (;;)
  198677. {
  198678. int n = 1000000;
  198679. while (--n > 0) {}
  198680. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  198681. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  198682. if (millisElapsed > 80)
  198683. {
  198684. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  198685. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  198686. return newResult;
  198687. lastResult = newResult;
  198688. }
  198689. }
  198690. }
  198691. bool Time::setSystemTimeToThisTime() const throw()
  198692. {
  198693. SYSTEMTIME st;
  198694. st.wDayOfWeek = 0;
  198695. st.wYear = (WORD) getYear();
  198696. st.wMonth = (WORD) (getMonth() + 1);
  198697. st.wDay = (WORD) getDayOfMonth();
  198698. st.wHour = (WORD) getHours();
  198699. st.wMinute = (WORD) getMinutes();
  198700. st.wSecond = (WORD) getSeconds();
  198701. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  198702. // do this twice because of daylight saving conversion problems - the
  198703. // first one sets it up, the second one kicks it in.
  198704. return SetLocalTime (&st) != 0
  198705. && SetLocalTime (&st) != 0;
  198706. }
  198707. int SystemStats::getPageSize() throw()
  198708. {
  198709. SYSTEM_INFO systemInfo;
  198710. GetSystemInfo (&systemInfo);
  198711. return systemInfo.dwPageSize;
  198712. }
  198713. #endif
  198714. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  198715. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  198716. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198717. // compiled on its own).
  198718. #if JUCE_INCLUDED_FILE
  198719. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198720. extern HWND juce_messageWindowHandle;
  198721. #endif
  198722. CriticalSection::CriticalSection() throw()
  198723. {
  198724. // (just to check the MS haven't changed this structure and broken things...)
  198725. #if _MSC_VER >= 1400
  198726. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  198727. #else
  198728. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  198729. #endif
  198730. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  198731. }
  198732. CriticalSection::~CriticalSection() throw()
  198733. {
  198734. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  198735. }
  198736. void CriticalSection::enter() const throw()
  198737. {
  198738. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  198739. }
  198740. bool CriticalSection::tryEnter() const throw()
  198741. {
  198742. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  198743. }
  198744. void CriticalSection::exit() const throw()
  198745. {
  198746. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  198747. }
  198748. WaitableEvent::WaitableEvent() throw()
  198749. : internal (CreateEvent (0, FALSE, FALSE, 0))
  198750. {
  198751. }
  198752. WaitableEvent::~WaitableEvent() throw()
  198753. {
  198754. CloseHandle (internal);
  198755. }
  198756. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  198757. {
  198758. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  198759. }
  198760. void WaitableEvent::signal() const throw()
  198761. {
  198762. SetEvent (internal);
  198763. }
  198764. void WaitableEvent::reset() const throw()
  198765. {
  198766. ResetEvent (internal);
  198767. }
  198768. void JUCE_API juce_threadEntryPoint (void*);
  198769. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  198770. {
  198771. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198772. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  198773. GetCurrentThreadId(), TRUE);
  198774. #endif
  198775. juce_threadEntryPoint (userData);
  198776. _endthreadex (0);
  198777. return 0;
  198778. }
  198779. void juce_CloseThreadHandle (void* handle) throw()
  198780. {
  198781. CloseHandle ((HANDLE) handle);
  198782. }
  198783. void* juce_createThread (void* userData) throw()
  198784. {
  198785. unsigned int threadId;
  198786. return (void*) _beginthreadex (0, 0,
  198787. &threadEntryProc,
  198788. userData,
  198789. 0, &threadId);
  198790. }
  198791. void juce_killThread (void* handle) throw()
  198792. {
  198793. if (handle != 0)
  198794. {
  198795. #ifdef JUCE_DEBUG
  198796. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  198797. #endif
  198798. TerminateThread (handle, 0);
  198799. }
  198800. }
  198801. void juce_setCurrentThreadName (const String& name) throw()
  198802. {
  198803. #if defined (JUCE_DEBUG) && JUCE_MSVC
  198804. struct
  198805. {
  198806. DWORD dwType;
  198807. LPCSTR szName;
  198808. DWORD dwThreadID;
  198809. DWORD dwFlags;
  198810. } info;
  198811. info.dwType = 0x1000;
  198812. info.szName = name;
  198813. info.dwThreadID = GetCurrentThreadId();
  198814. info.dwFlags = 0;
  198815. #define MS_VC_EXCEPTION 0x406d1388
  198816. __try
  198817. {
  198818. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  198819. }
  198820. __except (EXCEPTION_CONTINUE_EXECUTION)
  198821. {}
  198822. #else
  198823. (void) name;
  198824. #endif
  198825. }
  198826. Thread::ThreadID Thread::getCurrentThreadId() throw()
  198827. {
  198828. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  198829. }
  198830. // priority 1 to 10 where 5=normal, 1=low
  198831. bool juce_setThreadPriority (void* threadHandle, int priority) throw()
  198832. {
  198833. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  198834. if (priority < 1)
  198835. pri = THREAD_PRIORITY_IDLE;
  198836. else if (priority < 2)
  198837. pri = THREAD_PRIORITY_LOWEST;
  198838. else if (priority < 5)
  198839. pri = THREAD_PRIORITY_BELOW_NORMAL;
  198840. else if (priority < 7)
  198841. pri = THREAD_PRIORITY_NORMAL;
  198842. else if (priority < 9)
  198843. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  198844. else if (priority < 10)
  198845. pri = THREAD_PRIORITY_HIGHEST;
  198846. if (threadHandle == 0)
  198847. threadHandle = GetCurrentThread();
  198848. return SetThreadPriority (threadHandle, pri) != FALSE;
  198849. }
  198850. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  198851. {
  198852. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  198853. }
  198854. static HANDLE sleepEvent = 0;
  198855. void juce_initialiseThreadEvents() throw()
  198856. {
  198857. if (sleepEvent == 0)
  198858. #ifdef JUCE_DEBUG
  198859. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  198860. #else
  198861. sleepEvent = CreateEvent (0, 0, 0, 0);
  198862. #endif
  198863. }
  198864. void Thread::yield() throw()
  198865. {
  198866. Sleep (0);
  198867. }
  198868. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  198869. {
  198870. if (millisecs >= 10)
  198871. {
  198872. Sleep (millisecs);
  198873. }
  198874. else
  198875. {
  198876. jassert (sleepEvent != 0);
  198877. // unlike Sleep() this is guaranteed to return to the current thread after
  198878. // the time expires, so we'll use this for short waits, which are more likely
  198879. // to need to be accurate
  198880. WaitForSingleObject (sleepEvent, millisecs);
  198881. }
  198882. }
  198883. static int lastProcessPriority = -1;
  198884. // called by WindowDriver because Windows does wierd things to process priority
  198885. // when you swap apps, and this forces an update when the app is brought to the front.
  198886. void juce_repeatLastProcessPriority() throw()
  198887. {
  198888. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  198889. {
  198890. DWORD p;
  198891. switch (lastProcessPriority)
  198892. {
  198893. case Process::LowPriority:
  198894. p = IDLE_PRIORITY_CLASS;
  198895. break;
  198896. case Process::NormalPriority:
  198897. p = NORMAL_PRIORITY_CLASS;
  198898. break;
  198899. case Process::HighPriority:
  198900. p = HIGH_PRIORITY_CLASS;
  198901. break;
  198902. case Process::RealtimePriority:
  198903. p = REALTIME_PRIORITY_CLASS;
  198904. break;
  198905. default:
  198906. jassertfalse // bad priority value
  198907. return;
  198908. }
  198909. SetPriorityClass (GetCurrentProcess(), p);
  198910. }
  198911. }
  198912. void Process::setPriority (ProcessPriority prior)
  198913. {
  198914. if (lastProcessPriority != (int) prior)
  198915. {
  198916. lastProcessPriority = (int) prior;
  198917. juce_repeatLastProcessPriority();
  198918. }
  198919. }
  198920. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  198921. {
  198922. return IsDebuggerPresent() != FALSE;
  198923. }
  198924. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  198925. {
  198926. return juce_isRunningUnderDebugger();
  198927. }
  198928. void Process::raisePrivilege()
  198929. {
  198930. jassertfalse // xxx not implemented
  198931. }
  198932. void Process::lowerPrivilege()
  198933. {
  198934. jassertfalse // xxx not implemented
  198935. }
  198936. void Process::terminate()
  198937. {
  198938. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198939. _CrtDumpMemoryLeaks();
  198940. #endif
  198941. // bullet in the head in case there's a problem shutting down..
  198942. ExitProcess (0);
  198943. }
  198944. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  198945. {
  198946. void* result = 0;
  198947. JUCE_TRY
  198948. {
  198949. result = (void*) LoadLibrary (name);
  198950. }
  198951. JUCE_CATCH_ALL
  198952. return result;
  198953. }
  198954. void PlatformUtilities::freeDynamicLibrary (void* h)
  198955. {
  198956. JUCE_TRY
  198957. {
  198958. if (h != 0)
  198959. FreeLibrary ((HMODULE) h);
  198960. }
  198961. JUCE_CATCH_ALL
  198962. }
  198963. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  198964. {
  198965. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  198966. : 0;
  198967. }
  198968. InterProcessLock::InterProcessLock (const String& name_) throw()
  198969. : internal (0),
  198970. name (name_),
  198971. reentrancyLevel (0)
  198972. {
  198973. }
  198974. InterProcessLock::~InterProcessLock() throw()
  198975. {
  198976. exit();
  198977. }
  198978. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  198979. {
  198980. if (reentrancyLevel++ == 0)
  198981. {
  198982. internal = CreateMutex (0, TRUE, name);
  198983. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  198984. {
  198985. if (timeOutMillisecs == 0
  198986. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  198987. == WAIT_TIMEOUT)
  198988. {
  198989. ReleaseMutex (internal);
  198990. CloseHandle (internal);
  198991. internal = 0;
  198992. }
  198993. }
  198994. }
  198995. return (internal != 0);
  198996. }
  198997. void InterProcessLock::exit() throw()
  198998. {
  198999. if (--reentrancyLevel == 0 && internal != 0)
  199000. {
  199001. ReleaseMutex (internal);
  199002. CloseHandle (internal);
  199003. internal = 0;
  199004. }
  199005. }
  199006. #endif
  199007. /********* End of inlined file: juce_win32_Threads.cpp *********/
  199008. /********* Start of inlined file: juce_win32_Files.cpp *********/
  199009. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199010. // compiled on its own).
  199011. #if JUCE_INCLUDED_FILE
  199012. #ifndef CSIDL_MYMUSIC
  199013. #define CSIDL_MYMUSIC 0x000d
  199014. #endif
  199015. #ifndef CSIDL_MYVIDEO
  199016. #define CSIDL_MYVIDEO 0x000e
  199017. #endif
  199018. const tchar File::separator = T('\\');
  199019. const tchar* File::separatorString = T("\\");
  199020. bool juce_fileExists (const String& fileName,
  199021. const bool dontCountDirectories) throw()
  199022. {
  199023. if (fileName.isEmpty())
  199024. return false;
  199025. const DWORD attr = GetFileAttributes (fileName);
  199026. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  199027. : (attr != 0xffffffff);
  199028. }
  199029. bool juce_isDirectory (const String& fileName) throw()
  199030. {
  199031. const DWORD attr = GetFileAttributes (fileName);
  199032. return (attr != 0xffffffff)
  199033. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199034. }
  199035. bool juce_canWriteToFile (const String& fileName) throw()
  199036. {
  199037. const DWORD attr = GetFileAttributes (fileName);
  199038. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  199039. }
  199040. bool juce_setFileReadOnly (const String& fileName,
  199041. bool isReadOnly) throw()
  199042. {
  199043. DWORD attr = GetFileAttributes (fileName);
  199044. if (attr == 0xffffffff)
  199045. return false;
  199046. if (isReadOnly != juce_canWriteToFile (fileName))
  199047. return true;
  199048. if (isReadOnly)
  199049. attr |= FILE_ATTRIBUTE_READONLY;
  199050. else
  199051. attr &= ~FILE_ATTRIBUTE_READONLY;
  199052. return SetFileAttributes (fileName, attr) != FALSE;
  199053. }
  199054. bool File::isHidden() const throw()
  199055. {
  199056. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  199057. }
  199058. bool juce_deleteFile (const String& fileName) throw()
  199059. {
  199060. if (juce_isDirectory (fileName))
  199061. return RemoveDirectory (fileName) != 0;
  199062. return DeleteFile (fileName) != 0;
  199063. }
  199064. bool File::moveToTrash() const throw()
  199065. {
  199066. if (! exists())
  199067. return true;
  199068. SHFILEOPSTRUCT fos;
  199069. zerostruct (fos);
  199070. // The string we pass in must be double null terminated..
  199071. String doubleNullTermPath (getFullPathName() + " ");
  199072. TCHAR* p = (TCHAR*) (const TCHAR*) doubleNullTermPath;
  199073. p [getFullPathName().length()] = 0;
  199074. fos.wFunc = FO_DELETE;
  199075. fos.hwnd = (HWND) 0;
  199076. fos.pFrom = p;
  199077. fos.pTo = NULL;
  199078. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  199079. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  199080. return SHFileOperation (&fos) == 0;
  199081. }
  199082. bool juce_moveFile (const String& source, const String& dest) throw()
  199083. {
  199084. return MoveFile (source, dest) != 0;
  199085. }
  199086. bool juce_copyFile (const String& source, const String& dest) throw()
  199087. {
  199088. return CopyFile (source, dest, false) != 0;
  199089. }
  199090. void juce_createDirectory (const String& fileName) throw()
  199091. {
  199092. if (! juce_fileExists (fileName, true))
  199093. {
  199094. CreateDirectory (fileName, 0);
  199095. }
  199096. }
  199097. // return 0 if not possible
  199098. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  199099. {
  199100. HANDLE h;
  199101. if (forWriting)
  199102. {
  199103. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  199104. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  199105. if (h != INVALID_HANDLE_VALUE)
  199106. SetFilePointer (h, 0, 0, FILE_END);
  199107. else
  199108. h = 0;
  199109. }
  199110. else
  199111. {
  199112. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  199113. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  199114. if (h == INVALID_HANDLE_VALUE)
  199115. h = 0;
  199116. }
  199117. return (void*) h;
  199118. }
  199119. void juce_fileClose (void* handle) throw()
  199120. {
  199121. CloseHandle (handle);
  199122. }
  199123. int juce_fileRead (void* handle, void* buffer, int size) throw()
  199124. {
  199125. DWORD num = 0;
  199126. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  199127. return num;
  199128. }
  199129. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  199130. {
  199131. DWORD num;
  199132. WriteFile ((HANDLE) handle,
  199133. buffer, size,
  199134. &num, 0);
  199135. return num;
  199136. }
  199137. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  199138. {
  199139. LARGE_INTEGER li;
  199140. li.QuadPart = pos;
  199141. li.LowPart = SetFilePointer ((HANDLE) handle,
  199142. li.LowPart,
  199143. &li.HighPart,
  199144. FILE_BEGIN); // (returns -1 if it fails)
  199145. return li.QuadPart;
  199146. }
  199147. int64 juce_fileGetPosition (void* handle) throw()
  199148. {
  199149. LARGE_INTEGER li;
  199150. li.QuadPart = 0;
  199151. li.LowPart = SetFilePointer ((HANDLE) handle,
  199152. 0, &li.HighPart,
  199153. FILE_CURRENT); // (returns -1 if it fails)
  199154. return jmax ((int64) 0, li.QuadPart);
  199155. }
  199156. void juce_fileFlush (void* handle) throw()
  199157. {
  199158. FlushFileBuffers ((HANDLE) handle);
  199159. }
  199160. int64 juce_getFileSize (const String& fileName) throw()
  199161. {
  199162. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199163. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199164. {
  199165. return (((int64) attributes.nFileSizeHigh) << 32)
  199166. | attributes.nFileSizeLow;
  199167. }
  199168. return 0;
  199169. }
  199170. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  199171. {
  199172. // tell me if this fails!
  199173. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  199174. #if JUCE_GCC
  199175. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  199176. #else
  199177. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  199178. #endif
  199179. }
  199180. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  199181. {
  199182. #if JUCE_GCC
  199183. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  199184. #else
  199185. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  199186. #endif
  199187. }
  199188. void juce_getFileTimes (const String& fileName,
  199189. int64& modificationTime,
  199190. int64& accessTime,
  199191. int64& creationTime) throw()
  199192. {
  199193. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199194. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199195. {
  199196. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  199197. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  199198. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  199199. }
  199200. else
  199201. {
  199202. creationTime = accessTime = modificationTime = 0;
  199203. }
  199204. }
  199205. bool juce_setFileTimes (const String& fileName,
  199206. int64 modificationTime,
  199207. int64 accessTime,
  199208. int64 creationTime) throw()
  199209. {
  199210. FILETIME m, a, c;
  199211. if (modificationTime > 0)
  199212. timeToFileTime (modificationTime, &m);
  199213. if (accessTime > 0)
  199214. timeToFileTime (accessTime, &a);
  199215. if (creationTime > 0)
  199216. timeToFileTime (creationTime, &c);
  199217. void* const h = juce_fileOpen (fileName, true);
  199218. bool ok = false;
  199219. if (h != 0)
  199220. {
  199221. ok = SetFileTime ((HANDLE) h,
  199222. (creationTime > 0) ? &c : 0,
  199223. (accessTime > 0) ? &a : 0,
  199224. (modificationTime > 0) ? &m : 0) != 0;
  199225. juce_fileClose (h);
  199226. }
  199227. return ok;
  199228. }
  199229. // return '\0' separated list of strings
  199230. const StringArray juce_getFileSystemRoots() throw()
  199231. {
  199232. TCHAR buffer [2048];
  199233. buffer[0] = 0;
  199234. buffer[1] = 0;
  199235. GetLogicalDriveStrings (2048, buffer);
  199236. TCHAR* n = buffer;
  199237. StringArray roots;
  199238. while (*n != 0)
  199239. {
  199240. roots.add (String (n));
  199241. while (*n++ != 0)
  199242. {
  199243. }
  199244. }
  199245. roots.sort (true);
  199246. return roots;
  199247. }
  199248. const String juce_getVolumeLabel (const String& filenameOnVolume,
  199249. int& volumeSerialNumber) throw()
  199250. {
  199251. TCHAR n [4];
  199252. n[0] = *(const TCHAR*) filenameOnVolume;
  199253. n[1] = L':';
  199254. n[2] = L'\\';
  199255. n[3] = 0;
  199256. TCHAR dest [64];
  199257. DWORD serialNum;
  199258. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  199259. {
  199260. dest[0] = 0;
  199261. serialNum = 0;
  199262. }
  199263. volumeSerialNumber = serialNum;
  199264. return String (dest);
  199265. }
  199266. static int64 getDiskSpaceInfo (String fn, const bool total) throw()
  199267. {
  199268. if (fn[1] == T(':'))
  199269. fn = fn.substring (0, 2) + T("\\");
  199270. ULARGE_INTEGER spc, tot, totFree;
  199271. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  199272. return (int64) (total ? tot.QuadPart
  199273. : spc.QuadPart);
  199274. return 0;
  199275. }
  199276. int64 File::getBytesFreeOnVolume() const throw()
  199277. {
  199278. return getDiskSpaceInfo (getFullPathName(), false);
  199279. }
  199280. int64 File::getVolumeTotalSize() const throw()
  199281. {
  199282. return getDiskSpaceInfo (getFullPathName(), true);
  199283. }
  199284. static unsigned int getWindowsDriveType (const String& fileName) throw()
  199285. {
  199286. TCHAR n[4];
  199287. n[0] = *(const TCHAR*) fileName;
  199288. n[1] = L':';
  199289. n[2] = L'\\';
  199290. n[3] = 0;
  199291. return GetDriveType (n);
  199292. }
  199293. bool File::isOnCDRomDrive() const throw()
  199294. {
  199295. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  199296. }
  199297. bool File::isOnHardDisk() const throw()
  199298. {
  199299. if (fullPath.isEmpty())
  199300. return false;
  199301. const unsigned int n = getWindowsDriveType (getFullPathName());
  199302. if (fullPath.toLowerCase()[0] <= 'b'
  199303. && fullPath[1] == T(':'))
  199304. {
  199305. return n != DRIVE_REMOVABLE;
  199306. }
  199307. else
  199308. {
  199309. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  199310. }
  199311. }
  199312. bool File::isOnRemovableDrive() const throw()
  199313. {
  199314. if (fullPath.isEmpty())
  199315. return false;
  199316. const unsigned int n = getWindowsDriveType (getFullPathName());
  199317. return n == DRIVE_CDROM
  199318. || n == DRIVE_REMOTE
  199319. || n == DRIVE_REMOVABLE
  199320. || n == DRIVE_RAMDISK;
  199321. }
  199322. #define MAX_PATH_CHARS (MAX_PATH + 256)
  199323. static const File juce_getSpecialFolderPath (int type) throw()
  199324. {
  199325. WCHAR path [MAX_PATH_CHARS];
  199326. if (SHGetSpecialFolderPath (0, path, type, 0))
  199327. return File (String (path));
  199328. return File::nonexistent;
  199329. }
  199330. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  199331. {
  199332. int csidlType = 0;
  199333. switch (type)
  199334. {
  199335. case userHomeDirectory:
  199336. case userDocumentsDirectory:
  199337. csidlType = CSIDL_PERSONAL;
  199338. break;
  199339. case userDesktopDirectory:
  199340. csidlType = CSIDL_DESKTOP;
  199341. break;
  199342. case userApplicationDataDirectory:
  199343. csidlType = CSIDL_APPDATA;
  199344. break;
  199345. case commonApplicationDataDirectory:
  199346. csidlType = CSIDL_COMMON_APPDATA;
  199347. break;
  199348. case globalApplicationsDirectory:
  199349. csidlType = CSIDL_PROGRAM_FILES;
  199350. break;
  199351. case userMusicDirectory:
  199352. csidlType = CSIDL_MYMUSIC;
  199353. break;
  199354. case userMoviesDirectory:
  199355. csidlType = CSIDL_MYVIDEO;
  199356. break;
  199357. case tempDirectory:
  199358. {
  199359. WCHAR dest [2048];
  199360. dest[0] = 0;
  199361. GetTempPath (2048, dest);
  199362. return File (String (dest));
  199363. }
  199364. case currentExecutableFile:
  199365. case currentApplicationFile:
  199366. {
  199367. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  199368. WCHAR dest [MAX_PATH_CHARS];
  199369. dest[0] = 0;
  199370. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  199371. return File (String (dest));
  199372. }
  199373. break;
  199374. default:
  199375. jassertfalse // unknown type?
  199376. return File::nonexistent;
  199377. }
  199378. return juce_getSpecialFolderPath (csidlType);
  199379. }
  199380. const File File::getCurrentWorkingDirectory() throw()
  199381. {
  199382. WCHAR dest [MAX_PATH_CHARS];
  199383. dest[0] = 0;
  199384. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  199385. return File (String (dest));
  199386. }
  199387. bool File::setAsCurrentWorkingDirectory() const throw()
  199388. {
  199389. return SetCurrentDirectory (getFullPathName()) != FALSE;
  199390. }
  199391. const String File::getVersion() const throw()
  199392. {
  199393. String result;
  199394. DWORD handle = 0;
  199395. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  199396. void* buffer = juce_calloc (bufferSize);
  199397. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  199398. {
  199399. VS_FIXEDFILEINFO* vffi;
  199400. UINT len = 0;
  199401. if (VerQueryValue (buffer, _T("\\"), (LPVOID*) &vffi, &len))
  199402. {
  199403. result.printf (T("%d.%d.%d.%d"),
  199404. HIWORD (vffi->dwFileVersionMS),
  199405. LOWORD (vffi->dwFileVersionMS),
  199406. HIWORD (vffi->dwFileVersionLS),
  199407. LOWORD (vffi->dwFileVersionLS));
  199408. }
  199409. }
  199410. juce_free (buffer);
  199411. return result;
  199412. }
  199413. const File File::getLinkedTarget() const throw()
  199414. {
  199415. File result (*this);
  199416. String p (getFullPathName());
  199417. if (! exists())
  199418. p += T(".lnk");
  199419. else if (getFileExtension() != T(".lnk"))
  199420. return result;
  199421. ComSmartPtr <IShellLink> shellLink;
  199422. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink, CLSCTX_INPROC_SERVER)))
  199423. {
  199424. ComSmartPtr <IPersistFile> persistFile;
  199425. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  199426. {
  199427. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  199428. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  199429. {
  199430. WIN32_FIND_DATA winFindData;
  199431. WCHAR resolvedPath [MAX_PATH];
  199432. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  199433. result = File (resolvedPath);
  199434. }
  199435. }
  199436. }
  199437. return result;
  199438. }
  199439. template <class FindDataType>
  199440. static void getFindFileInfo (FindDataType& findData,
  199441. String& filename, bool* const isDir, bool* const isHidden,
  199442. int64* const fileSize, Time* const modTime, Time* const creationTime,
  199443. bool* const isReadOnly) throw()
  199444. {
  199445. filename = findData.cFileName;
  199446. if (isDir != 0)
  199447. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199448. if (isHidden != 0)
  199449. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  199450. if (fileSize != 0)
  199451. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  199452. if (modTime != 0)
  199453. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  199454. if (creationTime != 0)
  199455. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  199456. if (isReadOnly != 0)
  199457. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  199458. }
  199459. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  199460. bool* isDir, bool* isHidden, int64* fileSize,
  199461. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  199462. {
  199463. String wc (directory);
  199464. if (! wc.endsWithChar (File::separator))
  199465. wc += File::separator;
  199466. wc += wildCard;
  199467. WIN32_FIND_DATA findData;
  199468. HANDLE h = FindFirstFile (wc, &findData);
  199469. if (h != INVALID_HANDLE_VALUE)
  199470. {
  199471. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  199472. modTime, creationTime, isReadOnly);
  199473. return h;
  199474. }
  199475. firstResult = String::empty;
  199476. return 0;
  199477. }
  199478. bool juce_findFileNext (void* handle, String& resultFile,
  199479. bool* isDir, bool* isHidden, int64* fileSize,
  199480. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  199481. {
  199482. WIN32_FIND_DATA findData;
  199483. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  199484. {
  199485. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  199486. modTime, creationTime, isReadOnly);
  199487. return true;
  199488. }
  199489. resultFile = String::empty;
  199490. return false;
  199491. }
  199492. void juce_findFileClose (void* handle) throw()
  199493. {
  199494. FindClose (handle);
  199495. }
  199496. bool juce_launchFile (const String& fileName,
  199497. const String& parameters) throw()
  199498. {
  199499. HINSTANCE hInstance = 0;
  199500. JUCE_TRY
  199501. {
  199502. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  199503. }
  199504. JUCE_CATCH_ALL
  199505. return hInstance > (HINSTANCE) 32;
  199506. }
  199507. struct NamedPipeInternal
  199508. {
  199509. HANDLE pipeH;
  199510. HANDLE cancelEvent;
  199511. bool connected, createdPipe;
  199512. NamedPipeInternal()
  199513. : pipeH (0),
  199514. cancelEvent (0),
  199515. connected (false),
  199516. createdPipe (false)
  199517. {
  199518. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  199519. }
  199520. ~NamedPipeInternal()
  199521. {
  199522. disconnect();
  199523. if (pipeH != 0)
  199524. CloseHandle (pipeH);
  199525. CloseHandle (cancelEvent);
  199526. }
  199527. bool connect (const int timeOutMs)
  199528. {
  199529. if (! createdPipe)
  199530. return true;
  199531. if (! connected)
  199532. {
  199533. OVERLAPPED over;
  199534. zerostruct (over);
  199535. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  199536. if (ConnectNamedPipe (pipeH, &over))
  199537. {
  199538. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  199539. }
  199540. else
  199541. {
  199542. const int err = GetLastError();
  199543. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  199544. {
  199545. HANDLE handles[] = { over.hEvent, cancelEvent };
  199546. if (WaitForMultipleObjects (2, handles, FALSE,
  199547. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  199548. connected = true;
  199549. }
  199550. else if (err == ERROR_PIPE_CONNECTED)
  199551. {
  199552. connected = true;
  199553. }
  199554. }
  199555. CloseHandle (over.hEvent);
  199556. }
  199557. return connected;
  199558. }
  199559. void disconnect()
  199560. {
  199561. if (connected)
  199562. {
  199563. DisconnectNamedPipe (pipeH);
  199564. connected = false;
  199565. }
  199566. }
  199567. };
  199568. void NamedPipe::close()
  199569. {
  199570. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  199571. delete intern;
  199572. internal = 0;
  199573. }
  199574. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  199575. {
  199576. close();
  199577. NamedPipeInternal* const intern = new NamedPipeInternal();
  199578. String file ("\\\\.\\pipe\\");
  199579. file += pipeName;
  199580. intern->createdPipe = createPipe;
  199581. if (createPipe)
  199582. {
  199583. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  199584. PIPE_UNLIMITED_INSTANCES,
  199585. 4096, 4096, 0, NULL);
  199586. }
  199587. else
  199588. {
  199589. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  199590. FILE_FLAG_OVERLAPPED, 0);
  199591. }
  199592. if (intern->pipeH != INVALID_HANDLE_VALUE)
  199593. {
  199594. internal = intern;
  199595. return true;
  199596. }
  199597. delete intern;
  199598. return false;
  199599. }
  199600. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  199601. {
  199602. int bytesRead = -1;
  199603. bool waitAgain = true;
  199604. while (waitAgain && internal != 0)
  199605. {
  199606. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  199607. waitAgain = false;
  199608. if (! intern->connect (timeOutMilliseconds))
  199609. break;
  199610. if (maxBytesToRead <= 0)
  199611. return 0;
  199612. OVERLAPPED over;
  199613. zerostruct (over);
  199614. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  199615. unsigned long numRead;
  199616. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  199617. {
  199618. bytesRead = (int) numRead;
  199619. }
  199620. else if (GetLastError() == ERROR_IO_PENDING)
  199621. {
  199622. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  199623. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  199624. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  199625. : INFINITE);
  199626. if (waitResult != WAIT_OBJECT_0)
  199627. {
  199628. // if the operation timed out, let's cancel it...
  199629. CancelIo (intern->pipeH);
  199630. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  199631. }
  199632. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  199633. {
  199634. bytesRead = (int) numRead;
  199635. }
  199636. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  199637. {
  199638. intern->disconnect();
  199639. waitAgain = true;
  199640. }
  199641. }
  199642. else
  199643. {
  199644. waitAgain = internal != 0;
  199645. Sleep (5);
  199646. }
  199647. CloseHandle (over.hEvent);
  199648. }
  199649. return bytesRead;
  199650. }
  199651. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  199652. {
  199653. int bytesWritten = -1;
  199654. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  199655. if (intern != 0 && intern->connect (timeOutMilliseconds))
  199656. {
  199657. if (numBytesToWrite <= 0)
  199658. return 0;
  199659. OVERLAPPED over;
  199660. zerostruct (over);
  199661. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  199662. unsigned long numWritten;
  199663. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  199664. {
  199665. bytesWritten = (int) numWritten;
  199666. }
  199667. else if (GetLastError() == ERROR_IO_PENDING)
  199668. {
  199669. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  199670. DWORD waitResult;
  199671. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  199672. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  199673. : INFINITE);
  199674. if (waitResult != WAIT_OBJECT_0)
  199675. {
  199676. CancelIo (intern->pipeH);
  199677. WaitForSingleObject (over.hEvent, INFINITE);
  199678. }
  199679. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  199680. {
  199681. bytesWritten = (int) numWritten;
  199682. }
  199683. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  199684. {
  199685. intern->disconnect();
  199686. }
  199687. }
  199688. CloseHandle (over.hEvent);
  199689. }
  199690. return bytesWritten;
  199691. }
  199692. void NamedPipe::cancelPendingReads()
  199693. {
  199694. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  199695. if (intern != 0)
  199696. SetEvent (intern->cancelEvent);
  199697. }
  199698. #endif
  199699. /********* End of inlined file: juce_win32_Files.cpp *********/
  199700. /********* Start of inlined file: juce_win32_Network.cpp *********/
  199701. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199702. // compiled on its own).
  199703. #if JUCE_INCLUDED_FILE
  199704. #ifndef INTERNET_FLAG_NEED_FILE
  199705. #define INTERNET_FLAG_NEED_FILE 0x00000010
  199706. #endif
  199707. bool juce_isOnLine()
  199708. {
  199709. DWORD connectionType;
  199710. return InternetGetConnectedState (&connectionType, 0) != 0
  199711. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  199712. }
  199713. struct ConnectionAndRequestStruct
  199714. {
  199715. HINTERNET connection, request;
  199716. };
  199717. static HINTERNET sessionHandle = 0;
  199718. void* juce_openInternetFile (const String& url,
  199719. const String& headers,
  199720. const MemoryBlock& postData,
  199721. const bool isPost,
  199722. URL::OpenStreamProgressCallback* callback,
  199723. void* callbackContext,
  199724. int timeOutMs)
  199725. {
  199726. if (sessionHandle == 0)
  199727. sessionHandle = InternetOpen (_T("juce"),
  199728. INTERNET_OPEN_TYPE_PRECONFIG,
  199729. 0, 0, 0);
  199730. if (sessionHandle != 0)
  199731. {
  199732. // break up the url..
  199733. TCHAR file[1024], server[1024];
  199734. URL_COMPONENTS uc;
  199735. zerostruct (uc);
  199736. uc.dwStructSize = sizeof (uc);
  199737. uc.dwUrlPathLength = sizeof (file);
  199738. uc.dwHostNameLength = sizeof (server);
  199739. uc.lpszUrlPath = file;
  199740. uc.lpszHostName = server;
  199741. if (InternetCrackUrl (url, 0, 0, &uc))
  199742. {
  199743. if (timeOutMs == 0)
  199744. timeOutMs = 30000;
  199745. else if (timeOutMs < 0)
  199746. timeOutMs = -1;
  199747. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  199748. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  199749. HINTERNET connection = InternetConnect (sessionHandle,
  199750. uc.lpszHostName,
  199751. uc.nPort,
  199752. _T(""), _T(""),
  199753. isFtp ? INTERNET_SERVICE_FTP
  199754. : INTERNET_SERVICE_HTTP,
  199755. 0, 0);
  199756. if (connection != 0)
  199757. {
  199758. if (isFtp)
  199759. {
  199760. HINTERNET request = FtpOpenFile (connection,
  199761. uc.lpszUrlPath,
  199762. GENERIC_READ,
  199763. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  199764. 0);
  199765. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  199766. result->connection = connection;
  199767. result->request = request;
  199768. return result;
  199769. }
  199770. else
  199771. {
  199772. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  199773. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  199774. if (url.startsWithIgnoreCase (T("https:")))
  199775. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  199776. // IE7 seems to automatically work out when it's https)
  199777. HINTERNET request = HttpOpenRequest (connection,
  199778. isPost ? _T("POST")
  199779. : _T("GET"),
  199780. uc.lpszUrlPath,
  199781. 0, 0, mimeTypes, flags, 0);
  199782. if (request != 0)
  199783. {
  199784. INTERNET_BUFFERS buffers;
  199785. zerostruct (buffers);
  199786. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  199787. buffers.lpcszHeader = (LPCTSTR) headers;
  199788. buffers.dwHeadersLength = headers.length();
  199789. buffers.dwBufferTotal = (DWORD) postData.getSize();
  199790. ConnectionAndRequestStruct* result = 0;
  199791. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  199792. {
  199793. int bytesSent = 0;
  199794. for (;;)
  199795. {
  199796. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  199797. DWORD bytesDone = 0;
  199798. if (bytesToDo > 0
  199799. && ! InternetWriteFile (request,
  199800. ((const char*) postData.getData()) + bytesSent,
  199801. bytesToDo, &bytesDone))
  199802. {
  199803. break;
  199804. }
  199805. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  199806. {
  199807. result = new ConnectionAndRequestStruct();
  199808. result->connection = connection;
  199809. result->request = request;
  199810. HttpEndRequest (request, 0, 0, 0);
  199811. return result;
  199812. }
  199813. bytesSent += bytesDone;
  199814. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  199815. break;
  199816. }
  199817. }
  199818. InternetCloseHandle (request);
  199819. }
  199820. InternetCloseHandle (connection);
  199821. }
  199822. }
  199823. }
  199824. }
  199825. return 0;
  199826. }
  199827. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  199828. {
  199829. DWORD bytesRead = 0;
  199830. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  199831. if (crs != 0)
  199832. InternetReadFile (crs->request,
  199833. buffer, bytesToRead,
  199834. &bytesRead);
  199835. return bytesRead;
  199836. }
  199837. int juce_seekInInternetFile (void* handle, int newPosition)
  199838. {
  199839. if (handle != 0)
  199840. {
  199841. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  199842. return InternetSetFilePointer (crs->request,
  199843. newPosition, 0,
  199844. FILE_BEGIN, 0);
  199845. }
  199846. else
  199847. {
  199848. return -1;
  199849. }
  199850. }
  199851. int64 juce_getInternetFileContentLength (void* handle)
  199852. {
  199853. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  199854. if (crs != 0)
  199855. {
  199856. DWORD index = 0;
  199857. DWORD result = 0;
  199858. DWORD size = sizeof (result);
  199859. if (HttpQueryInfo (crs->request,
  199860. HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  199861. &result,
  199862. &size,
  199863. &index))
  199864. {
  199865. return (int64) result;
  199866. }
  199867. }
  199868. return -1;
  199869. }
  199870. void juce_closeInternetFile (void* handle)
  199871. {
  199872. if (handle != 0)
  199873. {
  199874. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  199875. InternetCloseHandle (crs->request);
  199876. InternetCloseHandle (crs->connection);
  199877. delete crs;
  199878. }
  199879. }
  199880. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  199881. {
  199882. int numFound = 0;
  199883. DynamicLibraryLoader dll ("iphlpapi.dll");
  199884. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  199885. if (getAdaptersInfo != 0)
  199886. {
  199887. ULONG len = sizeof (IP_ADAPTER_INFO);
  199888. MemoryBlock mb;
  199889. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  199890. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  199891. {
  199892. mb.setSize (len);
  199893. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  199894. }
  199895. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  199896. {
  199897. PIP_ADAPTER_INFO adapter = adapterInfo;
  199898. while (adapter != 0)
  199899. {
  199900. int64 mac = 0;
  199901. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  199902. mac = (mac << 8) | adapter->Address[i];
  199903. if (littleEndian)
  199904. mac = (int64) swapByteOrder ((uint64) mac);
  199905. if (numFound < maxNum && mac != 0)
  199906. addresses [numFound++] = mac;
  199907. adapter = adapter->Next;
  199908. }
  199909. }
  199910. }
  199911. return numFound;
  199912. }
  199913. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  199914. {
  199915. int numFound = 0;
  199916. DynamicLibraryLoader dll ("netapi32.dll");
  199917. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  199918. if (NetbiosCall != 0)
  199919. {
  199920. NCB ncb;
  199921. zerostruct (ncb);
  199922. typedef struct _ASTAT_
  199923. {
  199924. ADAPTER_STATUS adapt;
  199925. NAME_BUFFER NameBuff [30];
  199926. } ASTAT;
  199927. ASTAT astat;
  199928. zerostruct (astat);
  199929. LANA_ENUM enums;
  199930. zerostruct (enums);
  199931. ncb.ncb_command = NCBENUM;
  199932. ncb.ncb_buffer = (unsigned char*) &enums;
  199933. ncb.ncb_length = sizeof (LANA_ENUM);
  199934. NetbiosCall (&ncb);
  199935. for (int i = 0; i < enums.length; ++i)
  199936. {
  199937. zerostruct (ncb);
  199938. ncb.ncb_command = NCBRESET;
  199939. ncb.ncb_lana_num = enums.lana[i];
  199940. if (NetbiosCall (&ncb) == 0)
  199941. {
  199942. zerostruct (ncb);
  199943. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  199944. ncb.ncb_command = NCBASTAT;
  199945. ncb.ncb_lana_num = enums.lana[i];
  199946. ncb.ncb_buffer = (unsigned char*) &astat;
  199947. ncb.ncb_length = sizeof (ASTAT);
  199948. if (NetbiosCall (&ncb) == 0)
  199949. {
  199950. if (astat.adapt.adapter_type == 0xfe)
  199951. {
  199952. int64 mac = 0;
  199953. for (unsigned int i = 0; i < 6; ++i)
  199954. mac = (mac << 8) | astat.adapt.adapter_address[i];
  199955. if (littleEndian)
  199956. mac = (int64) swapByteOrder ((uint64) mac);
  199957. if (numFound < maxNum && mac != 0)
  199958. addresses [numFound++] = mac;
  199959. }
  199960. }
  199961. }
  199962. }
  199963. }
  199964. return numFound;
  199965. }
  199966. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  199967. {
  199968. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  199969. if (numFound == 0)
  199970. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  199971. return numFound;
  199972. }
  199973. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  199974. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  199975. const String& emailSubject,
  199976. const String& bodyText,
  199977. const StringArray& filesToAttach)
  199978. {
  199979. HMODULE h = LoadLibraryA ("MAPI32.dll");
  199980. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  199981. bool ok = false;
  199982. if (mapiSendMail != 0)
  199983. {
  199984. MapiMessage message;
  199985. zerostruct (message);
  199986. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  199987. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  199988. MapiRecipDesc recip;
  199989. zerostruct (recip);
  199990. recip.ulRecipClass = MAPI_TO;
  199991. String targetEmailAddress_ (targetEmailAddress);
  199992. if (targetEmailAddress_.isEmpty())
  199993. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  199994. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress_;
  199995. message.nRecipCount = 1;
  199996. message.lpRecips = &recip;
  199997. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  199998. mb.fillWith (0);
  199999. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  200000. message.nFileCount = filesToAttach.size();
  200001. message.lpFiles = files;
  200002. for (int i = 0; i < filesToAttach.size(); ++i)
  200003. {
  200004. files[i].nPosition = (ULONG) -1;
  200005. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  200006. }
  200007. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  200008. }
  200009. FreeLibrary (h);
  200010. return ok;
  200011. }
  200012. #endif
  200013. /********* End of inlined file: juce_win32_Network.cpp *********/
  200014. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  200015. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200016. // compiled on its own).
  200017. #if JUCE_INCLUDED_FILE
  200018. static HKEY findKeyForPath (String name,
  200019. const bool createForWriting,
  200020. String& valueName) throw()
  200021. {
  200022. HKEY rootKey = 0;
  200023. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  200024. rootKey = HKEY_CURRENT_USER;
  200025. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  200026. rootKey = HKEY_LOCAL_MACHINE;
  200027. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  200028. rootKey = HKEY_CLASSES_ROOT;
  200029. if (rootKey != 0)
  200030. {
  200031. name = name.substring (name.indexOfChar (T('\\')) + 1);
  200032. const int lastSlash = name.lastIndexOfChar (T('\\'));
  200033. valueName = name.substring (lastSlash + 1);
  200034. name = name.substring (0, lastSlash);
  200035. HKEY key;
  200036. DWORD result;
  200037. if (createForWriting)
  200038. {
  200039. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  200040. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  200041. return key;
  200042. }
  200043. else
  200044. {
  200045. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  200046. return key;
  200047. }
  200048. }
  200049. return 0;
  200050. }
  200051. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  200052. const String& defaultValue)
  200053. {
  200054. String valueName, s;
  200055. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200056. if (k != 0)
  200057. {
  200058. WCHAR buffer [2048];
  200059. unsigned long bufferSize = sizeof (buffer);
  200060. DWORD type = REG_SZ;
  200061. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  200062. s = buffer;
  200063. else
  200064. s = defaultValue;
  200065. RegCloseKey (k);
  200066. }
  200067. return s;
  200068. }
  200069. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  200070. const String& value)
  200071. {
  200072. String valueName;
  200073. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200074. if (k != 0)
  200075. {
  200076. RegSetValueEx (k, valueName, 0, REG_SZ,
  200077. (const BYTE*) (const WCHAR*) value,
  200078. sizeof (WCHAR) * (value.length() + 1));
  200079. RegCloseKey (k);
  200080. }
  200081. }
  200082. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  200083. {
  200084. bool exists = false;
  200085. String valueName;
  200086. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200087. if (k != 0)
  200088. {
  200089. unsigned char buffer [2048];
  200090. unsigned long bufferSize = sizeof (buffer);
  200091. DWORD type = 0;
  200092. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  200093. exists = true;
  200094. RegCloseKey (k);
  200095. }
  200096. return exists;
  200097. }
  200098. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  200099. {
  200100. String valueName;
  200101. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200102. if (k != 0)
  200103. {
  200104. RegDeleteValue (k, valueName);
  200105. RegCloseKey (k);
  200106. }
  200107. }
  200108. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  200109. {
  200110. String valueName;
  200111. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  200112. if (k != 0)
  200113. {
  200114. RegDeleteKey (k, valueName);
  200115. RegCloseKey (k);
  200116. }
  200117. }
  200118. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  200119. const String& symbolicDescription,
  200120. const String& fullDescription,
  200121. const File& targetExecutable,
  200122. int iconResourceNumber)
  200123. {
  200124. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  200125. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  200126. if (iconResourceNumber != 0)
  200127. setRegistryValue (key + "\\DefaultIcon\\",
  200128. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  200129. setRegistryValue (key + "\\", fullDescription);
  200130. setRegistryValue (key + "\\shell\\open\\command\\",
  200131. targetExecutable.getFullPathName() + " %1");
  200132. }
  200133. bool juce_IsRunningInWine() throw()
  200134. {
  200135. HKEY key;
  200136. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  200137. {
  200138. RegCloseKey (key);
  200139. return true;
  200140. }
  200141. return false;
  200142. }
  200143. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  200144. {
  200145. String s (::GetCommandLineW());
  200146. StringArray tokens;
  200147. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  200148. return tokens.joinIntoString (T(" "), 1);
  200149. }
  200150. static void* currentModuleHandle = 0;
  200151. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  200152. {
  200153. if (currentModuleHandle == 0)
  200154. currentModuleHandle = GetModuleHandle (0);
  200155. return currentModuleHandle;
  200156. }
  200157. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  200158. {
  200159. currentModuleHandle = newHandle;
  200160. }
  200161. void PlatformUtilities::fpuReset()
  200162. {
  200163. #if JUCE_MSVC
  200164. _clearfp();
  200165. #endif
  200166. }
  200167. void PlatformUtilities::beep()
  200168. {
  200169. MessageBeep (MB_OK);
  200170. }
  200171. #endif
  200172. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  200173. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200174. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  200175. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200176. // compiled on its own).
  200177. #if JUCE_INCLUDED_FILE
  200178. static const unsigned int specialId = WM_APP + 0x4400;
  200179. static const unsigned int broadcastId = WM_APP + 0x4403;
  200180. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  200181. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  200182. HWND juce_messageWindowHandle = 0;
  200183. extern long improbableWindowNumber; // defined in windowing.cpp
  200184. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  200185. const UINT message,
  200186. const WPARAM wParam,
  200187. const LPARAM lParam) throw()
  200188. {
  200189. JUCE_TRY
  200190. {
  200191. if (h == juce_messageWindowHandle)
  200192. {
  200193. if (message == specialCallbackId)
  200194. {
  200195. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  200196. return (LRESULT) (*func) ((void*) lParam);
  200197. }
  200198. else if (message == specialId)
  200199. {
  200200. // these are trapped early in the dispatch call, but must also be checked
  200201. // here in case there are windows modal dialog boxes doing their own
  200202. // dispatch loop and not calling our version
  200203. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  200204. return 0;
  200205. }
  200206. else if (message == broadcastId)
  200207. {
  200208. String* const messageString = (String*) lParam;
  200209. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  200210. delete messageString;
  200211. return 0;
  200212. }
  200213. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  200214. {
  200215. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  200216. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  200217. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  200218. return 0;
  200219. }
  200220. }
  200221. }
  200222. JUCE_CATCH_EXCEPTION
  200223. return DefWindowProc (h, message, wParam, lParam);
  200224. }
  200225. static bool isEventBlockedByModalComps (MSG& m)
  200226. {
  200227. if (Component::getNumCurrentlyModalComponents() == 0
  200228. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  200229. return false;
  200230. switch (m.message)
  200231. {
  200232. case WM_MOUSEMOVE:
  200233. case WM_NCMOUSEMOVE:
  200234. case 0x020A: /* WM_MOUSEWHEEL */
  200235. case 0x020E: /* WM_MOUSEHWHEEL */
  200236. case WM_KEYUP:
  200237. case WM_SYSKEYUP:
  200238. case WM_CHAR:
  200239. case WM_APPCOMMAND:
  200240. case WM_LBUTTONUP:
  200241. case WM_MBUTTONUP:
  200242. case WM_RBUTTONUP:
  200243. case WM_MOUSEACTIVATE:
  200244. case WM_NCMOUSEHOVER:
  200245. case WM_MOUSEHOVER:
  200246. return true;
  200247. case WM_NCLBUTTONDOWN:
  200248. case WM_NCLBUTTONDBLCLK:
  200249. case WM_NCRBUTTONDOWN:
  200250. case WM_NCRBUTTONDBLCLK:
  200251. case WM_NCMBUTTONDOWN:
  200252. case WM_NCMBUTTONDBLCLK:
  200253. case WM_LBUTTONDOWN:
  200254. case WM_LBUTTONDBLCLK:
  200255. case WM_MBUTTONDOWN:
  200256. case WM_MBUTTONDBLCLK:
  200257. case WM_RBUTTONDOWN:
  200258. case WM_RBUTTONDBLCLK:
  200259. case WM_KEYDOWN:
  200260. case WM_SYSKEYDOWN:
  200261. {
  200262. Component* const modal = Component::getCurrentlyModalComponent (0);
  200263. if (modal != 0)
  200264. modal->inputAttemptWhenModal();
  200265. return true;
  200266. }
  200267. default:
  200268. break;
  200269. }
  200270. return false;
  200271. }
  200272. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  200273. {
  200274. MSG m;
  200275. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  200276. return false;
  200277. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  200278. {
  200279. if (m.message == specialId
  200280. && m.hwnd == juce_messageWindowHandle)
  200281. {
  200282. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  200283. }
  200284. else if (! isEventBlockedByModalComps (m))
  200285. {
  200286. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  200287. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  200288. {
  200289. // if it's someone else's window being clicked on, and the focus is
  200290. // currently on a juce window, pass the kb focus over..
  200291. HWND currentFocus = GetFocus();
  200292. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  200293. SetFocus (m.hwnd);
  200294. }
  200295. TranslateMessage (&m);
  200296. DispatchMessage (&m);
  200297. }
  200298. }
  200299. return true;
  200300. }
  200301. bool juce_postMessageToSystemQueue (void* message)
  200302. {
  200303. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  200304. }
  200305. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  200306. void* userData)
  200307. {
  200308. if (MessageManager::getInstance()->isThisTheMessageThread())
  200309. {
  200310. return (*callback) (userData);
  200311. }
  200312. else
  200313. {
  200314. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  200315. // deadlock because the message manager is blocked from running, and can't
  200316. // call your function..
  200317. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  200318. return (void*) SendMessage (juce_messageWindowHandle,
  200319. specialCallbackId,
  200320. (WPARAM) callback,
  200321. (LPARAM) userData);
  200322. }
  200323. }
  200324. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  200325. {
  200326. if (hwnd != juce_messageWindowHandle)
  200327. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  200328. return TRUE;
  200329. }
  200330. void MessageManager::broadcastMessage (const String& value) throw()
  200331. {
  200332. VoidArray windows;
  200333. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  200334. const String localCopy (value);
  200335. COPYDATASTRUCT data;
  200336. data.dwData = broadcastId;
  200337. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  200338. data.lpData = (void*) (const juce_wchar*) localCopy;
  200339. for (int i = windows.size(); --i >= 0;)
  200340. {
  200341. HWND hwnd = (HWND) windows.getUnchecked(i);
  200342. TCHAR windowName [64]; // no need to read longer strings than this
  200343. GetWindowText (hwnd, windowName, 64);
  200344. windowName [63] = 0;
  200345. if (String (windowName) == String (messageWindowName))
  200346. {
  200347. DWORD_PTR result;
  200348. SendMessageTimeout (hwnd, WM_COPYDATA,
  200349. (WPARAM) juce_messageWindowHandle,
  200350. (LPARAM) &data,
  200351. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  200352. 8000,
  200353. &result);
  200354. }
  200355. }
  200356. }
  200357. static const String getMessageWindowClassName()
  200358. {
  200359. // this name has to be different for each app/dll instance because otherwise
  200360. // poor old Win32 can get a bit confused (even despite it not being a process-global
  200361. // window class).
  200362. static int number = 0;
  200363. if (number == 0)
  200364. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  200365. return T("JUCEcs_") + String (number);
  200366. }
  200367. void MessageManager::doPlatformSpecificInitialisation()
  200368. {
  200369. OleInitialize (0);
  200370. const String className (getMessageWindowClassName());
  200371. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200372. WNDCLASSEX wc;
  200373. zerostruct (wc);
  200374. wc.cbSize = sizeof (wc);
  200375. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  200376. wc.cbWndExtra = 4;
  200377. wc.hInstance = hmod;
  200378. wc.lpszClassName = className;
  200379. RegisterClassEx (&wc);
  200380. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  200381. messageWindowName,
  200382. 0, 0, 0, 0, 0, 0, 0,
  200383. hmod, 0);
  200384. }
  200385. void MessageManager::doPlatformSpecificShutdown()
  200386. {
  200387. DestroyWindow (juce_messageWindowHandle);
  200388. UnregisterClass (getMessageWindowClassName(), 0);
  200389. OleUninitialize();
  200390. }
  200391. #endif
  200392. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  200393. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  200394. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200395. // compiled on its own).
  200396. #if JUCE_INCLUDED_FILE
  200397. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  200398. // these are in the windows SDK, but need to be repeated here for GCC..
  200399. #ifndef GET_APPCOMMAND_LPARAM
  200400. #define FAPPCOMMAND_MASK 0xF000
  200401. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  200402. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  200403. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  200404. #define APPCOMMAND_MEDIA_STOP 13
  200405. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  200406. #define WM_APPCOMMAND 0x0319
  200407. #endif
  200408. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  200409. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  200410. extern bool juce_IsRunningInWine() throw();
  200411. #ifndef ULW_ALPHA
  200412. #define ULW_ALPHA 0x00000002
  200413. #endif
  200414. #ifndef AC_SRC_ALPHA
  200415. #define AC_SRC_ALPHA 0x01
  200416. #endif
  200417. #define DEBUG_REPAINT_TIMES 0
  200418. static HPALETTE palette = 0;
  200419. static bool createPaletteIfNeeded = true;
  200420. static bool shouldDeactivateTitleBar = true;
  200421. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  200422. #define WM_TRAYNOTIFY WM_USER + 100
  200423. using ::abs;
  200424. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  200425. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  200426. bool Desktop::canUseSemiTransparentWindows() throw()
  200427. {
  200428. if (updateLayeredWindow == 0)
  200429. {
  200430. if (! juce_IsRunningInWine())
  200431. {
  200432. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  200433. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  200434. }
  200435. }
  200436. return updateLayeredWindow != 0;
  200437. }
  200438. #undef DefWindowProc
  200439. #define DefWindowProc DefWindowProcW
  200440. const int extendedKeyModifier = 0x10000;
  200441. const int KeyPress::spaceKey = VK_SPACE;
  200442. const int KeyPress::returnKey = VK_RETURN;
  200443. const int KeyPress::escapeKey = VK_ESCAPE;
  200444. const int KeyPress::backspaceKey = VK_BACK;
  200445. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  200446. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  200447. const int KeyPress::tabKey = VK_TAB;
  200448. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  200449. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  200450. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  200451. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  200452. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  200453. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  200454. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  200455. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  200456. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  200457. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  200458. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  200459. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  200460. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  200461. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  200462. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  200463. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  200464. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  200465. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  200466. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  200467. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  200468. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  200469. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  200470. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  200471. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  200472. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  200473. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  200474. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  200475. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  200476. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  200477. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  200478. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  200479. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  200480. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  200481. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  200482. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  200483. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  200484. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  200485. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  200486. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  200487. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  200488. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  200489. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  200490. const int KeyPress::playKey = 0x30000;
  200491. const int KeyPress::stopKey = 0x30001;
  200492. const int KeyPress::fastForwardKey = 0x30002;
  200493. const int KeyPress::rewindKey = 0x30003;
  200494. class WindowsBitmapImage : public Image
  200495. {
  200496. public:
  200497. HBITMAP hBitmap;
  200498. BITMAPV4HEADER bitmapInfo;
  200499. HDC hdc;
  200500. unsigned char* bitmapData;
  200501. WindowsBitmapImage (const PixelFormat format_,
  200502. const int w, const int h, const bool clearImage)
  200503. : Image (format_, w, h)
  200504. {
  200505. jassert (format_ == RGB || format_ == ARGB);
  200506. pixelStride = (format_ == RGB) ? 3 : 4;
  200507. zerostruct (bitmapInfo);
  200508. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  200509. bitmapInfo.bV4Width = w;
  200510. bitmapInfo.bV4Height = h;
  200511. bitmapInfo.bV4Planes = 1;
  200512. bitmapInfo.bV4CSType = 1;
  200513. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  200514. if (format_ == ARGB)
  200515. {
  200516. bitmapInfo.bV4AlphaMask = 0xff000000;
  200517. bitmapInfo.bV4RedMask = 0xff0000;
  200518. bitmapInfo.bV4GreenMask = 0xff00;
  200519. bitmapInfo.bV4BlueMask = 0xff;
  200520. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  200521. }
  200522. else
  200523. {
  200524. bitmapInfo.bV4V4Compression = BI_RGB;
  200525. }
  200526. lineStride = -((w * pixelStride + 3) & ~3);
  200527. HDC dc = GetDC (0);
  200528. hdc = CreateCompatibleDC (dc);
  200529. ReleaseDC (0, dc);
  200530. SetMapMode (hdc, MM_TEXT);
  200531. hBitmap = CreateDIBSection (hdc,
  200532. (BITMAPINFO*) &(bitmapInfo),
  200533. DIB_RGB_COLORS,
  200534. (void**) &bitmapData,
  200535. 0, 0);
  200536. SelectObject (hdc, hBitmap);
  200537. if (format_ == ARGB && clearImage)
  200538. zeromem (bitmapData, abs (h * lineStride));
  200539. imageData = bitmapData - (lineStride * (h - 1));
  200540. }
  200541. ~WindowsBitmapImage()
  200542. {
  200543. DeleteDC (hdc);
  200544. DeleteObject (hBitmap);
  200545. imageData = 0; // to stop the base class freeing this
  200546. }
  200547. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  200548. const int x, const int y,
  200549. const RectangleList& maskedRegion) throw()
  200550. {
  200551. static HDRAWDIB hdd = 0;
  200552. static bool needToCreateDrawDib = true;
  200553. if (needToCreateDrawDib)
  200554. {
  200555. needToCreateDrawDib = false;
  200556. HDC dc = GetDC (0);
  200557. const int n = GetDeviceCaps (dc, BITSPIXEL);
  200558. ReleaseDC (0, dc);
  200559. // only open if we're not palettised
  200560. if (n > 8)
  200561. hdd = DrawDibOpen();
  200562. }
  200563. if (createPaletteIfNeeded)
  200564. {
  200565. HDC dc = GetDC (0);
  200566. const int n = GetDeviceCaps (dc, BITSPIXEL);
  200567. ReleaseDC (0, dc);
  200568. if (n <= 8)
  200569. palette = CreateHalftonePalette (dc);
  200570. createPaletteIfNeeded = false;
  200571. }
  200572. if (palette != 0)
  200573. {
  200574. SelectPalette (dc, palette, FALSE);
  200575. RealizePalette (dc);
  200576. SetStretchBltMode (dc, HALFTONE);
  200577. }
  200578. SetMapMode (dc, MM_TEXT);
  200579. if (transparent)
  200580. {
  200581. POINT p, pos;
  200582. SIZE size;
  200583. RECT windowBounds;
  200584. GetWindowRect (hwnd, &windowBounds);
  200585. p.x = -x;
  200586. p.y = -y;
  200587. pos.x = windowBounds.left;
  200588. pos.y = windowBounds.top;
  200589. size.cx = windowBounds.right - windowBounds.left;
  200590. size.cy = windowBounds.bottom - windowBounds.top;
  200591. BLENDFUNCTION bf;
  200592. bf.AlphaFormat = AC_SRC_ALPHA;
  200593. bf.BlendFlags = 0;
  200594. bf.BlendOp = AC_SRC_OVER;
  200595. bf.SourceConstantAlpha = 0xff;
  200596. if (! maskedRegion.isEmpty())
  200597. {
  200598. for (RectangleList::Iterator i (maskedRegion); i.next();)
  200599. {
  200600. const Rectangle& r = *i.getRectangle();
  200601. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  200602. }
  200603. }
  200604. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  200605. }
  200606. else
  200607. {
  200608. int savedDC = 0;
  200609. if (! maskedRegion.isEmpty())
  200610. {
  200611. savedDC = SaveDC (dc);
  200612. for (RectangleList::Iterator i (maskedRegion); i.next();)
  200613. {
  200614. const Rectangle& r = *i.getRectangle();
  200615. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  200616. }
  200617. }
  200618. const int w = getWidth();
  200619. const int h = getHeight();
  200620. if (hdd == 0)
  200621. {
  200622. StretchDIBits (dc,
  200623. x, y, w, h,
  200624. 0, 0, w, h,
  200625. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  200626. DIB_RGB_COLORS, SRCCOPY);
  200627. }
  200628. else
  200629. {
  200630. DrawDibDraw (hdd, dc, x, y, -1, -1,
  200631. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  200632. 0, 0, w, h, 0);
  200633. }
  200634. if (! maskedRegion.isEmpty())
  200635. RestoreDC (dc, savedDC);
  200636. }
  200637. }
  200638. juce_UseDebuggingNewOperator
  200639. private:
  200640. WindowsBitmapImage (const WindowsBitmapImage&);
  200641. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  200642. };
  200643. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  200644. static int currentModifiers = 0;
  200645. static int modifiersAtLastCallback = 0;
  200646. static void updateKeyModifiers() throw()
  200647. {
  200648. currentModifiers &= ~(ModifierKeys::shiftModifier
  200649. | ModifierKeys::ctrlModifier
  200650. | ModifierKeys::altModifier);
  200651. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  200652. currentModifiers |= ModifierKeys::shiftModifier;
  200653. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  200654. currentModifiers |= ModifierKeys::ctrlModifier;
  200655. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  200656. currentModifiers |= ModifierKeys::altModifier;
  200657. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  200658. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  200659. }
  200660. void ModifierKeys::updateCurrentModifiers() throw()
  200661. {
  200662. currentModifierFlags = currentModifiers;
  200663. }
  200664. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  200665. {
  200666. SHORT k = (SHORT) keyCode;
  200667. if ((keyCode & extendedKeyModifier) == 0
  200668. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  200669. k += (SHORT) T('A') - (SHORT) T('a');
  200670. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  200671. (SHORT) '+', VK_OEM_PLUS,
  200672. (SHORT) '-', VK_OEM_MINUS,
  200673. (SHORT) '.', VK_OEM_PERIOD,
  200674. (SHORT) ';', VK_OEM_1,
  200675. (SHORT) ':', VK_OEM_1,
  200676. (SHORT) '/', VK_OEM_2,
  200677. (SHORT) '?', VK_OEM_2,
  200678. (SHORT) '[', VK_OEM_4,
  200679. (SHORT) ']', VK_OEM_6 };
  200680. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  200681. if (k == translatedValues [i])
  200682. k = translatedValues [i + 1];
  200683. return (GetKeyState (k) & 0x8000) != 0;
  200684. }
  200685. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  200686. {
  200687. updateKeyModifiers();
  200688. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  200689. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  200690. currentModifiers |= ModifierKeys::leftButtonModifier;
  200691. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  200692. currentModifiers |= ModifierKeys::rightButtonModifier;
  200693. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  200694. currentModifiers |= ModifierKeys::middleButtonModifier;
  200695. return ModifierKeys (currentModifiers);
  200696. }
  200697. static int64 getMouseEventTime() throw()
  200698. {
  200699. static int64 eventTimeOffset = 0;
  200700. static DWORD lastMessageTime = 0;
  200701. const DWORD thisMessageTime = GetMessageTime();
  200702. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  200703. {
  200704. lastMessageTime = thisMessageTime;
  200705. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  200706. }
  200707. return eventTimeOffset + thisMessageTime;
  200708. }
  200709. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  200710. {
  200711. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  200712. return callback (userData);
  200713. else
  200714. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  200715. }
  200716. class Win32ComponentPeer : public ComponentPeer
  200717. {
  200718. public:
  200719. Win32ComponentPeer (Component* const component,
  200720. const int windowStyleFlags)
  200721. : ComponentPeer (component, windowStyleFlags),
  200722. dontRepaint (false),
  200723. fullScreen (false),
  200724. isDragging (false),
  200725. isMouseOver (false),
  200726. hasCreatedCaret (false),
  200727. currentWindowIcon (0),
  200728. taskBarIcon (0),
  200729. dropTarget (0)
  200730. {
  200731. callFunctionIfNotLocked (&createWindowCallback, (void*) this);
  200732. setTitle (component->getName());
  200733. if ((windowStyleFlags & windowHasDropShadow) != 0
  200734. && Desktop::canUseSemiTransparentWindows())
  200735. {
  200736. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  200737. if (shadower != 0)
  200738. shadower->setOwner (component);
  200739. }
  200740. else
  200741. {
  200742. shadower = 0;
  200743. }
  200744. }
  200745. ~Win32ComponentPeer()
  200746. {
  200747. setTaskBarIcon (0);
  200748. deleteAndZero (shadower);
  200749. // do this before the next bit to avoid messages arriving for this window
  200750. // before it's destroyed
  200751. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  200752. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  200753. if (currentWindowIcon != 0)
  200754. DestroyIcon (currentWindowIcon);
  200755. if (dropTarget != 0)
  200756. {
  200757. dropTarget->Release();
  200758. dropTarget = 0;
  200759. }
  200760. }
  200761. void* getNativeHandle() const
  200762. {
  200763. return (void*) hwnd;
  200764. }
  200765. void setVisible (bool shouldBeVisible)
  200766. {
  200767. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  200768. if (shouldBeVisible)
  200769. InvalidateRect (hwnd, 0, 0);
  200770. else
  200771. lastPaintTime = 0;
  200772. }
  200773. void setTitle (const String& title)
  200774. {
  200775. SetWindowText (hwnd, title);
  200776. }
  200777. void setPosition (int x, int y)
  200778. {
  200779. offsetWithinParent (x, y);
  200780. SetWindowPos (hwnd, 0,
  200781. x - windowBorder.getLeft(),
  200782. y - windowBorder.getTop(),
  200783. 0, 0,
  200784. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  200785. }
  200786. void repaintNowIfTransparent()
  200787. {
  200788. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  200789. handlePaintMessage();
  200790. }
  200791. void updateBorderSize()
  200792. {
  200793. WINDOWINFO info;
  200794. info.cbSize = sizeof (info);
  200795. if (GetWindowInfo (hwnd, &info))
  200796. {
  200797. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  200798. info.rcClient.left - info.rcWindow.left,
  200799. info.rcWindow.bottom - info.rcClient.bottom,
  200800. info.rcWindow.right - info.rcClient.right);
  200801. }
  200802. }
  200803. void setSize (int w, int h)
  200804. {
  200805. SetWindowPos (hwnd, 0, 0, 0,
  200806. w + windowBorder.getLeftAndRight(),
  200807. h + windowBorder.getTopAndBottom(),
  200808. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  200809. updateBorderSize();
  200810. repaintNowIfTransparent();
  200811. }
  200812. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  200813. {
  200814. fullScreen = isNowFullScreen;
  200815. offsetWithinParent (x, y);
  200816. SetWindowPos (hwnd, 0,
  200817. x - windowBorder.getLeft(),
  200818. y - windowBorder.getTop(),
  200819. w + windowBorder.getLeftAndRight(),
  200820. h + windowBorder.getTopAndBottom(),
  200821. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  200822. updateBorderSize();
  200823. repaintNowIfTransparent();
  200824. }
  200825. void getBounds (int& x, int& y, int& w, int& h) const
  200826. {
  200827. RECT r;
  200828. GetWindowRect (hwnd, &r);
  200829. x = r.left;
  200830. y = r.top;
  200831. w = r.right - x;
  200832. h = r.bottom - y;
  200833. HWND parentH = GetParent (hwnd);
  200834. if (parentH != 0)
  200835. {
  200836. GetWindowRect (parentH, &r);
  200837. x -= r.left;
  200838. y -= r.top;
  200839. }
  200840. x += windowBorder.getLeft();
  200841. y += windowBorder.getTop();
  200842. w -= windowBorder.getLeftAndRight();
  200843. h -= windowBorder.getTopAndBottom();
  200844. }
  200845. int getScreenX() const
  200846. {
  200847. RECT r;
  200848. GetWindowRect (hwnd, &r);
  200849. return r.left + windowBorder.getLeft();
  200850. }
  200851. int getScreenY() const
  200852. {
  200853. RECT r;
  200854. GetWindowRect (hwnd, &r);
  200855. return r.top + windowBorder.getTop();
  200856. }
  200857. void relativePositionToGlobal (int& x, int& y)
  200858. {
  200859. RECT r;
  200860. GetWindowRect (hwnd, &r);
  200861. x += r.left + windowBorder.getLeft();
  200862. y += r.top + windowBorder.getTop();
  200863. }
  200864. void globalPositionToRelative (int& x, int& y)
  200865. {
  200866. RECT r;
  200867. GetWindowRect (hwnd, &r);
  200868. x -= r.left + windowBorder.getLeft();
  200869. y -= r.top + windowBorder.getTop();
  200870. }
  200871. void setMinimised (bool shouldBeMinimised)
  200872. {
  200873. if (shouldBeMinimised != isMinimised())
  200874. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  200875. }
  200876. bool isMinimised() const
  200877. {
  200878. WINDOWPLACEMENT wp;
  200879. wp.length = sizeof (WINDOWPLACEMENT);
  200880. GetWindowPlacement (hwnd, &wp);
  200881. return wp.showCmd == SW_SHOWMINIMIZED;
  200882. }
  200883. void setFullScreen (bool shouldBeFullScreen)
  200884. {
  200885. setMinimised (false);
  200886. if (fullScreen != shouldBeFullScreen)
  200887. {
  200888. fullScreen = shouldBeFullScreen;
  200889. const ComponentDeletionWatcher deletionChecker (component);
  200890. if (! fullScreen)
  200891. {
  200892. const Rectangle boundsCopy (lastNonFullscreenBounds);
  200893. if (hasTitleBar())
  200894. ShowWindow (hwnd, SW_SHOWNORMAL);
  200895. if (! boundsCopy.isEmpty())
  200896. {
  200897. setBounds (boundsCopy.getX(),
  200898. boundsCopy.getY(),
  200899. boundsCopy.getWidth(),
  200900. boundsCopy.getHeight(),
  200901. false);
  200902. }
  200903. }
  200904. else
  200905. {
  200906. if (hasTitleBar())
  200907. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  200908. else
  200909. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  200910. }
  200911. if (! deletionChecker.hasBeenDeleted())
  200912. handleMovedOrResized();
  200913. }
  200914. }
  200915. bool isFullScreen() const
  200916. {
  200917. if (! hasTitleBar())
  200918. return fullScreen;
  200919. WINDOWPLACEMENT wp;
  200920. wp.length = sizeof (wp);
  200921. GetWindowPlacement (hwnd, &wp);
  200922. return wp.showCmd == SW_SHOWMAXIMIZED;
  200923. }
  200924. bool contains (int x, int y, bool trueIfInAChildWindow) const
  200925. {
  200926. RECT r;
  200927. GetWindowRect (hwnd, &r);
  200928. POINT p;
  200929. p.x = x + r.left + windowBorder.getLeft();
  200930. p.y = y + r.top + windowBorder.getTop();
  200931. HWND w = WindowFromPoint (p);
  200932. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  200933. }
  200934. const BorderSize getFrameSize() const
  200935. {
  200936. return windowBorder;
  200937. }
  200938. bool setAlwaysOnTop (bool alwaysOnTop)
  200939. {
  200940. const bool oldDeactivate = shouldDeactivateTitleBar;
  200941. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  200942. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  200943. 0, 0, 0, 0,
  200944. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  200945. shouldDeactivateTitleBar = oldDeactivate;
  200946. if (shadower != 0)
  200947. shadower->componentBroughtToFront (*component);
  200948. return true;
  200949. }
  200950. void toFront (bool makeActive)
  200951. {
  200952. setMinimised (false);
  200953. const bool oldDeactivate = shouldDeactivateTitleBar;
  200954. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  200955. callFunctionIfNotLocked (makeActive ? &toFrontCallback1
  200956. : &toFrontCallback2,
  200957. (void*) hwnd);
  200958. shouldDeactivateTitleBar = oldDeactivate;
  200959. if (! makeActive)
  200960. {
  200961. // in this case a broughttofront call won't have occured, so do it now..
  200962. handleBroughtToFront();
  200963. }
  200964. }
  200965. void toBehind (ComponentPeer* other)
  200966. {
  200967. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  200968. jassert (otherPeer != 0); // wrong type of window?
  200969. if (otherPeer != 0)
  200970. {
  200971. setMinimised (false);
  200972. // must be careful not to try to put a topmost window behind a normal one, or win32
  200973. // promotes the normal one to be topmost!
  200974. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  200975. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  200976. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  200977. else if (otherPeer->getComponent()->isAlwaysOnTop())
  200978. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  200979. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  200980. }
  200981. }
  200982. bool isFocused() const
  200983. {
  200984. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  200985. }
  200986. void grabFocus()
  200987. {
  200988. const bool oldDeactivate = shouldDeactivateTitleBar;
  200989. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  200990. callFunctionIfNotLocked (&setFocusCallback, (void*) hwnd);
  200991. shouldDeactivateTitleBar = oldDeactivate;
  200992. }
  200993. void textInputRequired (int /*x*/, int /*y*/)
  200994. {
  200995. if (! hasCreatedCaret)
  200996. {
  200997. hasCreatedCaret = true;
  200998. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  200999. }
  201000. ShowCaret (hwnd);
  201001. SetCaretPos (0, 0);
  201002. }
  201003. void repaint (int x, int y, int w, int h)
  201004. {
  201005. const RECT r = { x, y, x + w, y + h };
  201006. InvalidateRect (hwnd, &r, FALSE);
  201007. }
  201008. void performAnyPendingRepaintsNow()
  201009. {
  201010. MSG m;
  201011. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  201012. DispatchMessage (&m);
  201013. }
  201014. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  201015. {
  201016. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  201017. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  201018. return 0;
  201019. }
  201020. void setTaskBarIcon (const Image* const image)
  201021. {
  201022. if (image != 0)
  201023. {
  201024. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  201025. if (taskBarIcon == 0)
  201026. {
  201027. taskBarIcon = new NOTIFYICONDATA();
  201028. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  201029. taskBarIcon->hWnd = (HWND) hwnd;
  201030. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  201031. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  201032. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  201033. taskBarIcon->hIcon = hicon;
  201034. taskBarIcon->szTip[0] = 0;
  201035. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  201036. }
  201037. else
  201038. {
  201039. HICON oldIcon = taskBarIcon->hIcon;
  201040. taskBarIcon->hIcon = hicon;
  201041. taskBarIcon->uFlags = NIF_ICON;
  201042. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201043. DestroyIcon (oldIcon);
  201044. }
  201045. DestroyIcon (hicon);
  201046. }
  201047. else if (taskBarIcon != 0)
  201048. {
  201049. taskBarIcon->uFlags = 0;
  201050. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  201051. DestroyIcon (taskBarIcon->hIcon);
  201052. deleteAndZero (taskBarIcon);
  201053. }
  201054. }
  201055. void setTaskBarIconToolTip (const String& toolTip) const
  201056. {
  201057. if (taskBarIcon != 0)
  201058. {
  201059. taskBarIcon->uFlags = NIF_TIP;
  201060. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  201061. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201062. }
  201063. }
  201064. bool isInside (HWND h) const
  201065. {
  201066. return GetAncestor (hwnd, GA_ROOT) == h;
  201067. }
  201068. juce_UseDebuggingNewOperator
  201069. bool dontRepaint;
  201070. private:
  201071. HWND hwnd;
  201072. DropShadower* shadower;
  201073. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  201074. BorderSize windowBorder;
  201075. HICON currentWindowIcon;
  201076. NOTIFYICONDATA* taskBarIcon;
  201077. IDropTarget* dropTarget;
  201078. class TemporaryImage : public Timer
  201079. {
  201080. public:
  201081. TemporaryImage()
  201082. : image (0)
  201083. {
  201084. }
  201085. ~TemporaryImage()
  201086. {
  201087. delete image;
  201088. }
  201089. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  201090. {
  201091. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  201092. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  201093. {
  201094. delete image;
  201095. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  201096. }
  201097. startTimer (3000);
  201098. return image;
  201099. }
  201100. void timerCallback()
  201101. {
  201102. stopTimer();
  201103. deleteAndZero (image);
  201104. }
  201105. private:
  201106. WindowsBitmapImage* image;
  201107. TemporaryImage (const TemporaryImage&);
  201108. const TemporaryImage& operator= (const TemporaryImage&);
  201109. };
  201110. TemporaryImage offscreenImageGenerator;
  201111. class WindowClassHolder : public DeletedAtShutdown
  201112. {
  201113. public:
  201114. WindowClassHolder()
  201115. : windowClassName ("JUCE_")
  201116. {
  201117. // this name has to be different for each app/dll instance because otherwise
  201118. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201119. // window class).
  201120. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  201121. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201122. TCHAR moduleFile [1024];
  201123. moduleFile[0] = 0;
  201124. GetModuleFileName (moduleHandle, moduleFile, 1024);
  201125. WORD iconNum = 0;
  201126. WNDCLASSEX wcex;
  201127. wcex.cbSize = sizeof (wcex);
  201128. wcex.style = CS_OWNDC;
  201129. wcex.lpfnWndProc = (WNDPROC) windowProc;
  201130. wcex.lpszClassName = windowClassName;
  201131. wcex.cbClsExtra = 0;
  201132. wcex.cbWndExtra = 32;
  201133. wcex.hInstance = moduleHandle;
  201134. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201135. iconNum = 1;
  201136. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201137. wcex.hCursor = 0;
  201138. wcex.hbrBackground = 0;
  201139. wcex.lpszMenuName = 0;
  201140. RegisterClassEx (&wcex);
  201141. }
  201142. ~WindowClassHolder()
  201143. {
  201144. if (ComponentPeer::getNumPeers() == 0)
  201145. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  201146. clearSingletonInstance();
  201147. }
  201148. String windowClassName;
  201149. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  201150. };
  201151. static void* createWindowCallback (void* userData)
  201152. {
  201153. ((Win32ComponentPeer*) userData)->createWindow();
  201154. return 0;
  201155. }
  201156. void createWindow()
  201157. {
  201158. DWORD exstyle = WS_EX_ACCEPTFILES;
  201159. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  201160. if (hasTitleBar())
  201161. {
  201162. type |= WS_OVERLAPPED;
  201163. exstyle |= WS_EX_APPWINDOW;
  201164. if ((styleFlags & windowHasCloseButton) != 0)
  201165. {
  201166. type |= WS_SYSMENU;
  201167. }
  201168. else
  201169. {
  201170. // annoyingly, windows won't let you have a min/max button without a close button
  201171. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  201172. }
  201173. if ((styleFlags & windowIsResizable) != 0)
  201174. type |= WS_THICKFRAME;
  201175. }
  201176. else
  201177. {
  201178. type |= WS_POPUP | WS_SYSMENU;
  201179. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  201180. exstyle |= WS_EX_TOOLWINDOW;
  201181. else
  201182. exstyle |= WS_EX_APPWINDOW;
  201183. }
  201184. if ((styleFlags & windowHasMinimiseButton) != 0)
  201185. type |= WS_MINIMIZEBOX;
  201186. if ((styleFlags & windowHasMaximiseButton) != 0)
  201187. type |= WS_MAXIMIZEBOX;
  201188. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  201189. exstyle |= WS_EX_TRANSPARENT;
  201190. if ((styleFlags & windowIsSemiTransparent) != 0
  201191. && Desktop::canUseSemiTransparentWindows())
  201192. exstyle |= WS_EX_LAYERED;
  201193. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  201194. if (hwnd != 0)
  201195. {
  201196. SetWindowLongPtr (hwnd, 0, 0);
  201197. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  201198. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  201199. if (dropTarget == 0)
  201200. dropTarget = new JuceDropTarget (this);
  201201. RegisterDragDrop (hwnd, dropTarget);
  201202. updateBorderSize();
  201203. // Calling this function here is (for some reason) necessary to make Windows
  201204. // correctly enable the menu items that we specify in the wm_initmenu message.
  201205. GetSystemMenu (hwnd, false);
  201206. }
  201207. else
  201208. {
  201209. jassertfalse
  201210. }
  201211. }
  201212. static void* destroyWindowCallback (void* handle)
  201213. {
  201214. RevokeDragDrop ((HWND) handle);
  201215. DestroyWindow ((HWND) handle);
  201216. return 0;
  201217. }
  201218. static void* toFrontCallback1 (void* h)
  201219. {
  201220. SetForegroundWindow ((HWND) h);
  201221. return 0;
  201222. }
  201223. static void* toFrontCallback2 (void* h)
  201224. {
  201225. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201226. return 0;
  201227. }
  201228. static void* setFocusCallback (void* h)
  201229. {
  201230. SetFocus ((HWND) h);
  201231. return 0;
  201232. }
  201233. static void* getFocusCallback (void*)
  201234. {
  201235. return (void*) GetFocus();
  201236. }
  201237. void offsetWithinParent (int& x, int& y) const
  201238. {
  201239. if (isTransparent())
  201240. {
  201241. HWND parentHwnd = GetParent (hwnd);
  201242. if (parentHwnd != 0)
  201243. {
  201244. RECT parentRect;
  201245. GetWindowRect (parentHwnd, &parentRect);
  201246. x += parentRect.left;
  201247. y += parentRect.top;
  201248. }
  201249. }
  201250. }
  201251. bool isTransparent() const
  201252. {
  201253. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  201254. }
  201255. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  201256. void setIcon (const Image& newIcon)
  201257. {
  201258. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  201259. if (hicon != 0)
  201260. {
  201261. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  201262. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  201263. if (currentWindowIcon != 0)
  201264. DestroyIcon (currentWindowIcon);
  201265. currentWindowIcon = hicon;
  201266. }
  201267. }
  201268. void handlePaintMessage()
  201269. {
  201270. #if DEBUG_REPAINT_TIMES
  201271. const double paintStart = Time::getMillisecondCounterHiRes();
  201272. #endif
  201273. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  201274. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  201275. PAINTSTRUCT paintStruct;
  201276. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  201277. // message and become re-entrant, but that's OK
  201278. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  201279. // corrupt the image it's using to paint into, so do a check here.
  201280. static bool reentrant = false;
  201281. if (reentrant)
  201282. {
  201283. DeleteObject (rgn);
  201284. EndPaint (hwnd, &paintStruct);
  201285. return;
  201286. }
  201287. reentrant = true;
  201288. // this is the rectangle to update..
  201289. int x = paintStruct.rcPaint.left;
  201290. int y = paintStruct.rcPaint.top;
  201291. int w = paintStruct.rcPaint.right - x;
  201292. int h = paintStruct.rcPaint.bottom - y;
  201293. const bool transparent = isTransparent();
  201294. if (transparent)
  201295. {
  201296. // it's not possible to have a transparent window with a title bar at the moment!
  201297. jassert (! hasTitleBar());
  201298. RECT r;
  201299. GetWindowRect (hwnd, &r);
  201300. x = y = 0;
  201301. w = r.right - r.left;
  201302. h = r.bottom - r.top;
  201303. }
  201304. if (w > 0 && h > 0)
  201305. {
  201306. clearMaskedRegion();
  201307. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  201308. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  201309. RectangleList* const contextClip = context.getRawClipRegion();
  201310. contextClip->clear();
  201311. context.setOrigin (-x, -y);
  201312. bool needToPaintAll = true;
  201313. if (regionType == COMPLEXREGION && ! transparent)
  201314. {
  201315. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  201316. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  201317. DeleteObject (clipRgn);
  201318. char rgnData [8192];
  201319. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  201320. if (res > 0 && res <= sizeof (rgnData))
  201321. {
  201322. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  201323. if (hdr->iType == RDH_RECTANGLES
  201324. && hdr->rcBound.right - hdr->rcBound.left >= w
  201325. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  201326. {
  201327. needToPaintAll = false;
  201328. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  201329. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  201330. while (--num >= 0)
  201331. {
  201332. // (need to move this one pixel to the left because of a win32 bug)
  201333. const int cx = jmax (x, rects->left - 1);
  201334. const int cy = rects->top;
  201335. const int cw = rects->right - cx;
  201336. const int ch = rects->bottom - rects->top;
  201337. if (cx + cw - x <= w && cy + ch - y <= h)
  201338. {
  201339. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  201340. }
  201341. else
  201342. {
  201343. needToPaintAll = true;
  201344. break;
  201345. }
  201346. ++rects;
  201347. }
  201348. }
  201349. }
  201350. }
  201351. if (needToPaintAll)
  201352. {
  201353. contextClip->clear();
  201354. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  201355. }
  201356. if (transparent)
  201357. {
  201358. RectangleList::Iterator i (*contextClip);
  201359. while (i.next())
  201360. {
  201361. const Rectangle& r = *i.getRectangle();
  201362. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  201363. }
  201364. }
  201365. // if the component's not opaque, this won't draw properly unless the platform can support this
  201366. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  201367. updateCurrentModifiers();
  201368. handlePaint (context);
  201369. if (! dontRepaint)
  201370. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  201371. }
  201372. DeleteObject (rgn);
  201373. EndPaint (hwnd, &paintStruct);
  201374. reentrant = false;
  201375. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  201376. _fpreset(); // because some graphics cards can unmask FP exceptions
  201377. #endif
  201378. lastPaintTime = Time::getMillisecondCounter();
  201379. #if DEBUG_REPAINT_TIMES
  201380. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  201381. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  201382. #endif
  201383. }
  201384. void doMouseMove (const int x, const int y)
  201385. {
  201386. static uint32 lastMouseTime = 0;
  201387. // this can be set to throttle the mouse-messages to less than a
  201388. // certain number per second, as things can get unresponsive
  201389. // if each drag or move callback has to do a lot of work.
  201390. const int maxMouseMovesPerSecond = 60;
  201391. const int64 mouseEventTime = getMouseEventTime();
  201392. if (! isMouseOver)
  201393. {
  201394. isMouseOver = true;
  201395. TRACKMOUSEEVENT tme;
  201396. tme.cbSize = sizeof (tme);
  201397. tme.dwFlags = TME_LEAVE;
  201398. tme.hwndTrack = hwnd;
  201399. tme.dwHoverTime = 0;
  201400. if (! TrackMouseEvent (&tme))
  201401. {
  201402. jassertfalse;
  201403. }
  201404. updateKeyModifiers();
  201405. handleMouseEnter (x, y, mouseEventTime);
  201406. }
  201407. else if (! isDragging)
  201408. {
  201409. if (((unsigned int) x) < (unsigned int) component->getWidth()
  201410. && ((unsigned int) y) < (unsigned int) component->getHeight())
  201411. {
  201412. RECT r;
  201413. GetWindowRect (hwnd, &r);
  201414. POINT p;
  201415. p.x = x + r.left + windowBorder.getLeft();
  201416. p.y = y + r.top + windowBorder.getTop();
  201417. if (WindowFromPoint (p) == hwnd)
  201418. {
  201419. const uint32 now = Time::getMillisecondCounter();
  201420. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  201421. {
  201422. lastMouseTime = now;
  201423. handleMouseMove (x, y, mouseEventTime);
  201424. }
  201425. }
  201426. }
  201427. }
  201428. else
  201429. {
  201430. const uint32 now = Time::getMillisecondCounter();
  201431. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  201432. {
  201433. lastMouseTime = now;
  201434. handleMouseDrag (x, y, mouseEventTime);
  201435. }
  201436. }
  201437. }
  201438. void doMouseDown (const int x, const int y, const WPARAM wParam)
  201439. {
  201440. if (GetCapture() != hwnd)
  201441. SetCapture (hwnd);
  201442. doMouseMove (x, y);
  201443. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201444. if ((wParam & MK_LBUTTON) != 0)
  201445. currentModifiers |= ModifierKeys::leftButtonModifier;
  201446. if ((wParam & MK_RBUTTON) != 0)
  201447. currentModifiers |= ModifierKeys::rightButtonModifier;
  201448. if ((wParam & MK_MBUTTON) != 0)
  201449. currentModifiers |= ModifierKeys::middleButtonModifier;
  201450. updateKeyModifiers();
  201451. isDragging = true;
  201452. handleMouseDown (x, y, getMouseEventTime());
  201453. }
  201454. void doMouseUp (const int x, const int y, const WPARAM wParam)
  201455. {
  201456. int numButtons = 0;
  201457. if ((wParam & MK_LBUTTON) != 0)
  201458. ++numButtons;
  201459. if ((wParam & MK_RBUTTON) != 0)
  201460. ++numButtons;
  201461. if ((wParam & MK_MBUTTON) != 0)
  201462. ++numButtons;
  201463. const int oldModifiers = currentModifiers;
  201464. // update the currentmodifiers only after the callback, so the callback
  201465. // knows which button was released.
  201466. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201467. if ((wParam & MK_LBUTTON) != 0)
  201468. currentModifiers |= ModifierKeys::leftButtonModifier;
  201469. if ((wParam & MK_RBUTTON) != 0)
  201470. currentModifiers |= ModifierKeys::rightButtonModifier;
  201471. if ((wParam & MK_MBUTTON) != 0)
  201472. currentModifiers |= ModifierKeys::middleButtonModifier;
  201473. updateKeyModifiers();
  201474. isDragging = false;
  201475. // release the mouse capture if the user's not still got a button down
  201476. if (numButtons == 0 && hwnd == GetCapture())
  201477. ReleaseCapture();
  201478. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  201479. }
  201480. void doCaptureChanged()
  201481. {
  201482. if (isDragging)
  201483. {
  201484. RECT wr;
  201485. GetWindowRect (hwnd, &wr);
  201486. const DWORD mp = GetMessagePos();
  201487. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  201488. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  201489. (WPARAM) getMouseEventTime());
  201490. }
  201491. }
  201492. void doMouseExit()
  201493. {
  201494. if (isMouseOver)
  201495. {
  201496. isMouseOver = false;
  201497. RECT wr;
  201498. GetWindowRect (hwnd, &wr);
  201499. const DWORD mp = GetMessagePos();
  201500. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  201501. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  201502. getMouseEventTime());
  201503. }
  201504. }
  201505. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  201506. {
  201507. updateKeyModifiers();
  201508. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  201509. handleMouseWheel (isVertical ? 0 : amount,
  201510. isVertical ? amount : 0,
  201511. getMouseEventTime());
  201512. }
  201513. void sendModifierKeyChangeIfNeeded()
  201514. {
  201515. if (modifiersAtLastCallback != currentModifiers)
  201516. {
  201517. modifiersAtLastCallback = currentModifiers;
  201518. handleModifierKeysChange();
  201519. }
  201520. }
  201521. bool doKeyUp (const WPARAM key)
  201522. {
  201523. updateKeyModifiers();
  201524. switch (key)
  201525. {
  201526. case VK_SHIFT:
  201527. case VK_CONTROL:
  201528. case VK_MENU:
  201529. case VK_CAPITAL:
  201530. case VK_LWIN:
  201531. case VK_RWIN:
  201532. case VK_APPS:
  201533. case VK_NUMLOCK:
  201534. case VK_SCROLL:
  201535. case VK_LSHIFT:
  201536. case VK_RSHIFT:
  201537. case VK_LCONTROL:
  201538. case VK_LMENU:
  201539. case VK_RCONTROL:
  201540. case VK_RMENU:
  201541. sendModifierKeyChangeIfNeeded();
  201542. }
  201543. return handleKeyUpOrDown (false)
  201544. || Component::getCurrentlyModalComponent() != 0;
  201545. }
  201546. bool doKeyDown (const WPARAM key)
  201547. {
  201548. updateKeyModifiers();
  201549. bool used = false;
  201550. switch (key)
  201551. {
  201552. case VK_SHIFT:
  201553. case VK_LSHIFT:
  201554. case VK_RSHIFT:
  201555. case VK_CONTROL:
  201556. case VK_LCONTROL:
  201557. case VK_RCONTROL:
  201558. case VK_MENU:
  201559. case VK_LMENU:
  201560. case VK_RMENU:
  201561. case VK_LWIN:
  201562. case VK_RWIN:
  201563. case VK_CAPITAL:
  201564. case VK_NUMLOCK:
  201565. case VK_SCROLL:
  201566. case VK_APPS:
  201567. sendModifierKeyChangeIfNeeded();
  201568. break;
  201569. case VK_LEFT:
  201570. case VK_RIGHT:
  201571. case VK_UP:
  201572. case VK_DOWN:
  201573. case VK_PRIOR:
  201574. case VK_NEXT:
  201575. case VK_HOME:
  201576. case VK_END:
  201577. case VK_DELETE:
  201578. case VK_INSERT:
  201579. case VK_F1:
  201580. case VK_F2:
  201581. case VK_F3:
  201582. case VK_F4:
  201583. case VK_F5:
  201584. case VK_F6:
  201585. case VK_F7:
  201586. case VK_F8:
  201587. case VK_F9:
  201588. case VK_F10:
  201589. case VK_F11:
  201590. case VK_F12:
  201591. case VK_F13:
  201592. case VK_F14:
  201593. case VK_F15:
  201594. case VK_F16:
  201595. used = handleKeyUpOrDown (true);
  201596. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  201597. break;
  201598. case VK_ADD:
  201599. case VK_SUBTRACT:
  201600. case VK_MULTIPLY:
  201601. case VK_DIVIDE:
  201602. case VK_SEPARATOR:
  201603. case VK_DECIMAL:
  201604. used = handleKeyUpOrDown (true);
  201605. break;
  201606. default:
  201607. used = handleKeyUpOrDown (true);
  201608. {
  201609. MSG msg;
  201610. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  201611. {
  201612. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  201613. // manually generate the key-press event that matches this key-down.
  201614. const UINT keyChar = MapVirtualKey (key, 2);
  201615. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  201616. }
  201617. }
  201618. break;
  201619. }
  201620. if (Component::getCurrentlyModalComponent() != 0)
  201621. used = true;
  201622. return used;
  201623. }
  201624. bool doKeyChar (int key, const LPARAM flags)
  201625. {
  201626. updateKeyModifiers();
  201627. juce_wchar textChar = (juce_wchar) key;
  201628. const int virtualScanCode = (flags >> 16) & 0xff;
  201629. if (key >= '0' && key <= '9')
  201630. {
  201631. switch (virtualScanCode) // check for a numeric keypad scan-code
  201632. {
  201633. case 0x52:
  201634. case 0x4f:
  201635. case 0x50:
  201636. case 0x51:
  201637. case 0x4b:
  201638. case 0x4c:
  201639. case 0x4d:
  201640. case 0x47:
  201641. case 0x48:
  201642. case 0x49:
  201643. key = (key - '0') + KeyPress::numberPad0;
  201644. break;
  201645. default:
  201646. break;
  201647. }
  201648. }
  201649. else
  201650. {
  201651. // convert the scan code to an unmodified character code..
  201652. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  201653. UINT keyChar = MapVirtualKey (virtualKey, 2);
  201654. keyChar = LOWORD (keyChar);
  201655. if (keyChar != 0)
  201656. key = (int) keyChar;
  201657. // avoid sending junk text characters for some control-key combinations
  201658. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  201659. textChar = 0;
  201660. }
  201661. return handleKeyPress (key, textChar);
  201662. }
  201663. bool doAppCommand (const LPARAM lParam)
  201664. {
  201665. int key = 0;
  201666. switch (GET_APPCOMMAND_LPARAM (lParam))
  201667. {
  201668. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  201669. key = KeyPress::playKey;
  201670. break;
  201671. case APPCOMMAND_MEDIA_STOP:
  201672. key = KeyPress::stopKey;
  201673. break;
  201674. case APPCOMMAND_MEDIA_NEXTTRACK:
  201675. key = KeyPress::fastForwardKey;
  201676. break;
  201677. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  201678. key = KeyPress::rewindKey;
  201679. break;
  201680. }
  201681. if (key != 0)
  201682. {
  201683. updateKeyModifiers();
  201684. if (hwnd == GetActiveWindow())
  201685. {
  201686. handleKeyPress (key, 0);
  201687. return true;
  201688. }
  201689. }
  201690. return false;
  201691. }
  201692. class JuceDropTarget : public IDropTarget
  201693. {
  201694. public:
  201695. JuceDropTarget (Win32ComponentPeer* const owner_)
  201696. : owner (owner_),
  201697. refCount (1)
  201698. {
  201699. }
  201700. virtual ~JuceDropTarget()
  201701. {
  201702. jassert (refCount == 0);
  201703. }
  201704. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  201705. {
  201706. if (id == IID_IUnknown || id == IID_IDropTarget)
  201707. {
  201708. AddRef();
  201709. *result = this;
  201710. return S_OK;
  201711. }
  201712. *result = 0;
  201713. return E_NOINTERFACE;
  201714. }
  201715. ULONG __stdcall AddRef() { return ++refCount; }
  201716. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  201717. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  201718. {
  201719. updateFileList (pDataObject);
  201720. int x = mousePos.x, y = mousePos.y;
  201721. owner->globalPositionToRelative (x, y);
  201722. owner->handleFileDragMove (files, x, y);
  201723. *pdwEffect = DROPEFFECT_COPY;
  201724. return S_OK;
  201725. }
  201726. HRESULT __stdcall DragLeave()
  201727. {
  201728. owner->handleFileDragExit (files);
  201729. return S_OK;
  201730. }
  201731. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  201732. {
  201733. int x = mousePos.x, y = mousePos.y;
  201734. owner->globalPositionToRelative (x, y);
  201735. owner->handleFileDragMove (files, x, y);
  201736. *pdwEffect = DROPEFFECT_COPY;
  201737. return S_OK;
  201738. }
  201739. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  201740. {
  201741. updateFileList (pDataObject);
  201742. int x = mousePos.x, y = mousePos.y;
  201743. owner->globalPositionToRelative (x, y);
  201744. owner->handleFileDragDrop (files, x, y);
  201745. *pdwEffect = DROPEFFECT_COPY;
  201746. return S_OK;
  201747. }
  201748. private:
  201749. Win32ComponentPeer* const owner;
  201750. int refCount;
  201751. StringArray files;
  201752. void updateFileList (IDataObject* const pDataObject)
  201753. {
  201754. files.clear();
  201755. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  201756. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  201757. if (pDataObject->GetData (&format, &medium) == S_OK)
  201758. {
  201759. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  201760. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  201761. unsigned int i = 0;
  201762. if (pDropFiles->fWide)
  201763. {
  201764. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  201765. for (;;)
  201766. {
  201767. unsigned int len = 0;
  201768. while (i + len < totalLen && fname [i + len] != 0)
  201769. ++len;
  201770. if (len == 0)
  201771. break;
  201772. files.add (String (fname + i, len));
  201773. i += len + 1;
  201774. }
  201775. }
  201776. else
  201777. {
  201778. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  201779. for (;;)
  201780. {
  201781. unsigned int len = 0;
  201782. while (i + len < totalLen && fname [i + len] != 0)
  201783. ++len;
  201784. if (len == 0)
  201785. break;
  201786. files.add (String (fname + i, len));
  201787. i += len + 1;
  201788. }
  201789. }
  201790. GlobalUnlock (medium.hGlobal);
  201791. }
  201792. }
  201793. JuceDropTarget (const JuceDropTarget&);
  201794. const JuceDropTarget& operator= (const JuceDropTarget&);
  201795. };
  201796. void doSettingChange()
  201797. {
  201798. Desktop::getInstance().refreshMonitorSizes();
  201799. if (fullScreen && ! isMinimised())
  201800. {
  201801. const Rectangle r (component->getParentMonitorArea());
  201802. SetWindowPos (hwnd, 0,
  201803. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  201804. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  201805. }
  201806. }
  201807. public:
  201808. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  201809. {
  201810. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  201811. if (peer != 0)
  201812. return peer->peerWindowProc (h, message, wParam, lParam);
  201813. return DefWindowProc (h, message, wParam, lParam);
  201814. }
  201815. private:
  201816. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  201817. {
  201818. {
  201819. if (isValidPeer (this))
  201820. {
  201821. switch (message)
  201822. {
  201823. case WM_NCHITTEST:
  201824. if (hasTitleBar())
  201825. break;
  201826. return HTCLIENT;
  201827. case WM_PAINT:
  201828. handlePaintMessage();
  201829. return 0;
  201830. case WM_NCPAINT:
  201831. if (wParam != 1)
  201832. handlePaintMessage();
  201833. if (hasTitleBar())
  201834. break;
  201835. return 0;
  201836. case WM_ERASEBKGND:
  201837. case WM_NCCALCSIZE:
  201838. if (hasTitleBar())
  201839. break;
  201840. return 1;
  201841. case WM_MOUSEMOVE:
  201842. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  201843. return 0;
  201844. case WM_MOUSELEAVE:
  201845. doMouseExit();
  201846. return 0;
  201847. case WM_LBUTTONDOWN:
  201848. case WM_MBUTTONDOWN:
  201849. case WM_RBUTTONDOWN:
  201850. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  201851. return 0;
  201852. case WM_LBUTTONUP:
  201853. case WM_MBUTTONUP:
  201854. case WM_RBUTTONUP:
  201855. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  201856. return 0;
  201857. case WM_CAPTURECHANGED:
  201858. doCaptureChanged();
  201859. return 0;
  201860. case WM_NCMOUSEMOVE:
  201861. if (hasTitleBar())
  201862. break;
  201863. return 0;
  201864. case 0x020A: /* WM_MOUSEWHEEL */
  201865. doMouseWheel (wParam, true);
  201866. return 0;
  201867. case 0x020E: /* WM_MOUSEHWHEEL */
  201868. doMouseWheel (wParam, false);
  201869. return 0;
  201870. case WM_WINDOWPOSCHANGING:
  201871. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  201872. {
  201873. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  201874. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  201875. {
  201876. if (constrainer != 0)
  201877. {
  201878. const Rectangle current (component->getX() - windowBorder.getLeft(),
  201879. component->getY() - windowBorder.getTop(),
  201880. component->getWidth() + windowBorder.getLeftAndRight(),
  201881. component->getHeight() + windowBorder.getTopAndBottom());
  201882. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  201883. current,
  201884. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  201885. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  201886. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  201887. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  201888. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  201889. }
  201890. }
  201891. }
  201892. return 0;
  201893. case WM_WINDOWPOSCHANGED:
  201894. handleMovedOrResized();
  201895. if (dontRepaint)
  201896. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  201897. else
  201898. return 0;
  201899. case WM_KEYDOWN:
  201900. case WM_SYSKEYDOWN:
  201901. if (doKeyDown (wParam))
  201902. return 0;
  201903. break;
  201904. case WM_KEYUP:
  201905. case WM_SYSKEYUP:
  201906. if (doKeyUp (wParam))
  201907. return 0;
  201908. break;
  201909. case WM_CHAR:
  201910. if (doKeyChar ((int) wParam, lParam))
  201911. return 0;
  201912. break;
  201913. case WM_APPCOMMAND:
  201914. if (doAppCommand (lParam))
  201915. return TRUE;
  201916. break;
  201917. case WM_SETFOCUS:
  201918. updateKeyModifiers();
  201919. handleFocusGain();
  201920. break;
  201921. case WM_KILLFOCUS:
  201922. if (hasCreatedCaret)
  201923. {
  201924. hasCreatedCaret = false;
  201925. DestroyCaret();
  201926. }
  201927. handleFocusLoss();
  201928. break;
  201929. case WM_ACTIVATEAPP:
  201930. // Windows does weird things to process priority when you swap apps,
  201931. // so this forces an update when the app is brought to the front
  201932. if (wParam != FALSE)
  201933. juce_repeatLastProcessPriority();
  201934. else
  201935. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  201936. juce_CheckCurrentlyFocusedTopLevelWindow();
  201937. modifiersAtLastCallback = -1;
  201938. return 0;
  201939. case WM_ACTIVATE:
  201940. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  201941. {
  201942. modifiersAtLastCallback = -1;
  201943. updateKeyModifiers();
  201944. if (isMinimised())
  201945. {
  201946. component->repaint();
  201947. handleMovedOrResized();
  201948. if (! isValidMessageListener())
  201949. return 0;
  201950. }
  201951. if (LOWORD (wParam) == WA_CLICKACTIVE
  201952. && component->isCurrentlyBlockedByAnotherModalComponent())
  201953. {
  201954. int mx, my;
  201955. component->getMouseXYRelative (mx, my);
  201956. Component* const underMouse = component->getComponentAt (mx, my);
  201957. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  201958. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  201959. return 0;
  201960. }
  201961. handleBroughtToFront();
  201962. if (component->isCurrentlyBlockedByAnotherModalComponent())
  201963. Component::getCurrentlyModalComponent()->toFront (true);
  201964. return 0;
  201965. }
  201966. break;
  201967. case WM_NCACTIVATE:
  201968. // while a temporary window is being shown, prevent Windows from deactivating the
  201969. // title bars of our main windows.
  201970. if (wParam == 0 && ! shouldDeactivateTitleBar)
  201971. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  201972. break;
  201973. case WM_MOUSEACTIVATE:
  201974. if (! component->getMouseClickGrabsKeyboardFocus())
  201975. return MA_NOACTIVATE;
  201976. break;
  201977. case WM_SHOWWINDOW:
  201978. if (wParam != 0)
  201979. handleBroughtToFront();
  201980. break;
  201981. case WM_CLOSE:
  201982. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  201983. handleUserClosingWindow();
  201984. return 0;
  201985. case WM_QUIT:
  201986. if (JUCEApplication::getInstance() != 0)
  201987. JUCEApplication::getInstance()->systemRequestedQuit();
  201988. return 0;
  201989. case WM_QUERYENDSESSION:
  201990. if (JUCEApplication::getInstance() != 0)
  201991. {
  201992. JUCEApplication::getInstance()->systemRequestedQuit();
  201993. return MessageManager::getInstance()->hasStopMessageBeenSent();
  201994. }
  201995. return TRUE;
  201996. case WM_TRAYNOTIFY:
  201997. if (component->isCurrentlyBlockedByAnotherModalComponent())
  201998. {
  201999. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  202000. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202001. {
  202002. Component* const current = Component::getCurrentlyModalComponent();
  202003. if (current != 0)
  202004. current->inputAttemptWhenModal();
  202005. }
  202006. }
  202007. else
  202008. {
  202009. const int oldModifiers = currentModifiers;
  202010. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  202011. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  202012. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  202013. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  202014. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  202015. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  202016. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  202017. {
  202018. SetFocus (hwnd);
  202019. SetForegroundWindow (hwnd);
  202020. component->mouseDown (e);
  202021. }
  202022. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  202023. {
  202024. e.mods = ModifierKeys (oldModifiers);
  202025. component->mouseUp (e);
  202026. }
  202027. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202028. {
  202029. e.mods = ModifierKeys (oldModifiers);
  202030. component->mouseDoubleClick (e);
  202031. }
  202032. else if (lParam == WM_MOUSEMOVE)
  202033. {
  202034. component->mouseMove (e);
  202035. }
  202036. }
  202037. break;
  202038. case WM_SYNCPAINT:
  202039. return 0;
  202040. case WM_PALETTECHANGED:
  202041. InvalidateRect (h, 0, 0);
  202042. break;
  202043. case WM_DISPLAYCHANGE:
  202044. InvalidateRect (h, 0, 0);
  202045. createPaletteIfNeeded = true;
  202046. // intentional fall-through...
  202047. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  202048. doSettingChange();
  202049. break;
  202050. case WM_INITMENU:
  202051. if (! hasTitleBar())
  202052. {
  202053. if (isFullScreen())
  202054. {
  202055. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  202056. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  202057. }
  202058. else if (! isMinimised())
  202059. {
  202060. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  202061. }
  202062. }
  202063. break;
  202064. case WM_SYSCOMMAND:
  202065. switch (wParam & 0xfff0)
  202066. {
  202067. case SC_CLOSE:
  202068. if (sendInputAttemptWhenModalMessage())
  202069. return 0;
  202070. if (hasTitleBar())
  202071. {
  202072. PostMessage (h, WM_CLOSE, 0, 0);
  202073. return 0;
  202074. }
  202075. break;
  202076. case SC_KEYMENU:
  202077. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  202078. // obscure situations that can arise if a modal loop is started from an alt-key
  202079. // keypress).
  202080. if (hasTitleBar() && h == GetCapture())
  202081. ReleaseCapture();
  202082. break;
  202083. case SC_MAXIMIZE:
  202084. if (sendInputAttemptWhenModalMessage())
  202085. return 0;
  202086. setFullScreen (true);
  202087. return 0;
  202088. case SC_MINIMIZE:
  202089. if (sendInputAttemptWhenModalMessage())
  202090. return 0;
  202091. if (! hasTitleBar())
  202092. {
  202093. setMinimised (true);
  202094. return 0;
  202095. }
  202096. break;
  202097. case SC_RESTORE:
  202098. if (sendInputAttemptWhenModalMessage())
  202099. return 0;
  202100. if (hasTitleBar())
  202101. {
  202102. if (isFullScreen())
  202103. {
  202104. setFullScreen (false);
  202105. return 0;
  202106. }
  202107. }
  202108. else
  202109. {
  202110. if (isMinimised())
  202111. setMinimised (false);
  202112. else if (isFullScreen())
  202113. setFullScreen (false);
  202114. return 0;
  202115. }
  202116. break;
  202117. }
  202118. break;
  202119. case WM_NCLBUTTONDOWN:
  202120. case WM_NCRBUTTONDOWN:
  202121. case WM_NCMBUTTONDOWN:
  202122. sendInputAttemptWhenModalMessage();
  202123. break;
  202124. //case WM_IME_STARTCOMPOSITION;
  202125. // return 0;
  202126. case WM_GETDLGCODE:
  202127. return DLGC_WANTALLKEYS;
  202128. default:
  202129. break;
  202130. }
  202131. }
  202132. }
  202133. // (the message manager lock exits before calling this, to avoid deadlocks if
  202134. // this calls into non-juce windows)
  202135. return DefWindowProc (h, message, wParam, lParam);
  202136. }
  202137. bool sendInputAttemptWhenModalMessage()
  202138. {
  202139. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202140. {
  202141. Component* const current = Component::getCurrentlyModalComponent();
  202142. if (current != 0)
  202143. current->inputAttemptWhenModal();
  202144. return true;
  202145. }
  202146. return false;
  202147. }
  202148. Win32ComponentPeer (const Win32ComponentPeer&);
  202149. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  202150. };
  202151. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  202152. {
  202153. return new Win32ComponentPeer (this, styleFlags);
  202154. }
  202155. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  202156. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  202157. {
  202158. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202159. if (wp != 0)
  202160. wp->setTaskBarIcon (&newImage);
  202161. }
  202162. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  202163. {
  202164. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202165. if (wp != 0)
  202166. wp->setTaskBarIconToolTip (tooltip);
  202167. }
  202168. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  202169. {
  202170. DWORD val = GetWindowLong (h, styleType);
  202171. if (bitIsSet)
  202172. val |= feature;
  202173. else
  202174. val &= ~feature;
  202175. SetWindowLongPtr (h, styleType, val);
  202176. SetWindowPos (h, 0, 0, 0, 0, 0,
  202177. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  202178. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  202179. }
  202180. bool Process::isForegroundProcess() throw()
  202181. {
  202182. HWND fg = GetForegroundWindow();
  202183. if (fg == 0)
  202184. return true;
  202185. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  202186. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  202187. // have to see if any of our windows are children of the foreground window
  202188. fg = GetAncestor (fg, GA_ROOT);
  202189. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  202190. {
  202191. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  202192. if (wp != 0 && wp->isInside (fg))
  202193. return true;
  202194. }
  202195. return false;
  202196. }
  202197. bool AlertWindow::showNativeDialogBox (const String& title,
  202198. const String& bodyText,
  202199. bool isOkCancel)
  202200. {
  202201. return MessageBox (0, bodyText, title,
  202202. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  202203. : MB_OK)) == IDOK;
  202204. }
  202205. void Desktop::getMousePosition (int& x, int& y) throw()
  202206. {
  202207. POINT mousePos;
  202208. GetCursorPos (&mousePos);
  202209. x = mousePos.x;
  202210. y = mousePos.y;
  202211. }
  202212. void Desktop::setMousePosition (int x, int y) throw()
  202213. {
  202214. SetCursorPos (x, y);
  202215. }
  202216. class ScreenSaverDefeater : public Timer,
  202217. public DeletedAtShutdown
  202218. {
  202219. public:
  202220. ScreenSaverDefeater() throw()
  202221. {
  202222. startTimer (10000);
  202223. timerCallback();
  202224. }
  202225. ~ScreenSaverDefeater() {}
  202226. void timerCallback()
  202227. {
  202228. if (Process::isForegroundProcess())
  202229. {
  202230. // simulate a shift key getting pressed..
  202231. INPUT input[2];
  202232. input[0].type = INPUT_KEYBOARD;
  202233. input[0].ki.wVk = VK_SHIFT;
  202234. input[0].ki.dwFlags = 0;
  202235. input[0].ki.dwExtraInfo = 0;
  202236. input[1].type = INPUT_KEYBOARD;
  202237. input[1].ki.wVk = VK_SHIFT;
  202238. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  202239. input[1].ki.dwExtraInfo = 0;
  202240. SendInput (2, input, sizeof (INPUT));
  202241. }
  202242. }
  202243. };
  202244. static ScreenSaverDefeater* screenSaverDefeater = 0;
  202245. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202246. {
  202247. if (isEnabled)
  202248. {
  202249. deleteAndZero (screenSaverDefeater);
  202250. }
  202251. else if (screenSaverDefeater == 0)
  202252. {
  202253. screenSaverDefeater = new ScreenSaverDefeater();
  202254. }
  202255. }
  202256. bool Desktop::isScreenSaverEnabled() throw()
  202257. {
  202258. return screenSaverDefeater == 0;
  202259. }
  202260. /* (The code below is the "correct" way to disable the screen saver, but it
  202261. completely fails on winXP when the saver is password-protected...)
  202262. static bool juce_screenSaverEnabled = true;
  202263. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202264. {
  202265. juce_screenSaverEnabled = isEnabled;
  202266. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  202267. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  202268. }
  202269. bool Desktop::isScreenSaverEnabled() throw()
  202270. {
  202271. return juce_screenSaverEnabled;
  202272. }
  202273. */
  202274. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  202275. {
  202276. if (enableOrDisable)
  202277. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  202278. }
  202279. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  202280. {
  202281. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  202282. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  202283. return TRUE;
  202284. }
  202285. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  202286. {
  202287. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  202288. // make sure the first in the list is the main monitor
  202289. for (int i = 1; i < monitorCoords.size(); ++i)
  202290. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  202291. monitorCoords.swap (i, 0);
  202292. if (monitorCoords.size() == 0)
  202293. {
  202294. RECT r;
  202295. GetWindowRect (GetDesktopWindow(), &r);
  202296. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  202297. }
  202298. if (clipToWorkArea)
  202299. {
  202300. // clip the main monitor to the active non-taskbar area
  202301. RECT r;
  202302. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  202303. Rectangle& screen = monitorCoords.getReference (0);
  202304. screen.setPosition (jmax (screen.getX(), r.left),
  202305. jmax (screen.getY(), r.top));
  202306. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  202307. jmin (screen.getBottom(), r.bottom) - screen.getY());
  202308. }
  202309. }
  202310. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  202311. {
  202312. Image* im = 0;
  202313. if (bitmap != 0)
  202314. {
  202315. BITMAP bm;
  202316. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  202317. && bm.bmWidth > 0 && bm.bmHeight > 0)
  202318. {
  202319. HDC tempDC = GetDC (0);
  202320. HDC dc = CreateCompatibleDC (tempDC);
  202321. ReleaseDC (0, tempDC);
  202322. SelectObject (dc, bitmap);
  202323. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  202324. for (int y = bm.bmHeight; --y >= 0;)
  202325. {
  202326. for (int x = bm.bmWidth; --x >= 0;)
  202327. {
  202328. COLORREF col = GetPixel (dc, x, y);
  202329. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  202330. (uint8) GetGValue (col),
  202331. (uint8) GetBValue (col)));
  202332. }
  202333. }
  202334. DeleteDC (dc);
  202335. }
  202336. }
  202337. return im;
  202338. }
  202339. static Image* createImageFromHICON (HICON icon) throw()
  202340. {
  202341. ICONINFO info;
  202342. if (GetIconInfo (icon, &info))
  202343. {
  202344. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  202345. if (mask == 0)
  202346. return 0;
  202347. Image* const image = createImageFromHBITMAP (info.hbmColor);
  202348. if (image == 0)
  202349. return mask;
  202350. for (int y = image->getHeight(); --y >= 0;)
  202351. {
  202352. for (int x = image->getWidth(); --x >= 0;)
  202353. {
  202354. const float brightness = mask->getPixelAt (x, y).getBrightness();
  202355. if (brightness > 0.0f)
  202356. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  202357. }
  202358. }
  202359. delete mask;
  202360. return image;
  202361. }
  202362. return 0;
  202363. }
  202364. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  202365. {
  202366. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  202367. ICONINFO info;
  202368. info.fIcon = isIcon;
  202369. info.xHotspot = hotspotX;
  202370. info.yHotspot = hotspotY;
  202371. info.hbmMask = mask;
  202372. HICON hi = 0;
  202373. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  202374. {
  202375. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  202376. Graphics g (bitmap);
  202377. g.drawImageAt (&image, 0, 0);
  202378. info.hbmColor = bitmap.hBitmap;
  202379. hi = CreateIconIndirect (&info);
  202380. }
  202381. else
  202382. {
  202383. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  202384. HDC colDC = CreateCompatibleDC (GetDC (0));
  202385. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  202386. SelectObject (colDC, colour);
  202387. SelectObject (alphaDC, mask);
  202388. for (int y = image.getHeight(); --y >= 0;)
  202389. {
  202390. for (int x = image.getWidth(); --x >= 0;)
  202391. {
  202392. const Colour c (image.getPixelAt (x, y));
  202393. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  202394. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  202395. }
  202396. }
  202397. DeleteDC (colDC);
  202398. DeleteDC (alphaDC);
  202399. info.hbmColor = colour;
  202400. hi = CreateIconIndirect (&info);
  202401. DeleteObject (colour);
  202402. }
  202403. DeleteObject (mask);
  202404. return hi;
  202405. }
  202406. Image* juce_createIconForFile (const File& file)
  202407. {
  202408. Image* image = 0;
  202409. TCHAR filename [1024];
  202410. file.getFullPathName().copyToBuffer (filename, 1023);
  202411. WORD iconNum = 0;
  202412. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  202413. filename, &iconNum);
  202414. if (icon != 0)
  202415. {
  202416. image = createImageFromHICON (icon);
  202417. DestroyIcon (icon);
  202418. }
  202419. return image;
  202420. }
  202421. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  202422. {
  202423. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  202424. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  202425. const Image* im = &image;
  202426. Image* newIm = 0;
  202427. if (image.getWidth() > maxW || image.getHeight() > maxH)
  202428. {
  202429. im = newIm = image.createCopy (maxW, maxH);
  202430. hotspotX = (hotspotX * maxW) / image.getWidth();
  202431. hotspotY = (hotspotY * maxH) / image.getHeight();
  202432. }
  202433. void* cursorH = 0;
  202434. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  202435. if (os == SystemStats::WinXP)
  202436. {
  202437. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  202438. }
  202439. else
  202440. {
  202441. const int stride = (maxW + 7) >> 3;
  202442. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  202443. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  202444. int index = 0;
  202445. for (int y = 0; y < maxH; ++y)
  202446. {
  202447. for (int x = 0; x < maxW; ++x)
  202448. {
  202449. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  202450. const Colour pixelColour (im->getPixelAt (x, y));
  202451. if (pixelColour.getAlpha() < 127)
  202452. andPlane [index + (x >> 3)] |= bit;
  202453. else if (pixelColour.getBrightness() >= 0.5f)
  202454. xorPlane [index + (x >> 3)] |= bit;
  202455. }
  202456. index += stride;
  202457. }
  202458. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  202459. juce_free (andPlane);
  202460. juce_free (xorPlane);
  202461. }
  202462. delete newIm;
  202463. return cursorH;
  202464. }
  202465. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  202466. {
  202467. if (cursorHandle != 0 && ! isStandard)
  202468. DestroyCursor ((HCURSOR) cursorHandle);
  202469. }
  202470. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  202471. {
  202472. LPCTSTR cursorName = IDC_ARROW;
  202473. switch (type)
  202474. {
  202475. case MouseCursor::NormalCursor:
  202476. cursorName = IDC_ARROW;
  202477. break;
  202478. case MouseCursor::NoCursor:
  202479. return 0;
  202480. case MouseCursor::DraggingHandCursor:
  202481. {
  202482. static void* dragHandCursor = 0;
  202483. if (dragHandCursor == 0)
  202484. {
  202485. static const unsigned char dragHandData[] =
  202486. { 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,
  202487. 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,
  202488. 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 };
  202489. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  202490. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  202491. delete image;
  202492. }
  202493. return dragHandCursor;
  202494. }
  202495. case MouseCursor::WaitCursor:
  202496. cursorName = IDC_WAIT;
  202497. break;
  202498. case MouseCursor::IBeamCursor:
  202499. cursorName = IDC_IBEAM;
  202500. break;
  202501. case MouseCursor::PointingHandCursor:
  202502. cursorName = MAKEINTRESOURCE(32649);
  202503. break;
  202504. case MouseCursor::LeftRightResizeCursor:
  202505. case MouseCursor::LeftEdgeResizeCursor:
  202506. case MouseCursor::RightEdgeResizeCursor:
  202507. cursorName = IDC_SIZEWE;
  202508. break;
  202509. case MouseCursor::UpDownResizeCursor:
  202510. case MouseCursor::TopEdgeResizeCursor:
  202511. case MouseCursor::BottomEdgeResizeCursor:
  202512. cursorName = IDC_SIZENS;
  202513. break;
  202514. case MouseCursor::TopLeftCornerResizeCursor:
  202515. case MouseCursor::BottomRightCornerResizeCursor:
  202516. cursorName = IDC_SIZENWSE;
  202517. break;
  202518. case MouseCursor::TopRightCornerResizeCursor:
  202519. case MouseCursor::BottomLeftCornerResizeCursor:
  202520. cursorName = IDC_SIZENESW;
  202521. break;
  202522. case MouseCursor::UpDownLeftRightResizeCursor:
  202523. cursorName = IDC_SIZEALL;
  202524. break;
  202525. case MouseCursor::CrosshairCursor:
  202526. cursorName = IDC_CROSS;
  202527. break;
  202528. case MouseCursor::CopyingCursor:
  202529. // can't seem to find one of these in the win32 list..
  202530. break;
  202531. }
  202532. HCURSOR cursorH = LoadCursor (0, cursorName);
  202533. if (cursorH == 0)
  202534. cursorH = LoadCursor (0, IDC_ARROW);
  202535. return (void*) cursorH;
  202536. }
  202537. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  202538. {
  202539. SetCursor ((HCURSOR) getHandle());
  202540. }
  202541. void MouseCursor::showInAllWindows() const throw()
  202542. {
  202543. showInWindow (0);
  202544. }
  202545. class JuceDropSource : public IDropSource
  202546. {
  202547. int refCount;
  202548. public:
  202549. JuceDropSource()
  202550. : refCount (1)
  202551. {
  202552. }
  202553. virtual ~JuceDropSource()
  202554. {
  202555. jassert (refCount == 0);
  202556. }
  202557. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202558. {
  202559. if (id == IID_IUnknown || id == IID_IDropSource)
  202560. {
  202561. AddRef();
  202562. *result = this;
  202563. return S_OK;
  202564. }
  202565. *result = 0;
  202566. return E_NOINTERFACE;
  202567. }
  202568. ULONG __stdcall AddRef() { return ++refCount; }
  202569. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202570. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  202571. {
  202572. if (escapePressed)
  202573. return DRAGDROP_S_CANCEL;
  202574. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  202575. return DRAGDROP_S_DROP;
  202576. return S_OK;
  202577. }
  202578. HRESULT __stdcall GiveFeedback (DWORD)
  202579. {
  202580. return DRAGDROP_S_USEDEFAULTCURSORS;
  202581. }
  202582. };
  202583. class JuceEnumFormatEtc : public IEnumFORMATETC
  202584. {
  202585. public:
  202586. JuceEnumFormatEtc (const FORMATETC* const format_)
  202587. : refCount (1),
  202588. format (format_),
  202589. index (0)
  202590. {
  202591. }
  202592. virtual ~JuceEnumFormatEtc()
  202593. {
  202594. jassert (refCount == 0);
  202595. }
  202596. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202597. {
  202598. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  202599. {
  202600. AddRef();
  202601. *result = this;
  202602. return S_OK;
  202603. }
  202604. *result = 0;
  202605. return E_NOINTERFACE;
  202606. }
  202607. ULONG __stdcall AddRef() { return ++refCount; }
  202608. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202609. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  202610. {
  202611. if (result == 0)
  202612. return E_POINTER;
  202613. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  202614. newOne->index = index;
  202615. *result = newOne;
  202616. return S_OK;
  202617. }
  202618. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  202619. {
  202620. if (pceltFetched != 0)
  202621. *pceltFetched = 0;
  202622. else if (celt != 1)
  202623. return S_FALSE;
  202624. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  202625. {
  202626. copyFormatEtc (lpFormatEtc [0], *format);
  202627. ++index;
  202628. if (pceltFetched != 0)
  202629. *pceltFetched = 1;
  202630. return S_OK;
  202631. }
  202632. return S_FALSE;
  202633. }
  202634. HRESULT __stdcall Skip (ULONG celt)
  202635. {
  202636. if (index + (int) celt >= 1)
  202637. return S_FALSE;
  202638. index += celt;
  202639. return S_OK;
  202640. }
  202641. HRESULT __stdcall Reset()
  202642. {
  202643. index = 0;
  202644. return S_OK;
  202645. }
  202646. private:
  202647. int refCount;
  202648. const FORMATETC* const format;
  202649. int index;
  202650. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  202651. {
  202652. dest = source;
  202653. if (source.ptd != 0)
  202654. {
  202655. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  202656. *(dest.ptd) = *(source.ptd);
  202657. }
  202658. }
  202659. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  202660. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  202661. };
  202662. class JuceDataObject : public IDataObject
  202663. {
  202664. JuceDropSource* const dropSource;
  202665. const FORMATETC* const format;
  202666. const STGMEDIUM* const medium;
  202667. int refCount;
  202668. JuceDataObject (const JuceDataObject&);
  202669. const JuceDataObject& operator= (const JuceDataObject&);
  202670. public:
  202671. JuceDataObject (JuceDropSource* const dropSource_,
  202672. const FORMATETC* const format_,
  202673. const STGMEDIUM* const medium_)
  202674. : dropSource (dropSource_),
  202675. format (format_),
  202676. medium (medium_),
  202677. refCount (1)
  202678. {
  202679. }
  202680. virtual ~JuceDataObject()
  202681. {
  202682. jassert (refCount == 0);
  202683. }
  202684. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202685. {
  202686. if (id == IID_IUnknown || id == IID_IDataObject)
  202687. {
  202688. AddRef();
  202689. *result = this;
  202690. return S_OK;
  202691. }
  202692. *result = 0;
  202693. return E_NOINTERFACE;
  202694. }
  202695. ULONG __stdcall AddRef() { return ++refCount; }
  202696. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202697. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  202698. {
  202699. if (pFormatEtc->tymed == format->tymed
  202700. && pFormatEtc->cfFormat == format->cfFormat
  202701. && pFormatEtc->dwAspect == format->dwAspect)
  202702. {
  202703. pMedium->tymed = format->tymed;
  202704. pMedium->pUnkForRelease = 0;
  202705. if (format->tymed == TYMED_HGLOBAL)
  202706. {
  202707. const SIZE_T len = GlobalSize (medium->hGlobal);
  202708. void* const src = GlobalLock (medium->hGlobal);
  202709. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  202710. memcpy (dst, src, len);
  202711. GlobalUnlock (medium->hGlobal);
  202712. pMedium->hGlobal = dst;
  202713. return S_OK;
  202714. }
  202715. }
  202716. return DV_E_FORMATETC;
  202717. }
  202718. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  202719. {
  202720. if (f == 0)
  202721. return E_INVALIDARG;
  202722. if (f->tymed == format->tymed
  202723. && f->cfFormat == format->cfFormat
  202724. && f->dwAspect == format->dwAspect)
  202725. return S_OK;
  202726. return DV_E_FORMATETC;
  202727. }
  202728. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  202729. {
  202730. pFormatEtcOut->ptd = 0;
  202731. return E_NOTIMPL;
  202732. }
  202733. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  202734. {
  202735. if (result == 0)
  202736. return E_POINTER;
  202737. if (direction == DATADIR_GET)
  202738. {
  202739. *result = new JuceEnumFormatEtc (format);
  202740. return S_OK;
  202741. }
  202742. *result = 0;
  202743. return E_NOTIMPL;
  202744. }
  202745. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  202746. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  202747. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  202748. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  202749. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  202750. };
  202751. static HDROP createHDrop (const StringArray& fileNames) throw()
  202752. {
  202753. int totalChars = 0;
  202754. for (int i = fileNames.size(); --i >= 0;)
  202755. totalChars += fileNames[i].length() + 1;
  202756. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  202757. sizeof (DROPFILES)
  202758. + sizeof (WCHAR) * (totalChars + 2));
  202759. if (hDrop != 0)
  202760. {
  202761. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  202762. pDropFiles->pFiles = sizeof (DROPFILES);
  202763. pDropFiles->fWide = true;
  202764. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  202765. for (int i = 0; i < fileNames.size(); ++i)
  202766. {
  202767. fileNames[i].copyToBuffer (fname, 2048);
  202768. fname += fileNames[i].length() + 1;
  202769. }
  202770. *fname = 0;
  202771. GlobalUnlock (hDrop);
  202772. }
  202773. return hDrop;
  202774. }
  202775. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  202776. {
  202777. JuceDropSource* const source = new JuceDropSource();
  202778. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  202779. DWORD effect;
  202780. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  202781. data->Release();
  202782. source->Release();
  202783. return res == DRAGDROP_S_DROP;
  202784. }
  202785. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  202786. {
  202787. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  202788. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  202789. medium.hGlobal = createHDrop (files);
  202790. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  202791. : DROPEFFECT_COPY);
  202792. }
  202793. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  202794. {
  202795. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  202796. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  202797. const int numChars = text.length();
  202798. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  202799. char* d = (char*) GlobalLock (medium.hGlobal);
  202800. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  202801. format.cfFormat = CF_UNICODETEXT;
  202802. GlobalUnlock (medium.hGlobal);
  202803. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  202804. }
  202805. #endif
  202806. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  202807. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  202808. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202809. // compiled on its own).
  202810. #if JUCE_INCLUDED_FILE
  202811. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  202812. NEWTEXTMETRICEXW*,
  202813. int type,
  202814. LPARAM lParam)
  202815. {
  202816. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  202817. {
  202818. const String fontName (lpelfe->elfLogFont.lfFaceName);
  202819. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  202820. }
  202821. return 1;
  202822. }
  202823. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  202824. NEWTEXTMETRICEXW*,
  202825. int type,
  202826. LPARAM lParam)
  202827. {
  202828. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  202829. {
  202830. LOGFONTW lf;
  202831. zerostruct (lf);
  202832. lf.lfWeight = FW_DONTCARE;
  202833. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  202834. lf.lfQuality = DEFAULT_QUALITY;
  202835. lf.lfCharSet = DEFAULT_CHARSET;
  202836. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  202837. lf.lfPitchAndFamily = FF_DONTCARE;
  202838. const String fontName (lpelfe->elfLogFont.lfFaceName);
  202839. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  202840. HDC dc = CreateCompatibleDC (0);
  202841. EnumFontFamiliesEx (dc, &lf,
  202842. (FONTENUMPROCW) &wfontEnum2,
  202843. lParam, 0);
  202844. DeleteDC (dc);
  202845. }
  202846. return 1;
  202847. }
  202848. const StringArray Font::findAllTypefaceNames() throw()
  202849. {
  202850. StringArray results;
  202851. HDC dc = CreateCompatibleDC (0);
  202852. {
  202853. LOGFONTW lf;
  202854. zerostruct (lf);
  202855. lf.lfWeight = FW_DONTCARE;
  202856. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  202857. lf.lfQuality = DEFAULT_QUALITY;
  202858. lf.lfCharSet = DEFAULT_CHARSET;
  202859. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  202860. lf.lfPitchAndFamily = FF_DONTCARE;
  202861. lf.lfFaceName[0] = 0;
  202862. EnumFontFamiliesEx (dc, &lf,
  202863. (FONTENUMPROCW) &wfontEnum1,
  202864. (LPARAM) &results, 0);
  202865. }
  202866. DeleteDC (dc);
  202867. results.sort (true);
  202868. return results;
  202869. }
  202870. extern bool juce_IsRunningInWine() throw();
  202871. void Typeface::getDefaultFontNames (String& defaultSans,
  202872. String& defaultSerif,
  202873. String& defaultFixed) throw()
  202874. {
  202875. if (juce_IsRunningInWine())
  202876. {
  202877. // If we're running in Wine, then use fonts that might be available on Linux..
  202878. defaultSans = "Bitstream Vera Sans";
  202879. defaultSerif = "Bitstream Vera Serif";
  202880. defaultFixed = "Bitstream Vera Sans Mono";
  202881. }
  202882. else
  202883. {
  202884. defaultSans = "Verdana";
  202885. defaultSerif = "Times";
  202886. defaultFixed = "Lucida Console";
  202887. }
  202888. }
  202889. class FontDCHolder : private DeletedAtShutdown
  202890. {
  202891. HDC dc;
  202892. String fontName;
  202893. KERNINGPAIR* kps;
  202894. int numKPs;
  202895. bool bold, italic;
  202896. int size;
  202897. FontDCHolder (const FontDCHolder&);
  202898. const FontDCHolder& operator= (const FontDCHolder&);
  202899. public:
  202900. HFONT fontH;
  202901. FontDCHolder() throw()
  202902. : dc (0),
  202903. kps (0),
  202904. numKPs (0),
  202905. bold (false),
  202906. italic (false),
  202907. size (0)
  202908. {
  202909. }
  202910. ~FontDCHolder() throw()
  202911. {
  202912. if (dc != 0)
  202913. {
  202914. DeleteDC (dc);
  202915. DeleteObject (fontH);
  202916. juce_free (kps);
  202917. }
  202918. clearSingletonInstance();
  202919. }
  202920. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  202921. HDC loadFont (const String& fontName_,
  202922. const bool bold_,
  202923. const bool italic_,
  202924. const int size_) throw()
  202925. {
  202926. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  202927. {
  202928. fontName = fontName_;
  202929. bold = bold_;
  202930. italic = italic_;
  202931. size = size_;
  202932. if (dc != 0)
  202933. {
  202934. DeleteDC (dc);
  202935. DeleteObject (fontH);
  202936. juce_free (kps);
  202937. kps = 0;
  202938. }
  202939. fontH = 0;
  202940. dc = CreateCompatibleDC (0);
  202941. SetMapperFlags (dc, 0);
  202942. SetMapMode (dc, MM_TEXT);
  202943. LOGFONTW lfw;
  202944. zerostruct (lfw);
  202945. lfw.lfCharSet = DEFAULT_CHARSET;
  202946. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  202947. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  202948. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  202949. lfw.lfQuality = PROOF_QUALITY;
  202950. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  202951. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  202952. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  202953. lfw.lfHeight = size > 0 ? size : -256;
  202954. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  202955. if (standardSizedFont != 0)
  202956. {
  202957. if (SelectObject (dc, standardSizedFont) != 0)
  202958. {
  202959. fontH = standardSizedFont;
  202960. if (size == 0)
  202961. {
  202962. OUTLINETEXTMETRIC otm;
  202963. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  202964. {
  202965. lfw.lfHeight = -(int) otm.otmEMSquare;
  202966. fontH = CreateFontIndirect (&lfw);
  202967. SelectObject (dc, fontH);
  202968. DeleteObject (standardSizedFont);
  202969. }
  202970. }
  202971. }
  202972. else
  202973. {
  202974. jassertfalse
  202975. }
  202976. }
  202977. else
  202978. {
  202979. jassertfalse
  202980. }
  202981. }
  202982. return dc;
  202983. }
  202984. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  202985. {
  202986. if (kps == 0)
  202987. {
  202988. numKPs = GetKerningPairs (dc, 0, 0);
  202989. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  202990. GetKerningPairs (dc, numKPs, kps);
  202991. }
  202992. numKPs_ = numKPs;
  202993. return kps;
  202994. }
  202995. };
  202996. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  202997. static bool addGlyphToTypeface (HDC dc,
  202998. juce_wchar character,
  202999. Typeface& dest,
  203000. bool addKerning)
  203001. {
  203002. Path destShape;
  203003. GLYPHMETRICS gm;
  203004. float height;
  203005. BOOL ok = false;
  203006. {
  203007. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  203008. WORD index = 0;
  203009. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  203010. && index == 0xffff)
  203011. {
  203012. return false;
  203013. }
  203014. }
  203015. TEXTMETRIC tm;
  203016. ok = GetTextMetrics (dc, &tm);
  203017. height = (float) tm.tmHeight;
  203018. if (! ok)
  203019. {
  203020. dest.addGlyph (character, destShape, 0);
  203021. return true;
  203022. }
  203023. const float scaleX = 1.0f / height;
  203024. const float scaleY = -1.0f / height;
  203025. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  203026. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  203027. &gm, 0, 0, &identityMatrix);
  203028. if (bufSize > 0)
  203029. {
  203030. char* const data = (char*) juce_malloc (bufSize);
  203031. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  203032. bufSize, data, &identityMatrix);
  203033. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  203034. while ((char*) pheader < data + bufSize)
  203035. {
  203036. #define remapX(v) (scaleX * (v).x.value)
  203037. #define remapY(v) (scaleY * (v).y.value)
  203038. float x = remapX (pheader->pfxStart);
  203039. float y = remapY (pheader->pfxStart);
  203040. destShape.startNewSubPath (x, y);
  203041. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  203042. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  203043. while ((const char*) curve < curveEnd)
  203044. {
  203045. if (curve->wType == TT_PRIM_LINE)
  203046. {
  203047. for (int i = 0; i < curve->cpfx; ++i)
  203048. {
  203049. x = remapX (curve->apfx [i]);
  203050. y = remapY (curve->apfx [i]);
  203051. destShape.lineTo (x, y);
  203052. }
  203053. }
  203054. else if (curve->wType == TT_PRIM_QSPLINE)
  203055. {
  203056. for (int i = 0; i < curve->cpfx - 1; ++i)
  203057. {
  203058. const float x2 = remapX (curve->apfx [i]);
  203059. const float y2 = remapY (curve->apfx [i]);
  203060. float x3, y3;
  203061. if (i < curve->cpfx - 2)
  203062. {
  203063. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  203064. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  203065. }
  203066. else
  203067. {
  203068. x3 = remapX (curve->apfx [i + 1]);
  203069. y3 = remapY (curve->apfx [i + 1]);
  203070. }
  203071. destShape.quadraticTo (x2, y2, x3, y3);
  203072. x = x3;
  203073. y = y3;
  203074. }
  203075. }
  203076. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  203077. }
  203078. pheader = (const TTPOLYGONHEADER*) curve;
  203079. destShape.closeSubPath();
  203080. }
  203081. juce_free (data);
  203082. }
  203083. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  203084. if (addKerning)
  203085. {
  203086. int numKPs;
  203087. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203088. for (int i = 0; i < numKPs; ++i)
  203089. {
  203090. if (kps[i].wFirst == character)
  203091. {
  203092. dest.addKerningPair (kps[i].wFirst,
  203093. kps[i].wSecond,
  203094. kps[i].iKernAmount / height);
  203095. }
  203096. }
  203097. }
  203098. return true;
  203099. }
  203100. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  203101. {
  203102. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  203103. return addGlyphToTypeface (dc, character, *this, true);
  203104. }
  203105. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  203106. {
  203107. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  203108. int bufSize;
  203109. GLYPHMETRICS gm;
  203110. const UINT format = GGO_GRAY2_BITMAP;
  203111. const int shift = 6;
  203112. if (wGetGlyphOutlineW != 0)
  203113. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  203114. else
  203115. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  203116. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  203117. if (bufSize > 0)
  203118. {
  203119. topLeftX = (float) gm.gmptGlyphOrigin.x;
  203120. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  203121. uint8* const data = (uint8*) juce_calloc (bufSize);
  203122. if (wGetGlyphOutlineW != 0)
  203123. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203124. else
  203125. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203126. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  203127. for (int y = gm.gmBlackBoxY; --y >= 0;)
  203128. {
  203129. for (int x = gm.gmBlackBoxX; --x >= 0;)
  203130. {
  203131. const int level = data [x + y * stride] << shift;
  203132. if (level > 0)
  203133. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  203134. }
  203135. }
  203136. juce_free (data);
  203137. }
  203138. return im;
  203139. }*/
  203140. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  203141. bool bold,
  203142. bool italic,
  203143. bool addAllGlyphsToFont) throw()
  203144. {
  203145. clear();
  203146. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  203147. float height;
  203148. int firstChar, lastChar;
  203149. {
  203150. TEXTMETRIC tm;
  203151. GetTextMetrics (dc, &tm);
  203152. height = (float) tm.tmHeight;
  203153. firstChar = tm.tmFirstChar;
  203154. lastChar = tm.tmLastChar;
  203155. setAscent (tm.tmAscent / height);
  203156. setDefaultCharacter (tm.tmDefaultChar);
  203157. }
  203158. setName (fontName);
  203159. setBold (bold);
  203160. setItalic (italic);
  203161. if (addAllGlyphsToFont)
  203162. {
  203163. for (int character = firstChar; character <= lastChar; ++character)
  203164. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  203165. int numKPs;
  203166. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203167. for (int i = 0; i < numKPs; ++i)
  203168. {
  203169. addKerningPair (kps[i].wFirst,
  203170. kps[i].wSecond,
  203171. kps[i].iKernAmount / height);
  203172. }
  203173. }
  203174. }
  203175. #endif
  203176. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  203177. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203178. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203179. // compiled on its own).
  203180. #if JUCE_INCLUDED_FILE
  203181. static const void* defaultDirPath = 0;
  203182. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203183. static Component* currentExtraFileWin = 0;
  203184. static bool areThereAnyAlwaysOnTopWindows()
  203185. {
  203186. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203187. {
  203188. Component* c = Desktop::getInstance().getComponent (i);
  203189. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203190. return true;
  203191. }
  203192. return false;
  203193. }
  203194. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203195. {
  203196. if (msg == BFFM_INITIALIZED)
  203197. {
  203198. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203199. }
  203200. else if (msg == BFFM_VALIDATEFAILEDW)
  203201. {
  203202. returnedString = (LPCWSTR) lParam;
  203203. }
  203204. else if (msg == BFFM_VALIDATEFAILEDA)
  203205. {
  203206. returnedString = (const char*) lParam;
  203207. }
  203208. return 0;
  203209. }
  203210. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  203211. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203212. {
  203213. if (currentExtraFileWin != 0)
  203214. {
  203215. if (uiMsg == WM_INITDIALOG)
  203216. {
  203217. HWND dialogH = GetParent (hdlg);
  203218. jassert (dialogH != 0);
  203219. if (dialogH == 0)
  203220. dialogH = hdlg;
  203221. RECT r, cr;
  203222. GetWindowRect (dialogH, &r);
  203223. GetClientRect (dialogH, &cr);
  203224. SetWindowPos (dialogH, 0,
  203225. r.left, r.top,
  203226. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  203227. jmax (150, r.bottom - r.top),
  203228. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  203229. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  203230. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  203231. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  203232. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  203233. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  203234. }
  203235. else if (uiMsg == WM_NOTIFY)
  203236. {
  203237. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  203238. if (ofn->hdr.code == CDN_SELCHANGE)
  203239. {
  203240. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  203241. if (comp != 0)
  203242. {
  203243. TCHAR path [MAX_PATH * 2];
  203244. path[0] = 0;
  203245. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  203246. const String fn ((const WCHAR*) path);
  203247. comp->selectedFileChanged (File (fn));
  203248. }
  203249. }
  203250. }
  203251. }
  203252. return 0;
  203253. }
  203254. class FPComponentHolder : public Component
  203255. {
  203256. public:
  203257. FPComponentHolder()
  203258. {
  203259. setVisible (true);
  203260. setOpaque (true);
  203261. }
  203262. ~FPComponentHolder()
  203263. {
  203264. }
  203265. void paint (Graphics& g)
  203266. {
  203267. g.fillAll (Colours::lightgrey);
  203268. }
  203269. private:
  203270. FPComponentHolder (const FPComponentHolder&);
  203271. const FPComponentHolder& operator= (const FPComponentHolder&);
  203272. };
  203273. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  203274. const String& title,
  203275. const File& currentFileOrDirectory,
  203276. const String& filter,
  203277. bool selectsDirectory,
  203278. bool isSaveDialogue,
  203279. bool warnAboutOverwritingExistingFiles,
  203280. bool selectMultipleFiles,
  203281. FilePreviewComponent* extraInfoComponent)
  203282. {
  203283. const int numCharsAvailable = 32768;
  203284. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  203285. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  203286. int fnameIdx = 0;
  203287. JUCE_TRY
  203288. {
  203289. // use a modal window as the parent for this dialog box
  203290. // to block input from other app windows
  203291. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  203292. Component w (String::empty);
  203293. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  203294. mainMon.getY() + mainMon.getHeight() / 4,
  203295. 0, 0);
  203296. w.setOpaque (true);
  203297. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  203298. w.addToDesktop (0);
  203299. if (extraInfoComponent == 0)
  203300. w.enterModalState();
  203301. String initialDir;
  203302. if (currentFileOrDirectory.isDirectory())
  203303. {
  203304. initialDir = currentFileOrDirectory.getFullPathName();
  203305. }
  203306. else
  203307. {
  203308. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  203309. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  203310. }
  203311. if (currentExtraFileWin->isValidComponent())
  203312. {
  203313. jassertfalse
  203314. return;
  203315. }
  203316. if (selectsDirectory)
  203317. {
  203318. LPITEMIDLIST list = 0;
  203319. filenameSpace.fillWith (0);
  203320. {
  203321. BROWSEINFO bi;
  203322. zerostruct (bi);
  203323. bi.hwndOwner = (HWND) w.getWindowHandle();
  203324. bi.pszDisplayName = fname;
  203325. bi.lpszTitle = title;
  203326. bi.lpfn = browseCallbackProc;
  203327. #ifdef BIF_USENEWUI
  203328. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  203329. #else
  203330. bi.ulFlags = 0x50;
  203331. #endif
  203332. defaultDirPath = (const WCHAR*) initialDir;
  203333. list = SHBrowseForFolder (&bi);
  203334. if (! SHGetPathFromIDListW (list, fname))
  203335. {
  203336. fname[0] = 0;
  203337. returnedString = String::empty;
  203338. }
  203339. }
  203340. LPMALLOC al;
  203341. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  203342. al->Free (list);
  203343. defaultDirPath = 0;
  203344. if (returnedString.isNotEmpty())
  203345. {
  203346. const String stringFName (fname);
  203347. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  203348. returnedString = String::empty;
  203349. return;
  203350. }
  203351. }
  203352. else
  203353. {
  203354. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  203355. if (warnAboutOverwritingExistingFiles)
  203356. flags |= OFN_OVERWRITEPROMPT;
  203357. if (selectMultipleFiles)
  203358. flags |= OFN_ALLOWMULTISELECT;
  203359. if (extraInfoComponent != 0)
  203360. {
  203361. flags |= OFN_ENABLEHOOK;
  203362. currentExtraFileWin = new FPComponentHolder();
  203363. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  203364. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  203365. extraInfoComponent->getHeight());
  203366. currentExtraFileWin->addToDesktop (0);
  203367. currentExtraFileWin->enterModalState();
  203368. }
  203369. {
  203370. WCHAR filters [1024];
  203371. zeromem (filters, sizeof (filters));
  203372. filter.copyToBuffer (filters, 1024);
  203373. filter.copyToBuffer (filters + filter.length() + 1,
  203374. 1022 - filter.length());
  203375. OPENFILENAMEW of;
  203376. zerostruct (of);
  203377. #ifdef OPENFILENAME_SIZE_VERSION_400W
  203378. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  203379. #else
  203380. of.lStructSize = sizeof (of);
  203381. #endif
  203382. of.hwndOwner = (HWND) w.getWindowHandle();
  203383. of.lpstrFilter = filters;
  203384. of.nFilterIndex = 1;
  203385. of.lpstrFile = fname;
  203386. of.nMaxFile = numCharsAvailable;
  203387. of.lpstrInitialDir = initialDir;
  203388. of.lpstrTitle = title;
  203389. of.Flags = flags;
  203390. if (extraInfoComponent != 0)
  203391. of.lpfnHook = &openCallback;
  203392. if (isSaveDialogue)
  203393. {
  203394. if (! GetSaveFileName (&of))
  203395. fname[0] = 0;
  203396. else
  203397. fnameIdx = of.nFileOffset;
  203398. }
  203399. else
  203400. {
  203401. if (! GetOpenFileName (&of))
  203402. fname[0] = 0;
  203403. else
  203404. fnameIdx = of.nFileOffset;
  203405. }
  203406. }
  203407. }
  203408. }
  203409. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203410. catch (...)
  203411. {
  203412. fname[0] = 0;
  203413. }
  203414. #endif
  203415. deleteAndZero (currentExtraFileWin);
  203416. const WCHAR* const files = fname;
  203417. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  203418. {
  203419. const WCHAR* filename = files + fnameIdx;
  203420. while (*filename != 0)
  203421. {
  203422. const String filepath (String (files) + T("\\") + String (filename));
  203423. results.add (new File (filepath));
  203424. filename += CharacterFunctions::length (filename) + 1;
  203425. }
  203426. }
  203427. else if (files[0] != 0)
  203428. {
  203429. results.add (new File (files));
  203430. }
  203431. }
  203432. #endif
  203433. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  203434. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  203435. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203436. // compiled on its own).
  203437. #if JUCE_INCLUDED_FILE
  203438. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  203439. {
  203440. if (OpenClipboard (0) != 0)
  203441. {
  203442. if (EmptyClipboard() != 0)
  203443. {
  203444. const int len = text.length();
  203445. if (len > 0)
  203446. {
  203447. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  203448. (len + 1) * sizeof (wchar_t));
  203449. if (bufH != 0)
  203450. {
  203451. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  203452. text.copyToBuffer (data, len);
  203453. GlobalUnlock (bufH);
  203454. SetClipboardData (CF_UNICODETEXT, bufH);
  203455. }
  203456. }
  203457. }
  203458. CloseClipboard();
  203459. }
  203460. }
  203461. const String SystemClipboard::getTextFromClipboard() throw()
  203462. {
  203463. String result;
  203464. if (OpenClipboard (0) != 0)
  203465. {
  203466. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  203467. if (bufH != 0)
  203468. {
  203469. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  203470. if (data != 0)
  203471. {
  203472. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  203473. GlobalUnlock (bufH);
  203474. }
  203475. }
  203476. CloseClipboard();
  203477. }
  203478. return result;
  203479. }
  203480. #endif
  203481. /********* End of inlined file: juce_win32_Misc.cpp *********/
  203482. /********* Start of inlined file: juce_win32_ActiveXComponent.cpp *********/
  203483. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203484. // compiled on its own).
  203485. #if JUCE_INCLUDED_FILE
  203486. class JuceIStorage : public IStorage
  203487. {
  203488. int refCount;
  203489. public:
  203490. JuceIStorage() : refCount (1) {}
  203491. virtual ~JuceIStorage()
  203492. {
  203493. jassert (refCount == 0);
  203494. }
  203495. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203496. {
  203497. if (id == IID_IUnknown || id == IID_IStorage)
  203498. {
  203499. AddRef();
  203500. *result = this;
  203501. return S_OK;
  203502. }
  203503. *result = 0;
  203504. return E_NOINTERFACE;
  203505. }
  203506. ULONG __stdcall AddRef() { return ++refCount; }
  203507. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  203508. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  203509. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  203510. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  203511. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  203512. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  203513. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  203514. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  203515. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  203516. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  203517. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  203518. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  203519. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  203520. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  203521. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  203522. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  203523. juce_UseDebuggingNewOperator
  203524. };
  203525. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  203526. {
  203527. int refCount;
  203528. HWND window;
  203529. public:
  203530. JuceOleInPlaceFrame (HWND window_)
  203531. : refCount (1),
  203532. window (window_)
  203533. {
  203534. }
  203535. virtual ~JuceOleInPlaceFrame()
  203536. {
  203537. jassert (refCount == 0);
  203538. }
  203539. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203540. {
  203541. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  203542. {
  203543. AddRef();
  203544. *result = this;
  203545. return S_OK;
  203546. }
  203547. *result = 0;
  203548. return E_NOINTERFACE;
  203549. }
  203550. ULONG __stdcall AddRef() { return ++refCount; }
  203551. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  203552. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  203553. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  203554. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  203555. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  203556. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  203557. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  203558. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  203559. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  203560. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  203561. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  203562. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  203563. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  203564. juce_UseDebuggingNewOperator
  203565. };
  203566. class JuceIOleInPlaceSite : public IOleInPlaceSite
  203567. {
  203568. int refCount;
  203569. HWND window;
  203570. JuceOleInPlaceFrame* frame;
  203571. public:
  203572. JuceIOleInPlaceSite (HWND window_)
  203573. : refCount (1),
  203574. window (window_)
  203575. {
  203576. frame = new JuceOleInPlaceFrame (window);
  203577. }
  203578. virtual ~JuceIOleInPlaceSite()
  203579. {
  203580. jassert (refCount == 0);
  203581. frame->Release();
  203582. }
  203583. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203584. {
  203585. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  203586. {
  203587. AddRef();
  203588. *result = this;
  203589. return S_OK;
  203590. }
  203591. *result = 0;
  203592. return E_NOINTERFACE;
  203593. }
  203594. ULONG __stdcall AddRef() { return ++refCount; }
  203595. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  203596. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  203597. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  203598. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  203599. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  203600. HRESULT __stdcall OnUIActivate() { return S_OK; }
  203601. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  203602. {
  203603. frame->AddRef();
  203604. *lplpFrame = frame;
  203605. *lplpDoc = 0;
  203606. lpFrameInfo->fMDIApp = FALSE;
  203607. lpFrameInfo->hwndFrame = window;
  203608. lpFrameInfo->haccel = 0;
  203609. lpFrameInfo->cAccelEntries = 0;
  203610. return S_OK;
  203611. }
  203612. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  203613. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  203614. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  203615. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  203616. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  203617. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  203618. juce_UseDebuggingNewOperator
  203619. };
  203620. class JuceIOleClientSite : public IOleClientSite
  203621. {
  203622. int refCount;
  203623. JuceIOleInPlaceSite* inplaceSite;
  203624. public:
  203625. JuceIOleClientSite (HWND window)
  203626. : refCount (1)
  203627. {
  203628. inplaceSite = new JuceIOleInPlaceSite (window);
  203629. }
  203630. virtual ~JuceIOleClientSite()
  203631. {
  203632. jassert (refCount == 0);
  203633. inplaceSite->Release();
  203634. }
  203635. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203636. {
  203637. if (id == IID_IUnknown || id == IID_IOleClientSite)
  203638. {
  203639. AddRef();
  203640. *result = this;
  203641. return S_OK;
  203642. }
  203643. else if (id == IID_IOleInPlaceSite)
  203644. {
  203645. inplaceSite->AddRef();
  203646. *result = inplaceSite;
  203647. return S_OK;
  203648. }
  203649. *result = 0;
  203650. return E_NOINTERFACE;
  203651. }
  203652. ULONG __stdcall AddRef() { return ++refCount; }
  203653. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  203654. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  203655. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  203656. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  203657. HRESULT __stdcall ShowObject() { return S_OK; }
  203658. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  203659. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  203660. juce_UseDebuggingNewOperator
  203661. };
  203662. class ActiveXControlData : public ComponentMovementWatcher
  203663. {
  203664. ActiveXControlComponent* const owner;
  203665. bool wasShowing;
  203666. public:
  203667. HWND controlHWND;
  203668. IStorage* storage;
  203669. IOleClientSite* clientSite;
  203670. IOleObject* control;
  203671. ActiveXControlData (HWND hwnd,
  203672. ActiveXControlComponent* const owner_)
  203673. : ComponentMovementWatcher (owner_),
  203674. owner (owner_),
  203675. wasShowing (owner_ != 0 && owner_->isShowing()),
  203676. controlHWND (0),
  203677. storage (new JuceIStorage()),
  203678. clientSite (new JuceIOleClientSite (hwnd)),
  203679. control (0)
  203680. {
  203681. }
  203682. ~ActiveXControlData()
  203683. {
  203684. if (control != 0)
  203685. {
  203686. control->Close (OLECLOSE_NOSAVE);
  203687. control->Release();
  203688. }
  203689. clientSite->Release();
  203690. storage->Release();
  203691. }
  203692. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  203693. {
  203694. Component* const topComp = owner->getTopLevelComponent();
  203695. if (topComp->getPeer() != 0)
  203696. {
  203697. int x = 0, y = 0;
  203698. owner->relativePositionToOtherComponent (topComp, x, y);
  203699. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  203700. }
  203701. }
  203702. void componentPeerChanged()
  203703. {
  203704. const bool isShowingNow = owner->isShowing();
  203705. if (wasShowing != isShowingNow)
  203706. {
  203707. wasShowing = isShowingNow;
  203708. owner->setControlVisible (isShowingNow);
  203709. }
  203710. componentMovedOrResized (true, true);
  203711. }
  203712. void componentVisibilityChanged (Component&)
  203713. {
  203714. componentPeerChanged();
  203715. }
  203716. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  203717. {
  203718. return ((ActiveXControlData*) ax->control) != 0
  203719. && ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  203720. }
  203721. };
  203722. static VoidArray activeXComps;
  203723. static HWND getHWND (const ActiveXControlComponent* const component)
  203724. {
  203725. HWND hwnd = 0;
  203726. const IID iid = IID_IOleWindow;
  203727. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  203728. if (window != 0)
  203729. {
  203730. window->GetWindow (&hwnd);
  203731. window->Release();
  203732. }
  203733. return hwnd;
  203734. }
  203735. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  203736. {
  203737. RECT activeXRect, peerRect;
  203738. GetWindowRect (hwnd, &activeXRect);
  203739. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  203740. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  203741. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  203742. const int64 mouseEventTime = getMouseEventTime();
  203743. const int oldModifiers = currentModifiers;
  203744. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  203745. switch (message)
  203746. {
  203747. case WM_MOUSEMOVE:
  203748. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  203749. peer->handleMouseDrag (mx, my, mouseEventTime);
  203750. else
  203751. peer->handleMouseMove (mx, my, mouseEventTime);
  203752. break;
  203753. case WM_LBUTTONDOWN:
  203754. case WM_MBUTTONDOWN:
  203755. case WM_RBUTTONDOWN:
  203756. peer->handleMouseDown (mx, my, mouseEventTime);
  203757. break;
  203758. case WM_LBUTTONUP:
  203759. case WM_MBUTTONUP:
  203760. case WM_RBUTTONUP:
  203761. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  203762. break;
  203763. default:
  203764. break;
  203765. }
  203766. }
  203767. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  203768. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  203769. {
  203770. for (int i = activeXComps.size(); --i >= 0;)
  203771. {
  203772. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  203773. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  203774. {
  203775. switch (message)
  203776. {
  203777. case WM_MOUSEMOVE:
  203778. case WM_LBUTTONDOWN:
  203779. case WM_MBUTTONDOWN:
  203780. case WM_RBUTTONDOWN:
  203781. case WM_LBUTTONUP:
  203782. case WM_MBUTTONUP:
  203783. case WM_RBUTTONUP:
  203784. case WM_LBUTTONDBLCLK:
  203785. case WM_MBUTTONDBLCLK:
  203786. case WM_RBUTTONDBLCLK:
  203787. if (ax->isShowing())
  203788. {
  203789. ComponentPeer* const peer = ax->getPeer();
  203790. if (peer != 0)
  203791. {
  203792. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  203793. if (! ax->areMouseEventsAllowed())
  203794. return 0;
  203795. }
  203796. }
  203797. break;
  203798. default:
  203799. break;
  203800. }
  203801. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  203802. }
  203803. }
  203804. return DefWindowProc (hwnd, message, wParam, lParam);
  203805. }
  203806. ActiveXControlComponent::ActiveXControlComponent()
  203807. : originalWndProc (0),
  203808. control (0),
  203809. mouseEventsAllowed (true)
  203810. {
  203811. activeXComps.add (this);
  203812. }
  203813. ActiveXControlComponent::~ActiveXControlComponent()
  203814. {
  203815. deleteControl();
  203816. activeXComps.removeValue (this);
  203817. }
  203818. void ActiveXControlComponent::paint (Graphics& g)
  203819. {
  203820. if (control == 0)
  203821. g.fillAll (Colours::lightgrey);
  203822. }
  203823. bool ActiveXControlComponent::createControl (const void* controlIID)
  203824. {
  203825. deleteControl();
  203826. ComponentPeer* const peer = getPeer();
  203827. // the component must have already been added to a real window when you call this!
  203828. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  203829. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  203830. {
  203831. int x = 0, y = 0;
  203832. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  203833. HWND hwnd = (HWND) peer->getNativeHandle();
  203834. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  203835. HRESULT hr;
  203836. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  203837. info->clientSite, info->storage,
  203838. (void**) &(info->control))) == S_OK)
  203839. {
  203840. info->control->SetHostNames (L"Juce", 0);
  203841. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  203842. {
  203843. RECT rect;
  203844. rect.left = x;
  203845. rect.top = y;
  203846. rect.right = x + getWidth();
  203847. rect.bottom = y + getHeight();
  203848. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  203849. {
  203850. control = info;
  203851. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  203852. info->controlHWND = getHWND (this);
  203853. if (info->controlHWND != 0)
  203854. {
  203855. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  203856. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  203857. }
  203858. return true;
  203859. }
  203860. }
  203861. }
  203862. delete info;
  203863. }
  203864. return false;
  203865. }
  203866. void ActiveXControlComponent::deleteControl()
  203867. {
  203868. ActiveXControlData* const info = (ActiveXControlData*) control;
  203869. if (info != 0)
  203870. {
  203871. delete info;
  203872. control = 0;
  203873. originalWndProc = 0;
  203874. }
  203875. }
  203876. void* ActiveXControlComponent::queryInterface (const void* iid) const
  203877. {
  203878. ActiveXControlData* const info = (ActiveXControlData*) control;
  203879. void* result = 0;
  203880. if (info != 0 && info->control != 0
  203881. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  203882. return result;
  203883. return 0;
  203884. }
  203885. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  203886. {
  203887. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  203888. if (hwnd != 0)
  203889. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  203890. }
  203891. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  203892. {
  203893. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  203894. if (hwnd != 0)
  203895. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  203896. }
  203897. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  203898. {
  203899. mouseEventsAllowed = eventsCanReachControl;
  203900. }
  203901. #endif
  203902. /********* End of inlined file: juce_win32_ActiveXComponent.cpp *********/
  203903. /********* Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  203904. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203905. // compiled on its own).
  203906. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  203907. using namespace QTOLibrary;
  203908. using namespace QTOControlLib;
  203909. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  203910. static bool isQTAvailable = false;
  203911. struct QTMovieCompInternal
  203912. {
  203913. QTMovieCompInternal()
  203914. : dataHandle (0)
  203915. {
  203916. }
  203917. ~QTMovieCompInternal()
  203918. {
  203919. clearHandle();
  203920. }
  203921. IQTControlPtr qtControlInternal;
  203922. IQTMoviePtr qtMovieInternal;
  203923. Handle dataHandle;
  203924. void clearHandle()
  203925. {
  203926. if (dataHandle != 0)
  203927. {
  203928. DisposeHandle (dataHandle);
  203929. dataHandle = 0;
  203930. }
  203931. }
  203932. };
  203933. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  203934. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  203935. QuickTimeMovieComponent::QuickTimeMovieComponent()
  203936. : movieLoaded (false),
  203937. controllerVisible (true)
  203938. {
  203939. internal = new QTMovieCompInternal();
  203940. setMouseEventsAllowed (false);
  203941. }
  203942. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  203943. {
  203944. closeMovie();
  203945. qtControl = 0;
  203946. deleteControl();
  203947. delete internal;
  203948. internal = 0;
  203949. }
  203950. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  203951. {
  203952. if (! isQTAvailable)
  203953. {
  203954. isQTAvailable = (InitializeQTML (0) == noErr)
  203955. && (EnterMovies() == noErr);
  203956. }
  203957. return isQTAvailable;
  203958. }
  203959. void QuickTimeMovieComponent::createControlIfNeeded()
  203960. {
  203961. if (isShowing() && ! isControlCreated())
  203962. {
  203963. const IID qtIID = __uuidof (QTControl);
  203964. if (createControl (&qtIID))
  203965. {
  203966. const IID qtInterfaceIID = __uuidof (IQTControl);
  203967. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  203968. if (qtControl != 0)
  203969. {
  203970. qtControl->Release(); // it has one ref too many at this point
  203971. qtControl->QuickTimeInitialize();
  203972. qtControl->PutSizing (qtMovieFitsControl);
  203973. if (movieFile != File::nonexistent)
  203974. loadMovie (movieFile, controllerVisible);
  203975. }
  203976. }
  203977. }
  203978. }
  203979. bool QuickTimeMovieComponent::isControlCreated() const
  203980. {
  203981. return isControlOpen();
  203982. }
  203983. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  203984. const bool isControllerVisible)
  203985. {
  203986. movieFile = File::nonexistent;
  203987. movieLoaded = false;
  203988. qtMovie = 0;
  203989. controllerVisible = isControllerVisible;
  203990. createControlIfNeeded();
  203991. if (isControlCreated())
  203992. {
  203993. if (qtControl != 0)
  203994. {
  203995. qtControl->Put_MovieHandle (0);
  203996. ((QTMovieCompInternal*) internal)->clearHandle();
  203997. Movie movie;
  203998. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  203999. {
  204000. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  204001. qtMovie = qtControl->GetMovie();
  204002. if (qtMovie != 0)
  204003. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  204004. : qtMovieControllerTypeNone);
  204005. }
  204006. if (movie == 0)
  204007. ((QTMovieCompInternal*) internal)->clearHandle();
  204008. }
  204009. movieLoaded = (qtMovie != 0);
  204010. }
  204011. else
  204012. {
  204013. // You're trying to open a movie when the control hasn't yet been created, probably because
  204014. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  204015. jassertfalse
  204016. }
  204017. delete movieStream;
  204018. return movieLoaded;
  204019. }
  204020. void QuickTimeMovieComponent::closeMovie()
  204021. {
  204022. stop();
  204023. movieFile = File::nonexistent;
  204024. movieLoaded = false;
  204025. qtMovie = 0;
  204026. if (qtControl != 0)
  204027. qtControl->Put_MovieHandle (0);
  204028. ((QTMovieCompInternal*) internal)->clearHandle();
  204029. }
  204030. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  204031. {
  204032. return movieFile;
  204033. }
  204034. bool QuickTimeMovieComponent::isMovieOpen() const
  204035. {
  204036. return movieLoaded;
  204037. }
  204038. double QuickTimeMovieComponent::getMovieDuration() const
  204039. {
  204040. if (qtMovie != 0)
  204041. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  204042. return 0.0;
  204043. }
  204044. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  204045. {
  204046. if (qtMovie != 0)
  204047. {
  204048. struct QTRECT r = qtMovie->GetNaturalRect();
  204049. width = r.right - r.left;
  204050. height = r.bottom - r.top;
  204051. }
  204052. else
  204053. {
  204054. width = height = 0;
  204055. }
  204056. }
  204057. void QuickTimeMovieComponent::play()
  204058. {
  204059. if (qtMovie != 0)
  204060. qtMovie->Play();
  204061. }
  204062. void QuickTimeMovieComponent::stop()
  204063. {
  204064. if (qtMovie != 0)
  204065. qtMovie->Stop();
  204066. }
  204067. bool QuickTimeMovieComponent::isPlaying() const
  204068. {
  204069. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  204070. }
  204071. void QuickTimeMovieComponent::setPosition (const double seconds)
  204072. {
  204073. if (qtMovie != 0)
  204074. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  204075. }
  204076. double QuickTimeMovieComponent::getPosition() const
  204077. {
  204078. if (qtMovie != 0)
  204079. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  204080. return 0.0;
  204081. }
  204082. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  204083. {
  204084. if (qtMovie != 0)
  204085. qtMovie->PutRate (newSpeed);
  204086. }
  204087. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  204088. {
  204089. if (qtMovie != 0)
  204090. {
  204091. qtMovie->PutAudioVolume (newVolume);
  204092. qtMovie->PutAudioMute (newVolume <= 0);
  204093. }
  204094. }
  204095. float QuickTimeMovieComponent::getMovieVolume() const
  204096. {
  204097. if (qtMovie != 0)
  204098. return qtMovie->GetAudioVolume();
  204099. return 0.0f;
  204100. }
  204101. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  204102. {
  204103. if (qtMovie != 0)
  204104. qtMovie->PutLoop (shouldLoop);
  204105. }
  204106. bool QuickTimeMovieComponent::isLooping() const
  204107. {
  204108. return qtMovie != 0 && qtMovie->GetLoop();
  204109. }
  204110. bool QuickTimeMovieComponent::isControllerVisible() const
  204111. {
  204112. return controllerVisible;
  204113. }
  204114. void QuickTimeMovieComponent::parentHierarchyChanged()
  204115. {
  204116. createControlIfNeeded();
  204117. QTCompBaseClass::parentHierarchyChanged();
  204118. }
  204119. void QuickTimeMovieComponent::visibilityChanged()
  204120. {
  204121. createControlIfNeeded();
  204122. QTCompBaseClass::visibilityChanged();
  204123. }
  204124. void QuickTimeMovieComponent::paint (Graphics& g)
  204125. {
  204126. if (! isControlCreated())
  204127. g.fillAll (Colours::black);
  204128. }
  204129. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  204130. {
  204131. Handle dataRef = 0;
  204132. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  204133. if (err == noErr)
  204134. {
  204135. Str255 suffix;
  204136. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  204137. StringPtr name = suffix;
  204138. err = PtrAndHand (name, dataRef, name[0] + 1);
  204139. if (err == noErr)
  204140. {
  204141. long atoms[3];
  204142. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  204143. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  204144. atoms[2] = EndianU32_NtoB (MovieFileType);
  204145. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  204146. if (err == noErr)
  204147. return dataRef;
  204148. }
  204149. DisposeHandle (dataRef);
  204150. }
  204151. return 0;
  204152. }
  204153. static CFStringRef juceStringToCFString (const String& s)
  204154. {
  204155. const int len = s.length();
  204156. const juce_wchar* const t = (const juce_wchar*) s;
  204157. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  204158. for (int i = 0; i <= len; ++i)
  204159. temp[i] = t[i];
  204160. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  204161. juce_free (temp);
  204162. return result;
  204163. }
  204164. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  204165. {
  204166. Boolean trueBool = true;
  204167. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204168. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  204169. props[prop].propValueSize = sizeof (trueBool);
  204170. props[prop].propValueAddress = &trueBool;
  204171. ++prop;
  204172. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204173. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  204174. props[prop].propValueSize = sizeof (trueBool);
  204175. props[prop].propValueAddress = &trueBool;
  204176. ++prop;
  204177. Boolean isActive = true;
  204178. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  204179. props[prop].propID = kQTNewMoviePropertyID_Active;
  204180. props[prop].propValueSize = sizeof (isActive);
  204181. props[prop].propValueAddress = &isActive;
  204182. ++prop;
  204183. MacSetPort (0);
  204184. jassert (prop <= 5);
  204185. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  204186. return err == noErr;
  204187. }
  204188. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  204189. {
  204190. if (input == 0)
  204191. return false;
  204192. dataHandle = 0;
  204193. bool ok = false;
  204194. QTNewMoviePropertyElement props[5];
  204195. zeromem (props, sizeof (props));
  204196. int prop = 0;
  204197. DataReferenceRecord dr;
  204198. props[prop].propClass = kQTPropertyClass_DataLocation;
  204199. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  204200. props[prop].propValueSize = sizeof (dr);
  204201. props[prop].propValueAddress = (void*) &dr;
  204202. ++prop;
  204203. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  204204. if (fin != 0)
  204205. {
  204206. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  204207. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  204208. &dr.dataRef, &dr.dataRefType);
  204209. ok = openMovie (props, prop, movie);
  204210. DisposeHandle (dr.dataRef);
  204211. CFRelease (filePath);
  204212. }
  204213. else
  204214. {
  204215. // sanity-check because this currently needs to load the whole stream into memory..
  204216. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  204217. dataHandle = NewHandle ((Size) input->getTotalLength());
  204218. HLock (dataHandle);
  204219. // read the entire stream into memory - this is a pain, but can't get it to work
  204220. // properly using a custom callback to supply the data.
  204221. input->read (*dataHandle, (int) input->getTotalLength());
  204222. HUnlock (dataHandle);
  204223. // different types to get QT to try. (We should really be a bit smarter here by
  204224. // working out in advance which one the stream contains, rather than just trying
  204225. // each one)
  204226. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  204227. "\04.avi", "\04.m4a" };
  204228. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  204229. {
  204230. /* // this fails for some bizarre reason - it can be bodged to work with
  204231. // movies, but can't seem to do it for other file types..
  204232. QTNewMovieUserProcRecord procInfo;
  204233. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  204234. procInfo.getMovieUserProcRefcon = this;
  204235. procInfo.defaultDataRef.dataRef = dataRef;
  204236. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  204237. props[prop].propClass = kQTPropertyClass_DataLocation;
  204238. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  204239. props[prop].propValueSize = sizeof (procInfo);
  204240. props[prop].propValueAddress = (void*) &procInfo;
  204241. ++prop; */
  204242. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  204243. dr.dataRefType = HandleDataHandlerSubType;
  204244. ok = openMovie (props, prop, movie);
  204245. DisposeHandle (dr.dataRef);
  204246. }
  204247. }
  204248. return ok;
  204249. }
  204250. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  204251. const bool isControllerVisible)
  204252. {
  204253. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  204254. movieFile = movieFile_;
  204255. return ok;
  204256. }
  204257. void QuickTimeMovieComponent::goToStart()
  204258. {
  204259. setPosition (0.0);
  204260. }
  204261. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  204262. const RectanglePlacement& placement)
  204263. {
  204264. int normalWidth, normalHeight;
  204265. getMovieNormalSize (normalWidth, normalHeight);
  204266. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  204267. {
  204268. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  204269. placement.applyTo (x, y, w, h,
  204270. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  204271. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  204272. if (w > 0 && h > 0)
  204273. {
  204274. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  204275. roundDoubleToInt (w), roundDoubleToInt (h));
  204276. }
  204277. }
  204278. else
  204279. {
  204280. setBounds (spaceToFitWithin);
  204281. }
  204282. }
  204283. #endif
  204284. /********* End of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204285. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204286. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204287. // compiled on its own).
  204288. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  204289. class WebBrowserComponentInternal : public ActiveXControlComponent
  204290. {
  204291. public:
  204292. WebBrowserComponentInternal()
  204293. : browser (0),
  204294. connectionPoint (0),
  204295. adviseCookie (0)
  204296. {
  204297. }
  204298. ~WebBrowserComponentInternal()
  204299. {
  204300. if (connectionPoint != 0)
  204301. connectionPoint->Unadvise (adviseCookie);
  204302. if (browser != 0)
  204303. browser->Release();
  204304. }
  204305. void createBrowser()
  204306. {
  204307. createControl (&CLSID_WebBrowser);
  204308. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  204309. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  204310. if (connectionPointContainer != 0)
  204311. {
  204312. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  204313. &connectionPoint);
  204314. if (connectionPoint != 0)
  204315. {
  204316. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  204317. jassert (owner != 0);
  204318. EventHandler* handler = new EventHandler (owner);
  204319. connectionPoint->Advise (handler, &adviseCookie);
  204320. }
  204321. }
  204322. }
  204323. void goToURL (const String& url,
  204324. const StringArray* headers,
  204325. const MemoryBlock* postData)
  204326. {
  204327. if (browser != 0)
  204328. {
  204329. LPSAFEARRAY sa = 0;
  204330. _variant_t flags, frame, postDataVar, headersVar;
  204331. if (headers != 0)
  204332. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  204333. if (postData != 0 && postData->getSize() > 0)
  204334. {
  204335. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  204336. if (sa != 0)
  204337. {
  204338. void* data = 0;
  204339. SafeArrayAccessData (sa, &data);
  204340. jassert (data != 0);
  204341. if (data != 0)
  204342. {
  204343. postData->copyTo (data, 0, postData->getSize());
  204344. SafeArrayUnaccessData (sa);
  204345. VARIANT postDataVar2;
  204346. VariantInit (&postDataVar2);
  204347. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  204348. V_ARRAY (&postDataVar2) = sa;
  204349. postDataVar = postDataVar2;
  204350. }
  204351. }
  204352. }
  204353. browser->Navigate ((BSTR) (const OLECHAR*) url,
  204354. &flags, &frame,
  204355. &postDataVar, &headersVar);
  204356. if (sa != 0)
  204357. SafeArrayDestroy (sa);
  204358. }
  204359. }
  204360. IWebBrowser2* browser;
  204361. juce_UseDebuggingNewOperator
  204362. private:
  204363. IConnectionPoint* connectionPoint;
  204364. DWORD adviseCookie;
  204365. class EventHandler : public IDispatch
  204366. {
  204367. public:
  204368. EventHandler (WebBrowserComponent* owner_)
  204369. : owner (owner_),
  204370. refCount (0)
  204371. {
  204372. }
  204373. ~EventHandler()
  204374. {
  204375. }
  204376. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204377. {
  204378. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  204379. {
  204380. AddRef();
  204381. *result = this;
  204382. return S_OK;
  204383. }
  204384. *result = 0;
  204385. return E_NOINTERFACE;
  204386. }
  204387. ULONG __stdcall AddRef() { return ++refCount; }
  204388. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  204389. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  204390. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  204391. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  204392. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  204393. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  204394. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  204395. UINT __RPC_FAR* /*puArgErr*/)
  204396. {
  204397. switch (dispIdMember)
  204398. {
  204399. case DISPID_BEFORENAVIGATE2:
  204400. {
  204401. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  204402. String url;
  204403. if ((vurl->vt & VT_BYREF) != 0)
  204404. url = *vurl->pbstrVal;
  204405. else
  204406. url = vurl->bstrVal;
  204407. *pDispParams->rgvarg->pboolVal
  204408. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  204409. : VARIANT_TRUE;
  204410. return S_OK;
  204411. }
  204412. default:
  204413. break;
  204414. }
  204415. return E_NOTIMPL;
  204416. }
  204417. juce_UseDebuggingNewOperator
  204418. private:
  204419. WebBrowserComponent* const owner;
  204420. int refCount;
  204421. EventHandler (const EventHandler&);
  204422. const EventHandler& operator= (const EventHandler&);
  204423. };
  204424. };
  204425. WebBrowserComponent::WebBrowserComponent()
  204426. : browser (0),
  204427. blankPageShown (false)
  204428. {
  204429. setOpaque (true);
  204430. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  204431. }
  204432. WebBrowserComponent::~WebBrowserComponent()
  204433. {
  204434. delete browser;
  204435. }
  204436. void WebBrowserComponent::goToURL (const String& url,
  204437. const StringArray* headers,
  204438. const MemoryBlock* postData)
  204439. {
  204440. lastURL = url;
  204441. lastHeaders.clear();
  204442. if (headers != 0)
  204443. lastHeaders = *headers;
  204444. lastPostData.setSize (0);
  204445. if (postData != 0)
  204446. lastPostData = *postData;
  204447. blankPageShown = false;
  204448. browser->goToURL (url, headers, postData);
  204449. }
  204450. void WebBrowserComponent::stop()
  204451. {
  204452. if (browser->browser != 0)
  204453. browser->browser->Stop();
  204454. }
  204455. void WebBrowserComponent::goBack()
  204456. {
  204457. lastURL = String::empty;
  204458. blankPageShown = false;
  204459. if (browser->browser != 0)
  204460. browser->browser->GoBack();
  204461. }
  204462. void WebBrowserComponent::goForward()
  204463. {
  204464. lastURL = String::empty;
  204465. if (browser->browser != 0)
  204466. browser->browser->GoForward();
  204467. }
  204468. void WebBrowserComponent::refresh()
  204469. {
  204470. if (browser->browser != 0)
  204471. browser->browser->Refresh();
  204472. }
  204473. void WebBrowserComponent::paint (Graphics& g)
  204474. {
  204475. if (browser->browser == 0)
  204476. g.fillAll (Colours::white);
  204477. }
  204478. void WebBrowserComponent::checkWindowAssociation()
  204479. {
  204480. if (isShowing())
  204481. {
  204482. if (browser->browser == 0 && getPeer() != 0)
  204483. {
  204484. browser->createBrowser();
  204485. reloadLastURL();
  204486. }
  204487. else
  204488. {
  204489. if (blankPageShown)
  204490. goBack();
  204491. }
  204492. }
  204493. else
  204494. {
  204495. if (browser != 0 && ! blankPageShown)
  204496. {
  204497. // when the component becomes invisible, some stuff like flash
  204498. // carries on playing audio, so we need to force it onto a blank
  204499. // page to avoid this..
  204500. blankPageShown = true;
  204501. browser->goToURL ("about:blank", 0, 0);
  204502. }
  204503. }
  204504. }
  204505. void WebBrowserComponent::reloadLastURL()
  204506. {
  204507. if (lastURL.isNotEmpty())
  204508. {
  204509. goToURL (lastURL, &lastHeaders, &lastPostData);
  204510. lastURL = String::empty;
  204511. }
  204512. }
  204513. void WebBrowserComponent::parentHierarchyChanged()
  204514. {
  204515. checkWindowAssociation();
  204516. }
  204517. void WebBrowserComponent::resized()
  204518. {
  204519. browser->setSize (getWidth(), getHeight());
  204520. }
  204521. void WebBrowserComponent::visibilityChanged()
  204522. {
  204523. checkWindowAssociation();
  204524. }
  204525. bool WebBrowserComponent::pageAboutToLoad (const String&)
  204526. {
  204527. return true;
  204528. }
  204529. #endif
  204530. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204531. /********* Start of inlined file: juce_win32_OpenGLComponent.cpp *********/
  204532. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204533. // compiled on its own).
  204534. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  204535. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  204536. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  204537. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  204538. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  204539. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  204540. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  204541. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  204542. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  204543. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  204544. #define WGL_ACCELERATION_ARB 0x2003
  204545. #define WGL_SWAP_METHOD_ARB 0x2007
  204546. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  204547. #define WGL_PIXEL_TYPE_ARB 0x2013
  204548. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  204549. #define WGL_COLOR_BITS_ARB 0x2014
  204550. #define WGL_RED_BITS_ARB 0x2015
  204551. #define WGL_GREEN_BITS_ARB 0x2017
  204552. #define WGL_BLUE_BITS_ARB 0x2019
  204553. #define WGL_ALPHA_BITS_ARB 0x201B
  204554. #define WGL_DEPTH_BITS_ARB 0x2022
  204555. #define WGL_STENCIL_BITS_ARB 0x2023
  204556. #define WGL_FULL_ACCELERATION_ARB 0x2027
  204557. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  204558. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  204559. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  204560. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  204561. #define WGL_STEREO_ARB 0x2012
  204562. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  204563. #define WGL_SAMPLES_ARB 0x2042
  204564. #define WGL_TYPE_RGBA_ARB 0x202B
  204565. static void getWglExtensions (HDC dc, StringArray& result) throw()
  204566. {
  204567. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  204568. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  204569. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  204570. else
  204571. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  204572. }
  204573. class WindowedGLContext : public OpenGLContext
  204574. {
  204575. public:
  204576. WindowedGLContext (Component* const component_,
  204577. HGLRC contextToShareWith,
  204578. const OpenGLPixelFormat& pixelFormat)
  204579. : renderContext (0),
  204580. nativeWindow (0),
  204581. dc (0),
  204582. component (component_)
  204583. {
  204584. jassert (component != 0);
  204585. createNativeWindow();
  204586. // Use a default pixel format that should be supported everywhere
  204587. PIXELFORMATDESCRIPTOR pfd;
  204588. zerostruct (pfd);
  204589. pfd.nSize = sizeof (pfd);
  204590. pfd.nVersion = 1;
  204591. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  204592. pfd.iPixelType = PFD_TYPE_RGBA;
  204593. pfd.cColorBits = 24;
  204594. pfd.cDepthBits = 16;
  204595. const int format = ChoosePixelFormat (dc, &pfd);
  204596. if (format != 0)
  204597. SetPixelFormat (dc, format, &pfd);
  204598. renderContext = wglCreateContext (dc);
  204599. makeActive();
  204600. setPixelFormat (pixelFormat);
  204601. if (contextToShareWith != 0 && renderContext != 0)
  204602. wglShareLists (contextToShareWith, renderContext);
  204603. }
  204604. ~WindowedGLContext()
  204605. {
  204606. makeInactive();
  204607. wglDeleteContext (renderContext);
  204608. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  204609. delete nativeWindow;
  204610. }
  204611. bool makeActive() const throw()
  204612. {
  204613. jassert (renderContext != 0);
  204614. return wglMakeCurrent (dc, renderContext) != 0;
  204615. }
  204616. bool makeInactive() const throw()
  204617. {
  204618. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  204619. }
  204620. bool isActive() const throw()
  204621. {
  204622. return wglGetCurrentContext() == renderContext;
  204623. }
  204624. const OpenGLPixelFormat getPixelFormat() const
  204625. {
  204626. OpenGLPixelFormat pf;
  204627. makeActive();
  204628. StringArray availableExtensions;
  204629. getWglExtensions (dc, availableExtensions);
  204630. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  204631. return pf;
  204632. }
  204633. void* getRawContext() const throw()
  204634. {
  204635. return renderContext;
  204636. }
  204637. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  204638. {
  204639. makeActive();
  204640. PIXELFORMATDESCRIPTOR pfd;
  204641. zerostruct (pfd);
  204642. pfd.nSize = sizeof (pfd);
  204643. pfd.nVersion = 1;
  204644. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  204645. pfd.iPixelType = PFD_TYPE_RGBA;
  204646. pfd.iLayerType = PFD_MAIN_PLANE;
  204647. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  204648. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  204649. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  204650. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  204651. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  204652. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  204653. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  204654. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  204655. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  204656. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  204657. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  204658. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  204659. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  204660. int format = 0;
  204661. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  204662. StringArray availableExtensions;
  204663. getWglExtensions (dc, availableExtensions);
  204664. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  204665. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  204666. {
  204667. int attributes[64];
  204668. int n = 0;
  204669. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  204670. attributes[n++] = GL_TRUE;
  204671. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  204672. attributes[n++] = GL_TRUE;
  204673. attributes[n++] = WGL_ACCELERATION_ARB;
  204674. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  204675. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  204676. attributes[n++] = GL_TRUE;
  204677. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  204678. attributes[n++] = WGL_TYPE_RGBA_ARB;
  204679. attributes[n++] = WGL_COLOR_BITS_ARB;
  204680. attributes[n++] = pfd.cColorBits;
  204681. attributes[n++] = WGL_RED_BITS_ARB;
  204682. attributes[n++] = pixelFormat.redBits;
  204683. attributes[n++] = WGL_GREEN_BITS_ARB;
  204684. attributes[n++] = pixelFormat.greenBits;
  204685. attributes[n++] = WGL_BLUE_BITS_ARB;
  204686. attributes[n++] = pixelFormat.blueBits;
  204687. attributes[n++] = WGL_ALPHA_BITS_ARB;
  204688. attributes[n++] = pixelFormat.alphaBits;
  204689. attributes[n++] = WGL_DEPTH_BITS_ARB;
  204690. attributes[n++] = pixelFormat.depthBufferBits;
  204691. if (pixelFormat.stencilBufferBits > 0)
  204692. {
  204693. attributes[n++] = WGL_STENCIL_BITS_ARB;
  204694. attributes[n++] = pixelFormat.stencilBufferBits;
  204695. }
  204696. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  204697. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  204698. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  204699. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  204700. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  204701. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  204702. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  204703. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  204704. if (availableExtensions.contains ("WGL_ARB_multisample")
  204705. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  204706. {
  204707. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  204708. attributes[n++] = 1;
  204709. attributes[n++] = WGL_SAMPLES_ARB;
  204710. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  204711. }
  204712. attributes[n++] = 0;
  204713. UINT formatsCount;
  204714. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  204715. (void) ok;
  204716. jassert (ok);
  204717. }
  204718. else
  204719. {
  204720. format = ChoosePixelFormat (dc, &pfd);
  204721. }
  204722. if (format != 0)
  204723. {
  204724. makeInactive();
  204725. // win32 can't change the pixel format of a window, so need to delete the
  204726. // old one and create a new one..
  204727. jassert (nativeWindow != 0);
  204728. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  204729. delete nativeWindow;
  204730. createNativeWindow();
  204731. if (SetPixelFormat (dc, format, &pfd))
  204732. {
  204733. wglDeleteContext (renderContext);
  204734. renderContext = wglCreateContext (dc);
  204735. jassert (renderContext != 0);
  204736. return renderContext != 0;
  204737. }
  204738. }
  204739. return false;
  204740. }
  204741. void updateWindowPosition (int x, int y, int w, int h, int)
  204742. {
  204743. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  204744. x, y, w, h,
  204745. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204746. }
  204747. void repaint()
  204748. {
  204749. int x, y, w, h;
  204750. nativeWindow->getBounds (x, y, w, h);
  204751. nativeWindow->repaint (0, 0, w, h);
  204752. }
  204753. void swapBuffers()
  204754. {
  204755. SwapBuffers (dc);
  204756. }
  204757. bool setSwapInterval (const int numFramesPerSwap)
  204758. {
  204759. makeActive();
  204760. StringArray availableExtensions;
  204761. getWglExtensions (dc, availableExtensions);
  204762. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  204763. return availableExtensions.contains ("WGL_EXT_swap_control")
  204764. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  204765. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  204766. }
  204767. int getSwapInterval() const
  204768. {
  204769. makeActive();
  204770. StringArray availableExtensions;
  204771. getWglExtensions (dc, availableExtensions);
  204772. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  204773. if (availableExtensions.contains ("WGL_EXT_swap_control")
  204774. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  204775. return wglGetSwapIntervalEXT();
  204776. return 0;
  204777. }
  204778. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  204779. {
  204780. jassert (isActive());
  204781. StringArray availableExtensions;
  204782. getWglExtensions (dc, availableExtensions);
  204783. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  204784. int numTypes = 0;
  204785. if (availableExtensions.contains("WGL_ARB_pixel_format")
  204786. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  204787. {
  204788. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  204789. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  204790. jassertfalse
  204791. }
  204792. else
  204793. {
  204794. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  204795. }
  204796. OpenGLPixelFormat pf;
  204797. for (int i = 0; i < numTypes; ++i)
  204798. {
  204799. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  204800. {
  204801. bool alreadyListed = false;
  204802. for (int j = results.size(); --j >= 0;)
  204803. if (pf == *results.getUnchecked(j))
  204804. alreadyListed = true;
  204805. if (! alreadyListed)
  204806. results.add (new OpenGLPixelFormat (pf));
  204807. }
  204808. }
  204809. }
  204810. void* getNativeWindowHandle() const
  204811. {
  204812. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  204813. }
  204814. juce_UseDebuggingNewOperator
  204815. HGLRC renderContext;
  204816. private:
  204817. Win32ComponentPeer* nativeWindow;
  204818. Component* const component;
  204819. HDC dc;
  204820. void createNativeWindow()
  204821. {
  204822. nativeWindow = new Win32ComponentPeer (component, 0);
  204823. nativeWindow->dontRepaint = true;
  204824. nativeWindow->setVisible (true);
  204825. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  204826. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  204827. if (peer != 0)
  204828. {
  204829. SetParent (hwnd, (HWND) peer->getNativeHandle());
  204830. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  204831. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  204832. }
  204833. dc = GetDC (hwnd);
  204834. }
  204835. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  204836. OpenGLPixelFormat& result,
  204837. const StringArray& availableExtensions) const throw()
  204838. {
  204839. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  204840. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  204841. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  204842. {
  204843. int attributes[32];
  204844. int numAttributes = 0;
  204845. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  204846. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  204847. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  204848. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  204849. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  204850. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  204851. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  204852. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  204853. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  204854. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  204855. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  204856. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  204857. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  204858. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  204859. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  204860. if (availableExtensions.contains ("WGL_ARB_multisample"))
  204861. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  204862. int values[32];
  204863. zeromem (values, sizeof (values));
  204864. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  204865. {
  204866. int n = 0;
  204867. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  204868. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  204869. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  204870. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  204871. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  204872. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  204873. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  204874. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  204875. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  204876. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  204877. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  204878. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  204879. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  204880. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  204881. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  204882. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  204883. return isValidFormat;
  204884. }
  204885. else
  204886. {
  204887. jassertfalse
  204888. }
  204889. }
  204890. else
  204891. {
  204892. PIXELFORMATDESCRIPTOR pfd;
  204893. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  204894. {
  204895. result.redBits = pfd.cRedBits;
  204896. result.greenBits = pfd.cGreenBits;
  204897. result.blueBits = pfd.cBlueBits;
  204898. result.alphaBits = pfd.cAlphaBits;
  204899. result.depthBufferBits = pfd.cDepthBits;
  204900. result.stencilBufferBits = pfd.cStencilBits;
  204901. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  204902. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  204903. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  204904. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  204905. result.fullSceneAntiAliasingNumSamples = 0;
  204906. return true;
  204907. }
  204908. else
  204909. {
  204910. jassertfalse
  204911. }
  204912. }
  204913. return false;
  204914. }
  204915. WindowedGLContext (const WindowedGLContext&);
  204916. const WindowedGLContext& operator= (const WindowedGLContext&);
  204917. };
  204918. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  204919. const OpenGLPixelFormat& pixelFormat,
  204920. const OpenGLContext* const contextToShareWith)
  204921. {
  204922. WindowedGLContext* c = new WindowedGLContext (component,
  204923. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  204924. pixelFormat);
  204925. if (c->renderContext == 0)
  204926. deleteAndZero (c);
  204927. return c;
  204928. }
  204929. void* OpenGLComponent::getNativeWindowHandle() const
  204930. {
  204931. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle() : 0;
  204932. }
  204933. void juce_glViewport (const int w, const int h)
  204934. {
  204935. glViewport (0, 0, w, h);
  204936. }
  204937. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  204938. OwnedArray <OpenGLPixelFormat>& results)
  204939. {
  204940. Component tempComp;
  204941. {
  204942. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  204943. wc.makeActive();
  204944. wc.findAlternativeOpenGLPixelFormats (results);
  204945. }
  204946. }
  204947. #endif
  204948. /********* End of inlined file: juce_win32_OpenGLComponent.cpp *********/
  204949. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  204950. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204951. // compiled on its own).
  204952. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  204953. //***************************************************************************
  204954. // %%% TARGET STATUS VALUES %%%
  204955. //***************************************************************************
  204956. #define STATUS_GOOD 0x00 // Status Good
  204957. #define STATUS_CHKCOND 0x02 // Check Condition
  204958. #define STATUS_CONDMET 0x04 // Condition Met
  204959. #define STATUS_BUSY 0x08 // Busy
  204960. #define STATUS_INTERM 0x10 // Intermediate
  204961. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  204962. #define STATUS_RESCONF 0x18 // Reservation conflict
  204963. #define STATUS_COMTERM 0x22 // Command Terminated
  204964. #define STATUS_QFULL 0x28 // Queue full
  204965. //***************************************************************************
  204966. // %%% SCSI MISCELLANEOUS EQUATES %%%
  204967. //***************************************************************************
  204968. #define MAXLUN 7 // Maximum Logical Unit Id
  204969. #define MAXTARG 7 // Maximum Target Id
  204970. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  204971. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  204972. //***************************************************************************
  204973. // %%% Commands for all Device Types %%%
  204974. //***************************************************************************
  204975. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  204976. #define SCSI_COMPARE 0x39 // Compare (O)
  204977. #define SCSI_COPY 0x18 // Copy (O)
  204978. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  204979. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  204980. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  204981. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  204982. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  204983. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  204984. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  204985. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  204986. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  204987. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  204988. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  204989. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  204990. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  204991. //***************************************************************************
  204992. // %%% Commands Unique to Direct Access Devices %%%
  204993. //***************************************************************************
  204994. #define SCSI_COMPARE 0x39 // Compare (O)
  204995. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  204996. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  204997. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  204998. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  204999. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  205000. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  205001. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  205002. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  205003. #define SCSI_READ_LONG 0x3E // Read Long (O)
  205004. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  205005. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  205006. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  205007. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  205008. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  205009. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  205010. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  205011. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  205012. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  205013. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  205014. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  205015. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  205016. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  205017. #define SCSI_VERIFY 0x2F // Verify (O)
  205018. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  205019. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  205020. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  205021. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  205022. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  205023. //***************************************************************************
  205024. // %%% Commands Unique to Sequential Access Devices %%%
  205025. //***************************************************************************
  205026. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  205027. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  205028. #define SCSI_LOCATE 0x2B // Locate (O)
  205029. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  205030. #define SCSI_READ_POS 0x34 // Read Position (O)
  205031. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  205032. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  205033. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  205034. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  205035. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  205036. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  205037. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  205038. //***************************************************************************
  205039. // %%% Commands Unique to Printer Devices %%%
  205040. //***************************************************************************
  205041. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  205042. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  205043. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  205044. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  205045. //***************************************************************************
  205046. // %%% Commands Unique to Processor Devices %%%
  205047. //***************************************************************************
  205048. #define SCSI_RECEIVE 0x08 // Receive (O)
  205049. #define SCSI_SEND 0x0A // Send (O)
  205050. //***************************************************************************
  205051. // %%% Commands Unique to Write-Once Devices %%%
  205052. //***************************************************************************
  205053. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  205054. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  205055. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  205056. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  205057. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  205058. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  205059. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  205060. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  205061. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  205062. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  205063. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  205064. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  205065. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  205066. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  205067. //***************************************************************************
  205068. // %%% Commands Unique to CD-ROM Devices %%%
  205069. //***************************************************************************
  205070. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  205071. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  205072. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  205073. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  205074. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  205075. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  205076. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  205077. #define SCSI_READHEADER 0x44 // Read Header (O)
  205078. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  205079. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  205080. //***************************************************************************
  205081. // %%% Commands Unique to Scanner Devices %%%
  205082. //***************************************************************************
  205083. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  205084. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  205085. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  205086. #define SCSI_SCAN 0x1B // Scan (O)
  205087. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  205088. //***************************************************************************
  205089. // %%% Commands Unique to Optical Memory Devices %%%
  205090. //***************************************************************************
  205091. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  205092. //***************************************************************************
  205093. // %%% Commands Unique to Medium Changer Devices %%%
  205094. //***************************************************************************
  205095. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  205096. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  205097. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  205098. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  205099. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  205100. //***************************************************************************
  205101. // %%% Commands Unique to Communication Devices %%%
  205102. //***************************************************************************
  205103. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  205104. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  205105. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  205106. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  205107. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  205108. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  205109. //***************************************************************************
  205110. // %%% Request Sense Data Format %%%
  205111. //***************************************************************************
  205112. typedef struct {
  205113. BYTE ErrorCode; // Error Code (70H or 71H)
  205114. BYTE SegmentNum; // Number of current segment descriptor
  205115. BYTE SenseKey; // Sense Key(See bit definitions too)
  205116. BYTE InfoByte0; // Information MSB
  205117. BYTE InfoByte1; // Information MID
  205118. BYTE InfoByte2; // Information MID
  205119. BYTE InfoByte3; // Information LSB
  205120. BYTE AddSenLen; // Additional Sense Length
  205121. BYTE ComSpecInf0; // Command Specific Information MSB
  205122. BYTE ComSpecInf1; // Command Specific Information MID
  205123. BYTE ComSpecInf2; // Command Specific Information MID
  205124. BYTE ComSpecInf3; // Command Specific Information LSB
  205125. BYTE AddSenseCode; // Additional Sense Code
  205126. BYTE AddSenQual; // Additional Sense Code Qualifier
  205127. BYTE FieldRepUCode; // Field Replaceable Unit Code
  205128. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  205129. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  205130. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  205131. BYTE AddSenseBytes; // Additional Sense Bytes
  205132. } SENSE_DATA_FMT;
  205133. //***************************************************************************
  205134. // %%% REQUEST SENSE ERROR CODE %%%
  205135. //***************************************************************************
  205136. #define SERROR_CURRENT 0x70 // Current Errors
  205137. #define SERROR_DEFERED 0x71 // Deferred Errors
  205138. //***************************************************************************
  205139. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  205140. //***************************************************************************
  205141. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  205142. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  205143. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  205144. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  205145. //***************************************************************************
  205146. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  205147. //***************************************************************************
  205148. #define KEY_NOSENSE 0x00 // No Sense
  205149. #define KEY_RECERROR 0x01 // Recovered Error
  205150. #define KEY_NOTREADY 0x02 // Not Ready
  205151. #define KEY_MEDIUMERR 0x03 // Medium Error
  205152. #define KEY_HARDERROR 0x04 // Hardware Error
  205153. #define KEY_ILLGLREQ 0x05 // Illegal Request
  205154. #define KEY_UNITATT 0x06 // Unit Attention
  205155. #define KEY_DATAPROT 0x07 // Data Protect
  205156. #define KEY_BLANKCHK 0x08 // Blank Check
  205157. #define KEY_VENDSPEC 0x09 // Vendor Specific
  205158. #define KEY_COPYABORT 0x0A // Copy Abort
  205159. #define KEY_EQUAL 0x0C // Equal (Search)
  205160. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  205161. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  205162. #define KEY_RESERVED 0x0F // Reserved
  205163. //***************************************************************************
  205164. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  205165. //***************************************************************************
  205166. #define DTYPE_DASD 0x00 // Disk Device
  205167. #define DTYPE_SEQD 0x01 // Tape Device
  205168. #define DTYPE_PRNT 0x02 // Printer
  205169. #define DTYPE_PROC 0x03 // Processor
  205170. #define DTYPE_WORM 0x04 // Write-once read-multiple
  205171. #define DTYPE_CROM 0x05 // CD-ROM device
  205172. #define DTYPE_SCAN 0x06 // Scanner device
  205173. #define DTYPE_OPTI 0x07 // Optical memory device
  205174. #define DTYPE_JUKE 0x08 // Medium Changer device
  205175. #define DTYPE_COMM 0x09 // Communications device
  205176. #define DTYPE_RESL 0x0A // Reserved (low)
  205177. #define DTYPE_RESH 0x1E // Reserved (high)
  205178. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  205179. //***************************************************************************
  205180. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  205181. //***************************************************************************
  205182. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  205183. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  205184. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  205185. #define ANSI_RESLO 0x3 // Reserved (low)
  205186. #define ANSI_RESHI 0x7 // Reserved (high)
  205187. typedef struct
  205188. {
  205189. USHORT Length;
  205190. UCHAR ScsiStatus;
  205191. UCHAR PathId;
  205192. UCHAR TargetId;
  205193. UCHAR Lun;
  205194. UCHAR CdbLength;
  205195. UCHAR SenseInfoLength;
  205196. UCHAR DataIn;
  205197. ULONG DataTransferLength;
  205198. ULONG TimeOutValue;
  205199. ULONG DataBufferOffset;
  205200. ULONG SenseInfoOffset;
  205201. UCHAR Cdb[16];
  205202. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  205203. typedef struct
  205204. {
  205205. USHORT Length;
  205206. UCHAR ScsiStatus;
  205207. UCHAR PathId;
  205208. UCHAR TargetId;
  205209. UCHAR Lun;
  205210. UCHAR CdbLength;
  205211. UCHAR SenseInfoLength;
  205212. UCHAR DataIn;
  205213. ULONG DataTransferLength;
  205214. ULONG TimeOutValue;
  205215. PVOID DataBuffer;
  205216. ULONG SenseInfoOffset;
  205217. UCHAR Cdb[16];
  205218. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  205219. typedef struct
  205220. {
  205221. SCSI_PASS_THROUGH_DIRECT spt;
  205222. ULONG Filler;
  205223. UCHAR ucSenseBuf[32];
  205224. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  205225. typedef struct
  205226. {
  205227. ULONG Length;
  205228. UCHAR PortNumber;
  205229. UCHAR PathId;
  205230. UCHAR TargetId;
  205231. UCHAR Lun;
  205232. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  205233. #define METHOD_BUFFERED 0
  205234. #define METHOD_IN_DIRECT 1
  205235. #define METHOD_OUT_DIRECT 2
  205236. #define METHOD_NEITHER 3
  205237. #define FILE_ANY_ACCESS 0
  205238. #ifndef FILE_READ_ACCESS
  205239. #define FILE_READ_ACCESS (0x0001)
  205240. #endif
  205241. #ifndef FILE_WRITE_ACCESS
  205242. #define FILE_WRITE_ACCESS (0x0002)
  205243. #endif
  205244. #define IOCTL_SCSI_BASE 0x00000004
  205245. #define SCSI_IOCTL_DATA_OUT 0
  205246. #define SCSI_IOCTL_DATA_IN 1
  205247. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  205248. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  205249. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  205250. )
  205251. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205252. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  205253. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205254. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  205255. #define SENSE_LEN 14
  205256. #define SRB_DIR_SCSI 0x00
  205257. #define SRB_POSTING 0x01
  205258. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  205259. #define SRB_DIR_IN 0x08
  205260. #define SRB_DIR_OUT 0x10
  205261. #define SRB_EVENT_NOTIFY 0x40
  205262. #define RESIDUAL_COUNT_SUPPORTED 0x02
  205263. #define MAX_SRB_TIMEOUT 1080001u
  205264. #define DEFAULT_SRB_TIMEOUT 1080001u
  205265. #define SC_HA_INQUIRY 0x00
  205266. #define SC_GET_DEV_TYPE 0x01
  205267. #define SC_EXEC_SCSI_CMD 0x02
  205268. #define SC_ABORT_SRB 0x03
  205269. #define SC_RESET_DEV 0x04
  205270. #define SC_SET_HA_PARMS 0x05
  205271. #define SC_GET_DISK_INFO 0x06
  205272. #define SC_RESCAN_SCSI_BUS 0x07
  205273. #define SC_GETSET_TIMEOUTS 0x08
  205274. #define SS_PENDING 0x00
  205275. #define SS_COMP 0x01
  205276. #define SS_ABORTED 0x02
  205277. #define SS_ABORT_FAIL 0x03
  205278. #define SS_ERR 0x04
  205279. #define SS_INVALID_CMD 0x80
  205280. #define SS_INVALID_HA 0x81
  205281. #define SS_NO_DEVICE 0x82
  205282. #define SS_INVALID_SRB 0xE0
  205283. #define SS_OLD_MANAGER 0xE1
  205284. #define SS_BUFFER_ALIGN 0xE1
  205285. #define SS_ILLEGAL_MODE 0xE2
  205286. #define SS_NO_ASPI 0xE3
  205287. #define SS_FAILED_INIT 0xE4
  205288. #define SS_ASPI_IS_BUSY 0xE5
  205289. #define SS_BUFFER_TO_BIG 0xE6
  205290. #define SS_BUFFER_TOO_BIG 0xE6
  205291. #define SS_MISMATCHED_COMPONENTS 0xE7
  205292. #define SS_NO_ADAPTERS 0xE8
  205293. #define SS_INSUFFICIENT_RESOURCES 0xE9
  205294. #define SS_ASPI_IS_SHUTDOWN 0xEA
  205295. #define SS_BAD_INSTALL 0xEB
  205296. #define HASTAT_OK 0x00
  205297. #define HASTAT_SEL_TO 0x11
  205298. #define HASTAT_DO_DU 0x12
  205299. #define HASTAT_BUS_FREE 0x13
  205300. #define HASTAT_PHASE_ERR 0x14
  205301. #define HASTAT_TIMEOUT 0x09
  205302. #define HASTAT_COMMAND_TIMEOUT 0x0B
  205303. #define HASTAT_MESSAGE_REJECT 0x0D
  205304. #define HASTAT_BUS_RESET 0x0E
  205305. #define HASTAT_PARITY_ERROR 0x0F
  205306. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  205307. #define PACKED
  205308. #pragma pack(1)
  205309. typedef struct
  205310. {
  205311. BYTE SRB_Cmd;
  205312. BYTE SRB_Status;
  205313. BYTE SRB_HaID;
  205314. BYTE SRB_Flags;
  205315. DWORD SRB_Hdr_Rsvd;
  205316. BYTE HA_Count;
  205317. BYTE HA_SCSI_ID;
  205318. BYTE HA_ManagerId[16];
  205319. BYTE HA_Identifier[16];
  205320. BYTE HA_Unique[16];
  205321. WORD HA_Rsvd1;
  205322. BYTE pad[20];
  205323. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  205324. typedef struct
  205325. {
  205326. BYTE SRB_Cmd;
  205327. BYTE SRB_Status;
  205328. BYTE SRB_HaID;
  205329. BYTE SRB_Flags;
  205330. DWORD SRB_Hdr_Rsvd;
  205331. BYTE SRB_Target;
  205332. BYTE SRB_Lun;
  205333. BYTE SRB_DeviceType;
  205334. BYTE SRB_Rsvd1;
  205335. BYTE pad[68];
  205336. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  205337. typedef struct
  205338. {
  205339. BYTE SRB_Cmd;
  205340. BYTE SRB_Status;
  205341. BYTE SRB_HaID;
  205342. BYTE SRB_Flags;
  205343. DWORD SRB_Hdr_Rsvd;
  205344. BYTE SRB_Target;
  205345. BYTE SRB_Lun;
  205346. WORD SRB_Rsvd1;
  205347. DWORD SRB_BufLen;
  205348. BYTE FAR *SRB_BufPointer;
  205349. BYTE SRB_SenseLen;
  205350. BYTE SRB_CDBLen;
  205351. BYTE SRB_HaStat;
  205352. BYTE SRB_TargStat;
  205353. VOID FAR *SRB_PostProc;
  205354. BYTE SRB_Rsvd2[20];
  205355. BYTE CDBByte[16];
  205356. BYTE SenseArea[SENSE_LEN+2];
  205357. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  205358. typedef struct
  205359. {
  205360. BYTE SRB_Cmd;
  205361. BYTE SRB_Status;
  205362. BYTE SRB_HaId;
  205363. BYTE SRB_Flags;
  205364. DWORD SRB_Hdr_Rsvd;
  205365. } PACKED SRB, *PSRB, FAR *LPSRB;
  205366. #pragma pack()
  205367. struct CDDeviceInfo
  205368. {
  205369. char vendor[9];
  205370. char productId[17];
  205371. char rev[5];
  205372. char vendorSpec[21];
  205373. BYTE ha;
  205374. BYTE tgt;
  205375. BYTE lun;
  205376. char scsiDriveLetter; // will be 0 if not using scsi
  205377. };
  205378. class CDReadBuffer
  205379. {
  205380. public:
  205381. int startFrame;
  205382. int numFrames;
  205383. int dataStartOffset;
  205384. int dataLength;
  205385. BYTE* buffer;
  205386. int bufferSize;
  205387. int index;
  205388. bool wantsIndex;
  205389. CDReadBuffer (const int numberOfFrames)
  205390. : startFrame (0),
  205391. numFrames (0),
  205392. dataStartOffset (0),
  205393. dataLength (0),
  205394. index (0),
  205395. wantsIndex (false)
  205396. {
  205397. bufferSize = 2352 * numberOfFrames;
  205398. buffer = (BYTE*) malloc (bufferSize);
  205399. }
  205400. ~CDReadBuffer()
  205401. {
  205402. free (buffer);
  205403. }
  205404. bool isZero() const
  205405. {
  205406. BYTE* p = buffer + dataStartOffset;
  205407. for (int i = dataLength; --i >= 0;)
  205408. if (*p++ != 0)
  205409. return false;
  205410. return true;
  205411. }
  205412. };
  205413. class CDDeviceHandle;
  205414. class CDController
  205415. {
  205416. public:
  205417. CDController();
  205418. virtual ~CDController();
  205419. virtual bool read (CDReadBuffer* t) = 0;
  205420. virtual void shutDown();
  205421. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  205422. int getLastIndex();
  205423. public:
  205424. bool initialised;
  205425. CDDeviceHandle* deviceInfo;
  205426. int framesToCheck, framesOverlap;
  205427. void prepare (SRB_ExecSCSICmd& s);
  205428. void perform (SRB_ExecSCSICmd& s);
  205429. void setPaused (bool paused);
  205430. };
  205431. #pragma pack(1)
  205432. struct TOCTRACK
  205433. {
  205434. BYTE rsvd;
  205435. BYTE ADR;
  205436. BYTE trackNumber;
  205437. BYTE rsvd2;
  205438. BYTE addr[4];
  205439. };
  205440. struct TOC
  205441. {
  205442. WORD tocLen;
  205443. BYTE firstTrack;
  205444. BYTE lastTrack;
  205445. TOCTRACK tracks[100];
  205446. };
  205447. #pragma pack()
  205448. enum
  205449. {
  205450. READTYPE_ANY = 0,
  205451. READTYPE_ATAPI1 = 1,
  205452. READTYPE_ATAPI2 = 2,
  205453. READTYPE_READ6 = 3,
  205454. READTYPE_READ10 = 4,
  205455. READTYPE_READ_D8 = 5,
  205456. READTYPE_READ_D4 = 6,
  205457. READTYPE_READ_D4_1 = 7,
  205458. READTYPE_READ10_2 = 8
  205459. };
  205460. class CDDeviceHandle
  205461. {
  205462. public:
  205463. CDDeviceHandle (const CDDeviceInfo* const device)
  205464. : scsiHandle (0),
  205465. readType (READTYPE_ANY),
  205466. controller (0)
  205467. {
  205468. memcpy (&info, device, sizeof (info));
  205469. }
  205470. ~CDDeviceHandle()
  205471. {
  205472. if (controller != 0)
  205473. {
  205474. controller->shutDown();
  205475. delete controller;
  205476. }
  205477. if (scsiHandle != 0)
  205478. CloseHandle (scsiHandle);
  205479. }
  205480. bool readTOC (TOC* lpToc, bool useMSF);
  205481. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  205482. void openDrawer (bool shouldBeOpen);
  205483. CDDeviceInfo info;
  205484. HANDLE scsiHandle;
  205485. BYTE readType;
  205486. private:
  205487. CDController* controller;
  205488. bool testController (const int readType,
  205489. CDController* const newController,
  205490. CDReadBuffer* const bufferToUse);
  205491. };
  205492. DWORD (*fGetASPI32SupportInfo)(void);
  205493. DWORD (*fSendASPI32Command)(LPSRB);
  205494. static HINSTANCE winAspiLib = 0;
  205495. static bool usingScsi = false;
  205496. static bool initialised = false;
  205497. static bool InitialiseCDRipper()
  205498. {
  205499. if (! initialised)
  205500. {
  205501. initialised = true;
  205502. OSVERSIONINFO info;
  205503. info.dwOSVersionInfoSize = sizeof (info);
  205504. GetVersionEx (&info);
  205505. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  205506. if (! usingScsi)
  205507. {
  205508. fGetASPI32SupportInfo = 0;
  205509. fSendASPI32Command = 0;
  205510. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  205511. if (winAspiLib != 0)
  205512. {
  205513. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  205514. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  205515. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  205516. return false;
  205517. }
  205518. else
  205519. {
  205520. usingScsi = true;
  205521. }
  205522. }
  205523. }
  205524. return true;
  205525. }
  205526. static void DeinitialiseCDRipper()
  205527. {
  205528. if (winAspiLib != 0)
  205529. {
  205530. fGetASPI32SupportInfo = 0;
  205531. fSendASPI32Command = 0;
  205532. FreeLibrary (winAspiLib);
  205533. winAspiLib = 0;
  205534. }
  205535. initialised = false;
  205536. }
  205537. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  205538. {
  205539. TCHAR devicePath[8];
  205540. devicePath[0] = '\\';
  205541. devicePath[1] = '\\';
  205542. devicePath[2] = '.';
  205543. devicePath[3] = '\\';
  205544. devicePath[4] = driveLetter;
  205545. devicePath[5] = ':';
  205546. devicePath[6] = 0;
  205547. OSVERSIONINFO info;
  205548. info.dwOSVersionInfoSize = sizeof (info);
  205549. GetVersionEx (&info);
  205550. DWORD flags = GENERIC_READ;
  205551. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  205552. flags = GENERIC_READ | GENERIC_WRITE;
  205553. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  205554. if (h == INVALID_HANDLE_VALUE)
  205555. {
  205556. flags ^= GENERIC_WRITE;
  205557. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  205558. }
  205559. return h;
  205560. }
  205561. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  205562. const char driveLetter,
  205563. HANDLE& deviceHandle,
  205564. const bool retryOnFailure = true)
  205565. {
  205566. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  205567. zerostruct (s);
  205568. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  205569. s.spt.CdbLength = srb->SRB_CDBLen;
  205570. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  205571. ? SCSI_IOCTL_DATA_IN
  205572. : ((srb->SRB_Flags & SRB_DIR_OUT)
  205573. ? SCSI_IOCTL_DATA_OUT
  205574. : SCSI_IOCTL_DATA_UNSPECIFIED));
  205575. s.spt.DataTransferLength = srb->SRB_BufLen;
  205576. s.spt.TimeOutValue = 5;
  205577. s.spt.DataBuffer = srb->SRB_BufPointer;
  205578. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  205579. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  205580. srb->SRB_Status = SS_ERR;
  205581. srb->SRB_TargStat = 0x0004;
  205582. DWORD bytesReturned = 0;
  205583. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  205584. &s, sizeof (s),
  205585. &s, sizeof (s),
  205586. &bytesReturned, 0) != 0)
  205587. {
  205588. srb->SRB_Status = SS_COMP;
  205589. }
  205590. else if (retryOnFailure)
  205591. {
  205592. const DWORD error = GetLastError();
  205593. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  205594. {
  205595. if (error != ERROR_INVALID_HANDLE)
  205596. CloseHandle (deviceHandle);
  205597. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  205598. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  205599. }
  205600. }
  205601. return srb->SRB_Status;
  205602. }
  205603. // Controller types..
  205604. class ControllerType1 : public CDController
  205605. {
  205606. public:
  205607. ControllerType1() {}
  205608. ~ControllerType1() {}
  205609. bool read (CDReadBuffer* rb)
  205610. {
  205611. if (rb->numFrames * 2352 > rb->bufferSize)
  205612. return false;
  205613. SRB_ExecSCSICmd s;
  205614. prepare (s);
  205615. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205616. s.SRB_BufLen = rb->bufferSize;
  205617. s.SRB_BufPointer = rb->buffer;
  205618. s.SRB_CDBLen = 12;
  205619. s.CDBByte[0] = 0xBE;
  205620. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  205621. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  205622. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  205623. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  205624. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  205625. perform (s);
  205626. if (s.SRB_Status != SS_COMP)
  205627. return false;
  205628. rb->dataLength = rb->numFrames * 2352;
  205629. rb->dataStartOffset = 0;
  205630. return true;
  205631. }
  205632. };
  205633. class ControllerType2 : public CDController
  205634. {
  205635. public:
  205636. ControllerType2() {}
  205637. ~ControllerType2() {}
  205638. void shutDown()
  205639. {
  205640. if (initialised)
  205641. {
  205642. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  205643. SRB_ExecSCSICmd s;
  205644. prepare (s);
  205645. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  205646. s.SRB_BufLen = 0x0C;
  205647. s.SRB_BufPointer = bufPointer;
  205648. s.SRB_CDBLen = 6;
  205649. s.CDBByte[0] = 0x15;
  205650. s.CDBByte[4] = 0x0C;
  205651. perform (s);
  205652. }
  205653. }
  205654. bool init()
  205655. {
  205656. SRB_ExecSCSICmd s;
  205657. s.SRB_Status = SS_ERR;
  205658. if (deviceInfo->readType == READTYPE_READ10_2)
  205659. {
  205660. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  205661. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  205662. for (int i = 0; i < 2; ++i)
  205663. {
  205664. prepare (s);
  205665. s.SRB_Flags = SRB_EVENT_NOTIFY;
  205666. s.SRB_BufLen = 0x14;
  205667. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  205668. s.SRB_CDBLen = 6;
  205669. s.CDBByte[0] = 0x15;
  205670. s.CDBByte[1] = 0x10;
  205671. s.CDBByte[4] = 0x14;
  205672. perform (s);
  205673. if (s.SRB_Status != SS_COMP)
  205674. return false;
  205675. }
  205676. }
  205677. else
  205678. {
  205679. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  205680. prepare (s);
  205681. s.SRB_Flags = SRB_EVENT_NOTIFY;
  205682. s.SRB_BufLen = 0x0C;
  205683. s.SRB_BufPointer = bufPointer;
  205684. s.SRB_CDBLen = 6;
  205685. s.CDBByte[0] = 0x15;
  205686. s.CDBByte[4] = 0x0C;
  205687. perform (s);
  205688. }
  205689. return s.SRB_Status == SS_COMP;
  205690. }
  205691. bool read (CDReadBuffer* rb)
  205692. {
  205693. if (rb->numFrames * 2352 > rb->bufferSize)
  205694. return false;
  205695. if (!initialised)
  205696. {
  205697. initialised = init();
  205698. if (!initialised)
  205699. return false;
  205700. }
  205701. SRB_ExecSCSICmd s;
  205702. prepare (s);
  205703. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205704. s.SRB_BufLen = rb->bufferSize;
  205705. s.SRB_BufPointer = rb->buffer;
  205706. s.SRB_CDBLen = 10;
  205707. s.CDBByte[0] = 0x28;
  205708. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  205709. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  205710. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  205711. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  205712. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  205713. perform (s);
  205714. if (s.SRB_Status != SS_COMP)
  205715. return false;
  205716. rb->dataLength = rb->numFrames * 2352;
  205717. rb->dataStartOffset = 0;
  205718. return true;
  205719. }
  205720. };
  205721. class ControllerType3 : public CDController
  205722. {
  205723. public:
  205724. ControllerType3() {}
  205725. ~ControllerType3() {}
  205726. bool read (CDReadBuffer* rb)
  205727. {
  205728. if (rb->numFrames * 2352 > rb->bufferSize)
  205729. return false;
  205730. if (!initialised)
  205731. {
  205732. setPaused (false);
  205733. initialised = true;
  205734. }
  205735. SRB_ExecSCSICmd s;
  205736. prepare (s);
  205737. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205738. s.SRB_BufLen = rb->numFrames * 2352;
  205739. s.SRB_BufPointer = rb->buffer;
  205740. s.SRB_CDBLen = 12;
  205741. s.CDBByte[0] = 0xD8;
  205742. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  205743. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  205744. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  205745. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  205746. perform (s);
  205747. if (s.SRB_Status != SS_COMP)
  205748. return false;
  205749. rb->dataLength = rb->numFrames * 2352;
  205750. rb->dataStartOffset = 0;
  205751. return true;
  205752. }
  205753. };
  205754. class ControllerType4 : public CDController
  205755. {
  205756. public:
  205757. ControllerType4() {}
  205758. ~ControllerType4() {}
  205759. bool selectD4Mode()
  205760. {
  205761. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  205762. SRB_ExecSCSICmd s;
  205763. prepare (s);
  205764. s.SRB_Flags = SRB_EVENT_NOTIFY;
  205765. s.SRB_CDBLen = 6;
  205766. s.SRB_BufLen = 12;
  205767. s.SRB_BufPointer = bufPointer;
  205768. s.CDBByte[0] = 0x15;
  205769. s.CDBByte[1] = 0x10;
  205770. s.CDBByte[4] = 0x08;
  205771. perform (s);
  205772. return s.SRB_Status == SS_COMP;
  205773. }
  205774. bool read (CDReadBuffer* rb)
  205775. {
  205776. if (rb->numFrames * 2352 > rb->bufferSize)
  205777. return false;
  205778. if (!initialised)
  205779. {
  205780. setPaused (true);
  205781. if (deviceInfo->readType == READTYPE_READ_D4_1)
  205782. selectD4Mode();
  205783. initialised = true;
  205784. }
  205785. SRB_ExecSCSICmd s;
  205786. prepare (s);
  205787. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205788. s.SRB_BufLen = rb->bufferSize;
  205789. s.SRB_BufPointer = rb->buffer;
  205790. s.SRB_CDBLen = 10;
  205791. s.CDBByte[0] = 0xD4;
  205792. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  205793. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  205794. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  205795. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  205796. perform (s);
  205797. if (s.SRB_Status != SS_COMP)
  205798. return false;
  205799. rb->dataLength = rb->numFrames * 2352;
  205800. rb->dataStartOffset = 0;
  205801. return true;
  205802. }
  205803. };
  205804. CDController::CDController() : initialised (false)
  205805. {
  205806. }
  205807. CDController::~CDController()
  205808. {
  205809. }
  205810. void CDController::prepare (SRB_ExecSCSICmd& s)
  205811. {
  205812. zerostruct (s);
  205813. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  205814. s.SRB_HaID = deviceInfo->info.ha;
  205815. s.SRB_Target = deviceInfo->info.tgt;
  205816. s.SRB_Lun = deviceInfo->info.lun;
  205817. s.SRB_SenseLen = SENSE_LEN;
  205818. }
  205819. void CDController::perform (SRB_ExecSCSICmd& s)
  205820. {
  205821. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  205822. s.SRB_PostProc = (void*)event;
  205823. ResetEvent (event);
  205824. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  205825. deviceInfo->info.scsiDriveLetter,
  205826. deviceInfo->scsiHandle)
  205827. : fSendASPI32Command ((LPSRB)&s);
  205828. if (status == SS_PENDING)
  205829. WaitForSingleObject (event, 4000);
  205830. CloseHandle (event);
  205831. }
  205832. void CDController::setPaused (bool paused)
  205833. {
  205834. SRB_ExecSCSICmd s;
  205835. prepare (s);
  205836. s.SRB_Flags = SRB_EVENT_NOTIFY;
  205837. s.SRB_CDBLen = 10;
  205838. s.CDBByte[0] = 0x4B;
  205839. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  205840. perform (s);
  205841. }
  205842. void CDController::shutDown()
  205843. {
  205844. }
  205845. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  205846. {
  205847. if (overlapBuffer != 0)
  205848. {
  205849. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  205850. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  205851. if (doJitter
  205852. && overlapBuffer->startFrame > 0
  205853. && overlapBuffer->numFrames > 0
  205854. && overlapBuffer->dataLength > 0)
  205855. {
  205856. const int numFrames = rb->numFrames;
  205857. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  205858. {
  205859. rb->startFrame -= framesOverlap;
  205860. if (framesToCheck < framesOverlap
  205861. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  205862. rb->numFrames += framesOverlap;
  205863. }
  205864. else
  205865. {
  205866. overlapBuffer->dataLength = 0;
  205867. overlapBuffer->startFrame = 0;
  205868. overlapBuffer->numFrames = 0;
  205869. }
  205870. }
  205871. if (! read (rb))
  205872. return false;
  205873. if (doJitter)
  205874. {
  205875. const int checkLen = framesToCheck * 2352;
  205876. const int maxToCheck = rb->dataLength - checkLen;
  205877. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  205878. return true;
  205879. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  205880. bool found = false;
  205881. for (int i = 0; i < maxToCheck; ++i)
  205882. {
  205883. if (!memcmp (p, rb->buffer + i, checkLen))
  205884. {
  205885. i += checkLen;
  205886. rb->dataStartOffset = i;
  205887. rb->dataLength -= i;
  205888. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  205889. found = true;
  205890. break;
  205891. }
  205892. }
  205893. rb->numFrames = rb->dataLength / 2352;
  205894. rb->dataLength = 2352 * rb->numFrames;
  205895. if (!found)
  205896. return false;
  205897. }
  205898. if (canDoJitter)
  205899. {
  205900. memcpy (overlapBuffer->buffer,
  205901. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  205902. 2352 * framesToCheck);
  205903. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  205904. overlapBuffer->numFrames = framesToCheck;
  205905. overlapBuffer->dataLength = 2352 * framesToCheck;
  205906. overlapBuffer->dataStartOffset = 0;
  205907. }
  205908. else
  205909. {
  205910. overlapBuffer->startFrame = 0;
  205911. overlapBuffer->numFrames = 0;
  205912. overlapBuffer->dataLength = 0;
  205913. }
  205914. return true;
  205915. }
  205916. else
  205917. {
  205918. return read (rb);
  205919. }
  205920. }
  205921. int CDController::getLastIndex()
  205922. {
  205923. char qdata[100];
  205924. SRB_ExecSCSICmd s;
  205925. prepare (s);
  205926. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205927. s.SRB_BufLen = sizeof (qdata);
  205928. s.SRB_BufPointer = (BYTE*)qdata;
  205929. s.SRB_CDBLen = 12;
  205930. s.CDBByte[0] = 0x42;
  205931. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  205932. s.CDBByte[2] = 64;
  205933. s.CDBByte[3] = 1; // get current position
  205934. s.CDBByte[7] = 0;
  205935. s.CDBByte[8] = (BYTE)sizeof (qdata);
  205936. perform (s);
  205937. if (s.SRB_Status == SS_COMP)
  205938. return qdata[7];
  205939. return 0;
  205940. }
  205941. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  205942. {
  205943. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  205944. SRB_ExecSCSICmd s;
  205945. zerostruct (s);
  205946. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  205947. s.SRB_HaID = info.ha;
  205948. s.SRB_Target = info.tgt;
  205949. s.SRB_Lun = info.lun;
  205950. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205951. s.SRB_BufLen = 0x324;
  205952. s.SRB_BufPointer = (BYTE*)lpToc;
  205953. s.SRB_SenseLen = 0x0E;
  205954. s.SRB_CDBLen = 0x0A;
  205955. s.SRB_PostProc = (void*)event;
  205956. s.CDBByte[0] = 0x43;
  205957. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  205958. s.CDBByte[7] = 0x03;
  205959. s.CDBByte[8] = 0x24;
  205960. ResetEvent (event);
  205961. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  205962. : fSendASPI32Command ((LPSRB)&s);
  205963. if (status == SS_PENDING)
  205964. WaitForSingleObject (event, 4000);
  205965. CloseHandle (event);
  205966. return (s.SRB_Status == SS_COMP);
  205967. }
  205968. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  205969. CDReadBuffer* const overlapBuffer)
  205970. {
  205971. if (controller == 0)
  205972. {
  205973. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  205974. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  205975. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  205976. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  205977. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  205978. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  205979. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  205980. }
  205981. buffer->index = 0;
  205982. if ((controller != 0)
  205983. && controller->readAudio (buffer, overlapBuffer))
  205984. {
  205985. if (buffer->wantsIndex)
  205986. buffer->index = controller->getLastIndex();
  205987. return true;
  205988. }
  205989. return false;
  205990. }
  205991. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  205992. {
  205993. if (shouldBeOpen)
  205994. {
  205995. if (controller != 0)
  205996. {
  205997. controller->shutDown();
  205998. delete controller;
  205999. controller = 0;
  206000. }
  206001. if (scsiHandle != 0)
  206002. {
  206003. CloseHandle (scsiHandle);
  206004. scsiHandle = 0;
  206005. }
  206006. }
  206007. SRB_ExecSCSICmd s;
  206008. zerostruct (s);
  206009. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206010. s.SRB_HaID = info.ha;
  206011. s.SRB_Target = info.tgt;
  206012. s.SRB_Lun = info.lun;
  206013. s.SRB_SenseLen = SENSE_LEN;
  206014. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206015. s.SRB_BufLen = 0;
  206016. s.SRB_BufPointer = 0;
  206017. s.SRB_CDBLen = 12;
  206018. s.CDBByte[0] = 0x1b;
  206019. s.CDBByte[1] = (BYTE)(info.lun << 5);
  206020. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  206021. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206022. s.SRB_PostProc = (void*)event;
  206023. ResetEvent (event);
  206024. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206025. : fSendASPI32Command ((LPSRB)&s);
  206026. if (status == SS_PENDING)
  206027. WaitForSingleObject (event, 4000);
  206028. CloseHandle (event);
  206029. }
  206030. bool CDDeviceHandle::testController (const int type,
  206031. CDController* const newController,
  206032. CDReadBuffer* const rb)
  206033. {
  206034. controller = newController;
  206035. readType = (BYTE)type;
  206036. controller->deviceInfo = this;
  206037. controller->framesToCheck = 1;
  206038. controller->framesOverlap = 3;
  206039. bool passed = false;
  206040. memset (rb->buffer, 0xcd, rb->bufferSize);
  206041. if (controller->read (rb))
  206042. {
  206043. passed = true;
  206044. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  206045. int wrong = 0;
  206046. for (int i = rb->dataLength / 4; --i >= 0;)
  206047. {
  206048. if (*p++ == (int) 0xcdcdcdcd)
  206049. {
  206050. if (++wrong == 4)
  206051. {
  206052. passed = false;
  206053. break;
  206054. }
  206055. }
  206056. else
  206057. {
  206058. wrong = 0;
  206059. }
  206060. }
  206061. }
  206062. if (! passed)
  206063. {
  206064. controller->shutDown();
  206065. delete controller;
  206066. controller = 0;
  206067. }
  206068. return passed;
  206069. }
  206070. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  206071. {
  206072. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206073. const int bufSize = 128;
  206074. BYTE buffer[bufSize];
  206075. zeromem (buffer, bufSize);
  206076. SRB_ExecSCSICmd s;
  206077. zerostruct (s);
  206078. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206079. s.SRB_HaID = ha;
  206080. s.SRB_Target = tgt;
  206081. s.SRB_Lun = lun;
  206082. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206083. s.SRB_BufLen = bufSize;
  206084. s.SRB_BufPointer = buffer;
  206085. s.SRB_SenseLen = SENSE_LEN;
  206086. s.SRB_CDBLen = 6;
  206087. s.SRB_PostProc = (void*)event;
  206088. s.CDBByte[0] = SCSI_INQUIRY;
  206089. s.CDBByte[4] = 100;
  206090. ResetEvent (event);
  206091. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  206092. WaitForSingleObject (event, 4000);
  206093. CloseHandle (event);
  206094. if (s.SRB_Status == SS_COMP)
  206095. {
  206096. memcpy (dev->vendor, &buffer[8], 8);
  206097. memcpy (dev->productId, &buffer[16], 16);
  206098. memcpy (dev->rev, &buffer[32], 4);
  206099. memcpy (dev->vendorSpec, &buffer[36], 20);
  206100. }
  206101. }
  206102. static int FindCDDevices (CDDeviceInfo* const list,
  206103. int maxItems)
  206104. {
  206105. int count = 0;
  206106. if (usingScsi)
  206107. {
  206108. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  206109. {
  206110. TCHAR drivePath[8];
  206111. drivePath[0] = driveLetter;
  206112. drivePath[1] = ':';
  206113. drivePath[2] = '\\';
  206114. drivePath[3] = 0;
  206115. if (GetDriveType (drivePath) == DRIVE_CDROM)
  206116. {
  206117. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  206118. if (h != INVALID_HANDLE_VALUE)
  206119. {
  206120. BYTE buffer[100], passThroughStruct[1024];
  206121. zeromem (buffer, sizeof (buffer));
  206122. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206123. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  206124. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  206125. p->spt.CdbLength = 6;
  206126. p->spt.SenseInfoLength = 24;
  206127. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  206128. p->spt.DataTransferLength = 100;
  206129. p->spt.TimeOutValue = 2;
  206130. p->spt.DataBuffer = buffer;
  206131. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206132. p->spt.Cdb[0] = 0x12;
  206133. p->spt.Cdb[4] = 100;
  206134. DWORD bytesReturned = 0;
  206135. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206136. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206137. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206138. &bytesReturned, 0) != 0)
  206139. {
  206140. zeromem (&list[count], sizeof (CDDeviceInfo));
  206141. list[count].scsiDriveLetter = driveLetter;
  206142. memcpy (list[count].vendor, &buffer[8], 8);
  206143. memcpy (list[count].productId, &buffer[16], 16);
  206144. memcpy (list[count].rev, &buffer[32], 4);
  206145. memcpy (list[count].vendorSpec, &buffer[36], 20);
  206146. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206147. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  206148. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  206149. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  206150. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  206151. &bytesReturned, 0) != 0)
  206152. {
  206153. list[count].ha = scsiAddr->PortNumber;
  206154. list[count].tgt = scsiAddr->TargetId;
  206155. list[count].lun = scsiAddr->Lun;
  206156. ++count;
  206157. }
  206158. }
  206159. CloseHandle (h);
  206160. }
  206161. }
  206162. }
  206163. }
  206164. else
  206165. {
  206166. const DWORD d = fGetASPI32SupportInfo();
  206167. BYTE status = HIBYTE (LOWORD (d));
  206168. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  206169. return 0;
  206170. const int numAdapters = LOBYTE (LOWORD (d));
  206171. for (BYTE ha = 0; ha < numAdapters; ++ha)
  206172. {
  206173. SRB_HAInquiry s;
  206174. zerostruct (s);
  206175. s.SRB_Cmd = SC_HA_INQUIRY;
  206176. s.SRB_HaID = ha;
  206177. fSendASPI32Command ((LPSRB)&s);
  206178. if (s.SRB_Status == SS_COMP)
  206179. {
  206180. maxItems = (int)s.HA_Unique[3];
  206181. if (maxItems == 0)
  206182. maxItems = 8;
  206183. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  206184. {
  206185. for (BYTE lun = 0; lun < 8; ++lun)
  206186. {
  206187. SRB_GDEVBlock sb;
  206188. zerostruct (sb);
  206189. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  206190. sb.SRB_HaID = ha;
  206191. sb.SRB_Target = tgt;
  206192. sb.SRB_Lun = lun;
  206193. fSendASPI32Command ((LPSRB) &sb);
  206194. if (sb.SRB_Status == SS_COMP
  206195. && sb.SRB_DeviceType == DTYPE_CROM)
  206196. {
  206197. zeromem (&list[count], sizeof (CDDeviceInfo));
  206198. list[count].ha = ha;
  206199. list[count].tgt = tgt;
  206200. list[count].lun = lun;
  206201. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  206202. ++count;
  206203. }
  206204. }
  206205. }
  206206. }
  206207. }
  206208. }
  206209. return count;
  206210. }
  206211. static int ripperUsers = 0;
  206212. static bool initialisedOk = false;
  206213. class DeinitialiseTimer : private Timer,
  206214. private DeletedAtShutdown
  206215. {
  206216. DeinitialiseTimer (const DeinitialiseTimer&);
  206217. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  206218. public:
  206219. DeinitialiseTimer()
  206220. {
  206221. startTimer (4000);
  206222. }
  206223. ~DeinitialiseTimer()
  206224. {
  206225. if (--ripperUsers == 0)
  206226. DeinitialiseCDRipper();
  206227. }
  206228. void timerCallback()
  206229. {
  206230. delete this;
  206231. }
  206232. juce_UseDebuggingNewOperator
  206233. };
  206234. static void incUserCount()
  206235. {
  206236. if (ripperUsers++ == 0)
  206237. initialisedOk = InitialiseCDRipper();
  206238. }
  206239. static void decUserCount()
  206240. {
  206241. new DeinitialiseTimer();
  206242. }
  206243. struct CDDeviceWrapper
  206244. {
  206245. CDDeviceHandle* cdH;
  206246. CDReadBuffer* overlapBuffer;
  206247. bool jitter;
  206248. };
  206249. static int getAddressOf (const TOCTRACK* const t)
  206250. {
  206251. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  206252. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  206253. }
  206254. static int getMSFAddressOf (const TOCTRACK* const t)
  206255. {
  206256. return 60 * t->addr[1] + t->addr[2];
  206257. }
  206258. static const int samplesPerFrame = 44100 / 75;
  206259. static const int bytesPerFrame = samplesPerFrame * 4;
  206260. const StringArray AudioCDReader::getAvailableCDNames()
  206261. {
  206262. StringArray results;
  206263. incUserCount();
  206264. if (initialisedOk)
  206265. {
  206266. CDDeviceInfo list[8];
  206267. const int num = FindCDDevices (list, 8);
  206268. decUserCount();
  206269. for (int i = 0; i < num; ++i)
  206270. {
  206271. String s;
  206272. if (list[i].scsiDriveLetter > 0)
  206273. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  206274. s << String (list[i].vendor).trim()
  206275. << T(" ") << String (list[i].productId).trim()
  206276. << T(" ") << String (list[i].rev).trim();
  206277. results.add (s);
  206278. }
  206279. }
  206280. return results;
  206281. }
  206282. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  206283. {
  206284. SRB_GDEVBlock s;
  206285. zerostruct (s);
  206286. s.SRB_Cmd = SC_GET_DEV_TYPE;
  206287. s.SRB_HaID = device->ha;
  206288. s.SRB_Target = device->tgt;
  206289. s.SRB_Lun = device->lun;
  206290. if (usingScsi)
  206291. {
  206292. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  206293. if (h != INVALID_HANDLE_VALUE)
  206294. {
  206295. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  206296. cdh->scsiHandle = h;
  206297. return cdh;
  206298. }
  206299. }
  206300. else
  206301. {
  206302. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  206303. && s.SRB_DeviceType == DTYPE_CROM)
  206304. {
  206305. return new CDDeviceHandle (device);
  206306. }
  206307. }
  206308. return 0;
  206309. }
  206310. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  206311. {
  206312. incUserCount();
  206313. if (initialisedOk)
  206314. {
  206315. CDDeviceInfo list[8];
  206316. const int num = FindCDDevices (list, 8);
  206317. if (((unsigned int) deviceIndex) < (unsigned int) num)
  206318. {
  206319. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  206320. if (handle != 0)
  206321. {
  206322. CDDeviceWrapper* const d = new CDDeviceWrapper();
  206323. d->cdH = handle;
  206324. d->overlapBuffer = new CDReadBuffer(3);
  206325. return new AudioCDReader (d);
  206326. }
  206327. }
  206328. }
  206329. decUserCount();
  206330. return 0;
  206331. }
  206332. AudioCDReader::AudioCDReader (void* handle_)
  206333. : AudioFormatReader (0, T("CD Audio")),
  206334. handle (handle_),
  206335. indexingEnabled (false),
  206336. lastIndex (0),
  206337. firstFrameInBuffer (0),
  206338. samplesInBuffer (0)
  206339. {
  206340. jassert (handle_ != 0);
  206341. refreshTrackLengths();
  206342. sampleRate = 44100.0;
  206343. bitsPerSample = 16;
  206344. lengthInSamples = getPositionOfTrackStart (numTracks);
  206345. numChannels = 2;
  206346. usesFloatingPointData = false;
  206347. buffer.setSize (4 * bytesPerFrame, true);
  206348. }
  206349. AudioCDReader::~AudioCDReader()
  206350. {
  206351. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  206352. delete device->cdH;
  206353. delete device->overlapBuffer;
  206354. delete device;
  206355. decUserCount();
  206356. }
  206357. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  206358. int64 startSampleInFile, int numSamples)
  206359. {
  206360. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206361. bool ok = true;
  206362. while (numSamples > 0)
  206363. {
  206364. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  206365. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  206366. if (startSampleInFile >= bufferStartSample
  206367. && startSampleInFile < bufferEndSample)
  206368. {
  206369. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  206370. int* const l = destSamples[0] + startOffsetInDestBuffer;
  206371. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  206372. const short* src = (const short*) buffer.getData();
  206373. src += 2 * (startSampleInFile - bufferStartSample);
  206374. for (int i = 0; i < toDo; ++i)
  206375. {
  206376. l[i] = src [i << 1] << 16;
  206377. if (r != 0)
  206378. r[i] = src [(i << 1) + 1] << 16;
  206379. }
  206380. startOffsetInDestBuffer += toDo;
  206381. startSampleInFile += toDo;
  206382. numSamples -= toDo;
  206383. }
  206384. else
  206385. {
  206386. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  206387. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  206388. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  206389. {
  206390. device->overlapBuffer->dataLength = 0;
  206391. device->overlapBuffer->startFrame = 0;
  206392. device->overlapBuffer->numFrames = 0;
  206393. device->jitter = false;
  206394. }
  206395. firstFrameInBuffer = frameNeeded;
  206396. lastIndex = 0;
  206397. CDReadBuffer readBuffer (framesInBuffer + 4);
  206398. readBuffer.wantsIndex = indexingEnabled;
  206399. int i;
  206400. for (i = 5; --i >= 0;)
  206401. {
  206402. readBuffer.startFrame = frameNeeded;
  206403. readBuffer.numFrames = framesInBuffer;
  206404. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  206405. break;
  206406. else
  206407. device->overlapBuffer->dataLength = 0;
  206408. }
  206409. if (i >= 0)
  206410. {
  206411. memcpy ((char*) buffer.getData(),
  206412. readBuffer.buffer + readBuffer.dataStartOffset,
  206413. readBuffer.dataLength);
  206414. samplesInBuffer = readBuffer.dataLength >> 2;
  206415. lastIndex = readBuffer.index;
  206416. }
  206417. else
  206418. {
  206419. int* l = destSamples[0] + startOffsetInDestBuffer;
  206420. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  206421. while (--numSamples >= 0)
  206422. {
  206423. *l++ = 0;
  206424. if (r != 0)
  206425. *r++ = 0;
  206426. }
  206427. // sometimes the read fails for just the very last couple of blocks, so
  206428. // we'll ignore and errors in the last half-second of the disk..
  206429. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  206430. break;
  206431. }
  206432. }
  206433. }
  206434. return ok;
  206435. }
  206436. bool AudioCDReader::isCDStillPresent() const
  206437. {
  206438. TOC toc;
  206439. zerostruct (toc);
  206440. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  206441. }
  206442. int AudioCDReader::getNumTracks() const
  206443. {
  206444. return numTracks;
  206445. }
  206446. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  206447. {
  206448. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  206449. : 0;
  206450. }
  206451. void AudioCDReader::refreshTrackLengths()
  206452. {
  206453. zeromem (trackStarts, sizeof (trackStarts));
  206454. zeromem (audioTracks, sizeof (audioTracks));
  206455. TOC toc;
  206456. zerostruct (toc);
  206457. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  206458. {
  206459. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  206460. for (int i = 0; i <= numTracks; ++i)
  206461. {
  206462. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  206463. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  206464. }
  206465. }
  206466. else
  206467. {
  206468. numTracks = 0;
  206469. }
  206470. }
  206471. bool AudioCDReader::isTrackAudio (int trackNum) const
  206472. {
  206473. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  206474. : false;
  206475. }
  206476. void AudioCDReader::enableIndexScanning (bool b)
  206477. {
  206478. indexingEnabled = b;
  206479. }
  206480. int AudioCDReader::getLastIndex() const
  206481. {
  206482. return lastIndex;
  206483. }
  206484. const int framesPerIndexRead = 4;
  206485. int AudioCDReader::getIndexAt (int samplePos)
  206486. {
  206487. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206488. const int frameNeeded = samplePos / samplesPerFrame;
  206489. device->overlapBuffer->dataLength = 0;
  206490. device->overlapBuffer->startFrame = 0;
  206491. device->overlapBuffer->numFrames = 0;
  206492. device->jitter = false;
  206493. firstFrameInBuffer = 0;
  206494. lastIndex = 0;
  206495. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  206496. readBuffer.wantsIndex = true;
  206497. int i;
  206498. for (i = 5; --i >= 0;)
  206499. {
  206500. readBuffer.startFrame = frameNeeded;
  206501. readBuffer.numFrames = framesPerIndexRead;
  206502. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  206503. break;
  206504. }
  206505. if (i >= 0)
  206506. return readBuffer.index;
  206507. return -1;
  206508. }
  206509. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  206510. {
  206511. Array <int> indexes;
  206512. const int trackStart = getPositionOfTrackStart (trackNumber);
  206513. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  206514. bool needToScan = true;
  206515. if (trackEnd - trackStart > 20 * 44100)
  206516. {
  206517. // check the end of the track for indexes before scanning the whole thing
  206518. needToScan = false;
  206519. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  206520. bool seenAnIndex = false;
  206521. while (pos <= trackEnd - samplesPerFrame)
  206522. {
  206523. const int index = getIndexAt (pos);
  206524. if (index == 0)
  206525. {
  206526. // lead-out, so skip back a bit if we've not found any indexes yet..
  206527. if (seenAnIndex)
  206528. break;
  206529. pos -= 44100 * 5;
  206530. if (pos < trackStart)
  206531. break;
  206532. }
  206533. else
  206534. {
  206535. if (index > 0)
  206536. seenAnIndex = true;
  206537. if (index > 1)
  206538. {
  206539. needToScan = true;
  206540. break;
  206541. }
  206542. pos += samplesPerFrame * framesPerIndexRead;
  206543. }
  206544. }
  206545. }
  206546. if (needToScan)
  206547. {
  206548. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206549. int pos = trackStart;
  206550. int last = -1;
  206551. while (pos < trackEnd - samplesPerFrame * 10)
  206552. {
  206553. const int frameNeeded = pos / samplesPerFrame;
  206554. device->overlapBuffer->dataLength = 0;
  206555. device->overlapBuffer->startFrame = 0;
  206556. device->overlapBuffer->numFrames = 0;
  206557. device->jitter = false;
  206558. firstFrameInBuffer = 0;
  206559. CDReadBuffer readBuffer (4);
  206560. readBuffer.wantsIndex = true;
  206561. int i;
  206562. for (i = 5; --i >= 0;)
  206563. {
  206564. readBuffer.startFrame = frameNeeded;
  206565. readBuffer.numFrames = framesPerIndexRead;
  206566. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  206567. break;
  206568. }
  206569. if (i < 0)
  206570. break;
  206571. if (readBuffer.index > last && readBuffer.index > 1)
  206572. {
  206573. last = readBuffer.index;
  206574. indexes.add (pos);
  206575. }
  206576. pos += samplesPerFrame * framesPerIndexRead;
  206577. }
  206578. indexes.removeValue (trackStart);
  206579. }
  206580. return indexes;
  206581. }
  206582. int AudioCDReader::getCDDBId()
  206583. {
  206584. refreshTrackLengths();
  206585. if (numTracks > 0)
  206586. {
  206587. TOC toc;
  206588. zerostruct (toc);
  206589. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  206590. {
  206591. int n = 0;
  206592. for (int i = numTracks; --i >= 0;)
  206593. {
  206594. int j = getMSFAddressOf (&toc.tracks[i]);
  206595. while (j > 0)
  206596. {
  206597. n += (j % 10);
  206598. j /= 10;
  206599. }
  206600. }
  206601. if (n != 0)
  206602. {
  206603. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  206604. - getMSFAddressOf (&toc.tracks[0]);
  206605. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  206606. }
  206607. }
  206608. }
  206609. return 0;
  206610. }
  206611. void AudioCDReader::ejectDisk()
  206612. {
  206613. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  206614. }
  206615. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  206616. {
  206617. CoInitialize (0);
  206618. IDiscMaster* dm;
  206619. IDiscRecorder* result = 0;
  206620. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  206621. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  206622. IID_IDiscMaster,
  206623. (void**) &dm)))
  206624. {
  206625. if (SUCCEEDED (dm->Open()))
  206626. {
  206627. IEnumDiscRecorders* drEnum = 0;
  206628. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  206629. {
  206630. IDiscRecorder* dr = 0;
  206631. DWORD dummy;
  206632. int index = 0;
  206633. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  206634. {
  206635. if (indexToOpen == index)
  206636. {
  206637. result = dr;
  206638. break;
  206639. }
  206640. else if (list != 0)
  206641. {
  206642. BSTR path;
  206643. if (SUCCEEDED (dr->GetPath (&path)))
  206644. list->add ((const WCHAR*) path);
  206645. }
  206646. ++index;
  206647. dr->Release();
  206648. }
  206649. drEnum->Release();
  206650. }
  206651. /*if (redbookFormat != 0)
  206652. {
  206653. IEnumDiscMasterFormats* mfEnum;
  206654. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  206655. {
  206656. IID formatIID;
  206657. DWORD dummy;
  206658. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  206659. {
  206660. }
  206661. mfEnum->Release();
  206662. }
  206663. redbookFormat
  206664. }*/
  206665. if (master == 0)
  206666. dm->Close();
  206667. }
  206668. if (master != 0)
  206669. *master = dm;
  206670. else
  206671. dm->Release();
  206672. }
  206673. return result;
  206674. }
  206675. const StringArray AudioCDBurner::findAvailableDevices()
  206676. {
  206677. StringArray devs;
  206678. enumCDBurners (&devs, -1, 0);
  206679. return devs;
  206680. }
  206681. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  206682. {
  206683. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  206684. if (b->internal == 0)
  206685. deleteAndZero (b);
  206686. return b;
  206687. }
  206688. class CDBurnerInfo : public IDiscMasterProgressEvents
  206689. {
  206690. public:
  206691. CDBurnerInfo()
  206692. : refCount (1),
  206693. progress (0),
  206694. shouldCancel (false),
  206695. listener (0)
  206696. {
  206697. }
  206698. ~CDBurnerInfo()
  206699. {
  206700. }
  206701. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206702. {
  206703. if (result == 0)
  206704. return E_POINTER;
  206705. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  206706. {
  206707. AddRef();
  206708. *result = this;
  206709. return S_OK;
  206710. }
  206711. *result = 0;
  206712. return E_NOINTERFACE;
  206713. }
  206714. ULONG __stdcall AddRef() { return ++refCount; }
  206715. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206716. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  206717. {
  206718. if (listener != 0 && ! shouldCancel)
  206719. shouldCancel = listener->audioCDBurnProgress (progress);
  206720. *pbCancel = shouldCancel;
  206721. return S_OK;
  206722. }
  206723. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  206724. {
  206725. progress = nCompleted / (float) nTotal;
  206726. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  206727. return E_NOTIMPL;
  206728. }
  206729. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  206730. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  206731. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  206732. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  206733. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  206734. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  206735. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  206736. IDiscMaster* discMaster;
  206737. IDiscRecorder* discRecorder;
  206738. IRedbookDiscMaster* redbook;
  206739. AudioCDBurner::BurnProgressListener* listener;
  206740. float progress;
  206741. bool shouldCancel;
  206742. private:
  206743. int refCount;
  206744. };
  206745. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  206746. : internal (0)
  206747. {
  206748. IDiscMaster* discMaster;
  206749. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  206750. if (dr != 0)
  206751. {
  206752. IRedbookDiscMaster* redbook;
  206753. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  206754. hr = discMaster->SetActiveDiscRecorder (dr);
  206755. CDBurnerInfo* const info = new CDBurnerInfo();
  206756. internal = info;
  206757. info->discMaster = discMaster;
  206758. info->discRecorder = dr;
  206759. info->redbook = redbook;
  206760. }
  206761. }
  206762. AudioCDBurner::~AudioCDBurner()
  206763. {
  206764. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206765. if (info != 0)
  206766. {
  206767. info->discRecorder->Close();
  206768. info->redbook->Release();
  206769. info->discRecorder->Release();
  206770. info->discMaster->Release();
  206771. info->Release();
  206772. }
  206773. }
  206774. bool AudioCDBurner::isDiskPresent() const
  206775. {
  206776. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206777. HRESULT hr = info->discRecorder->OpenExclusive();
  206778. long type, flags;
  206779. hr = info->discRecorder->QueryMediaType (&type, &flags);
  206780. info->discRecorder->Close();
  206781. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  206782. }
  206783. int AudioCDBurner::getNumAvailableAudioBlocks() const
  206784. {
  206785. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206786. long blocksFree = 0;
  206787. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  206788. return blocksFree;
  206789. }
  206790. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  206791. const bool ejectDiscAfterwards,
  206792. const bool performFakeBurnForTesting)
  206793. {
  206794. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206795. info->listener = listener;
  206796. info->progress = 0;
  206797. info->shouldCancel = false;
  206798. UINT_PTR cookie;
  206799. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  206800. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  206801. ejectDiscAfterwards);
  206802. String error;
  206803. if (hr != S_OK)
  206804. {
  206805. const char* e = "Couldn't open or write to the CD device";
  206806. if (hr == IMAPI_E_USERABORT)
  206807. e = "User cancelled the write operation";
  206808. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  206809. e = "No Disk present";
  206810. error = e;
  206811. }
  206812. info->discMaster->ProgressUnadvise (cookie);
  206813. info->listener = 0;
  206814. return error;
  206815. }
  206816. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  206817. {
  206818. if (source == 0)
  206819. return false;
  206820. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206821. long bytesPerBlock;
  206822. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  206823. const int samplesPerBlock = bytesPerBlock / 4;
  206824. bool ok = true;
  206825. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  206826. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  206827. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  206828. int samplesDone = 0;
  206829. source->prepareToPlay (samplesPerBlock, 44100.0);
  206830. while (ok)
  206831. {
  206832. {
  206833. AudioSourceChannelInfo info;
  206834. info.buffer = &sourceBuffer;
  206835. info.numSamples = samplesPerBlock;
  206836. info.startSample = 0;
  206837. sourceBuffer.clear();
  206838. source->getNextAudioBlock (info);
  206839. }
  206840. zeromem (buffer, bytesPerBlock);
  206841. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  206842. buffer, samplesPerBlock, 4);
  206843. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  206844. buffer + 2, samplesPerBlock, 4);
  206845. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  206846. if (hr != S_OK)
  206847. ok = false;
  206848. samplesDone += samplesPerBlock;
  206849. if (samplesDone >= numSamples)
  206850. break;
  206851. }
  206852. juce_free (buffer);
  206853. hr = info->redbook->CloseAudioTrack();
  206854. delete source;
  206855. return ok && hr == S_OK;
  206856. }
  206857. #endif
  206858. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  206859. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  206860. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206861. // compiled on its own).
  206862. #if JUCE_INCLUDED_FILE
  206863. static const int midiBufferSize = 1024 * 10;
  206864. static const int numInHeaders = 32;
  206865. static const int inBufferSize = 256;
  206866. static Array <void*, CriticalSection> activeMidiThreads;
  206867. using ::free;
  206868. class MidiInThread : public Thread
  206869. {
  206870. public:
  206871. MidiInThread (MidiInput* const input_,
  206872. MidiInputCallback* const callback_)
  206873. : Thread ("Juce Midi"),
  206874. hIn (0),
  206875. input (input_),
  206876. callback (callback_),
  206877. isStarted (false),
  206878. startTime (0),
  206879. pendingLength(0)
  206880. {
  206881. for (int i = numInHeaders; --i >= 0;)
  206882. {
  206883. zeromem (&hdr[i], sizeof (MIDIHDR));
  206884. hdr[i].lpData = inData[i];
  206885. hdr[i].dwBufferLength = inBufferSize;
  206886. }
  206887. };
  206888. ~MidiInThread()
  206889. {
  206890. stop();
  206891. if (hIn != 0)
  206892. {
  206893. int count = 5;
  206894. while (--count >= 0)
  206895. {
  206896. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  206897. break;
  206898. Sleep (20);
  206899. }
  206900. }
  206901. }
  206902. void handle (const uint32 message, const uint32 timeStamp) throw()
  206903. {
  206904. const int byte = message & 0xff;
  206905. if (byte < 0x80)
  206906. return;
  206907. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  206908. const double time = timeStampToTime (timeStamp);
  206909. lock.enter();
  206910. if (pendingLength < midiBufferSize - 12)
  206911. {
  206912. char* const p = pending + pendingLength;
  206913. *(double*) p = time;
  206914. *(uint32*) (p + 8) = numBytes;
  206915. *(uint32*) (p + 12) = message;
  206916. pendingLength += 12 + numBytes;
  206917. }
  206918. else
  206919. {
  206920. jassertfalse // midi buffer overflow! You might need to increase the size..
  206921. }
  206922. lock.exit();
  206923. notify();
  206924. }
  206925. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  206926. {
  206927. const int num = hdr->dwBytesRecorded;
  206928. if (num > 0)
  206929. {
  206930. const double time = timeStampToTime (timeStamp);
  206931. lock.enter();
  206932. if (pendingLength < midiBufferSize - (8 + num))
  206933. {
  206934. char* const p = pending + pendingLength;
  206935. *(double*) p = time;
  206936. *(uint32*) (p + 8) = num;
  206937. memcpy (p + 12, hdr->lpData, num);
  206938. pendingLength += 12 + num;
  206939. }
  206940. else
  206941. {
  206942. jassertfalse // midi buffer overflow! You might need to increase the size..
  206943. }
  206944. lock.exit();
  206945. notify();
  206946. }
  206947. }
  206948. void writeBlock (const int i) throw()
  206949. {
  206950. hdr[i].dwBytesRecorded = 0;
  206951. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  206952. jassert (res == MMSYSERR_NOERROR);
  206953. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  206954. jassert (res == MMSYSERR_NOERROR);
  206955. }
  206956. void run()
  206957. {
  206958. MemoryBlock pendingCopy (64);
  206959. while (! threadShouldExit())
  206960. {
  206961. for (int i = 0; i < numInHeaders; ++i)
  206962. {
  206963. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  206964. {
  206965. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  206966. (void) res;
  206967. jassert (res == MMSYSERR_NOERROR);
  206968. writeBlock (i);
  206969. }
  206970. }
  206971. lock.enter();
  206972. int len = pendingLength;
  206973. if (len > 0)
  206974. {
  206975. pendingCopy.ensureSize (len);
  206976. pendingCopy.copyFrom (pending, 0, len);
  206977. pendingLength = 0;
  206978. }
  206979. lock.exit();
  206980. //xxx needs to figure out if blocks are broken up or not
  206981. if (len == 0)
  206982. {
  206983. wait (500);
  206984. }
  206985. else
  206986. {
  206987. const char* p = (const char*) pendingCopy.getData();
  206988. while (len > 0)
  206989. {
  206990. const double time = *(const double*) p;
  206991. const int messageLen = *(const int*) (p + 8);
  206992. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  206993. callback->handleIncomingMidiMessage (input, message);
  206994. p += 12 + messageLen;
  206995. len -= 12 + messageLen;
  206996. }
  206997. }
  206998. }
  206999. }
  207000. void start() throw()
  207001. {
  207002. jassert (hIn != 0);
  207003. if (hIn != 0 && ! isStarted)
  207004. {
  207005. stop();
  207006. activeMidiThreads.addIfNotAlreadyThere (this);
  207007. int i;
  207008. for (i = 0; i < numInHeaders; ++i)
  207009. writeBlock (i);
  207010. startTime = Time::getMillisecondCounter();
  207011. MMRESULT res = midiInStart (hIn);
  207012. jassert (res == MMSYSERR_NOERROR);
  207013. if (res == MMSYSERR_NOERROR)
  207014. {
  207015. isStarted = true;
  207016. pendingLength = 0;
  207017. startThread (6);
  207018. }
  207019. }
  207020. }
  207021. void stop() throw()
  207022. {
  207023. if (isStarted)
  207024. {
  207025. stopThread (5000);
  207026. midiInReset (hIn);
  207027. midiInStop (hIn);
  207028. activeMidiThreads.removeValue (this);
  207029. lock.enter();
  207030. lock.exit();
  207031. for (int i = numInHeaders; --i >= 0;)
  207032. {
  207033. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207034. {
  207035. int c = 10;
  207036. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  207037. Sleep (20);
  207038. jassert (c >= 0);
  207039. }
  207040. }
  207041. isStarted = false;
  207042. pendingLength = 0;
  207043. }
  207044. }
  207045. juce_UseDebuggingNewOperator
  207046. HMIDIIN hIn;
  207047. private:
  207048. MidiInput* input;
  207049. MidiInputCallback* callback;
  207050. bool isStarted;
  207051. uint32 startTime;
  207052. CriticalSection lock;
  207053. MIDIHDR hdr [numInHeaders];
  207054. char inData [numInHeaders] [inBufferSize];
  207055. int pendingLength;
  207056. char pending [midiBufferSize];
  207057. double timeStampToTime (uint32 timeStamp) throw()
  207058. {
  207059. timeStamp += startTime;
  207060. const uint32 now = Time::getMillisecondCounter();
  207061. if (timeStamp > now)
  207062. {
  207063. if (timeStamp > now + 2)
  207064. --startTime;
  207065. timeStamp = now;
  207066. }
  207067. return 0.001 * timeStamp;
  207068. }
  207069. MidiInThread (const MidiInThread&);
  207070. const MidiInThread& operator= (const MidiInThread&);
  207071. };
  207072. static void CALLBACK midiInCallback (HMIDIIN,
  207073. UINT uMsg,
  207074. DWORD_PTR dwInstance,
  207075. DWORD_PTR midiMessage,
  207076. DWORD_PTR timeStamp)
  207077. {
  207078. MidiInThread* const thread = (MidiInThread*) dwInstance;
  207079. if (thread != 0 && activeMidiThreads.contains (thread))
  207080. {
  207081. if (uMsg == MIM_DATA)
  207082. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  207083. else if (uMsg == MIM_LONGDATA)
  207084. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  207085. }
  207086. }
  207087. const StringArray MidiInput::getDevices()
  207088. {
  207089. StringArray s;
  207090. const int num = midiInGetNumDevs();
  207091. for (int i = 0; i < num; ++i)
  207092. {
  207093. MIDIINCAPS mc;
  207094. zerostruct (mc);
  207095. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207096. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207097. }
  207098. return s;
  207099. }
  207100. int MidiInput::getDefaultDeviceIndex()
  207101. {
  207102. return 0;
  207103. }
  207104. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  207105. {
  207106. if (callback == 0)
  207107. return 0;
  207108. UINT deviceId = MIDI_MAPPER;
  207109. int n = 0;
  207110. String name;
  207111. const int num = midiInGetNumDevs();
  207112. for (int i = 0; i < num; ++i)
  207113. {
  207114. MIDIINCAPS mc;
  207115. zerostruct (mc);
  207116. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207117. {
  207118. if (index == n)
  207119. {
  207120. deviceId = i;
  207121. name = String (mc.szPname, sizeof (mc.szPname));
  207122. break;
  207123. }
  207124. ++n;
  207125. }
  207126. }
  207127. MidiInput* const in = new MidiInput (name);
  207128. MidiInThread* const thread = new MidiInThread (in, callback);
  207129. HMIDIIN h;
  207130. HRESULT err = midiInOpen (&h, deviceId,
  207131. (DWORD_PTR) &midiInCallback,
  207132. (DWORD_PTR) thread,
  207133. CALLBACK_FUNCTION);
  207134. if (err == MMSYSERR_NOERROR)
  207135. {
  207136. thread->hIn = h;
  207137. in->internal = (void*) thread;
  207138. return in;
  207139. }
  207140. else
  207141. {
  207142. delete in;
  207143. delete thread;
  207144. return 0;
  207145. }
  207146. }
  207147. MidiInput::MidiInput (const String& name_)
  207148. : name (name_),
  207149. internal (0)
  207150. {
  207151. }
  207152. MidiInput::~MidiInput()
  207153. {
  207154. if (internal != 0)
  207155. {
  207156. MidiInThread* const thread = (MidiInThread*) internal;
  207157. delete thread;
  207158. }
  207159. }
  207160. void MidiInput::start()
  207161. {
  207162. ((MidiInThread*) internal)->start();
  207163. }
  207164. void MidiInput::stop()
  207165. {
  207166. ((MidiInThread*) internal)->stop();
  207167. }
  207168. struct MidiOutHandle
  207169. {
  207170. int refCount;
  207171. UINT deviceId;
  207172. HMIDIOUT handle;
  207173. juce_UseDebuggingNewOperator
  207174. };
  207175. static VoidArray handles (4);
  207176. const StringArray MidiOutput::getDevices()
  207177. {
  207178. StringArray s;
  207179. const int num = midiOutGetNumDevs();
  207180. for (int i = 0; i < num; ++i)
  207181. {
  207182. MIDIOUTCAPS mc;
  207183. zerostruct (mc);
  207184. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207185. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207186. }
  207187. return s;
  207188. }
  207189. int MidiOutput::getDefaultDeviceIndex()
  207190. {
  207191. const int num = midiOutGetNumDevs();
  207192. int n = 0;
  207193. for (int i = 0; i < num; ++i)
  207194. {
  207195. MIDIOUTCAPS mc;
  207196. zerostruct (mc);
  207197. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207198. {
  207199. if ((mc.wTechnology & MOD_MAPPER) != 0)
  207200. return n;
  207201. ++n;
  207202. }
  207203. }
  207204. return 0;
  207205. }
  207206. MidiOutput* MidiOutput::openDevice (int index)
  207207. {
  207208. UINT deviceId = MIDI_MAPPER;
  207209. const int num = midiOutGetNumDevs();
  207210. int i, n = 0;
  207211. for (i = 0; i < num; ++i)
  207212. {
  207213. MIDIOUTCAPS mc;
  207214. zerostruct (mc);
  207215. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207216. {
  207217. // use the microsoft sw synth as a default - best not to allow deviceId
  207218. // to be MIDI_MAPPER, or else device sharing breaks
  207219. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  207220. deviceId = i;
  207221. if (index == n)
  207222. {
  207223. deviceId = i;
  207224. break;
  207225. }
  207226. ++n;
  207227. }
  207228. }
  207229. for (i = handles.size(); --i >= 0;)
  207230. {
  207231. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  207232. if (han != 0 && han->deviceId == deviceId)
  207233. {
  207234. han->refCount++;
  207235. MidiOutput* const out = new MidiOutput();
  207236. out->internal = (void*) han;
  207237. return out;
  207238. }
  207239. }
  207240. for (i = 4; --i >= 0;)
  207241. {
  207242. HMIDIOUT h = 0;
  207243. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  207244. if (res == MMSYSERR_NOERROR)
  207245. {
  207246. MidiOutHandle* const han = new MidiOutHandle();
  207247. han->deviceId = deviceId;
  207248. han->refCount = 1;
  207249. han->handle = h;
  207250. handles.add (han);
  207251. MidiOutput* const out = new MidiOutput();
  207252. out->internal = (void*) han;
  207253. return out;
  207254. }
  207255. else if (res == MMSYSERR_ALLOCATED)
  207256. {
  207257. Sleep (100);
  207258. }
  207259. else
  207260. {
  207261. break;
  207262. }
  207263. }
  207264. return 0;
  207265. }
  207266. MidiOutput::~MidiOutput()
  207267. {
  207268. MidiOutHandle* const h = (MidiOutHandle*) internal;
  207269. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  207270. {
  207271. midiOutClose (h->handle);
  207272. handles.removeValue ((void*) h);
  207273. delete h;
  207274. }
  207275. }
  207276. void MidiOutput::reset()
  207277. {
  207278. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  207279. midiOutReset (h->handle);
  207280. }
  207281. bool MidiOutput::getVolume (float& leftVol,
  207282. float& rightVol)
  207283. {
  207284. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207285. DWORD n;
  207286. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  207287. {
  207288. const unsigned short* const nn = (const unsigned short*) &n;
  207289. rightVol = nn[0] / (float) 0xffff;
  207290. leftVol = nn[1] / (float) 0xffff;
  207291. return true;
  207292. }
  207293. else
  207294. {
  207295. rightVol = leftVol = 1.0f;
  207296. return false;
  207297. }
  207298. }
  207299. void MidiOutput::setVolume (float leftVol,
  207300. float rightVol)
  207301. {
  207302. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  207303. DWORD n;
  207304. unsigned short* const nn = (unsigned short*) &n;
  207305. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  207306. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  207307. midiOutSetVolume (handle->handle, n);
  207308. }
  207309. void MidiOutput::sendMessageNow (const MidiMessage& message)
  207310. {
  207311. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207312. if (message.getRawDataSize() > 3
  207313. || message.isSysEx())
  207314. {
  207315. MIDIHDR h;
  207316. zerostruct (h);
  207317. h.lpData = (char*) message.getRawData();
  207318. h.dwBufferLength = message.getRawDataSize();
  207319. h.dwBytesRecorded = message.getRawDataSize();
  207320. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  207321. {
  207322. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  207323. if (res == MMSYSERR_NOERROR)
  207324. {
  207325. while ((h.dwFlags & MHDR_DONE) == 0)
  207326. Sleep (1);
  207327. int count = 500; // 1 sec timeout
  207328. while (--count >= 0)
  207329. {
  207330. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  207331. if (res == MIDIERR_STILLPLAYING)
  207332. Sleep (2);
  207333. else
  207334. break;
  207335. }
  207336. }
  207337. }
  207338. }
  207339. else
  207340. {
  207341. midiOutShortMsg (handle->handle,
  207342. *(unsigned int*) message.getRawData());
  207343. }
  207344. }
  207345. #endif
  207346. /********* End of inlined file: juce_win32_Midi.cpp *********/
  207347. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  207348. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207349. // compiled on its own).
  207350. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  207351. #undef WINDOWS
  207352. // #define ASIO_DEBUGGING
  207353. #ifdef ASIO_DEBUGGING
  207354. #define log(a) { Logger::writeToLog (a); DBG (a) }
  207355. #else
  207356. #define log(a) {}
  207357. #endif
  207358. #ifdef ASIO_DEBUGGING
  207359. static void logError (const String& context, long error)
  207360. {
  207361. String err ("unknown error");
  207362. if (error == ASE_NotPresent)
  207363. err = "Not Present";
  207364. else if (error == ASE_HWMalfunction)
  207365. err = "Hardware Malfunction";
  207366. else if (error == ASE_InvalidParameter)
  207367. err = "Invalid Parameter";
  207368. else if (error == ASE_InvalidMode)
  207369. err = "Invalid Mode";
  207370. else if (error == ASE_SPNotAdvancing)
  207371. err = "Sample position not advancing";
  207372. else if (error == ASE_NoClock)
  207373. err = "No Clock";
  207374. else if (error == ASE_NoMemory)
  207375. err = "Out of memory";
  207376. log (T("!!error: ") + context + T(" - ") + err);
  207377. }
  207378. #else
  207379. #define logError(a, b) {}
  207380. #endif
  207381. class ASIOAudioIODevice;
  207382. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  207383. static const int maxASIOChannels = 160;
  207384. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  207385. private Timer
  207386. {
  207387. public:
  207388. Component ourWindow;
  207389. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  207390. const String& optionalDllForDirectLoading_)
  207391. : AudioIODevice (name_, T("ASIO")),
  207392. asioObject (0),
  207393. classId (classId_),
  207394. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  207395. currentBitDepth (16),
  207396. currentSampleRate (0),
  207397. tempBuffer (0),
  207398. isOpen_ (false),
  207399. isStarted (false),
  207400. postOutput (true),
  207401. insideControlPanelModalLoop (false),
  207402. shouldUsePreferredSize (false)
  207403. {
  207404. name = name_;
  207405. ourWindow.addToDesktop (0);
  207406. windowHandle = ourWindow.getWindowHandle();
  207407. jassert (currentASIODev [slotNumber] == 0);
  207408. currentASIODev [slotNumber] = this;
  207409. openDevice();
  207410. }
  207411. ~ASIOAudioIODevice()
  207412. {
  207413. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  207414. if (currentASIODev[i] == this)
  207415. currentASIODev[i] = 0;
  207416. close();
  207417. log ("ASIO - exiting");
  207418. removeCurrentDriver();
  207419. juce_free (tempBuffer);
  207420. }
  207421. void updateSampleRates()
  207422. {
  207423. // find a list of sample rates..
  207424. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  207425. sampleRates.clear();
  207426. if (asioObject != 0)
  207427. {
  207428. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  207429. {
  207430. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  207431. if (err == 0)
  207432. {
  207433. sampleRates.add ((int) possibleSampleRates[index]);
  207434. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  207435. }
  207436. else if (err != ASE_NoClock)
  207437. {
  207438. logError (T("CanSampleRate"), err);
  207439. }
  207440. }
  207441. if (sampleRates.size() == 0)
  207442. {
  207443. double cr = 0;
  207444. const long err = asioObject->getSampleRate (&cr);
  207445. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  207446. if (err == 0)
  207447. sampleRates.add ((int) cr);
  207448. }
  207449. }
  207450. }
  207451. const StringArray getOutputChannelNames()
  207452. {
  207453. return outputChannelNames;
  207454. }
  207455. const StringArray getInputChannelNames()
  207456. {
  207457. return inputChannelNames;
  207458. }
  207459. int getNumSampleRates()
  207460. {
  207461. return sampleRates.size();
  207462. }
  207463. double getSampleRate (int index)
  207464. {
  207465. return sampleRates [index];
  207466. }
  207467. int getNumBufferSizesAvailable()
  207468. {
  207469. return bufferSizes.size();
  207470. }
  207471. int getBufferSizeSamples (int index)
  207472. {
  207473. return bufferSizes [index];
  207474. }
  207475. int getDefaultBufferSize()
  207476. {
  207477. return preferredSize;
  207478. }
  207479. const String open (const BitArray& inputChannels,
  207480. const BitArray& outputChannels,
  207481. double sr,
  207482. int bufferSizeSamples)
  207483. {
  207484. close();
  207485. currentCallback = 0;
  207486. if (bufferSizeSamples <= 0)
  207487. shouldUsePreferredSize = true;
  207488. if (asioObject == 0 || ! isASIOOpen)
  207489. {
  207490. log ("Warning: device not open");
  207491. const String err (openDevice());
  207492. if (asioObject == 0 || ! isASIOOpen)
  207493. return err;
  207494. }
  207495. isStarted = false;
  207496. bufferIndex = -1;
  207497. long err = 0;
  207498. long newPreferredSize = 0;
  207499. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  207500. minSize = 0;
  207501. maxSize = 0;
  207502. newPreferredSize = 0;
  207503. granularity = 0;
  207504. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  207505. {
  207506. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  207507. shouldUsePreferredSize = true;
  207508. preferredSize = newPreferredSize;
  207509. }
  207510. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  207511. // dynamic changes to the buffer size...
  207512. shouldUsePreferredSize = shouldUsePreferredSize
  207513. || getName().containsIgnoreCase (T("Digidesign"));
  207514. if (shouldUsePreferredSize)
  207515. {
  207516. log ("Using preferred size for buffer..");
  207517. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  207518. {
  207519. bufferSizeSamples = preferredSize;
  207520. }
  207521. else
  207522. {
  207523. bufferSizeSamples = 1024;
  207524. logError ("GetBufferSize1", err);
  207525. }
  207526. shouldUsePreferredSize = false;
  207527. }
  207528. int sampleRate = roundDoubleToInt (sr);
  207529. currentSampleRate = sampleRate;
  207530. currentBlockSizeSamples = bufferSizeSamples;
  207531. currentChansOut.clear();
  207532. currentChansIn.clear();
  207533. zeromem (inBuffers, sizeof (inBuffers));
  207534. zeromem (outBuffers, sizeof (outBuffers));
  207535. updateSampleRates();
  207536. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  207537. sampleRate = sampleRates[0];
  207538. jassert (sampleRate != 0);
  207539. if (sampleRate == 0)
  207540. sampleRate = 44100;
  207541. long numSources = 32;
  207542. ASIOClockSource clocks[32];
  207543. zeromem (clocks, sizeof (clocks));
  207544. asioObject->getClockSources (clocks, &numSources);
  207545. bool isSourceSet = false;
  207546. // careful not to remove this loop because it does more than just logging!
  207547. int i;
  207548. for (i = 0; i < numSources; ++i)
  207549. {
  207550. String s ("clock: ");
  207551. s += clocks[i].name;
  207552. if (clocks[i].isCurrentSource)
  207553. {
  207554. isSourceSet = true;
  207555. s << " (cur)";
  207556. }
  207557. log (s);
  207558. }
  207559. if (numSources > 1 && ! isSourceSet)
  207560. {
  207561. log ("setting clock source");
  207562. asioObject->setClockSource (clocks[0].index);
  207563. Thread::sleep (20);
  207564. }
  207565. else
  207566. {
  207567. if (numSources == 0)
  207568. {
  207569. log ("ASIO - no clock sources!");
  207570. }
  207571. }
  207572. double cr = 0;
  207573. err = asioObject->getSampleRate (&cr);
  207574. if (err == 0)
  207575. {
  207576. currentSampleRate = cr;
  207577. }
  207578. else
  207579. {
  207580. logError ("GetSampleRate", err);
  207581. currentSampleRate = 0;
  207582. }
  207583. error = String::empty;
  207584. needToReset = false;
  207585. isReSync = false;
  207586. err = 0;
  207587. bool buffersCreated = false;
  207588. if (currentSampleRate != sampleRate)
  207589. {
  207590. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  207591. err = asioObject->setSampleRate (sampleRate);
  207592. if (err == ASE_NoClock && numSources > 0)
  207593. {
  207594. log ("trying to set a clock source..");
  207595. Thread::sleep (10);
  207596. err = asioObject->setClockSource (clocks[0].index);
  207597. if (err != 0)
  207598. {
  207599. logError ("SetClock", err);
  207600. }
  207601. Thread::sleep (10);
  207602. err = asioObject->setSampleRate (sampleRate);
  207603. }
  207604. }
  207605. if (err == 0)
  207606. {
  207607. currentSampleRate = sampleRate;
  207608. if (needToReset)
  207609. {
  207610. if (isReSync)
  207611. {
  207612. log ("Resync request");
  207613. }
  207614. log ("! Resetting ASIO after sample rate change");
  207615. removeCurrentDriver();
  207616. loadDriver();
  207617. const String error (initDriver());
  207618. if (error.isNotEmpty())
  207619. {
  207620. log (T("ASIOInit: ") + error);
  207621. }
  207622. needToReset = false;
  207623. isReSync = false;
  207624. }
  207625. numActiveInputChans = 0;
  207626. numActiveOutputChans = 0;
  207627. ASIOBufferInfo* info = bufferInfos;
  207628. int i;
  207629. for (i = 0; i < totalNumInputChans; ++i)
  207630. {
  207631. if (inputChannels[i])
  207632. {
  207633. currentChansIn.setBit (i);
  207634. info->isInput = 1;
  207635. info->channelNum = i;
  207636. info->buffers[0] = info->buffers[1] = 0;
  207637. ++info;
  207638. ++numActiveInputChans;
  207639. }
  207640. }
  207641. for (i = 0; i < totalNumOutputChans; ++i)
  207642. {
  207643. if (outputChannels[i])
  207644. {
  207645. currentChansOut.setBit (i);
  207646. info->isInput = 0;
  207647. info->channelNum = i;
  207648. info->buffers[0] = info->buffers[1] = 0;
  207649. ++info;
  207650. ++numActiveOutputChans;
  207651. }
  207652. }
  207653. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  207654. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  207655. if (currentASIODev[0] == this)
  207656. {
  207657. callbacks.bufferSwitch = &bufferSwitchCallback0;
  207658. callbacks.asioMessage = &asioMessagesCallback0;
  207659. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  207660. }
  207661. else if (currentASIODev[1] == this)
  207662. {
  207663. callbacks.bufferSwitch = &bufferSwitchCallback1;
  207664. callbacks.asioMessage = &asioMessagesCallback1;
  207665. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  207666. }
  207667. else if (currentASIODev[2] == this)
  207668. {
  207669. callbacks.bufferSwitch = &bufferSwitchCallback2;
  207670. callbacks.asioMessage = &asioMessagesCallback2;
  207671. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  207672. }
  207673. else
  207674. {
  207675. jassertfalse
  207676. }
  207677. log ("disposing buffers");
  207678. err = asioObject->disposeBuffers();
  207679. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  207680. err = asioObject->createBuffers (bufferInfos,
  207681. totalBuffers,
  207682. currentBlockSizeSamples,
  207683. &callbacks);
  207684. if (err != 0)
  207685. {
  207686. currentBlockSizeSamples = preferredSize;
  207687. logError ("create buffers 2", err);
  207688. asioObject->disposeBuffers();
  207689. err = asioObject->createBuffers (bufferInfos,
  207690. totalBuffers,
  207691. currentBlockSizeSamples,
  207692. &callbacks);
  207693. }
  207694. if (err == 0)
  207695. {
  207696. buffersCreated = true;
  207697. juce_free (tempBuffer);
  207698. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  207699. int n = 0;
  207700. Array <int> types;
  207701. currentBitDepth = 16;
  207702. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  207703. {
  207704. if (inputChannels[i])
  207705. {
  207706. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  207707. ASIOChannelInfo channelInfo;
  207708. zerostruct (channelInfo);
  207709. channelInfo.channel = i;
  207710. channelInfo.isInput = 1;
  207711. asioObject->getChannelInfo (&channelInfo);
  207712. types.addIfNotAlreadyThere (channelInfo.type);
  207713. typeToFormatParameters (channelInfo.type,
  207714. inputChannelBitDepths[n],
  207715. inputChannelBytesPerSample[n],
  207716. inputChannelIsFloat[n],
  207717. inputChannelLittleEndian[n]);
  207718. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  207719. ++n;
  207720. }
  207721. }
  207722. jassert (numActiveInputChans == n);
  207723. n = 0;
  207724. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  207725. {
  207726. if (outputChannels[i])
  207727. {
  207728. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  207729. ASIOChannelInfo channelInfo;
  207730. zerostruct (channelInfo);
  207731. channelInfo.channel = i;
  207732. channelInfo.isInput = 0;
  207733. asioObject->getChannelInfo (&channelInfo);
  207734. types.addIfNotAlreadyThere (channelInfo.type);
  207735. typeToFormatParameters (channelInfo.type,
  207736. outputChannelBitDepths[n],
  207737. outputChannelBytesPerSample[n],
  207738. outputChannelIsFloat[n],
  207739. outputChannelLittleEndian[n]);
  207740. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  207741. ++n;
  207742. }
  207743. }
  207744. jassert (numActiveOutputChans == n);
  207745. for (i = types.size(); --i >= 0;)
  207746. {
  207747. log (T("channel format: ") + String (types[i]));
  207748. }
  207749. jassert (n <= totalBuffers);
  207750. for (i = 0; i < numActiveOutputChans; ++i)
  207751. {
  207752. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  207753. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  207754. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  207755. {
  207756. log ("!! Null buffers");
  207757. }
  207758. else
  207759. {
  207760. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  207761. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  207762. }
  207763. }
  207764. inputLatency = outputLatency = 0;
  207765. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  207766. {
  207767. log ("ASIO - no latencies");
  207768. }
  207769. else
  207770. {
  207771. log (T("ASIO latencies: ")
  207772. + String ((int) outputLatency)
  207773. + T(", ")
  207774. + String ((int) inputLatency));
  207775. }
  207776. isOpen_ = true;
  207777. log ("starting ASIO");
  207778. calledback = false;
  207779. err = asioObject->start();
  207780. if (err != 0)
  207781. {
  207782. isOpen_ = false;
  207783. log ("ASIO - stop on failure");
  207784. Thread::sleep (10);
  207785. asioObject->stop();
  207786. error = "Can't start device";
  207787. Thread::sleep (10);
  207788. }
  207789. else
  207790. {
  207791. int count = 300;
  207792. while (--count > 0 && ! calledback)
  207793. Thread::sleep (10);
  207794. isStarted = true;
  207795. if (! calledback)
  207796. {
  207797. error = "Device didn't start correctly";
  207798. log ("ASIO didn't callback - stopping..");
  207799. asioObject->stop();
  207800. }
  207801. }
  207802. }
  207803. else
  207804. {
  207805. error = "Can't create i/o buffers";
  207806. }
  207807. }
  207808. else
  207809. {
  207810. error = "Can't set sample rate: ";
  207811. error << sampleRate;
  207812. }
  207813. if (error.isNotEmpty())
  207814. {
  207815. logError (error, err);
  207816. if (asioObject != 0 && buffersCreated)
  207817. asioObject->disposeBuffers();
  207818. Thread::sleep (20);
  207819. isStarted = false;
  207820. isOpen_ = false;
  207821. close();
  207822. }
  207823. needToReset = false;
  207824. isReSync = false;
  207825. return error;
  207826. }
  207827. void close()
  207828. {
  207829. error = String::empty;
  207830. stopTimer();
  207831. stop();
  207832. if (isASIOOpen && isOpen_)
  207833. {
  207834. const ScopedLock sl (callbackLock);
  207835. isOpen_ = false;
  207836. isStarted = false;
  207837. needToReset = false;
  207838. isReSync = false;
  207839. log ("ASIO - stopping");
  207840. if (asioObject != 0)
  207841. {
  207842. Thread::sleep (20);
  207843. asioObject->stop();
  207844. Thread::sleep (10);
  207845. asioObject->disposeBuffers();
  207846. }
  207847. Thread::sleep (10);
  207848. }
  207849. }
  207850. bool isOpen()
  207851. {
  207852. return isOpen_ || insideControlPanelModalLoop;
  207853. }
  207854. int getCurrentBufferSizeSamples()
  207855. {
  207856. return currentBlockSizeSamples;
  207857. }
  207858. double getCurrentSampleRate()
  207859. {
  207860. return currentSampleRate;
  207861. }
  207862. const BitArray getActiveOutputChannels() const
  207863. {
  207864. return currentChansOut;
  207865. }
  207866. const BitArray getActiveInputChannels() const
  207867. {
  207868. return currentChansIn;
  207869. }
  207870. int getCurrentBitDepth()
  207871. {
  207872. return currentBitDepth;
  207873. }
  207874. int getOutputLatencyInSamples()
  207875. {
  207876. return outputLatency + currentBlockSizeSamples / 4;
  207877. }
  207878. int getInputLatencyInSamples()
  207879. {
  207880. return inputLatency + currentBlockSizeSamples / 4;
  207881. }
  207882. void start (AudioIODeviceCallback* callback)
  207883. {
  207884. if (callback != 0)
  207885. {
  207886. callback->audioDeviceAboutToStart (this);
  207887. const ScopedLock sl (callbackLock);
  207888. currentCallback = callback;
  207889. }
  207890. }
  207891. void stop()
  207892. {
  207893. AudioIODeviceCallback* const lastCallback = currentCallback;
  207894. {
  207895. const ScopedLock sl (callbackLock);
  207896. currentCallback = 0;
  207897. }
  207898. if (lastCallback != 0)
  207899. lastCallback->audioDeviceStopped();
  207900. }
  207901. bool isPlaying()
  207902. {
  207903. return isASIOOpen && (currentCallback != 0);
  207904. }
  207905. const String getLastError()
  207906. {
  207907. return error;
  207908. }
  207909. bool hasControlPanel() const
  207910. {
  207911. return true;
  207912. }
  207913. bool showControlPanel()
  207914. {
  207915. log ("ASIO - showing control panel");
  207916. Component modalWindow (String::empty);
  207917. modalWindow.setOpaque (true);
  207918. modalWindow.addToDesktop (0);
  207919. modalWindow.enterModalState();
  207920. bool done = false;
  207921. JUCE_TRY
  207922. {
  207923. // are there are devices that need to be closed before showing their control panel?
  207924. // close();
  207925. insideControlPanelModalLoop = true;
  207926. const uint32 started = Time::getMillisecondCounter();
  207927. if (asioObject != 0)
  207928. {
  207929. asioObject->controlPanel();
  207930. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  207931. log (T("spent: ") + String (spent));
  207932. if (spent > 300)
  207933. {
  207934. shouldUsePreferredSize = true;
  207935. done = true;
  207936. }
  207937. }
  207938. }
  207939. JUCE_CATCH_ALL
  207940. insideControlPanelModalLoop = false;
  207941. return done;
  207942. }
  207943. void resetRequest() throw()
  207944. {
  207945. needToReset = true;
  207946. }
  207947. void resyncRequest() throw()
  207948. {
  207949. needToReset = true;
  207950. isReSync = true;
  207951. }
  207952. void timerCallback()
  207953. {
  207954. if (! insideControlPanelModalLoop)
  207955. {
  207956. stopTimer();
  207957. // used to cause a reset
  207958. log ("! ASIO restart request!");
  207959. if (isOpen_)
  207960. {
  207961. AudioIODeviceCallback* const oldCallback = currentCallback;
  207962. close();
  207963. open (BitArray (currentChansIn), BitArray (currentChansOut),
  207964. currentSampleRate, currentBlockSizeSamples);
  207965. if (oldCallback != 0)
  207966. start (oldCallback);
  207967. }
  207968. }
  207969. else
  207970. {
  207971. startTimer (100);
  207972. }
  207973. }
  207974. juce_UseDebuggingNewOperator
  207975. private:
  207976. IASIO* volatile asioObject;
  207977. ASIOCallbacks callbacks;
  207978. void* windowHandle;
  207979. CLSID classId;
  207980. const String optionalDllForDirectLoading;
  207981. String error;
  207982. long totalNumInputChans, totalNumOutputChans;
  207983. StringArray inputChannelNames, outputChannelNames;
  207984. Array<int> sampleRates, bufferSizes;
  207985. long inputLatency, outputLatency;
  207986. long minSize, maxSize, preferredSize, granularity;
  207987. int volatile currentBlockSizeSamples;
  207988. int volatile currentBitDepth;
  207989. double volatile currentSampleRate;
  207990. BitArray currentChansOut, currentChansIn;
  207991. AudioIODeviceCallback* volatile currentCallback;
  207992. CriticalSection callbackLock;
  207993. ASIOBufferInfo bufferInfos [maxASIOChannels];
  207994. float* inBuffers [maxASIOChannels];
  207995. float* outBuffers [maxASIOChannels];
  207996. int inputChannelBitDepths [maxASIOChannels];
  207997. int outputChannelBitDepths [maxASIOChannels];
  207998. int inputChannelBytesPerSample [maxASIOChannels];
  207999. int outputChannelBytesPerSample [maxASIOChannels];
  208000. bool inputChannelIsFloat [maxASIOChannels];
  208001. bool outputChannelIsFloat [maxASIOChannels];
  208002. bool inputChannelLittleEndian [maxASIOChannels];
  208003. bool outputChannelLittleEndian [maxASIOChannels];
  208004. WaitableEvent event1;
  208005. float* tempBuffer;
  208006. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  208007. bool isOpen_, isStarted;
  208008. bool volatile isASIOOpen;
  208009. bool volatile calledback;
  208010. bool volatile littleEndian, postOutput, needToReset, isReSync;
  208011. bool volatile insideControlPanelModalLoop;
  208012. bool volatile shouldUsePreferredSize;
  208013. void removeCurrentDriver()
  208014. {
  208015. if (asioObject != 0)
  208016. {
  208017. asioObject->Release();
  208018. asioObject = 0;
  208019. }
  208020. }
  208021. bool loadDriver()
  208022. {
  208023. removeCurrentDriver();
  208024. JUCE_TRY
  208025. {
  208026. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  208027. classId, (void**) &asioObject) == S_OK)
  208028. {
  208029. return true;
  208030. }
  208031. // If a class isn't registered but we have a path for it, we can fallback to
  208032. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  208033. if (optionalDllForDirectLoading.isNotEmpty())
  208034. {
  208035. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  208036. if (h != 0)
  208037. {
  208038. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  208039. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  208040. if (dllGetClassObject != 0)
  208041. {
  208042. IClassFactory* classFactory = 0;
  208043. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  208044. if (classFactory != 0)
  208045. {
  208046. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  208047. classFactory->Release();
  208048. }
  208049. return asioObject != 0;
  208050. }
  208051. }
  208052. }
  208053. }
  208054. JUCE_CATCH_ALL
  208055. asioObject = 0;
  208056. return false;
  208057. }
  208058. const String initDriver()
  208059. {
  208060. if (asioObject != 0)
  208061. {
  208062. char buffer [256];
  208063. zeromem (buffer, sizeof (buffer));
  208064. if (! asioObject->init (windowHandle))
  208065. {
  208066. asioObject->getErrorMessage (buffer);
  208067. return String (buffer, sizeof (buffer) - 1);
  208068. }
  208069. // just in case any daft drivers expect this to be called..
  208070. asioObject->getDriverName (buffer);
  208071. return String::empty;
  208072. }
  208073. return "No Driver";
  208074. }
  208075. const String openDevice()
  208076. {
  208077. // use this in case the driver starts opening dialog boxes..
  208078. Component modalWindow (String::empty);
  208079. modalWindow.setOpaque (true);
  208080. modalWindow.addToDesktop (0);
  208081. modalWindow.enterModalState();
  208082. // open the device and get its info..
  208083. log (T("opening ASIO device: ") + getName());
  208084. needToReset = false;
  208085. isReSync = false;
  208086. outputChannelNames.clear();
  208087. inputChannelNames.clear();
  208088. bufferSizes.clear();
  208089. sampleRates.clear();
  208090. isASIOOpen = false;
  208091. isOpen_ = false;
  208092. totalNumInputChans = 0;
  208093. totalNumOutputChans = 0;
  208094. numActiveInputChans = 0;
  208095. numActiveOutputChans = 0;
  208096. currentCallback = 0;
  208097. error = String::empty;
  208098. if (getName().isEmpty())
  208099. return error;
  208100. long err = 0;
  208101. if (loadDriver())
  208102. {
  208103. if ((error = initDriver()).isEmpty())
  208104. {
  208105. numActiveInputChans = 0;
  208106. numActiveOutputChans = 0;
  208107. totalNumInputChans = 0;
  208108. totalNumOutputChans = 0;
  208109. if (asioObject != 0
  208110. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  208111. {
  208112. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  208113. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208114. {
  208115. // find a list of buffer sizes..
  208116. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  208117. if (granularity >= 0)
  208118. {
  208119. granularity = jmax (1, (int) granularity);
  208120. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  208121. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  208122. }
  208123. else if (granularity < 0)
  208124. {
  208125. for (int i = 0; i < 18; ++i)
  208126. {
  208127. const int s = (1 << i);
  208128. if (s >= minSize && s <= maxSize)
  208129. bufferSizes.add (s);
  208130. }
  208131. }
  208132. if (! bufferSizes.contains (preferredSize))
  208133. bufferSizes.insert (0, preferredSize);
  208134. double currentRate = 0;
  208135. asioObject->getSampleRate (&currentRate);
  208136. if (currentRate <= 0.0 || currentRate > 192001.0)
  208137. {
  208138. log ("setting sample rate");
  208139. err = asioObject->setSampleRate (44100.0);
  208140. if (err != 0)
  208141. {
  208142. logError ("setting sample rate", err);
  208143. }
  208144. asioObject->getSampleRate (&currentRate);
  208145. }
  208146. currentSampleRate = currentRate;
  208147. postOutput = (asioObject->outputReady() == 0);
  208148. if (postOutput)
  208149. {
  208150. log ("ASIO outputReady = ok");
  208151. }
  208152. updateSampleRates();
  208153. // ..because cubase does it at this point
  208154. inputLatency = outputLatency = 0;
  208155. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208156. {
  208157. log ("ASIO - no latencies");
  208158. }
  208159. log (String ("latencies: ")
  208160. + String ((int) inputLatency)
  208161. + T(", ") + String ((int) outputLatency));
  208162. // create some dummy buffers now.. because cubase does..
  208163. numActiveInputChans = 0;
  208164. numActiveOutputChans = 0;
  208165. ASIOBufferInfo* info = bufferInfos;
  208166. int i, numChans = 0;
  208167. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  208168. {
  208169. info->isInput = 1;
  208170. info->channelNum = i;
  208171. info->buffers[0] = info->buffers[1] = 0;
  208172. ++info;
  208173. ++numChans;
  208174. }
  208175. const int outputBufferIndex = numChans;
  208176. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  208177. {
  208178. info->isInput = 0;
  208179. info->channelNum = i;
  208180. info->buffers[0] = info->buffers[1] = 0;
  208181. ++info;
  208182. ++numChans;
  208183. }
  208184. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208185. if (currentASIODev[0] == this)
  208186. {
  208187. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208188. callbacks.asioMessage = &asioMessagesCallback0;
  208189. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208190. }
  208191. else if (currentASIODev[1] == this)
  208192. {
  208193. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208194. callbacks.asioMessage = &asioMessagesCallback1;
  208195. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208196. }
  208197. else if (currentASIODev[2] == this)
  208198. {
  208199. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208200. callbacks.asioMessage = &asioMessagesCallback2;
  208201. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208202. }
  208203. else
  208204. {
  208205. jassertfalse
  208206. }
  208207. log (T("creating buffers (dummy): ") + String (numChans)
  208208. + T(", ") + String ((int) preferredSize));
  208209. if (preferredSize > 0)
  208210. {
  208211. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  208212. if (err != 0)
  208213. {
  208214. logError ("dummy buffers", err);
  208215. }
  208216. }
  208217. long newInps = 0, newOuts = 0;
  208218. asioObject->getChannels (&newInps, &newOuts);
  208219. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  208220. {
  208221. totalNumInputChans = newInps;
  208222. totalNumOutputChans = newOuts;
  208223. log (String ((int) totalNumInputChans) + T(" in; ")
  208224. + String ((int) totalNumOutputChans) + T(" out"));
  208225. }
  208226. updateSampleRates();
  208227. ASIOChannelInfo channelInfo;
  208228. channelInfo.type = 0;
  208229. for (i = 0; i < totalNumInputChans; ++i)
  208230. {
  208231. zerostruct (channelInfo);
  208232. channelInfo.channel = i;
  208233. channelInfo.isInput = 1;
  208234. asioObject->getChannelInfo (&channelInfo);
  208235. inputChannelNames.add (String (channelInfo.name));
  208236. }
  208237. for (i = 0; i < totalNumOutputChans; ++i)
  208238. {
  208239. zerostruct (channelInfo);
  208240. channelInfo.channel = i;
  208241. channelInfo.isInput = 0;
  208242. asioObject->getChannelInfo (&channelInfo);
  208243. outputChannelNames.add (String (channelInfo.name));
  208244. typeToFormatParameters (channelInfo.type,
  208245. outputChannelBitDepths[i],
  208246. outputChannelBytesPerSample[i],
  208247. outputChannelIsFloat[i],
  208248. outputChannelLittleEndian[i]);
  208249. if (i < 2)
  208250. {
  208251. // clear the channels that are used with the dummy stuff
  208252. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  208253. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  208254. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  208255. }
  208256. }
  208257. outputChannelNames.trim();
  208258. inputChannelNames.trim();
  208259. outputChannelNames.appendNumbersToDuplicates (false, true);
  208260. inputChannelNames.appendNumbersToDuplicates (false, true);
  208261. // start and stop because cubase does it..
  208262. asioObject->getLatencies (&inputLatency, &outputLatency);
  208263. if ((err = asioObject->start()) != 0)
  208264. {
  208265. // ignore an error here, as it might start later after setting other stuff up
  208266. logError ("ASIO start", err);
  208267. }
  208268. Thread::sleep (100);
  208269. asioObject->stop();
  208270. }
  208271. else
  208272. {
  208273. error = "Can't detect buffer sizes";
  208274. }
  208275. }
  208276. else
  208277. {
  208278. error = "Can't detect asio channels";
  208279. }
  208280. }
  208281. }
  208282. else
  208283. {
  208284. error = "No such device";
  208285. }
  208286. if (error.isNotEmpty())
  208287. {
  208288. logError (error, err);
  208289. if (asioObject != 0)
  208290. asioObject->disposeBuffers();
  208291. removeCurrentDriver();
  208292. isASIOOpen = false;
  208293. }
  208294. else
  208295. {
  208296. isASIOOpen = true;
  208297. log ("ASIO device open");
  208298. }
  208299. isOpen_ = false;
  208300. needToReset = false;
  208301. isReSync = false;
  208302. return error;
  208303. }
  208304. void callback (const long index) throw()
  208305. {
  208306. if (isStarted)
  208307. {
  208308. bufferIndex = index;
  208309. processBuffer();
  208310. }
  208311. else
  208312. {
  208313. if (postOutput && (asioObject != 0))
  208314. asioObject->outputReady();
  208315. }
  208316. calledback = true;
  208317. }
  208318. void processBuffer() throw()
  208319. {
  208320. const ASIOBufferInfo* const infos = bufferInfos;
  208321. const int bi = bufferIndex;
  208322. const ScopedLock sl (callbackLock);
  208323. if (needToReset)
  208324. {
  208325. needToReset = false;
  208326. if (isReSync)
  208327. {
  208328. log ("! ASIO resync");
  208329. isReSync = false;
  208330. }
  208331. else
  208332. {
  208333. startTimer (20);
  208334. }
  208335. }
  208336. if (bi >= 0)
  208337. {
  208338. const int samps = currentBlockSizeSamples;
  208339. if (currentCallback != 0)
  208340. {
  208341. int i;
  208342. for (i = 0; i < numActiveInputChans; ++i)
  208343. {
  208344. float* const dst = inBuffers[i];
  208345. jassert (dst != 0);
  208346. const char* const src = (const char*) (infos[i].buffers[bi]);
  208347. if (inputChannelIsFloat[i])
  208348. {
  208349. memcpy (dst, src, samps * sizeof (float));
  208350. }
  208351. else
  208352. {
  208353. jassert (dst == tempBuffer + (samps * i));
  208354. switch (inputChannelBitDepths[i])
  208355. {
  208356. case 16:
  208357. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  208358. samps, inputChannelLittleEndian[i]);
  208359. break;
  208360. case 24:
  208361. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  208362. samps, inputChannelLittleEndian[i]);
  208363. break;
  208364. case 32:
  208365. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  208366. samps, inputChannelLittleEndian[i]);
  208367. break;
  208368. case 64:
  208369. jassertfalse
  208370. break;
  208371. }
  208372. }
  208373. }
  208374. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  208375. numActiveInputChans,
  208376. outBuffers,
  208377. numActiveOutputChans,
  208378. samps);
  208379. for (i = 0; i < numActiveOutputChans; ++i)
  208380. {
  208381. float* const src = outBuffers[i];
  208382. jassert (src != 0);
  208383. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  208384. if (outputChannelIsFloat[i])
  208385. {
  208386. memcpy (dst, src, samps * sizeof (float));
  208387. }
  208388. else
  208389. {
  208390. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  208391. switch (outputChannelBitDepths[i])
  208392. {
  208393. case 16:
  208394. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  208395. samps, outputChannelLittleEndian[i]);
  208396. break;
  208397. case 24:
  208398. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  208399. samps, outputChannelLittleEndian[i]);
  208400. break;
  208401. case 32:
  208402. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  208403. samps, outputChannelLittleEndian[i]);
  208404. break;
  208405. case 64:
  208406. jassertfalse
  208407. break;
  208408. }
  208409. }
  208410. }
  208411. }
  208412. else
  208413. {
  208414. for (int i = 0; i < numActiveOutputChans; ++i)
  208415. {
  208416. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  208417. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  208418. }
  208419. }
  208420. }
  208421. if (postOutput)
  208422. asioObject->outputReady();
  208423. }
  208424. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  208425. {
  208426. if (currentASIODev[0] != 0)
  208427. currentASIODev[0]->callback (index);
  208428. return 0;
  208429. }
  208430. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  208431. {
  208432. if (currentASIODev[1] != 0)
  208433. currentASIODev[1]->callback (index);
  208434. return 0;
  208435. }
  208436. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  208437. {
  208438. if (currentASIODev[2] != 0)
  208439. currentASIODev[2]->callback (index);
  208440. return 0;
  208441. }
  208442. static void bufferSwitchCallback0 (long index, long) throw()
  208443. {
  208444. if (currentASIODev[0] != 0)
  208445. currentASIODev[0]->callback (index);
  208446. }
  208447. static void bufferSwitchCallback1 (long index, long) throw()
  208448. {
  208449. if (currentASIODev[1] != 0)
  208450. currentASIODev[1]->callback (index);
  208451. }
  208452. static void bufferSwitchCallback2 (long index, long) throw()
  208453. {
  208454. if (currentASIODev[2] != 0)
  208455. currentASIODev[2]->callback (index);
  208456. }
  208457. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  208458. {
  208459. return asioMessagesCallback (selector, value, 0);
  208460. }
  208461. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  208462. {
  208463. return asioMessagesCallback (selector, value, 1);
  208464. }
  208465. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  208466. {
  208467. return asioMessagesCallback (selector, value, 2);
  208468. }
  208469. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  208470. {
  208471. switch (selector)
  208472. {
  208473. case kAsioSelectorSupported:
  208474. if (value == kAsioResetRequest
  208475. || value == kAsioEngineVersion
  208476. || value == kAsioResyncRequest
  208477. || value == kAsioLatenciesChanged
  208478. || value == kAsioSupportsInputMonitor)
  208479. return 1;
  208480. break;
  208481. case kAsioBufferSizeChange:
  208482. break;
  208483. case kAsioResetRequest:
  208484. if (currentASIODev[deviceIndex] != 0)
  208485. currentASIODev[deviceIndex]->resetRequest();
  208486. return 1;
  208487. case kAsioResyncRequest:
  208488. if (currentASIODev[deviceIndex] != 0)
  208489. currentASIODev[deviceIndex]->resyncRequest();
  208490. return 1;
  208491. case kAsioLatenciesChanged:
  208492. return 1;
  208493. case kAsioEngineVersion:
  208494. return 2;
  208495. case kAsioSupportsTimeInfo:
  208496. case kAsioSupportsTimeCode:
  208497. return 0;
  208498. }
  208499. return 0;
  208500. }
  208501. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  208502. {
  208503. }
  208504. static void convertInt16ToFloat (const char* src,
  208505. float* dest,
  208506. const int srcStrideBytes,
  208507. int numSamples,
  208508. const bool littleEndian) throw()
  208509. {
  208510. const double g = 1.0 / 32768.0;
  208511. if (littleEndian)
  208512. {
  208513. while (--numSamples >= 0)
  208514. {
  208515. *dest++ = (float) (g * (short) littleEndianShort (src));
  208516. src += srcStrideBytes;
  208517. }
  208518. }
  208519. else
  208520. {
  208521. while (--numSamples >= 0)
  208522. {
  208523. *dest++ = (float) (g * (short) bigEndianShort (src));
  208524. src += srcStrideBytes;
  208525. }
  208526. }
  208527. }
  208528. static void convertFloatToInt16 (const float* src,
  208529. char* dest,
  208530. const int dstStrideBytes,
  208531. int numSamples,
  208532. const bool littleEndian) throw()
  208533. {
  208534. const double maxVal = (double) 0x7fff;
  208535. if (littleEndian)
  208536. {
  208537. while (--numSamples >= 0)
  208538. {
  208539. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  208540. dest += dstStrideBytes;
  208541. }
  208542. }
  208543. else
  208544. {
  208545. while (--numSamples >= 0)
  208546. {
  208547. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  208548. dest += dstStrideBytes;
  208549. }
  208550. }
  208551. }
  208552. static void convertInt24ToFloat (const char* src,
  208553. float* dest,
  208554. const int srcStrideBytes,
  208555. int numSamples,
  208556. const bool littleEndian) throw()
  208557. {
  208558. const double g = 1.0 / 0x7fffff;
  208559. if (littleEndian)
  208560. {
  208561. while (--numSamples >= 0)
  208562. {
  208563. *dest++ = (float) (g * littleEndian24Bit (src));
  208564. src += srcStrideBytes;
  208565. }
  208566. }
  208567. else
  208568. {
  208569. while (--numSamples >= 0)
  208570. {
  208571. *dest++ = (float) (g * bigEndian24Bit (src));
  208572. src += srcStrideBytes;
  208573. }
  208574. }
  208575. }
  208576. static void convertFloatToInt24 (const float* src,
  208577. char* dest,
  208578. const int dstStrideBytes,
  208579. int numSamples,
  208580. const bool littleEndian) throw()
  208581. {
  208582. const double maxVal = (double) 0x7fffff;
  208583. if (littleEndian)
  208584. {
  208585. while (--numSamples >= 0)
  208586. {
  208587. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  208588. dest += dstStrideBytes;
  208589. }
  208590. }
  208591. else
  208592. {
  208593. while (--numSamples >= 0)
  208594. {
  208595. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  208596. dest += dstStrideBytes;
  208597. }
  208598. }
  208599. }
  208600. static void convertInt32ToFloat (const char* src,
  208601. float* dest,
  208602. const int srcStrideBytes,
  208603. int numSamples,
  208604. const bool littleEndian) throw()
  208605. {
  208606. const double g = 1.0 / 0x7fffffff;
  208607. if (littleEndian)
  208608. {
  208609. while (--numSamples >= 0)
  208610. {
  208611. *dest++ = (float) (g * (int) littleEndianInt (src));
  208612. src += srcStrideBytes;
  208613. }
  208614. }
  208615. else
  208616. {
  208617. while (--numSamples >= 0)
  208618. {
  208619. *dest++ = (float) (g * (int) bigEndianInt (src));
  208620. src += srcStrideBytes;
  208621. }
  208622. }
  208623. }
  208624. static void convertFloatToInt32 (const float* src,
  208625. char* dest,
  208626. const int dstStrideBytes,
  208627. int numSamples,
  208628. const bool littleEndian) throw()
  208629. {
  208630. const double maxVal = (double) 0x7fffffff;
  208631. if (littleEndian)
  208632. {
  208633. while (--numSamples >= 0)
  208634. {
  208635. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  208636. dest += dstStrideBytes;
  208637. }
  208638. }
  208639. else
  208640. {
  208641. while (--numSamples >= 0)
  208642. {
  208643. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  208644. dest += dstStrideBytes;
  208645. }
  208646. }
  208647. }
  208648. static void typeToFormatParameters (const long type,
  208649. int& bitDepth,
  208650. int& byteStride,
  208651. bool& formatIsFloat,
  208652. bool& littleEndian) throw()
  208653. {
  208654. bitDepth = 0;
  208655. littleEndian = false;
  208656. formatIsFloat = false;
  208657. switch (type)
  208658. {
  208659. case ASIOSTInt16MSB:
  208660. case ASIOSTInt16LSB:
  208661. case ASIOSTInt32MSB16:
  208662. case ASIOSTInt32LSB16:
  208663. bitDepth = 16; break;
  208664. case ASIOSTFloat32MSB:
  208665. case ASIOSTFloat32LSB:
  208666. formatIsFloat = true;
  208667. bitDepth = 32; break;
  208668. case ASIOSTInt32MSB:
  208669. case ASIOSTInt32LSB:
  208670. bitDepth = 32; break;
  208671. case ASIOSTInt24MSB:
  208672. case ASIOSTInt24LSB:
  208673. case ASIOSTInt32MSB24:
  208674. case ASIOSTInt32LSB24:
  208675. case ASIOSTInt32MSB18:
  208676. case ASIOSTInt32MSB20:
  208677. case ASIOSTInt32LSB18:
  208678. case ASIOSTInt32LSB20:
  208679. bitDepth = 24; break;
  208680. case ASIOSTFloat64MSB:
  208681. case ASIOSTFloat64LSB:
  208682. default:
  208683. bitDepth = 64;
  208684. break;
  208685. }
  208686. switch (type)
  208687. {
  208688. case ASIOSTInt16MSB:
  208689. case ASIOSTInt32MSB16:
  208690. case ASIOSTFloat32MSB:
  208691. case ASIOSTFloat64MSB:
  208692. case ASIOSTInt32MSB:
  208693. case ASIOSTInt32MSB18:
  208694. case ASIOSTInt32MSB20:
  208695. case ASIOSTInt32MSB24:
  208696. case ASIOSTInt24MSB:
  208697. littleEndian = false; break;
  208698. case ASIOSTInt16LSB:
  208699. case ASIOSTInt32LSB16:
  208700. case ASIOSTFloat32LSB:
  208701. case ASIOSTFloat64LSB:
  208702. case ASIOSTInt32LSB:
  208703. case ASIOSTInt32LSB18:
  208704. case ASIOSTInt32LSB20:
  208705. case ASIOSTInt32LSB24:
  208706. case ASIOSTInt24LSB:
  208707. littleEndian = true; break;
  208708. default:
  208709. break;
  208710. }
  208711. switch (type)
  208712. {
  208713. case ASIOSTInt16LSB:
  208714. case ASIOSTInt16MSB:
  208715. byteStride = 2; break;
  208716. case ASIOSTInt24LSB:
  208717. case ASIOSTInt24MSB:
  208718. byteStride = 3; break;
  208719. case ASIOSTInt32MSB16:
  208720. case ASIOSTInt32LSB16:
  208721. case ASIOSTInt32MSB:
  208722. case ASIOSTInt32MSB18:
  208723. case ASIOSTInt32MSB20:
  208724. case ASIOSTInt32MSB24:
  208725. case ASIOSTInt32LSB:
  208726. case ASIOSTInt32LSB18:
  208727. case ASIOSTInt32LSB20:
  208728. case ASIOSTInt32LSB24:
  208729. case ASIOSTFloat32LSB:
  208730. case ASIOSTFloat32MSB:
  208731. byteStride = 4; break;
  208732. case ASIOSTFloat64MSB:
  208733. case ASIOSTFloat64LSB:
  208734. byteStride = 8; break;
  208735. default:
  208736. break;
  208737. }
  208738. }
  208739. };
  208740. class ASIOAudioIODeviceType : public AudioIODeviceType
  208741. {
  208742. public:
  208743. ASIOAudioIODeviceType()
  208744. : AudioIODeviceType (T("ASIO")),
  208745. classIds (2),
  208746. hasScanned (false)
  208747. {
  208748. CoInitialize (0);
  208749. }
  208750. ~ASIOAudioIODeviceType()
  208751. {
  208752. }
  208753. void scanForDevices()
  208754. {
  208755. hasScanned = true;
  208756. deviceNames.clear();
  208757. classIds.clear();
  208758. HKEY hk = 0;
  208759. int index = 0;
  208760. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  208761. {
  208762. for (;;)
  208763. {
  208764. char name [256];
  208765. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  208766. {
  208767. addDriverInfo (name, hk);
  208768. }
  208769. else
  208770. {
  208771. break;
  208772. }
  208773. }
  208774. RegCloseKey (hk);
  208775. }
  208776. }
  208777. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  208778. {
  208779. jassert (hasScanned); // need to call scanForDevices() before doing this
  208780. return deviceNames;
  208781. }
  208782. int getDefaultDeviceIndex (const bool) const
  208783. {
  208784. jassert (hasScanned); // need to call scanForDevices() before doing this
  208785. for (int i = deviceNames.size(); --i >= 0;)
  208786. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  208787. return i; // asio4all is a safe choice for a default..
  208788. #if JUCE_DEBUG
  208789. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  208790. return 1; // (the digi m-box driver crashes the app when you run
  208791. // it in the debugger, which can be a bit annoying)
  208792. #endif
  208793. return 0;
  208794. }
  208795. static int findFreeSlot()
  208796. {
  208797. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  208798. if (currentASIODev[i] == 0)
  208799. return i;
  208800. jassertfalse; // unfortunately you can only have a finite number
  208801. // of ASIO devices open at the same time..
  208802. return -1;
  208803. }
  208804. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  208805. {
  208806. jassert (hasScanned); // need to call scanForDevices() before doing this
  208807. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  208808. }
  208809. bool hasSeparateInputsAndOutputs() const { return false; }
  208810. AudioIODevice* createDevice (const String& outputDeviceName,
  208811. const String& inputDeviceName)
  208812. {
  208813. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  208814. (void) inputDeviceName;
  208815. jassert (hasScanned); // need to call scanForDevices() before doing this
  208816. const int index = deviceNames.indexOf (outputDeviceName);
  208817. if (index >= 0)
  208818. {
  208819. const int freeSlot = findFreeSlot();
  208820. if (freeSlot >= 0)
  208821. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  208822. }
  208823. return 0;
  208824. }
  208825. juce_UseDebuggingNewOperator
  208826. private:
  208827. StringArray deviceNames;
  208828. OwnedArray <CLSID> classIds;
  208829. bool hasScanned;
  208830. static bool checkClassIsOk (const String& classId)
  208831. {
  208832. HKEY hk = 0;
  208833. bool ok = false;
  208834. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  208835. {
  208836. int index = 0;
  208837. for (;;)
  208838. {
  208839. char buf [512];
  208840. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  208841. {
  208842. if (classId.equalsIgnoreCase (buf))
  208843. {
  208844. HKEY subKey, pathKey;
  208845. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  208846. {
  208847. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  208848. {
  208849. char pathName [600];
  208850. DWORD dtype = REG_SZ;
  208851. DWORD dsize = sizeof (pathName);
  208852. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  208853. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  208854. {
  208855. OFSTRUCT of;
  208856. zerostruct (of);
  208857. of.cBytes = sizeof (of);
  208858. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  208859. }
  208860. RegCloseKey (pathKey);
  208861. }
  208862. RegCloseKey (subKey);
  208863. }
  208864. break;
  208865. }
  208866. }
  208867. else
  208868. {
  208869. break;
  208870. }
  208871. }
  208872. RegCloseKey (hk);
  208873. }
  208874. return ok;
  208875. }
  208876. void addDriverInfo (const String& keyName, HKEY hk)
  208877. {
  208878. HKEY subKey;
  208879. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  208880. {
  208881. char buf [256];
  208882. DWORD dtype = REG_SZ;
  208883. DWORD dsize = sizeof (buf);
  208884. zeromem (buf, dsize);
  208885. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  208886. {
  208887. if (dsize > 0 && checkClassIsOk (buf))
  208888. {
  208889. wchar_t classIdStr [130];
  208890. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  208891. String deviceName;
  208892. CLSID classId;
  208893. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  208894. {
  208895. dtype = REG_SZ;
  208896. dsize = sizeof (buf);
  208897. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  208898. deviceName = buf;
  208899. else
  208900. deviceName = keyName;
  208901. log (T("found ") + deviceName);
  208902. deviceNames.add (deviceName);
  208903. classIds.add (new CLSID (classId));
  208904. }
  208905. }
  208906. RegCloseKey (subKey);
  208907. }
  208908. }
  208909. }
  208910. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  208911. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  208912. };
  208913. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  208914. {
  208915. return new ASIOAudioIODeviceType();
  208916. }
  208917. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  208918. void* guid,
  208919. const String& optionalDllForDirectLoading)
  208920. {
  208921. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  208922. if (freeSlot < 0)
  208923. return 0;
  208924. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  208925. }
  208926. #undef log
  208927. #endif
  208928. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  208929. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  208930. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208931. // compiled on its own).
  208932. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  208933. END_JUCE_NAMESPACE
  208934. extern "C"
  208935. {
  208936. // Declare just the minimum number of interfaces for the DSound objects that we need..
  208937. typedef struct typeDSBUFFERDESC
  208938. {
  208939. DWORD dwSize;
  208940. DWORD dwFlags;
  208941. DWORD dwBufferBytes;
  208942. DWORD dwReserved;
  208943. LPWAVEFORMATEX lpwfxFormat;
  208944. GUID guid3DAlgorithm;
  208945. } DSBUFFERDESC;
  208946. struct IDirectSoundBuffer;
  208947. #undef INTERFACE
  208948. #define INTERFACE IDirectSound
  208949. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  208950. {
  208951. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  208952. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  208953. STDMETHOD_(ULONG,Release) (THIS) PURE;
  208954. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  208955. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  208956. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  208957. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  208958. STDMETHOD(Compact) (THIS) PURE;
  208959. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  208960. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  208961. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  208962. };
  208963. #undef INTERFACE
  208964. #define INTERFACE IDirectSoundBuffer
  208965. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  208966. {
  208967. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  208968. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  208969. STDMETHOD_(ULONG,Release) (THIS) PURE;
  208970. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  208971. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  208972. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  208973. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  208974. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  208975. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  208976. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  208977. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  208978. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  208979. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  208980. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  208981. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  208982. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  208983. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  208984. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  208985. STDMETHOD(Stop) (THIS) PURE;
  208986. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  208987. STDMETHOD(Restore) (THIS) PURE;
  208988. };
  208989. typedef struct typeDSCBUFFERDESC
  208990. {
  208991. DWORD dwSize;
  208992. DWORD dwFlags;
  208993. DWORD dwBufferBytes;
  208994. DWORD dwReserved;
  208995. LPWAVEFORMATEX lpwfxFormat;
  208996. } DSCBUFFERDESC;
  208997. struct IDirectSoundCaptureBuffer;
  208998. #undef INTERFACE
  208999. #define INTERFACE IDirectSoundCapture
  209000. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  209001. {
  209002. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209003. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209004. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209005. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  209006. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209007. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209008. };
  209009. #undef INTERFACE
  209010. #define INTERFACE IDirectSoundCaptureBuffer
  209011. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  209012. {
  209013. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209014. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209015. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209016. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209017. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209018. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209019. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209020. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  209021. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209022. STDMETHOD(Start) (THIS_ DWORD) PURE;
  209023. STDMETHOD(Stop) (THIS) PURE;
  209024. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209025. };
  209026. };
  209027. BEGIN_JUCE_NAMESPACE
  209028. static const String getDSErrorMessage (HRESULT hr)
  209029. {
  209030. const char* result = 0;
  209031. switch (hr)
  209032. {
  209033. case MAKE_HRESULT(1, 0x878, 10):
  209034. result = "Device already allocated";
  209035. break;
  209036. case MAKE_HRESULT(1, 0x878, 30):
  209037. result = "Control unavailable";
  209038. break;
  209039. case E_INVALIDARG:
  209040. result = "Invalid parameter";
  209041. break;
  209042. case MAKE_HRESULT(1, 0x878, 50):
  209043. result = "Invalid call";
  209044. break;
  209045. case E_FAIL:
  209046. result = "Generic error";
  209047. break;
  209048. case MAKE_HRESULT(1, 0x878, 70):
  209049. result = "Priority level error";
  209050. break;
  209051. case E_OUTOFMEMORY:
  209052. result = "Out of memory";
  209053. break;
  209054. case MAKE_HRESULT(1, 0x878, 100):
  209055. result = "Bad format";
  209056. break;
  209057. case E_NOTIMPL:
  209058. result = "Unsupported function";
  209059. break;
  209060. case MAKE_HRESULT(1, 0x878, 120):
  209061. result = "No driver";
  209062. break;
  209063. case MAKE_HRESULT(1, 0x878, 130):
  209064. result = "Already initialised";
  209065. break;
  209066. case CLASS_E_NOAGGREGATION:
  209067. result = "No aggregation";
  209068. break;
  209069. case MAKE_HRESULT(1, 0x878, 150):
  209070. result = "Buffer lost";
  209071. break;
  209072. case MAKE_HRESULT(1, 0x878, 160):
  209073. result = "Another app has priority";
  209074. break;
  209075. case MAKE_HRESULT(1, 0x878, 170):
  209076. result = "Uninitialised";
  209077. break;
  209078. case E_NOINTERFACE:
  209079. result = "No interface";
  209080. break;
  209081. case S_OK:
  209082. result = "No error";
  209083. break;
  209084. default:
  209085. return "Unknown error: " + String ((int) hr);
  209086. }
  209087. return result;
  209088. }
  209089. #define DS_DEBUGGING 1
  209090. #ifdef DS_DEBUGGING
  209091. #define CATCH JUCE_CATCH_EXCEPTION
  209092. #undef log
  209093. #define log(a) Logger::writeToLog(a);
  209094. #undef logError
  209095. #define logError(a) logDSError(a, __LINE__);
  209096. static void logDSError (HRESULT hr, int lineNum)
  209097. {
  209098. if (hr != S_OK)
  209099. {
  209100. String error ("DS error at line ");
  209101. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  209102. log (error);
  209103. }
  209104. }
  209105. #else
  209106. #define CATCH JUCE_CATCH_ALL
  209107. #define log(a)
  209108. #define logError(a)
  209109. #endif
  209110. #define DSOUND_FUNCTION(functionName, params) \
  209111. typedef HRESULT (WINAPI *type##functionName) params; \
  209112. static type##functionName ds##functionName = 0;
  209113. #define DSOUND_FUNCTION_LOAD(functionName) \
  209114. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  209115. jassert (ds##functionName != 0);
  209116. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  209117. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  209118. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  209119. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  209120. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209121. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209122. static void initialiseDSoundFunctions()
  209123. {
  209124. if (dsDirectSoundCreate == 0)
  209125. {
  209126. HMODULE h = LoadLibraryA ("dsound.dll");
  209127. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  209128. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  209129. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  209130. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  209131. }
  209132. }
  209133. class DSoundInternalOutChannel
  209134. {
  209135. String name;
  209136. LPGUID guid;
  209137. int sampleRate, bufferSizeSamples;
  209138. float* leftBuffer;
  209139. float* rightBuffer;
  209140. IDirectSound* pDirectSound;
  209141. IDirectSoundBuffer* pOutputBuffer;
  209142. DWORD writeOffset;
  209143. int totalBytesPerBuffer;
  209144. int bytesPerBuffer;
  209145. unsigned int lastPlayCursor;
  209146. public:
  209147. int bitDepth;
  209148. bool doneFlag;
  209149. DSoundInternalOutChannel (const String& name_,
  209150. LPGUID guid_,
  209151. int rate,
  209152. int bufferSize,
  209153. float* left,
  209154. float* right)
  209155. : name (name_),
  209156. guid (guid_),
  209157. sampleRate (rate),
  209158. bufferSizeSamples (bufferSize),
  209159. leftBuffer (left),
  209160. rightBuffer (right),
  209161. pDirectSound (0),
  209162. pOutputBuffer (0),
  209163. bitDepth (16)
  209164. {
  209165. }
  209166. ~DSoundInternalOutChannel()
  209167. {
  209168. close();
  209169. }
  209170. void close()
  209171. {
  209172. HRESULT hr;
  209173. if (pOutputBuffer != 0)
  209174. {
  209175. JUCE_TRY
  209176. {
  209177. log (T("closing dsound out: ") + name);
  209178. hr = pOutputBuffer->Stop();
  209179. logError (hr);
  209180. }
  209181. CATCH
  209182. JUCE_TRY
  209183. {
  209184. hr = pOutputBuffer->Release();
  209185. logError (hr);
  209186. }
  209187. CATCH
  209188. pOutputBuffer = 0;
  209189. }
  209190. if (pDirectSound != 0)
  209191. {
  209192. JUCE_TRY
  209193. {
  209194. hr = pDirectSound->Release();
  209195. logError (hr);
  209196. }
  209197. CATCH
  209198. pDirectSound = 0;
  209199. }
  209200. }
  209201. const String open()
  209202. {
  209203. log (T("opening dsound out device: ") + name
  209204. + T(" rate=") + String (sampleRate)
  209205. + T(" bits=") + String (bitDepth)
  209206. + T(" buf=") + String (bufferSizeSamples));
  209207. pDirectSound = 0;
  209208. pOutputBuffer = 0;
  209209. writeOffset = 0;
  209210. String error;
  209211. HRESULT hr = E_NOINTERFACE;
  209212. if (dsDirectSoundCreate != 0)
  209213. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  209214. if (hr == S_OK)
  209215. {
  209216. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  209217. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  209218. const int numChannels = 2;
  209219. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  209220. logError (hr);
  209221. if (hr == S_OK)
  209222. {
  209223. IDirectSoundBuffer* pPrimaryBuffer;
  209224. DSBUFFERDESC primaryDesc;
  209225. zerostruct (primaryDesc);
  209226. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209227. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  209228. primaryDesc.dwBufferBytes = 0;
  209229. primaryDesc.lpwfxFormat = 0;
  209230. log ("opening dsound out step 2");
  209231. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  209232. logError (hr);
  209233. if (hr == S_OK)
  209234. {
  209235. WAVEFORMATEX wfFormat;
  209236. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  209237. wfFormat.nChannels = (unsigned short) numChannels;
  209238. wfFormat.nSamplesPerSec = sampleRate;
  209239. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  209240. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  209241. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  209242. wfFormat.cbSize = 0;
  209243. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  209244. logError (hr);
  209245. if (hr == S_OK)
  209246. {
  209247. DSBUFFERDESC secondaryDesc;
  209248. zerostruct (secondaryDesc);
  209249. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209250. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  209251. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  209252. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  209253. secondaryDesc.lpwfxFormat = &wfFormat;
  209254. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  209255. logError (hr);
  209256. if (hr == S_OK)
  209257. {
  209258. log ("opening dsound out step 3");
  209259. DWORD dwDataLen;
  209260. unsigned char* pDSBuffData;
  209261. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  209262. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  209263. logError (hr);
  209264. if (hr == S_OK)
  209265. {
  209266. zeromem (pDSBuffData, dwDataLen);
  209267. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  209268. if (hr == S_OK)
  209269. {
  209270. hr = pOutputBuffer->SetCurrentPosition (0);
  209271. if (hr == S_OK)
  209272. {
  209273. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  209274. if (hr == S_OK)
  209275. return String::empty;
  209276. }
  209277. }
  209278. }
  209279. }
  209280. }
  209281. }
  209282. }
  209283. }
  209284. error = getDSErrorMessage (hr);
  209285. close();
  209286. return error;
  209287. }
  209288. void synchronisePosition()
  209289. {
  209290. if (pOutputBuffer != 0)
  209291. {
  209292. DWORD playCursor;
  209293. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  209294. }
  209295. }
  209296. bool service()
  209297. {
  209298. if (pOutputBuffer == 0)
  209299. return true;
  209300. DWORD playCursor, writeCursor;
  209301. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  209302. if (hr != S_OK)
  209303. {
  209304. logError (hr);
  209305. jassertfalse
  209306. return true;
  209307. }
  209308. int playWriteGap = writeCursor - playCursor;
  209309. if (playWriteGap < 0)
  209310. playWriteGap += totalBytesPerBuffer;
  209311. int bytesEmpty = playCursor - writeOffset;
  209312. if (bytesEmpty < 0)
  209313. bytesEmpty += totalBytesPerBuffer;
  209314. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  209315. {
  209316. writeOffset = writeCursor;
  209317. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  209318. }
  209319. if (bytesEmpty >= bytesPerBuffer)
  209320. {
  209321. LPBYTE lpbuf1 = 0;
  209322. LPBYTE lpbuf2 = 0;
  209323. DWORD dwSize1 = 0;
  209324. DWORD dwSize2 = 0;
  209325. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  209326. bytesPerBuffer,
  209327. (void**) &lpbuf1, &dwSize1,
  209328. (void**) &lpbuf2, &dwSize2, 0);
  209329. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  209330. {
  209331. pOutputBuffer->Restore();
  209332. hr = pOutputBuffer->Lock (writeOffset,
  209333. bytesPerBuffer,
  209334. (void**) &lpbuf1, &dwSize1,
  209335. (void**) &lpbuf2, &dwSize2, 0);
  209336. }
  209337. if (hr == S_OK)
  209338. {
  209339. if (bitDepth == 16)
  209340. {
  209341. const float gainL = 32767.0f;
  209342. const float gainR = 32767.0f;
  209343. int* dest = (int*)lpbuf1;
  209344. const float* left = leftBuffer;
  209345. const float* right = rightBuffer;
  209346. int samples1 = dwSize1 >> 2;
  209347. int samples2 = dwSize2 >> 2;
  209348. if (left == 0)
  209349. {
  209350. while (--samples1 >= 0)
  209351. {
  209352. int r = roundFloatToInt (gainR * *right++);
  209353. if (r < -32768)
  209354. r = -32768;
  209355. else if (r > 32767)
  209356. r = 32767;
  209357. *dest++ = (r << 16);
  209358. }
  209359. dest = (int*)lpbuf2;
  209360. while (--samples2 >= 0)
  209361. {
  209362. int r = roundFloatToInt (gainR * *right++);
  209363. if (r < -32768)
  209364. r = -32768;
  209365. else if (r > 32767)
  209366. r = 32767;
  209367. *dest++ = (r << 16);
  209368. }
  209369. }
  209370. else if (right == 0)
  209371. {
  209372. while (--samples1 >= 0)
  209373. {
  209374. int l = roundFloatToInt (gainL * *left++);
  209375. if (l < -32768)
  209376. l = -32768;
  209377. else if (l > 32767)
  209378. l = 32767;
  209379. l &= 0xffff;
  209380. *dest++ = l;
  209381. }
  209382. dest = (int*)lpbuf2;
  209383. while (--samples2 >= 0)
  209384. {
  209385. int l = roundFloatToInt (gainL * *left++);
  209386. if (l < -32768)
  209387. l = -32768;
  209388. else if (l > 32767)
  209389. l = 32767;
  209390. l &= 0xffff;
  209391. *dest++ = l;
  209392. }
  209393. }
  209394. else
  209395. {
  209396. while (--samples1 >= 0)
  209397. {
  209398. int l = roundFloatToInt (gainL * *left++);
  209399. if (l < -32768)
  209400. l = -32768;
  209401. else if (l > 32767)
  209402. l = 32767;
  209403. l &= 0xffff;
  209404. int r = roundFloatToInt (gainR * *right++);
  209405. if (r < -32768)
  209406. r = -32768;
  209407. else if (r > 32767)
  209408. r = 32767;
  209409. *dest++ = (r << 16) | l;
  209410. }
  209411. dest = (int*)lpbuf2;
  209412. while (--samples2 >= 0)
  209413. {
  209414. int l = roundFloatToInt (gainL * *left++);
  209415. if (l < -32768)
  209416. l = -32768;
  209417. else if (l > 32767)
  209418. l = 32767;
  209419. l &= 0xffff;
  209420. int r = roundFloatToInt (gainR * *right++);
  209421. if (r < -32768)
  209422. r = -32768;
  209423. else if (r > 32767)
  209424. r = 32767;
  209425. *dest++ = (r << 16) | l;
  209426. }
  209427. }
  209428. }
  209429. else
  209430. {
  209431. jassertfalse
  209432. }
  209433. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  209434. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  209435. }
  209436. else
  209437. {
  209438. jassertfalse
  209439. logError (hr);
  209440. }
  209441. bytesEmpty -= bytesPerBuffer;
  209442. return true;
  209443. }
  209444. else
  209445. {
  209446. return false;
  209447. }
  209448. }
  209449. };
  209450. struct DSoundInternalInChannel
  209451. {
  209452. String name;
  209453. LPGUID guid;
  209454. int sampleRate, bufferSizeSamples;
  209455. float* leftBuffer;
  209456. float* rightBuffer;
  209457. IDirectSound* pDirectSound;
  209458. IDirectSoundCapture* pDirectSoundCapture;
  209459. IDirectSoundCaptureBuffer* pInputBuffer;
  209460. public:
  209461. unsigned int readOffset;
  209462. int bytesPerBuffer, totalBytesPerBuffer;
  209463. int bitDepth;
  209464. bool doneFlag;
  209465. DSoundInternalInChannel (const String& name_,
  209466. LPGUID guid_,
  209467. int rate,
  209468. int bufferSize,
  209469. float* left,
  209470. float* right)
  209471. : name (name_),
  209472. guid (guid_),
  209473. sampleRate (rate),
  209474. bufferSizeSamples (bufferSize),
  209475. leftBuffer (left),
  209476. rightBuffer (right),
  209477. pDirectSound (0),
  209478. pDirectSoundCapture (0),
  209479. pInputBuffer (0),
  209480. bitDepth (16)
  209481. {
  209482. }
  209483. ~DSoundInternalInChannel()
  209484. {
  209485. close();
  209486. }
  209487. void close()
  209488. {
  209489. HRESULT hr;
  209490. if (pInputBuffer != 0)
  209491. {
  209492. JUCE_TRY
  209493. {
  209494. log (T("closing dsound in: ") + name);
  209495. hr = pInputBuffer->Stop();
  209496. logError (hr);
  209497. }
  209498. CATCH
  209499. JUCE_TRY
  209500. {
  209501. hr = pInputBuffer->Release();
  209502. logError (hr);
  209503. }
  209504. CATCH
  209505. pInputBuffer = 0;
  209506. }
  209507. if (pDirectSoundCapture != 0)
  209508. {
  209509. JUCE_TRY
  209510. {
  209511. hr = pDirectSoundCapture->Release();
  209512. logError (hr);
  209513. }
  209514. CATCH
  209515. pDirectSoundCapture = 0;
  209516. }
  209517. if (pDirectSound != 0)
  209518. {
  209519. JUCE_TRY
  209520. {
  209521. hr = pDirectSound->Release();
  209522. logError (hr);
  209523. }
  209524. CATCH
  209525. pDirectSound = 0;
  209526. }
  209527. }
  209528. const String open()
  209529. {
  209530. log (T("opening dsound in device: ") + name
  209531. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  209532. pDirectSound = 0;
  209533. pDirectSoundCapture = 0;
  209534. pInputBuffer = 0;
  209535. readOffset = 0;
  209536. totalBytesPerBuffer = 0;
  209537. String error;
  209538. HRESULT hr = E_NOINTERFACE;
  209539. if (dsDirectSoundCaptureCreate != 0)
  209540. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  209541. logError (hr);
  209542. if (hr == S_OK)
  209543. {
  209544. const int numChannels = 2;
  209545. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  209546. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  209547. WAVEFORMATEX wfFormat;
  209548. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  209549. wfFormat.nChannels = (unsigned short)numChannels;
  209550. wfFormat.nSamplesPerSec = sampleRate;
  209551. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  209552. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  209553. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  209554. wfFormat.cbSize = 0;
  209555. DSCBUFFERDESC captureDesc;
  209556. zerostruct (captureDesc);
  209557. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  209558. captureDesc.dwFlags = 0;
  209559. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  209560. captureDesc.lpwfxFormat = &wfFormat;
  209561. log (T("opening dsound in step 2"));
  209562. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  209563. logError (hr);
  209564. if (hr == S_OK)
  209565. {
  209566. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  209567. logError (hr);
  209568. if (hr == S_OK)
  209569. return String::empty;
  209570. }
  209571. }
  209572. error = getDSErrorMessage (hr);
  209573. close();
  209574. return error;
  209575. }
  209576. void synchronisePosition()
  209577. {
  209578. if (pInputBuffer != 0)
  209579. {
  209580. DWORD capturePos;
  209581. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  209582. }
  209583. }
  209584. bool service()
  209585. {
  209586. if (pInputBuffer == 0)
  209587. return true;
  209588. DWORD capturePos, readPos;
  209589. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  209590. logError (hr);
  209591. if (hr != S_OK)
  209592. return true;
  209593. int bytesFilled = readPos - readOffset;
  209594. if (bytesFilled < 0)
  209595. bytesFilled += totalBytesPerBuffer;
  209596. if (bytesFilled >= bytesPerBuffer)
  209597. {
  209598. LPBYTE lpbuf1 = 0;
  209599. LPBYTE lpbuf2 = 0;
  209600. DWORD dwsize1 = 0;
  209601. DWORD dwsize2 = 0;
  209602. HRESULT hr = pInputBuffer->Lock (readOffset,
  209603. bytesPerBuffer,
  209604. (void**) &lpbuf1, &dwsize1,
  209605. (void**) &lpbuf2, &dwsize2, 0);
  209606. if (hr == S_OK)
  209607. {
  209608. if (bitDepth == 16)
  209609. {
  209610. const float g = 1.0f / 32768.0f;
  209611. float* destL = leftBuffer;
  209612. float* destR = rightBuffer;
  209613. int samples1 = dwsize1 >> 2;
  209614. int samples2 = dwsize2 >> 2;
  209615. const short* src = (const short*)lpbuf1;
  209616. if (destL == 0)
  209617. {
  209618. while (--samples1 >= 0)
  209619. {
  209620. ++src;
  209621. *destR++ = *src++ * g;
  209622. }
  209623. src = (const short*)lpbuf2;
  209624. while (--samples2 >= 0)
  209625. {
  209626. ++src;
  209627. *destR++ = *src++ * g;
  209628. }
  209629. }
  209630. else if (destR == 0)
  209631. {
  209632. while (--samples1 >= 0)
  209633. {
  209634. *destL++ = *src++ * g;
  209635. ++src;
  209636. }
  209637. src = (const short*)lpbuf2;
  209638. while (--samples2 >= 0)
  209639. {
  209640. *destL++ = *src++ * g;
  209641. ++src;
  209642. }
  209643. }
  209644. else
  209645. {
  209646. while (--samples1 >= 0)
  209647. {
  209648. *destL++ = *src++ * g;
  209649. *destR++ = *src++ * g;
  209650. }
  209651. src = (const short*)lpbuf2;
  209652. while (--samples2 >= 0)
  209653. {
  209654. *destL++ = *src++ * g;
  209655. *destR++ = *src++ * g;
  209656. }
  209657. }
  209658. }
  209659. else
  209660. {
  209661. jassertfalse
  209662. }
  209663. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  209664. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  209665. }
  209666. else
  209667. {
  209668. logError (hr);
  209669. jassertfalse
  209670. }
  209671. bytesFilled -= bytesPerBuffer;
  209672. return true;
  209673. }
  209674. else
  209675. {
  209676. return false;
  209677. }
  209678. }
  209679. };
  209680. class DSoundAudioIODevice : public AudioIODevice,
  209681. public Thread
  209682. {
  209683. public:
  209684. DSoundAudioIODevice (const String& deviceName,
  209685. const int outputDeviceIndex_,
  209686. const int inputDeviceIndex_)
  209687. : AudioIODevice (deviceName, "DirectSound"),
  209688. Thread ("Juce DSound"),
  209689. isOpen_ (false),
  209690. isStarted (false),
  209691. outputDeviceIndex (outputDeviceIndex_),
  209692. inputDeviceIndex (inputDeviceIndex_),
  209693. inChans (4),
  209694. outChans (4),
  209695. numInputBuffers (0),
  209696. numOutputBuffers (0),
  209697. totalSamplesOut (0),
  209698. sampleRate (0.0),
  209699. inputBuffers (0),
  209700. outputBuffers (0),
  209701. callback (0),
  209702. bufferSizeSamples (0)
  209703. {
  209704. if (outputDeviceIndex_ >= 0)
  209705. {
  209706. outChannels.add (TRANS("Left"));
  209707. outChannels.add (TRANS("Right"));
  209708. }
  209709. if (inputDeviceIndex_ >= 0)
  209710. {
  209711. inChannels.add (TRANS("Left"));
  209712. inChannels.add (TRANS("Right"));
  209713. }
  209714. }
  209715. ~DSoundAudioIODevice()
  209716. {
  209717. close();
  209718. }
  209719. const StringArray getOutputChannelNames()
  209720. {
  209721. return outChannels;
  209722. }
  209723. const StringArray getInputChannelNames()
  209724. {
  209725. return inChannels;
  209726. }
  209727. int getNumSampleRates()
  209728. {
  209729. return 4;
  209730. }
  209731. double getSampleRate (int index)
  209732. {
  209733. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  209734. return samps [jlimit (0, 3, index)];
  209735. }
  209736. int getNumBufferSizesAvailable()
  209737. {
  209738. return 50;
  209739. }
  209740. int getBufferSizeSamples (int index)
  209741. {
  209742. int n = 64;
  209743. for (int i = 0; i < index; ++i)
  209744. n += (n < 512) ? 32
  209745. : ((n < 1024) ? 64
  209746. : ((n < 2048) ? 128 : 256));
  209747. return n;
  209748. }
  209749. int getDefaultBufferSize()
  209750. {
  209751. return 2560;
  209752. }
  209753. const String open (const BitArray& inputChannels,
  209754. const BitArray& outputChannels,
  209755. double sampleRate,
  209756. int bufferSizeSamples)
  209757. {
  209758. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  209759. isOpen_ = lastError.isEmpty();
  209760. return lastError;
  209761. }
  209762. void close()
  209763. {
  209764. stop();
  209765. if (isOpen_)
  209766. {
  209767. closeDevice();
  209768. isOpen_ = false;
  209769. }
  209770. }
  209771. bool isOpen()
  209772. {
  209773. return isOpen_ && isThreadRunning();
  209774. }
  209775. int getCurrentBufferSizeSamples()
  209776. {
  209777. return bufferSizeSamples;
  209778. }
  209779. double getCurrentSampleRate()
  209780. {
  209781. return sampleRate;
  209782. }
  209783. int getCurrentBitDepth()
  209784. {
  209785. int i, bits = 256;
  209786. for (i = inChans.size(); --i >= 0;)
  209787. bits = jmin (bits, inChans[i]->bitDepth);
  209788. for (i = outChans.size(); --i >= 0;)
  209789. bits = jmin (bits, outChans[i]->bitDepth);
  209790. if (bits > 32)
  209791. bits = 16;
  209792. return bits;
  209793. }
  209794. const BitArray getActiveOutputChannels() const
  209795. {
  209796. return enabledOutputs;
  209797. }
  209798. const BitArray getActiveInputChannels() const
  209799. {
  209800. return enabledInputs;
  209801. }
  209802. int getOutputLatencyInSamples()
  209803. {
  209804. return (int) (getCurrentBufferSizeSamples() * 1.5);
  209805. }
  209806. int getInputLatencyInSamples()
  209807. {
  209808. return getOutputLatencyInSamples();
  209809. }
  209810. void start (AudioIODeviceCallback* call)
  209811. {
  209812. if (isOpen_ && call != 0 && ! isStarted)
  209813. {
  209814. if (! isThreadRunning())
  209815. {
  209816. // something gone wrong and the thread's stopped..
  209817. isOpen_ = false;
  209818. return;
  209819. }
  209820. call->audioDeviceAboutToStart (this);
  209821. const ScopedLock sl (startStopLock);
  209822. callback = call;
  209823. isStarted = true;
  209824. }
  209825. }
  209826. void stop()
  209827. {
  209828. if (isStarted)
  209829. {
  209830. AudioIODeviceCallback* const callbackLocal = callback;
  209831. {
  209832. const ScopedLock sl (startStopLock);
  209833. isStarted = false;
  209834. }
  209835. if (callbackLocal != 0)
  209836. callbackLocal->audioDeviceStopped();
  209837. }
  209838. }
  209839. bool isPlaying()
  209840. {
  209841. return isStarted && isOpen_ && isThreadRunning();
  209842. }
  209843. const String getLastError()
  209844. {
  209845. return lastError;
  209846. }
  209847. juce_UseDebuggingNewOperator
  209848. StringArray inChannels, outChannels;
  209849. int outputDeviceIndex, inputDeviceIndex;
  209850. private:
  209851. bool isOpen_;
  209852. bool isStarted;
  209853. String lastError;
  209854. OwnedArray <DSoundInternalInChannel> inChans;
  209855. OwnedArray <DSoundInternalOutChannel> outChans;
  209856. WaitableEvent startEvent;
  209857. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  209858. int volatile totalSamplesOut;
  209859. int64 volatile lastBlockTime;
  209860. double sampleRate;
  209861. BitArray enabledInputs, enabledOutputs;
  209862. float** inputBuffers;
  209863. float** outputBuffers;
  209864. AudioIODeviceCallback* callback;
  209865. CriticalSection startStopLock;
  209866. DSoundAudioIODevice (const DSoundAudioIODevice&);
  209867. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  209868. const String openDevice (const BitArray& inputChannels,
  209869. const BitArray& outputChannels,
  209870. double sampleRate_,
  209871. int bufferSizeSamples_);
  209872. void closeDevice()
  209873. {
  209874. isStarted = false;
  209875. stopThread (5000);
  209876. inChans.clear();
  209877. outChans.clear();
  209878. int i;
  209879. for (i = 0; i < numInputBuffers; ++i)
  209880. juce_free (inputBuffers[i]);
  209881. delete[] inputBuffers;
  209882. inputBuffers = 0;
  209883. numInputBuffers = 0;
  209884. for (i = 0; i < numOutputBuffers; ++i)
  209885. juce_free (outputBuffers[i]);
  209886. delete[] outputBuffers;
  209887. outputBuffers = 0;
  209888. numOutputBuffers = 0;
  209889. }
  209890. void resync()
  209891. {
  209892. if (! threadShouldExit())
  209893. {
  209894. sleep (5);
  209895. int i;
  209896. for (i = 0; i < outChans.size(); ++i)
  209897. outChans.getUnchecked(i)->synchronisePosition();
  209898. for (i = 0; i < inChans.size(); ++i)
  209899. inChans.getUnchecked(i)->synchronisePosition();
  209900. }
  209901. }
  209902. public:
  209903. void run()
  209904. {
  209905. while (! threadShouldExit())
  209906. {
  209907. if (wait (100))
  209908. break;
  209909. }
  209910. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  209911. const int maxTimeMS = jmax (5, 3 * latencyMs);
  209912. while (! threadShouldExit())
  209913. {
  209914. int numToDo = 0;
  209915. uint32 startTime = Time::getMillisecondCounter();
  209916. int i;
  209917. for (i = inChans.size(); --i >= 0;)
  209918. {
  209919. inChans.getUnchecked(i)->doneFlag = false;
  209920. ++numToDo;
  209921. }
  209922. for (i = outChans.size(); --i >= 0;)
  209923. {
  209924. outChans.getUnchecked(i)->doneFlag = false;
  209925. ++numToDo;
  209926. }
  209927. if (numToDo > 0)
  209928. {
  209929. const int maxCount = 3;
  209930. int count = maxCount;
  209931. for (;;)
  209932. {
  209933. for (i = inChans.size(); --i >= 0;)
  209934. {
  209935. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  209936. if ((! in->doneFlag) && in->service())
  209937. {
  209938. in->doneFlag = true;
  209939. --numToDo;
  209940. }
  209941. }
  209942. for (i = outChans.size(); --i >= 0;)
  209943. {
  209944. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  209945. if ((! out->doneFlag) && out->service())
  209946. {
  209947. out->doneFlag = true;
  209948. --numToDo;
  209949. }
  209950. }
  209951. if (numToDo <= 0)
  209952. break;
  209953. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  209954. {
  209955. resync();
  209956. break;
  209957. }
  209958. if (--count <= 0)
  209959. {
  209960. Sleep (1);
  209961. count = maxCount;
  209962. }
  209963. if (threadShouldExit())
  209964. return;
  209965. }
  209966. }
  209967. else
  209968. {
  209969. sleep (1);
  209970. }
  209971. const ScopedLock sl (startStopLock);
  209972. if (isStarted)
  209973. {
  209974. JUCE_TRY
  209975. {
  209976. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  209977. numInputBuffers,
  209978. outputBuffers,
  209979. numOutputBuffers,
  209980. bufferSizeSamples);
  209981. }
  209982. JUCE_CATCH_EXCEPTION
  209983. totalSamplesOut += bufferSizeSamples;
  209984. }
  209985. else
  209986. {
  209987. for (i = 0; i < numOutputBuffers; ++i)
  209988. if (outputBuffers[i] != 0)
  209989. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  209990. totalSamplesOut = 0;
  209991. sleep (1);
  209992. }
  209993. }
  209994. }
  209995. };
  209996. class DSoundAudioIODeviceType : public AudioIODeviceType
  209997. {
  209998. public:
  209999. DSoundAudioIODeviceType()
  210000. : AudioIODeviceType (T("DirectSound")),
  210001. hasScanned (false)
  210002. {
  210003. initialiseDSoundFunctions();
  210004. }
  210005. ~DSoundAudioIODeviceType()
  210006. {
  210007. }
  210008. void scanForDevices()
  210009. {
  210010. hasScanned = true;
  210011. outputDeviceNames.clear();
  210012. outputGuids.clear();
  210013. inputDeviceNames.clear();
  210014. inputGuids.clear();
  210015. if (dsDirectSoundEnumerateW != 0)
  210016. {
  210017. dsDirectSoundEnumerateW (outputEnumProcW, this);
  210018. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  210019. }
  210020. }
  210021. const StringArray getDeviceNames (const bool wantInputNames) const
  210022. {
  210023. jassert (hasScanned); // need to call scanForDevices() before doing this
  210024. return wantInputNames ? inputDeviceNames
  210025. : outputDeviceNames;
  210026. }
  210027. int getDefaultDeviceIndex (const bool /*forInput*/) const
  210028. {
  210029. jassert (hasScanned); // need to call scanForDevices() before doing this
  210030. return 0;
  210031. }
  210032. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  210033. {
  210034. jassert (hasScanned); // need to call scanForDevices() before doing this
  210035. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  210036. if (d == 0)
  210037. return -1;
  210038. return asInput ? d->inputDeviceIndex
  210039. : d->outputDeviceIndex;
  210040. }
  210041. bool hasSeparateInputsAndOutputs() const { return true; }
  210042. AudioIODevice* createDevice (const String& outputDeviceName,
  210043. const String& inputDeviceName)
  210044. {
  210045. jassert (hasScanned); // need to call scanForDevices() before doing this
  210046. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  210047. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  210048. if (outputIndex >= 0 || inputIndex >= 0)
  210049. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  210050. : inputDeviceName,
  210051. outputIndex, inputIndex);
  210052. return 0;
  210053. }
  210054. juce_UseDebuggingNewOperator
  210055. StringArray outputDeviceNames;
  210056. OwnedArray <GUID> outputGuids;
  210057. StringArray inputDeviceNames;
  210058. OwnedArray <GUID> inputGuids;
  210059. private:
  210060. bool hasScanned;
  210061. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  210062. {
  210063. desc = desc.trim();
  210064. if (desc.isNotEmpty())
  210065. {
  210066. const String origDesc (desc);
  210067. int n = 2;
  210068. while (outputDeviceNames.contains (desc))
  210069. desc = origDesc + T(" (") + String (n++) + T(")");
  210070. outputDeviceNames.add (desc);
  210071. if (lpGUID != 0)
  210072. outputGuids.add (new GUID (*lpGUID));
  210073. else
  210074. outputGuids.add (0);
  210075. }
  210076. return TRUE;
  210077. }
  210078. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210079. {
  210080. return ((DSoundAudioIODeviceType*) object)
  210081. ->outputEnumProc (lpGUID, String (description));
  210082. }
  210083. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210084. {
  210085. return ((DSoundAudioIODeviceType*) object)
  210086. ->outputEnumProc (lpGUID, String (description));
  210087. }
  210088. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  210089. {
  210090. desc = desc.trim();
  210091. if (desc.isNotEmpty())
  210092. {
  210093. const String origDesc (desc);
  210094. int n = 2;
  210095. while (inputDeviceNames.contains (desc))
  210096. desc = origDesc + T(" (") + String (n++) + T(")");
  210097. inputDeviceNames.add (desc);
  210098. if (lpGUID != 0)
  210099. inputGuids.add (new GUID (*lpGUID));
  210100. else
  210101. inputGuids.add (0);
  210102. }
  210103. return TRUE;
  210104. }
  210105. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210106. {
  210107. return ((DSoundAudioIODeviceType*) object)
  210108. ->inputEnumProc (lpGUID, String (description));
  210109. }
  210110. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210111. {
  210112. return ((DSoundAudioIODeviceType*) object)
  210113. ->inputEnumProc (lpGUID, String (description));
  210114. }
  210115. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  210116. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  210117. };
  210118. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  210119. const BitArray& outputChannels,
  210120. double sampleRate_,
  210121. int bufferSizeSamples_)
  210122. {
  210123. closeDevice();
  210124. totalSamplesOut = 0;
  210125. sampleRate = sampleRate_;
  210126. if (bufferSizeSamples_ <= 0)
  210127. bufferSizeSamples_ = 960; // use as a default size if none is set.
  210128. bufferSizeSamples = bufferSizeSamples_ & ~7;
  210129. DSoundAudioIODeviceType dlh;
  210130. dlh.scanForDevices();
  210131. enabledInputs = inputChannels;
  210132. enabledInputs.setRange (inChannels.size(),
  210133. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  210134. false);
  210135. numInputBuffers = enabledInputs.countNumberOfSetBits();
  210136. inputBuffers = new float* [numInputBuffers + 2];
  210137. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  210138. int i, numIns = 0;
  210139. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  210140. {
  210141. float* left = 0;
  210142. float* right = 0;
  210143. if (enabledInputs[i])
  210144. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210145. if (enabledInputs[i + 1])
  210146. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210147. if (left != 0 || right != 0)
  210148. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  210149. dlh.inputGuids [inputDeviceIndex],
  210150. (int) sampleRate, bufferSizeSamples,
  210151. left, right));
  210152. }
  210153. enabledOutputs = outputChannels;
  210154. enabledOutputs.setRange (outChannels.size(),
  210155. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  210156. false);
  210157. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  210158. outputBuffers = new float* [numOutputBuffers + 2];
  210159. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  210160. int numOuts = 0;
  210161. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  210162. {
  210163. float* left = 0;
  210164. float* right = 0;
  210165. if (enabledOutputs[i])
  210166. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210167. if (enabledOutputs[i + 1])
  210168. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210169. if (left != 0 || right != 0)
  210170. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  210171. dlh.outputGuids [outputDeviceIndex],
  210172. (int) sampleRate, bufferSizeSamples,
  210173. left, right));
  210174. }
  210175. String error;
  210176. // boost our priority while opening the devices to try to get better sync between them
  210177. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  210178. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  210179. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  210180. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  210181. for (i = 0; i < outChans.size(); ++i)
  210182. {
  210183. error = outChans[i]->open();
  210184. if (error.isNotEmpty())
  210185. {
  210186. error = T("Error opening ") + dlh.outputDeviceNames[i]
  210187. + T(": \"") + error + T("\"");
  210188. break;
  210189. }
  210190. }
  210191. if (error.isEmpty())
  210192. {
  210193. for (i = 0; i < inChans.size(); ++i)
  210194. {
  210195. error = inChans[i]->open();
  210196. if (error.isNotEmpty())
  210197. {
  210198. error = T("Error opening ") + dlh.inputDeviceNames[i]
  210199. + T(": \"") + error + T("\"");
  210200. break;
  210201. }
  210202. }
  210203. }
  210204. if (error.isEmpty())
  210205. {
  210206. totalSamplesOut = 0;
  210207. for (i = 0; i < outChans.size(); ++i)
  210208. outChans.getUnchecked(i)->synchronisePosition();
  210209. for (i = 0; i < inChans.size(); ++i)
  210210. inChans.getUnchecked(i)->synchronisePosition();
  210211. startThread (9);
  210212. sleep (10);
  210213. notify();
  210214. }
  210215. else
  210216. {
  210217. log (error);
  210218. }
  210219. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  210220. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  210221. return error;
  210222. }
  210223. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  210224. {
  210225. return new DSoundAudioIODeviceType();
  210226. }
  210227. #undef log
  210228. #endif
  210229. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  210230. /********* Start of inlined file: juce_win32_WASAPI.cpp *********/
  210231. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210232. // compiled on its own).
  210233. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  210234. #if 1
  210235. const String getAudioErrorDesc (HRESULT hr)
  210236. {
  210237. const char* e = 0;
  210238. switch (hr)
  210239. {
  210240. case E_POINTER: e = "E_POINTER"; break;
  210241. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  210242. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  210243. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  210244. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  210245. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  210246. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  210247. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  210248. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  210249. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  210250. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  210251. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  210252. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  210253. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  210254. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  210255. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  210256. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  210257. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  210258. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  210259. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  210260. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  210261. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  210262. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  210263. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  210264. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  210265. default: return String::toHexString ((int) hr);
  210266. }
  210267. return e;
  210268. }
  210269. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  210270. #define OK(a) wasapi_checkResult(a)
  210271. static bool wasapi_checkResult (HRESULT hr)
  210272. {
  210273. logFailure (hr);
  210274. return SUCCEEDED (hr);
  210275. }
  210276. #else
  210277. #define logFailure(hr) {}
  210278. #define OK(a) SUCCEEDED(a)
  210279. #endif
  210280. static const String wasapi_getDeviceID (IMMDevice* const device)
  210281. {
  210282. String s;
  210283. WCHAR* deviceId = 0;
  210284. if (OK (device->GetId (&deviceId)))
  210285. {
  210286. s = String (deviceId);
  210287. CoTaskMemFree (deviceId);
  210288. }
  210289. return s;
  210290. }
  210291. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  210292. {
  210293. EDataFlow flow = eRender;
  210294. ComSmartPtr <IMMEndpoint> endPoint;
  210295. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  210296. (void) OK (endPoint->GetDataFlow (&flow));
  210297. return flow;
  210298. }
  210299. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  210300. {
  210301. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  210302. }
  210303. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  210304. {
  210305. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  210306. : sizeof (WAVEFORMATEX));
  210307. }
  210308. class WASAPIDeviceBase
  210309. {
  210310. public:
  210311. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_)
  210312. : device (device_),
  210313. sampleRate (0),
  210314. numChannels (0),
  210315. actualNumChannels (0),
  210316. defaultSampleRate (0),
  210317. minBufferSize (0),
  210318. defaultBufferSize (0),
  210319. latencySamples (0)
  210320. {
  210321. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  210322. ComSmartPtr <IAudioClient> tempClient (createClient());
  210323. if (tempClient == 0)
  210324. return;
  210325. REFERENCE_TIME defaultPeriod, minPeriod;
  210326. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  210327. return;
  210328. WAVEFORMATEX* mixFormat = 0;
  210329. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  210330. return;
  210331. WAVEFORMATEXTENSIBLE format;
  210332. wasapi_copyWavFormat (format, mixFormat);
  210333. CoTaskMemFree (mixFormat);
  210334. actualNumChannels = numChannels = format.Format.nChannels;
  210335. defaultSampleRate = format.Format.nSamplesPerSec;
  210336. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  210337. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  210338. FloatElementComparator<double> comparator;
  210339. rates.addSorted (comparator, defaultSampleRate);
  210340. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210341. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  210342. {
  210343. if (ratesToTest[i] == defaultSampleRate)
  210344. continue;
  210345. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  210346. if (SUCCEEDED (tempClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, 0)))
  210347. if (! rates.contains (ratesToTest[i]))
  210348. rates.addSorted (comparator, ratesToTest[i]);
  210349. }
  210350. }
  210351. ~WASAPIDeviceBase()
  210352. {
  210353. device = 0;
  210354. CloseHandle (clientEvent);
  210355. }
  210356. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  210357. bool openClient (const double newSampleRate, const BitArray& newChannels)
  210358. {
  210359. sampleRate = newSampleRate;
  210360. channels = newChannels;
  210361. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  210362. numChannels = channels.getHighestBit() + 1;
  210363. if (numChannels == 0)
  210364. return true;
  210365. client = createClient();
  210366. if (client != 0
  210367. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  210368. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  210369. {
  210370. channelMaps.clear();
  210371. for (int i = 0; i <= channels.getHighestBit(); ++i)
  210372. if (channels[i])
  210373. channelMaps.add (i);
  210374. REFERENCE_TIME latency;
  210375. if (OK (client->GetStreamLatency (&latency)))
  210376. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  210377. (void) OK (client->GetBufferSize (&actualBufferSize));
  210378. return OK (client->SetEventHandle (clientEvent));
  210379. }
  210380. return false;
  210381. }
  210382. void closeClient()
  210383. {
  210384. if (client != 0)
  210385. client->Stop();
  210386. client = 0;
  210387. ResetEvent (clientEvent);
  210388. }
  210389. ComSmartPtr <IMMDevice> device;
  210390. ComSmartPtr <IAudioClient> client;
  210391. double sampleRate, defaultSampleRate;
  210392. int numChannels, actualNumChannels;
  210393. int minBufferSize, defaultBufferSize, latencySamples;
  210394. Array <double> rates;
  210395. HANDLE clientEvent;
  210396. BitArray channels;
  210397. AudioDataConverters::DataFormat dataFormat;
  210398. Array <int> channelMaps;
  210399. UINT32 actualBufferSize;
  210400. int bytesPerSample;
  210401. private:
  210402. const ComSmartPtr <IAudioClient> createClient()
  210403. {
  210404. ComSmartPtr <IAudioClient> client;
  210405. if (device != 0)
  210406. {
  210407. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  210408. logFailure (hr);
  210409. }
  210410. return client;
  210411. }
  210412. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  210413. {
  210414. WAVEFORMATEXTENSIBLE format;
  210415. zerostruct (format);
  210416. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  210417. {
  210418. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  210419. }
  210420. else
  210421. {
  210422. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  210423. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  210424. }
  210425. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  210426. format.Format.nChannels = (WORD) numChannels;
  210427. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  210428. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  210429. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  210430. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  210431. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  210432. switch (numChannels)
  210433. {
  210434. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  210435. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  210436. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  210437. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  210438. 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;
  210439. default: break;
  210440. }
  210441. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  210442. HRESULT hr = client->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, (WAVEFORMATEX**) &nearestFormat);
  210443. logFailure (hr);
  210444. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  210445. {
  210446. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  210447. hr = S_OK;
  210448. }
  210449. CoTaskMemFree (nearestFormat);
  210450. GUID session;
  210451. if (hr == S_OK
  210452. && OK (client->Initialize (AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  210453. 0, 0, (WAVEFORMATEX*) &format, &session)))
  210454. {
  210455. actualNumChannels = format.Format.nChannels;
  210456. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  210457. bytesPerSample = format.Format.wBitsPerSample / 8;
  210458. dataFormat = isFloat ? AudioDataConverters::float32LE
  210459. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  210460. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  210461. : AudioDataConverters::int16LE)));
  210462. return true;
  210463. }
  210464. return false;
  210465. }
  210466. };
  210467. class WASAPIInputDevice : public WASAPIDeviceBase
  210468. {
  210469. public:
  210470. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_)
  210471. : WASAPIDeviceBase (device_),
  210472. reservoir (1, 1)
  210473. {
  210474. }
  210475. ~WASAPIInputDevice()
  210476. {
  210477. close();
  210478. }
  210479. bool open (const double newSampleRate, const BitArray& newChannels)
  210480. {
  210481. reservoirSize = 0;
  210482. reservoirCapacity = 16384;
  210483. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  210484. return openClient (newSampleRate, newChannels)
  210485. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  210486. }
  210487. void close()
  210488. {
  210489. closeClient();
  210490. captureClient = 0;
  210491. reservoir.setSize (0);
  210492. }
  210493. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  210494. {
  210495. if (numChannels <= 0)
  210496. return;
  210497. int offset = 0;
  210498. while (bufferSize > 0)
  210499. {
  210500. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  210501. {
  210502. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  210503. for (int i = 0; i < numDestBuffers; ++i)
  210504. {
  210505. float* const dest = destBuffers[i] + offset;
  210506. const int srcChan = channelMaps.getUnchecked(i);
  210507. switch (dataFormat)
  210508. {
  210509. case AudioDataConverters::float32LE:
  210510. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  210511. break;
  210512. case AudioDataConverters::int32LE:
  210513. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  210514. break;
  210515. case AudioDataConverters::int24LE:
  210516. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  210517. break;
  210518. case AudioDataConverters::int16LE:
  210519. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  210520. break;
  210521. default: jassertfalse; break;
  210522. }
  210523. }
  210524. bufferSize -= samplesToDo;
  210525. offset += samplesToDo;
  210526. reservoirSize -= samplesToDo;
  210527. }
  210528. else
  210529. {
  210530. UINT32 packetLength = 0;
  210531. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  210532. break;
  210533. if (packetLength == 0)
  210534. {
  210535. if (thread.threadShouldExit())
  210536. break;
  210537. Thread::sleep (1);
  210538. continue;
  210539. }
  210540. uint8* inputData = 0;
  210541. UINT32 numSamplesAvailable;
  210542. DWORD flags;
  210543. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  210544. {
  210545. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  210546. for (int i = 0; i < numDestBuffers; ++i)
  210547. {
  210548. float* const dest = destBuffers[i] + offset;
  210549. const int srcChan = channelMaps.getUnchecked(i);
  210550. switch (dataFormat)
  210551. {
  210552. case AudioDataConverters::float32LE:
  210553. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  210554. break;
  210555. case AudioDataConverters::int32LE:
  210556. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  210557. break;
  210558. case AudioDataConverters::int24LE:
  210559. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  210560. break;
  210561. case AudioDataConverters::int16LE:
  210562. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  210563. break;
  210564. default: jassertfalse; break;
  210565. }
  210566. }
  210567. bufferSize -= samplesToDo;
  210568. offset += samplesToDo;
  210569. if (samplesToDo < numSamplesAvailable)
  210570. {
  210571. reservoirSize = jmin (numSamplesAvailable - samplesToDo, reservoirCapacity);
  210572. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  210573. bytesPerSample * actualNumChannels * reservoirSize);
  210574. }
  210575. captureClient->ReleaseBuffer (numSamplesAvailable);
  210576. }
  210577. }
  210578. }
  210579. }
  210580. ComSmartPtr <IAudioCaptureClient> captureClient;
  210581. MemoryBlock reservoir;
  210582. int reservoirSize, reservoirCapacity;
  210583. };
  210584. class WASAPIOutputDevice : public WASAPIDeviceBase
  210585. {
  210586. public:
  210587. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_)
  210588. : WASAPIDeviceBase (device_)
  210589. {
  210590. }
  210591. ~WASAPIOutputDevice()
  210592. {
  210593. close();
  210594. }
  210595. bool open (const double newSampleRate, const BitArray& newChannels)
  210596. {
  210597. return openClient (newSampleRate, newChannels)
  210598. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  210599. }
  210600. void close()
  210601. {
  210602. closeClient();
  210603. renderClient = 0;
  210604. }
  210605. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  210606. {
  210607. if (numChannels <= 0)
  210608. return;
  210609. int offset = 0;
  210610. while (bufferSize > 0)
  210611. {
  210612. UINT32 padding = 0;
  210613. if (! OK (client->GetCurrentPadding (&padding)))
  210614. return;
  210615. const int samplesToDo = jmin ((int) (actualBufferSize - padding), bufferSize);
  210616. if (samplesToDo <= 0)
  210617. {
  210618. if (thread.threadShouldExit())
  210619. break;
  210620. Thread::sleep (0);
  210621. continue;
  210622. }
  210623. uint8* outputData = 0;
  210624. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  210625. {
  210626. for (int i = 0; i < numSrcBuffers; ++i)
  210627. {
  210628. const float* const source = srcBuffers[i] + offset;
  210629. const int destChan = channelMaps.getUnchecked(i);
  210630. switch (dataFormat)
  210631. {
  210632. case AudioDataConverters::float32LE:
  210633. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  210634. break;
  210635. case AudioDataConverters::int32LE:
  210636. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  210637. break;
  210638. case AudioDataConverters::int24LE:
  210639. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  210640. break;
  210641. case AudioDataConverters::int16LE:
  210642. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  210643. break;
  210644. default: jassertfalse; break;
  210645. }
  210646. }
  210647. renderClient->ReleaseBuffer (samplesToDo, 0);
  210648. offset += samplesToDo;
  210649. bufferSize -= samplesToDo;
  210650. }
  210651. }
  210652. }
  210653. ComSmartPtr <IAudioRenderClient> renderClient;
  210654. };
  210655. class WASAPIAudioIODevice : public AudioIODevice,
  210656. public Thread
  210657. {
  210658. public:
  210659. WASAPIAudioIODevice (const String& deviceName,
  210660. const int outputDeviceIndex_, const String& outputDeviceId_,
  210661. const int inputDeviceIndex_, const String& inputDeviceId_)
  210662. : AudioIODevice (deviceName, "Windows Audio"),
  210663. Thread ("Juce WASAPI"),
  210664. isOpen_ (false),
  210665. isStarted (false),
  210666. outputDevice (0),
  210667. outputDeviceIndex (outputDeviceIndex_),
  210668. outputDeviceId (outputDeviceId_),
  210669. inputDevice (0),
  210670. inputDeviceIndex (inputDeviceIndex_),
  210671. inputDeviceId (inputDeviceId_),
  210672. currentBufferSizeSamples (0),
  210673. currentSampleRate (0),
  210674. callback (0)
  210675. {
  210676. }
  210677. ~WASAPIAudioIODevice()
  210678. {
  210679. close();
  210680. deleteAndZero (inputDevice);
  210681. deleteAndZero (outputDevice);
  210682. }
  210683. bool initialise()
  210684. {
  210685. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  210686. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  210687. latencyIn = latencyOut = 0;
  210688. Array <double> ratesIn, ratesOut;
  210689. if (createDevices())
  210690. {
  210691. jassert (inputDevice != 0 || outputDevice != 0);
  210692. if (inputDevice != 0 && outputDevice != 0)
  210693. {
  210694. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  210695. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  210696. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  210697. sampleRates = inputDevice->rates;
  210698. sampleRates.removeValuesNotIn (outputDevice->rates);
  210699. jassert (sampleRates.size() > 0); // in and out devices don't share any common sample rates!
  210700. }
  210701. else
  210702. {
  210703. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  210704. defaultSampleRate = d->defaultSampleRate;
  210705. minBufferSize = d->minBufferSize;
  210706. defaultBufferSize = d->defaultBufferSize;
  210707. sampleRates = d->rates;
  210708. }
  210709. IntegerElementComparator<int> comparator;
  210710. bufferSizes.addSorted (comparator, defaultBufferSize);
  210711. if (minBufferSize != defaultBufferSize)
  210712. bufferSizes.addSorted (comparator, minBufferSize);
  210713. int n = 64;
  210714. for (int i = 0; i < 40; ++i)
  210715. {
  210716. if (n >= minBufferSize && ! bufferSizes.contains (n))
  210717. bufferSizes.addSorted (comparator, n);
  210718. n += (n < 512) ? 32
  210719. : ((n < 1024) ? 64
  210720. : ((n < 2048) ? 128 : 256));
  210721. }
  210722. return true;
  210723. }
  210724. return false;
  210725. }
  210726. const StringArray getOutputChannelNames()
  210727. {
  210728. StringArray outChannels;
  210729. if (outputDevice != 0)
  210730. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  210731. outChannels.add ("Output channel " + String (i));
  210732. return outChannels;
  210733. }
  210734. const StringArray getInputChannelNames()
  210735. {
  210736. StringArray inChannels;
  210737. if (inputDevice != 0)
  210738. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  210739. inChannels.add ("Input channel " + String (i));
  210740. return inChannels;
  210741. }
  210742. int getNumSampleRates() { return sampleRates.size(); }
  210743. double getSampleRate (int index) { return sampleRates [index]; }
  210744. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  210745. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  210746. int getDefaultBufferSize() { return defaultBufferSize; }
  210747. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  210748. double getCurrentSampleRate() { return currentSampleRate; }
  210749. int getCurrentBitDepth() { return 32; }
  210750. int getOutputLatencyInSamples() { return latencyOut; }
  210751. int getInputLatencyInSamples() { return latencyIn; }
  210752. const BitArray getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BitArray(); }
  210753. const BitArray getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BitArray(); }
  210754. const String getLastError() { return lastError; }
  210755. const String open (const BitArray& inputChannels, const BitArray& outputChannels,
  210756. double sampleRate, int bufferSizeSamples)
  210757. {
  210758. close();
  210759. lastError = String::empty;
  210760. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  210761. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  210762. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  210763. {
  210764. lastError = "Couldn't open the input device!";
  210765. return lastError;
  210766. }
  210767. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  210768. {
  210769. close();
  210770. lastError = "Couldn't open the output device!";
  210771. return lastError;
  210772. }
  210773. if (inputDevice != 0 && inputDevice->client != 0)
  210774. {
  210775. HRESULT hr = inputDevice->client->Start();
  210776. logFailure (hr); //xxx handle this
  210777. }
  210778. if (outputDevice != 0 && outputDevice->client != 0)
  210779. {
  210780. HRESULT hr = outputDevice->client->Start();
  210781. logFailure (hr); //xxx handle this
  210782. }
  210783. startThread (8);
  210784. isOpen_ = true;
  210785. return lastError;
  210786. }
  210787. void close()
  210788. {
  210789. stop();
  210790. if (inputDevice != 0)
  210791. SetEvent (inputDevice->clientEvent);
  210792. if (outputDevice != 0)
  210793. SetEvent (outputDevice->clientEvent);
  210794. stopThread (5000);
  210795. if (inputDevice != 0)
  210796. inputDevice->close();
  210797. if (outputDevice != 0)
  210798. outputDevice->close();
  210799. isOpen_ = false;
  210800. }
  210801. bool isOpen() { return isOpen_ && isThreadRunning(); }
  210802. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  210803. void start (AudioIODeviceCallback* call)
  210804. {
  210805. if (isOpen_ && call != 0 && ! isStarted)
  210806. {
  210807. if (! isThreadRunning())
  210808. {
  210809. // something's gone wrong and the thread's stopped..
  210810. isOpen_ = false;
  210811. return;
  210812. }
  210813. call->audioDeviceAboutToStart (this);
  210814. const ScopedLock sl (startStopLock);
  210815. callback = call;
  210816. isStarted = true;
  210817. }
  210818. }
  210819. void stop()
  210820. {
  210821. if (isStarted)
  210822. {
  210823. AudioIODeviceCallback* const callbackLocal = callback;
  210824. {
  210825. const ScopedLock sl (startStopLock);
  210826. isStarted = false;
  210827. }
  210828. if (callbackLocal != 0)
  210829. callbackLocal->audioDeviceStopped();
  210830. }
  210831. }
  210832. void run()
  210833. {
  210834. const int bufferSize = currentBufferSizeSamples;
  210835. HANDLE events[2];
  210836. int numEvents = 0;
  210837. if (inputDevice != 0)
  210838. events [numEvents++] = inputDevice->clientEvent;
  210839. if (outputDevice != 0)
  210840. events [numEvents++] = outputDevice->clientEvent;
  210841. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  210842. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  210843. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  210844. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  210845. float** const inputBuffers = ins.getArrayOfChannels();
  210846. float** const outputBuffers = outs.getArrayOfChannels();
  210847. ins.clear();
  210848. while (! threadShouldExit())
  210849. {
  210850. const DWORD result = WaitForMultipleObjects (numEvents, events, true, 1000);
  210851. if (result == WAIT_TIMEOUT)
  210852. continue;
  210853. if (threadShouldExit())
  210854. break;
  210855. if (inputDevice != 0)
  210856. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  210857. // Make the callback..
  210858. {
  210859. const ScopedLock sl (startStopLock);
  210860. if (isStarted)
  210861. {
  210862. JUCE_TRY
  210863. {
  210864. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  210865. numInputBuffers,
  210866. outputBuffers,
  210867. numOutputBuffers,
  210868. bufferSize);
  210869. }
  210870. JUCE_CATCH_EXCEPTION
  210871. }
  210872. else
  210873. {
  210874. outs.clear();
  210875. }
  210876. }
  210877. if (outputDevice != 0)
  210878. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  210879. }
  210880. }
  210881. juce_UseDebuggingNewOperator
  210882. int outputDeviceIndex, inputDeviceIndex;
  210883. String outputDeviceId, inputDeviceId;
  210884. String lastError;
  210885. private:
  210886. // Device stats...
  210887. WASAPIInputDevice* inputDevice;
  210888. WASAPIOutputDevice* outputDevice;
  210889. double defaultSampleRate;
  210890. int minBufferSize, defaultBufferSize;
  210891. int latencyIn, latencyOut;
  210892. Array <double> sampleRates;
  210893. Array <int> bufferSizes;
  210894. // Active state...
  210895. bool isOpen_, isStarted;
  210896. int currentBufferSizeSamples;
  210897. double currentSampleRate;
  210898. AudioIODeviceCallback* callback;
  210899. CriticalSection startStopLock;
  210900. bool createDevices()
  210901. {
  210902. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  210903. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  210904. return false;
  210905. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  210906. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  210907. return false;
  210908. UINT32 numDevices = 0;
  210909. if (! OK (deviceCollection->GetCount (&numDevices)))
  210910. return false;
  210911. for (UINT32 i = 0; i < numDevices; ++i)
  210912. {
  210913. ComSmartPtr <IMMDevice> device;
  210914. if (! OK (deviceCollection->Item (i, &device)))
  210915. continue;
  210916. const String deviceId (wasapi_getDeviceID (device));
  210917. if (deviceId.isEmpty())
  210918. continue;
  210919. const EDataFlow flow = wasapi_getDataFlow (device);
  210920. if (deviceId == inputDeviceId && flow == eCapture)
  210921. inputDevice = new WASAPIInputDevice (device);
  210922. else if (deviceId == outputDeviceId && flow == eRender)
  210923. outputDevice = new WASAPIOutputDevice (device);
  210924. }
  210925. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  210926. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  210927. }
  210928. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  210929. const WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  210930. };
  210931. class WASAPIAudioIODeviceType : public AudioIODeviceType
  210932. {
  210933. public:
  210934. WASAPIAudioIODeviceType()
  210935. : AudioIODeviceType (T("Windows Audio")),
  210936. hasScanned (false)
  210937. {
  210938. }
  210939. ~WASAPIAudioIODeviceType()
  210940. {
  210941. }
  210942. void scanForDevices()
  210943. {
  210944. hasScanned = true;
  210945. outputDeviceNames.clear();
  210946. inputDeviceNames.clear();
  210947. outputDeviceIds.clear();
  210948. inputDeviceIds.clear();
  210949. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  210950. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  210951. return;
  210952. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  210953. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  210954. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  210955. UINT32 numDevices = 0;
  210956. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  210957. && OK (deviceCollection->GetCount (&numDevices))))
  210958. return;
  210959. for (UINT32 i = 0; i < numDevices; ++i)
  210960. {
  210961. ComSmartPtr <IMMDevice> device;
  210962. if (! OK (deviceCollection->Item (i, &device)))
  210963. continue;
  210964. const String deviceId (wasapi_getDeviceID (device));
  210965. DWORD state = 0;
  210966. if (! OK (device->GetState (&state)))
  210967. continue;
  210968. if (state != DEVICE_STATE_ACTIVE)
  210969. continue;
  210970. String name;
  210971. {
  210972. ComSmartPtr <IPropertyStore> properties;
  210973. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  210974. continue;
  210975. PROPVARIANT value;
  210976. PropVariantInit (&value);
  210977. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  210978. name = value.pwszVal;
  210979. PropVariantClear (&value);
  210980. }
  210981. const EDataFlow flow = wasapi_getDataFlow (device);
  210982. if (flow == eRender)
  210983. {
  210984. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  210985. outputDeviceIds.insert (index, deviceId);
  210986. outputDeviceNames.insert (index, name);
  210987. }
  210988. else if (flow == eCapture)
  210989. {
  210990. const int index = (deviceId == defaultCapture) ? 0 : -1;
  210991. inputDeviceIds.insert (index, deviceId);
  210992. inputDeviceNames.insert (index, name);
  210993. }
  210994. }
  210995. }
  210996. const StringArray getDeviceNames (const bool wantInputNames) const
  210997. {
  210998. jassert (hasScanned); // need to call scanForDevices() before doing this
  210999. return wantInputNames ? inputDeviceNames
  211000. : outputDeviceNames;
  211001. }
  211002. int getDefaultDeviceIndex (const bool /*forInput*/) const
  211003. {
  211004. jassert (hasScanned); // need to call scanForDevices() before doing this
  211005. return 0;
  211006. }
  211007. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  211008. {
  211009. jassert (hasScanned); // need to call scanForDevices() before doing this
  211010. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  211011. return (d == 0) ? -1 : (asInput ? d->inputDeviceIndex : d->outputDeviceIndex);
  211012. }
  211013. bool hasSeparateInputsAndOutputs() const { return true; }
  211014. AudioIODevice* createDevice (const String& outputDeviceName,
  211015. const String& inputDeviceName)
  211016. {
  211017. jassert (hasScanned); // need to call scanForDevices() before doing this
  211018. WASAPIAudioIODevice* d = 0;
  211019. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211020. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211021. if (outputIndex >= 0 || inputIndex >= 0)
  211022. {
  211023. d = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211024. : inputDeviceName,
  211025. outputIndex, outputDeviceIds [outputIndex],
  211026. inputIndex, inputDeviceIds [inputIndex]);
  211027. if (! d->initialise())
  211028. deleteAndZero (d);
  211029. }
  211030. return d;
  211031. }
  211032. juce_UseDebuggingNewOperator
  211033. StringArray outputDeviceNames, outputDeviceIds;
  211034. StringArray inputDeviceNames, inputDeviceIds;
  211035. private:
  211036. bool hasScanned;
  211037. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  211038. {
  211039. String s;
  211040. IMMDevice* dev = 0;
  211041. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  211042. eMultimedia, &dev)))
  211043. {
  211044. WCHAR* deviceId = 0;
  211045. if (OK (dev->GetId (&deviceId)))
  211046. {
  211047. s = String (deviceId);
  211048. CoTaskMemFree (deviceId);
  211049. }
  211050. dev->Release();
  211051. }
  211052. return s;
  211053. }
  211054. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  211055. const WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  211056. };
  211057. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  211058. {
  211059. return new WASAPIAudioIODeviceType();
  211060. }
  211061. #undef logFailure
  211062. #undef OK
  211063. #endif
  211064. /********* End of inlined file: juce_win32_WASAPI.cpp *********/
  211065. /********* Start of inlined file: juce_win32_CameraDevice.cpp *********/
  211066. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211067. // compiled on its own).
  211068. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  211069. class DShowCameraDeviceInteral : public ChangeBroadcaster
  211070. {
  211071. public:
  211072. DShowCameraDeviceInteral (CameraDevice* const owner_,
  211073. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  211074. const ComSmartPtr <IBaseFilter>& filter_,
  211075. int minWidth, int minHeight,
  211076. int maxWidth, int maxHeight)
  211077. : owner (owner_),
  211078. captureGraphBuilder (captureGraphBuilder_),
  211079. filter (filter_),
  211080. ok (false),
  211081. imageNeedsFlipping (false),
  211082. width (0),
  211083. height (0),
  211084. activeUsers (0),
  211085. recordNextFrameTime (false)
  211086. {
  211087. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph, CLSCTX_INPROC);
  211088. if (FAILED (hr))
  211089. return;
  211090. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  211091. if (FAILED (hr))
  211092. return;
  211093. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  211094. if (FAILED (hr))
  211095. return;
  211096. {
  211097. ComSmartPtr <IAMStreamConfig> streamConfig;
  211098. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE,
  211099. 0,
  211100. filter,
  211101. IID_IAMStreamConfig,
  211102. (void**) &streamConfig);
  211103. if (streamConfig != 0)
  211104. {
  211105. getVideoSizes (streamConfig);
  211106. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  211107. return;
  211108. }
  211109. }
  211110. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  211111. if (FAILED (hr))
  211112. return;
  211113. hr = smartTee.CoCreateInstance (CLSID_SmartTee, CLSCTX_INPROC_SERVER);
  211114. if (FAILED (hr))
  211115. return;
  211116. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  211117. if (FAILED (hr))
  211118. return;
  211119. if (! connectFilters (filter, smartTee))
  211120. return;
  211121. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  211122. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber, CLSCTX_INPROC_SERVER);
  211123. if (FAILED (hr))
  211124. return;
  211125. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  211126. if (FAILED (hr))
  211127. return;
  211128. AM_MEDIA_TYPE mt;
  211129. zerostruct (mt);
  211130. mt.majortype = MEDIATYPE_Video;
  211131. mt.subtype = MEDIASUBTYPE_RGB24;
  211132. mt.formattype = FORMAT_VideoInfo;
  211133. sampleGrabber->SetMediaType (&mt);
  211134. callback = new GrabberCallback (*this);
  211135. sampleGrabber->SetCallback (callback, 1);
  211136. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  211137. if (FAILED (hr))
  211138. return;
  211139. ComSmartPtr <IPin> grabberInputPin;
  211140. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  211141. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  211142. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  211143. return;
  211144. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  211145. if (FAILED (hr))
  211146. return;
  211147. zerostruct (mt);
  211148. hr = sampleGrabber->GetConnectedMediaType (&mt);
  211149. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  211150. width = pVih->bmiHeader.biWidth;
  211151. height = pVih->bmiHeader.biHeight;
  211152. ComSmartPtr <IBaseFilter> nullFilter;
  211153. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer, CLSCTX_INPROC_SERVER);
  211154. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  211155. if (connectFilters (sampleGrabberBase, nullFilter)
  211156. && addGraphToRot())
  211157. {
  211158. activeImage = new Image (Image::RGB, width, height, true);
  211159. loadingImage = new Image (Image::RGB, width, height, true);
  211160. ok = true;
  211161. }
  211162. }
  211163. ~DShowCameraDeviceInteral()
  211164. {
  211165. mediaControl->Stop();
  211166. removeGraphFromRot();
  211167. for (int i = viewerComps.size(); --i >= 0;)
  211168. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  211169. callback = 0;
  211170. graphBuilder = 0;
  211171. sampleGrabber = 0;
  211172. mediaControl = 0;
  211173. filter = 0;
  211174. captureGraphBuilder = 0;
  211175. smartTee = 0;
  211176. smartTeePreviewOutputPin = 0;
  211177. smartTeeCaptureOutputPin = 0;
  211178. mux = 0;
  211179. fileWriter = 0;
  211180. delete activeImage;
  211181. delete loadingImage;
  211182. }
  211183. void addUser()
  211184. {
  211185. if (ok && activeUsers++ == 0)
  211186. mediaControl->Run();
  211187. }
  211188. void removeUser()
  211189. {
  211190. if (ok && --activeUsers == 0)
  211191. mediaControl->Stop();
  211192. }
  211193. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  211194. {
  211195. if (recordNextFrameTime)
  211196. {
  211197. firstRecordedTime = Time::getCurrentTime();
  211198. recordNextFrameTime = false;
  211199. }
  211200. imageSwapLock.enter();
  211201. int ls, ps;
  211202. const int lineStride = width * 3;
  211203. uint8* const dest = loadingImage->lockPixelDataReadWrite (0, 0, width, height, ls, ps);
  211204. for (int i = 0; i < height; ++i)
  211205. memcpy (dest + ls * ((height - 1) - i),
  211206. buffer + lineStride * i,
  211207. lineStride);
  211208. loadingImage->releasePixelDataReadWrite (dest);
  211209. imageNeedsFlipping = true;
  211210. imageSwapLock.exit();
  211211. callListeners (*loadingImage);
  211212. sendChangeMessage (this);
  211213. }
  211214. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  211215. {
  211216. if (imageNeedsFlipping)
  211217. {
  211218. imageSwapLock.enter();
  211219. swapVariables (loadingImage, activeImage);
  211220. imageNeedsFlipping = false;
  211221. imageSwapLock.exit();
  211222. }
  211223. RectanglePlacement rp (RectanglePlacement::centred);
  211224. double dx = 0, dy = 0, dw = width, dh = height;
  211225. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  211226. const int rx = roundDoubleToInt (dx), ry = roundDoubleToInt (dy);
  211227. const int rw = roundDoubleToInt (dw), rh = roundDoubleToInt (dh);
  211228. g.saveState();
  211229. g.excludeClipRegion (rx, ry, rw, rh);
  211230. g.fillAll (Colours::black);
  211231. g.restoreState();
  211232. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  211233. }
  211234. bool createFileCaptureFilter (const File& file)
  211235. {
  211236. removeFileCaptureFilter();
  211237. file.deleteFile();
  211238. mediaControl->Stop();
  211239. firstRecordedTime = Time();
  211240. recordNextFrameTime = true;
  211241. HRESULT hr = mux.CoCreateInstance (CLSID_AviDest, CLSCTX_INPROC_SERVER);
  211242. if (SUCCEEDED (hr))
  211243. {
  211244. hr = graphBuilder->AddFilter (mux, _T("AVI Mux"));
  211245. if (SUCCEEDED (hr))
  211246. {
  211247. fileWriter.CoCreateInstance (CLSID_FileWriter, CLSCTX_INPROC_SERVER);
  211248. if (SUCCEEDED (hr))
  211249. {
  211250. ComSmartPtr <IFileSinkFilter> fileSink;
  211251. hr = fileWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  211252. if (SUCCEEDED (hr))
  211253. {
  211254. AM_MEDIA_TYPE mt;
  211255. zerostruct (mt);
  211256. mt.majortype = MEDIATYPE_Stream;
  211257. mt.subtype = MEDIASUBTYPE_Avi;
  211258. mt.formattype = FORMAT_VideoInfo;
  211259. hr = fileSink->SetFileName (file.getFullPathName(), &mt);
  211260. if (SUCCEEDED (hr))
  211261. {
  211262. hr = graphBuilder->AddFilter (fileWriter, _T("File Writer"));
  211263. if (SUCCEEDED (hr))
  211264. {
  211265. ComSmartPtr <IPin> muxInputPin, muxOutputPin, writerInput;
  211266. if (getPin (mux, PINDIR_INPUT, &muxInputPin)
  211267. && getPin (mux, PINDIR_OUTPUT, &muxOutputPin)
  211268. && getPin (fileWriter, PINDIR_INPUT, &writerInput))
  211269. {
  211270. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, muxInputPin);
  211271. if (SUCCEEDED (hr))
  211272. {
  211273. hr = graphBuilder->Connect (muxOutputPin, writerInput);
  211274. if (SUCCEEDED (hr))
  211275. {
  211276. if (ok && activeUsers > 0)
  211277. mediaControl->Run();
  211278. return true;
  211279. }
  211280. }
  211281. }
  211282. }
  211283. }
  211284. }
  211285. }
  211286. }
  211287. }
  211288. removeFileCaptureFilter();
  211289. if (ok && activeUsers > 0)
  211290. mediaControl->Run();
  211291. return false;
  211292. }
  211293. void removeFileCaptureFilter()
  211294. {
  211295. mediaControl->Stop();
  211296. if (mux != 0)
  211297. {
  211298. graphBuilder->RemoveFilter (mux);
  211299. mux = 0;
  211300. }
  211301. if (fileWriter != 0)
  211302. {
  211303. graphBuilder->RemoveFilter (fileWriter);
  211304. fileWriter = 0;
  211305. }
  211306. if (ok && activeUsers > 0)
  211307. mediaControl->Run();
  211308. }
  211309. void addListener (CameraImageListener* listenerToAdd)
  211310. {
  211311. const ScopedLock sl (listenerLock);
  211312. if (listeners.size() == 0)
  211313. addUser();
  211314. listeners.addIfNotAlreadyThere (listenerToAdd);
  211315. }
  211316. void removeListener (CameraImageListener* listenerToRemove)
  211317. {
  211318. const ScopedLock sl (listenerLock);
  211319. listeners.removeValue (listenerToRemove);
  211320. if (listeners.size() == 0)
  211321. removeUser();
  211322. }
  211323. void callListeners (Image& image)
  211324. {
  211325. const ScopedLock sl (listenerLock);
  211326. for (int i = listeners.size(); --i >= 0;)
  211327. {
  211328. CameraImageListener* l = (CameraImageListener*) listeners[i];
  211329. if (l != 0)
  211330. l->imageReceived (image);
  211331. }
  211332. }
  211333. class DShowCaptureViewerComp : public Component,
  211334. public ChangeListener
  211335. {
  211336. public:
  211337. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  211338. : owner (owner_)
  211339. {
  211340. setOpaque (true);
  211341. owner->addChangeListener (this);
  211342. owner->addUser();
  211343. owner->viewerComps.add (this);
  211344. setSize (owner_->width, owner_->height);
  211345. }
  211346. ~DShowCaptureViewerComp()
  211347. {
  211348. if (owner != 0)
  211349. {
  211350. owner->viewerComps.removeValue (this);
  211351. owner->removeUser();
  211352. owner->removeChangeListener (this);
  211353. }
  211354. }
  211355. void ownerDeleted()
  211356. {
  211357. owner = 0;
  211358. }
  211359. void paint (Graphics& g)
  211360. {
  211361. g.setColour (Colours::black);
  211362. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  211363. if (owner != 0)
  211364. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  211365. else
  211366. g.fillAll (Colours::black);
  211367. }
  211368. void changeListenerCallback (void*)
  211369. {
  211370. repaint();
  211371. }
  211372. private:
  211373. DShowCameraDeviceInteral* owner;
  211374. };
  211375. bool ok;
  211376. int width, height;
  211377. Time firstRecordedTime;
  211378. VoidArray viewerComps;
  211379. private:
  211380. CameraDevice* const owner;
  211381. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  211382. ComSmartPtr <IBaseFilter> filter;
  211383. ComSmartPtr <IBaseFilter> smartTee;
  211384. ComSmartPtr <IGraphBuilder> graphBuilder;
  211385. ComSmartPtr <ISampleGrabber> sampleGrabber;
  211386. ComSmartPtr <IMediaControl> mediaControl;
  211387. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  211388. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  211389. ComSmartPtr <IBaseFilter> mux, fileWriter;
  211390. int activeUsers;
  211391. Array <int> widths, heights;
  211392. DWORD graphRegistrationID;
  211393. CriticalSection imageSwapLock;
  211394. bool imageNeedsFlipping;
  211395. Image* loadingImage;
  211396. Image* activeImage;
  211397. bool recordNextFrameTime;
  211398. void getVideoSizes (IAMStreamConfig* const streamConfig)
  211399. {
  211400. widths.clear();
  211401. heights.clear();
  211402. int count = 0, size = 0;
  211403. streamConfig->GetNumberOfCapabilities (&count, &size);
  211404. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  211405. {
  211406. for (int i = 0; i < count; ++i)
  211407. {
  211408. VIDEO_STREAM_CONFIG_CAPS scc;
  211409. AM_MEDIA_TYPE* config;
  211410. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  211411. if (SUCCEEDED (hr))
  211412. {
  211413. const int w = scc.InputSize.cx;
  211414. const int h = scc.InputSize.cy;
  211415. bool duplicate = false;
  211416. for (int j = widths.size(); --j >= 0;)
  211417. {
  211418. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  211419. {
  211420. duplicate = true;
  211421. break;
  211422. }
  211423. }
  211424. if (! duplicate)
  211425. {
  211426. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  211427. widths.add (w);
  211428. heights.add (h);
  211429. }
  211430. deleteMediaType (config);
  211431. }
  211432. }
  211433. }
  211434. }
  211435. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  211436. const int minWidth, const int minHeight,
  211437. const int maxWidth, const int maxHeight)
  211438. {
  211439. int count = 0, size = 0;
  211440. streamConfig->GetNumberOfCapabilities (&count, &size);
  211441. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  211442. {
  211443. for (int i = 0; i < count; ++i)
  211444. {
  211445. VIDEO_STREAM_CONFIG_CAPS scc;
  211446. AM_MEDIA_TYPE* config;
  211447. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  211448. if (SUCCEEDED (hr))
  211449. {
  211450. if (scc.InputSize.cx >= minWidth
  211451. && scc.InputSize.cy >= minHeight
  211452. && scc.InputSize.cx <= maxWidth
  211453. && scc.InputSize.cy <= maxHeight)
  211454. {
  211455. hr = streamConfig->SetFormat (config);
  211456. deleteMediaType (config);
  211457. return SUCCEEDED (hr);
  211458. }
  211459. deleteMediaType (config);
  211460. }
  211461. }
  211462. }
  211463. return false;
  211464. }
  211465. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  211466. {
  211467. ComSmartPtr <IEnumPins> enumerator;
  211468. ComSmartPtr <IPin> pin;
  211469. filter->EnumPins (&enumerator);
  211470. while (enumerator->Next (1, &pin, 0) == S_OK)
  211471. {
  211472. PIN_DIRECTION dir;
  211473. pin->QueryDirection (&dir);
  211474. if (wantedDirection == dir)
  211475. {
  211476. PIN_INFO info;
  211477. zerostruct (info);
  211478. pin->QueryPinInfo (&info);
  211479. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  211480. {
  211481. pin.p->AddRef();
  211482. *result = pin;
  211483. return true;
  211484. }
  211485. }
  211486. }
  211487. return false;
  211488. }
  211489. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  211490. {
  211491. ComSmartPtr <IPin> in, out;
  211492. return getPin (first, PINDIR_OUTPUT, &out)
  211493. && getPin (second, PINDIR_INPUT, &in)
  211494. && SUCCEEDED (graphBuilder->Connect (out, in));
  211495. }
  211496. bool addGraphToRot()
  211497. {
  211498. ComSmartPtr <IRunningObjectTable> rot;
  211499. if (FAILED (GetRunningObjectTable (0, &rot)))
  211500. return false;
  211501. ComSmartPtr <IMoniker> moniker;
  211502. WCHAR buffer[128];
  211503. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  211504. if (FAILED (hr))
  211505. return false;
  211506. graphRegistrationID = 0;
  211507. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  211508. }
  211509. void removeGraphFromRot()
  211510. {
  211511. ComSmartPtr <IRunningObjectTable> rot;
  211512. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  211513. rot->Revoke (graphRegistrationID);
  211514. }
  211515. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  211516. {
  211517. if (pmt->cbFormat != 0)
  211518. CoTaskMemFree ((PVOID) pmt->pbFormat);
  211519. if (pmt->pUnk != 0)
  211520. pmt->pUnk->Release();
  211521. CoTaskMemFree (pmt);
  211522. }
  211523. class GrabberCallback : public ISampleGrabberCB
  211524. {
  211525. public:
  211526. GrabberCallback (DShowCameraDeviceInteral& owner_)
  211527. : owner (owner_)
  211528. {
  211529. }
  211530. HRESULT __stdcall QueryInterface (REFIID id, void** result)
  211531. {
  211532. if (id == IID_IUnknown)
  211533. *result = dynamic_cast <IUnknown*> (this);
  211534. else if (id == IID_ISampleGrabberCB)
  211535. *result = dynamic_cast <ISampleGrabberCB*> (this);
  211536. else
  211537. {
  211538. *result = 0;
  211539. return E_NOINTERFACE;
  211540. }
  211541. AddRef();
  211542. return S_OK;
  211543. }
  211544. ULONG __stdcall AddRef() { return ++refCount; }
  211545. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  211546. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  211547. {
  211548. return E_FAIL;
  211549. }
  211550. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  211551. {
  211552. owner.handleFrame (time, buffer, bufferSize);
  211553. return S_OK;
  211554. }
  211555. private:
  211556. int refCount;
  211557. DShowCameraDeviceInteral& owner;
  211558. GrabberCallback (const GrabberCallback&);
  211559. const GrabberCallback& operator= (const GrabberCallback&);
  211560. };
  211561. ComSmartPtr <GrabberCallback> callback;
  211562. VoidArray listeners;
  211563. CriticalSection listenerLock;
  211564. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  211565. const DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  211566. };
  211567. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  211568. : name (name_)
  211569. {
  211570. isRecording = false;
  211571. }
  211572. CameraDevice::~CameraDevice()
  211573. {
  211574. stopRecording();
  211575. delete (DShowCameraDeviceInteral*) internal;
  211576. internal = 0;
  211577. }
  211578. Component* CameraDevice::createViewerComponent()
  211579. {
  211580. return new DShowCameraDeviceInteral::DShowCaptureViewerComp ((DShowCameraDeviceInteral*) internal);
  211581. }
  211582. const String CameraDevice::getFileExtension()
  211583. {
  211584. return ".avi";
  211585. }
  211586. void CameraDevice::startRecordingToFile (const File& file)
  211587. {
  211588. stopRecording();
  211589. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  211590. d->addUser();
  211591. isRecording = d->createFileCaptureFilter (file);
  211592. }
  211593. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  211594. {
  211595. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  211596. return d->firstRecordedTime;
  211597. }
  211598. void CameraDevice::stopRecording()
  211599. {
  211600. if (isRecording)
  211601. {
  211602. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  211603. d->removeFileCaptureFilter();
  211604. d->removeUser();
  211605. isRecording = false;
  211606. }
  211607. }
  211608. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  211609. {
  211610. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  211611. if (listenerToAdd != 0)
  211612. d->addListener (listenerToAdd);
  211613. }
  211614. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  211615. {
  211616. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  211617. if (listenerToRemove != 0)
  211618. d->removeListener (listenerToRemove);
  211619. }
  211620. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  211621. const int deviceIndexToOpen,
  211622. String& name)
  211623. {
  211624. int index = 0;
  211625. ComSmartPtr <IBaseFilter> result;
  211626. ComSmartPtr <ICreateDevEnum> pDevEnum;
  211627. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum, CLSCTX_INPROC);
  211628. if (SUCCEEDED (hr))
  211629. {
  211630. ComSmartPtr <IEnumMoniker> enumerator;
  211631. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  211632. if (SUCCEEDED (hr) && enumerator != 0)
  211633. {
  211634. ComSmartPtr <IBaseFilter> captureFilter;
  211635. ComSmartPtr <IMoniker> moniker;
  211636. ULONG fetched;
  211637. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  211638. {
  211639. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  211640. if (SUCCEEDED (hr))
  211641. {
  211642. ComSmartPtr <IPropertyBag> propertyBag;
  211643. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  211644. if (SUCCEEDED (hr))
  211645. {
  211646. VARIANT var;
  211647. var.vt = VT_BSTR;
  211648. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  211649. propertyBag = 0;
  211650. if (SUCCEEDED (hr))
  211651. {
  211652. if (names != 0)
  211653. names->add (var.bstrVal);
  211654. if (index == deviceIndexToOpen)
  211655. {
  211656. name = var.bstrVal;
  211657. result = captureFilter;
  211658. captureFilter = 0;
  211659. break;
  211660. }
  211661. ++index;
  211662. }
  211663. moniker = 0;
  211664. }
  211665. captureFilter = 0;
  211666. }
  211667. }
  211668. }
  211669. }
  211670. return result;
  211671. }
  211672. const StringArray CameraDevice::getAvailableDevices()
  211673. {
  211674. StringArray devs;
  211675. String dummy;
  211676. enumerateCameras (&devs, -1, dummy);
  211677. return devs;
  211678. }
  211679. CameraDevice* CameraDevice::openDevice (int index,
  211680. int minWidth, int minHeight,
  211681. int maxWidth, int maxHeight)
  211682. {
  211683. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  211684. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2, CLSCTX_INPROC);
  211685. if (SUCCEEDED (hr))
  211686. {
  211687. String name;
  211688. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  211689. if (filter != 0)
  211690. {
  211691. CameraDevice* const cam = new CameraDevice (name, index);
  211692. DShowCameraDeviceInteral* const intern
  211693. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  211694. minWidth, minHeight, maxWidth, maxHeight);
  211695. cam->internal = intern;
  211696. if (intern->ok)
  211697. return cam;
  211698. else
  211699. delete cam;
  211700. }
  211701. }
  211702. return 0;
  211703. }
  211704. #endif
  211705. /********* End of inlined file: juce_win32_CameraDevice.cpp *********/
  211706. #endif
  211707. // Auto-link the other win32 libs that are needed by library calls..
  211708. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  211709. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  211710. // Auto-links to various win32 libs that are needed by library calls..
  211711. #pragma comment(lib, "kernel32.lib")
  211712. #pragma comment(lib, "user32.lib")
  211713. #pragma comment(lib, "shell32.lib")
  211714. #pragma comment(lib, "gdi32.lib")
  211715. #pragma comment(lib, "vfw32.lib")
  211716. #pragma comment(lib, "comdlg32.lib")
  211717. #pragma comment(lib, "winmm.lib")
  211718. #pragma comment(lib, "wininet.lib")
  211719. #pragma comment(lib, "ole32.lib")
  211720. #pragma comment(lib, "advapi32.lib")
  211721. #pragma comment(lib, "ws2_32.lib")
  211722. #pragma comment(lib, "comsupp.lib")
  211723. #pragma comment(lib, "version.lib")
  211724. #if JUCE_OPENGL
  211725. #pragma comment(lib, "OpenGL32.Lib")
  211726. #pragma comment(lib, "GlU32.Lib")
  211727. #endif
  211728. #if JUCE_QUICKTIME
  211729. #pragma comment (lib, "QTMLClient.lib")
  211730. #endif
  211731. #if JUCE_USE_CAMERA
  211732. #pragma comment (lib, "Strmiids.lib")
  211733. #endif
  211734. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  211735. #endif
  211736. END_JUCE_NAMESPACE
  211737. /********* End of inlined file: juce_win32_NativeCode.cpp *********/
  211738. #endif
  211739. #if JUCE_LINUX
  211740. /********* Start of inlined file: juce_linux_NativeCode.cpp *********/
  211741. /*
  211742. This file wraps together all the mac-specific code, so that
  211743. we can include all the native headers just once, and compile all our
  211744. platform-specific stuff in one big lump, keeping it out of the way of
  211745. the rest of the codebase.
  211746. */
  211747. BEGIN_JUCE_NAMESPACE
  211748. /* Remove this macro if you're having problems compiling the cpu affinity
  211749. calls (the API for these has changed about quite a bit in various Linux
  211750. versions, and a lot of distros seem to ship with obsolete versions)
  211751. */
  211752. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  211753. #define SUPPORT_AFFINITIES 1
  211754. #endif
  211755. #define JUCE_INCLUDED_FILE 1
  211756. // Now include the actual code files..
  211757. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  211758. /*
  211759. This file contains posix routines that are common to both the Linux and Mac builds.
  211760. It gets included directly in the cpp files for these platforms.
  211761. */
  211762. CriticalSection::CriticalSection() throw()
  211763. {
  211764. pthread_mutexattr_t atts;
  211765. pthread_mutexattr_init (&atts);
  211766. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  211767. pthread_mutex_init (&internal, &atts);
  211768. }
  211769. CriticalSection::~CriticalSection() throw()
  211770. {
  211771. pthread_mutex_destroy (&internal);
  211772. }
  211773. void CriticalSection::enter() const throw()
  211774. {
  211775. pthread_mutex_lock (&internal);
  211776. }
  211777. bool CriticalSection::tryEnter() const throw()
  211778. {
  211779. return pthread_mutex_trylock (&internal) == 0;
  211780. }
  211781. void CriticalSection::exit() const throw()
  211782. {
  211783. pthread_mutex_unlock (&internal);
  211784. }
  211785. struct EventStruct
  211786. {
  211787. pthread_cond_t condition;
  211788. pthread_mutex_t mutex;
  211789. bool triggered;
  211790. };
  211791. WaitableEvent::WaitableEvent() throw()
  211792. {
  211793. EventStruct* const es = new EventStruct();
  211794. es->triggered = false;
  211795. pthread_cond_init (&es->condition, 0);
  211796. pthread_mutex_init (&es->mutex, 0);
  211797. internal = es;
  211798. }
  211799. WaitableEvent::~WaitableEvent() throw()
  211800. {
  211801. EventStruct* const es = (EventStruct*) internal;
  211802. pthread_cond_destroy (&es->condition);
  211803. pthread_mutex_destroy (&es->mutex);
  211804. delete es;
  211805. }
  211806. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  211807. {
  211808. EventStruct* const es = (EventStruct*) internal;
  211809. bool ok = true;
  211810. pthread_mutex_lock (&es->mutex);
  211811. if (timeOutMillisecs < 0)
  211812. {
  211813. while (! es->triggered)
  211814. pthread_cond_wait (&es->condition, &es->mutex);
  211815. }
  211816. else
  211817. {
  211818. while (! es->triggered)
  211819. {
  211820. struct timeval t;
  211821. gettimeofday (&t, 0);
  211822. struct timespec time;
  211823. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  211824. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  211825. if (time.tv_nsec >= 1000000000)
  211826. {
  211827. time.tv_nsec -= 1000000000;
  211828. time.tv_sec++;
  211829. }
  211830. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  211831. {
  211832. ok = false;
  211833. break;
  211834. }
  211835. }
  211836. }
  211837. es->triggered = false;
  211838. pthread_mutex_unlock (&es->mutex);
  211839. return ok;
  211840. }
  211841. void WaitableEvent::signal() const throw()
  211842. {
  211843. EventStruct* const es = (EventStruct*) internal;
  211844. pthread_mutex_lock (&es->mutex);
  211845. es->triggered = true;
  211846. pthread_cond_broadcast (&es->condition);
  211847. pthread_mutex_unlock (&es->mutex);
  211848. }
  211849. void WaitableEvent::reset() const throw()
  211850. {
  211851. EventStruct* const es = (EventStruct*) internal;
  211852. pthread_mutex_lock (&es->mutex);
  211853. es->triggered = false;
  211854. pthread_mutex_unlock (&es->mutex);
  211855. }
  211856. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  211857. {
  211858. struct timespec time;
  211859. time.tv_sec = millisecs / 1000;
  211860. time.tv_nsec = (millisecs % 1000) * 1000000;
  211861. nanosleep (&time, 0);
  211862. }
  211863. const tchar File::separator = T('/');
  211864. const tchar* File::separatorString = T("/");
  211865. bool juce_copyFile (const String& s, const String& d) throw();
  211866. static bool juce_stat (const String& fileName, struct stat& info) throw()
  211867. {
  211868. return fileName.isNotEmpty()
  211869. && (stat (fileName.toUTF8(), &info) == 0);
  211870. }
  211871. bool juce_isDirectory (const String& fileName) throw()
  211872. {
  211873. struct stat info;
  211874. return fileName.isEmpty()
  211875. || (juce_stat (fileName, info)
  211876. && ((info.st_mode & S_IFDIR) != 0));
  211877. }
  211878. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  211879. {
  211880. if (fileName.isEmpty())
  211881. return false;
  211882. const char* const fileNameUTF8 = fileName.toUTF8();
  211883. bool exists = access (fileNameUTF8, F_OK) == 0;
  211884. if (exists && dontCountDirectories)
  211885. {
  211886. struct stat info;
  211887. const int res = stat (fileNameUTF8, &info);
  211888. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  211889. exists = false;
  211890. }
  211891. return exists;
  211892. }
  211893. int64 juce_getFileSize (const String& fileName) throw()
  211894. {
  211895. struct stat info;
  211896. return juce_stat (fileName, info) ? info.st_size : 0;
  211897. }
  211898. bool juce_canWriteToFile (const String& fileName) throw()
  211899. {
  211900. return access (fileName.toUTF8(), W_OK) == 0;
  211901. }
  211902. bool juce_deleteFile (const String& fileName) throw()
  211903. {
  211904. if (juce_isDirectory (fileName))
  211905. return rmdir ((const char*) fileName.toUTF8()) == 0;
  211906. else
  211907. return remove ((const char*) fileName.toUTF8()) == 0;
  211908. }
  211909. bool juce_moveFile (const String& source, const String& dest) throw()
  211910. {
  211911. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  211912. return true;
  211913. if (juce_canWriteToFile (source)
  211914. && juce_copyFile (source, dest))
  211915. {
  211916. if (juce_deleteFile (source))
  211917. return true;
  211918. juce_deleteFile (dest);
  211919. }
  211920. return false;
  211921. }
  211922. void juce_createDirectory (const String& fileName) throw()
  211923. {
  211924. mkdir (fileName.toUTF8(), 0777);
  211925. }
  211926. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  211927. {
  211928. int flags = O_RDONLY;
  211929. if (forWriting)
  211930. {
  211931. if (juce_fileExists (fileName, false))
  211932. {
  211933. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  211934. if (f != -1)
  211935. lseek (f, 0, SEEK_END);
  211936. return (void*) f;
  211937. }
  211938. else
  211939. {
  211940. flags = O_RDWR + O_CREAT;
  211941. }
  211942. }
  211943. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  211944. }
  211945. void juce_fileClose (void* handle) throw()
  211946. {
  211947. if (handle != 0)
  211948. close ((int) (pointer_sized_int) handle);
  211949. }
  211950. int juce_fileRead (void* handle, void* buffer, int size) throw()
  211951. {
  211952. if (handle != 0)
  211953. return read ((int) (pointer_sized_int) handle, buffer, size);
  211954. return 0;
  211955. }
  211956. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  211957. {
  211958. if (handle != 0)
  211959. return write ((int) (pointer_sized_int) handle, buffer, size);
  211960. return 0;
  211961. }
  211962. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  211963. {
  211964. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  211965. return pos;
  211966. return -1;
  211967. }
  211968. int64 juce_fileGetPosition (void* handle) throw()
  211969. {
  211970. if (handle != 0)
  211971. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  211972. else
  211973. return -1;
  211974. }
  211975. void juce_fileFlush (void* handle) throw()
  211976. {
  211977. if (handle != 0)
  211978. fsync ((int) (pointer_sized_int) handle);
  211979. }
  211980. const File juce_getExecutableFile()
  211981. {
  211982. Dl_info exeInfo;
  211983. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  211984. return File (exeInfo.dli_fname);
  211985. }
  211986. // if this file doesn't exist, find a parent of it that does..
  211987. static bool doStatFS (const File* file, struct statfs& result) throw()
  211988. {
  211989. File f (*file);
  211990. for (int i = 5; --i >= 0;)
  211991. {
  211992. if (f.exists())
  211993. break;
  211994. f = f.getParentDirectory();
  211995. }
  211996. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  211997. }
  211998. int64 File::getBytesFreeOnVolume() const throw()
  211999. {
  212000. struct statfs buf;
  212001. if (doStatFS (this, buf))
  212002. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  212003. return 0;
  212004. }
  212005. int64 File::getVolumeTotalSize() const throw()
  212006. {
  212007. struct statfs buf;
  212008. if (doStatFS (this, buf))
  212009. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  212010. return 0;
  212011. }
  212012. const String juce_getVolumeLabel (const String& filenameOnVolume,
  212013. int& volumeSerialNumber) throw()
  212014. {
  212015. volumeSerialNumber = 0;
  212016. #if JUCE_MAC
  212017. struct VolAttrBuf
  212018. {
  212019. u_int32_t length;
  212020. attrreference_t mountPointRef;
  212021. char mountPointSpace [MAXPATHLEN];
  212022. } attrBuf;
  212023. struct attrlist attrList;
  212024. zerostruct (attrList);
  212025. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  212026. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  212027. File f (filenameOnVolume);
  212028. for (;;)
  212029. {
  212030. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  212031. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  212032. {
  212033. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  212034. (int) attrBuf.mountPointRef.attr_length);
  212035. }
  212036. const File parent (f.getParentDirectory());
  212037. if (f == parent)
  212038. break;
  212039. f = parent;
  212040. }
  212041. #endif
  212042. return String::empty;
  212043. }
  212044. void juce_runSystemCommand (const String& command)
  212045. {
  212046. int result = system ((const char*) command.toUTF8());
  212047. (void) result;
  212048. }
  212049. const String juce_getOutputFromCommand (const String& command)
  212050. {
  212051. // slight bodge here, as we just pipe the output into a temp file and read it...
  212052. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  212053. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  212054. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  212055. String result (tempFile.loadFileAsString());
  212056. tempFile.deleteFile();
  212057. return result;
  212058. }
  212059. #if JUCE_64BIT
  212060. #define filedesc ((long long) internal)
  212061. #else
  212062. #define filedesc ((int) internal)
  212063. #endif
  212064. InterProcessLock::InterProcessLock (const String& name_) throw()
  212065. : internal (0),
  212066. name (name_),
  212067. reentrancyLevel (0)
  212068. {
  212069. #if JUCE_MAC
  212070. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  212071. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  212072. #else
  212073. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  212074. #endif
  212075. temp.create();
  212076. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  212077. }
  212078. InterProcessLock::~InterProcessLock() throw()
  212079. {
  212080. while (reentrancyLevel > 0)
  212081. this->exit();
  212082. close (filedesc);
  212083. }
  212084. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  212085. {
  212086. if (internal == 0)
  212087. return false;
  212088. if (reentrancyLevel != 0)
  212089. return true;
  212090. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  212091. struct flock fl;
  212092. zerostruct (fl);
  212093. fl.l_whence = SEEK_SET;
  212094. fl.l_type = F_WRLCK;
  212095. for (;;)
  212096. {
  212097. const int result = fcntl (filedesc, F_SETLK, &fl);
  212098. if (result >= 0)
  212099. {
  212100. ++reentrancyLevel;
  212101. return true;
  212102. }
  212103. if (errno != EINTR)
  212104. {
  212105. if (timeOutMillisecs == 0
  212106. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  212107. break;
  212108. Thread::sleep (10);
  212109. }
  212110. }
  212111. return false;
  212112. }
  212113. void InterProcessLock::exit() throw()
  212114. {
  212115. if (reentrancyLevel > 0 && internal != 0)
  212116. {
  212117. --reentrancyLevel;
  212118. struct flock fl;
  212119. zerostruct (fl);
  212120. fl.l_whence = SEEK_SET;
  212121. fl.l_type = F_UNLCK;
  212122. for (;;)
  212123. {
  212124. const int result = fcntl (filedesc, F_SETLKW, &fl);
  212125. if (result >= 0 || errno != EINTR)
  212126. break;
  212127. }
  212128. }
  212129. }
  212130. /********* End of inlined file: juce_posix_SharedCode.h *********/
  212131. /********* Start of inlined file: juce_linux_Files.cpp *********/
  212132. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212133. // compiled on its own).
  212134. #ifdef JUCE_INCLUDED_FILE
  212135. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  212136. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  212137. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  212138. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  212139. void juce_getFileTimes (const String& fileName,
  212140. int64& modificationTime,
  212141. int64& accessTime,
  212142. int64& creationTime) throw()
  212143. {
  212144. modificationTime = 0;
  212145. accessTime = 0;
  212146. creationTime = 0;
  212147. struct stat info;
  212148. const int res = stat (fileName.toUTF8(), &info);
  212149. if (res == 0)
  212150. {
  212151. modificationTime = (int64) info.st_mtime * 1000;
  212152. accessTime = (int64) info.st_atime * 1000;
  212153. creationTime = (int64) info.st_ctime * 1000;
  212154. }
  212155. }
  212156. bool juce_setFileTimes (const String& fileName,
  212157. int64 modificationTime,
  212158. int64 accessTime,
  212159. int64 creationTime) throw()
  212160. {
  212161. struct utimbuf times;
  212162. times.actime = (time_t) (accessTime / 1000);
  212163. times.modtime = (time_t) (modificationTime / 1000);
  212164. return utime (fileName.toUTF8(), &times) == 0;
  212165. }
  212166. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  212167. {
  212168. struct stat info;
  212169. const int res = stat (fileName.toUTF8(), &info);
  212170. if (res != 0)
  212171. return false;
  212172. info.st_mode &= 0777; // Just permissions
  212173. if( isReadOnly )
  212174. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  212175. else
  212176. // Give everybody write permission?
  212177. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  212178. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  212179. }
  212180. bool juce_copyFile (const String& s, const String& d) throw()
  212181. {
  212182. const File source (s), dest (d);
  212183. FileInputStream* in = source.createInputStream();
  212184. bool ok = false;
  212185. if (in != 0)
  212186. {
  212187. if (dest.deleteFile())
  212188. {
  212189. FileOutputStream* const out = dest.createOutputStream();
  212190. if (out != 0)
  212191. {
  212192. const int bytesCopied = out->writeFromInputStream (*in, -1);
  212193. delete out;
  212194. ok = (bytesCopied == source.getSize());
  212195. if (! ok)
  212196. dest.deleteFile();
  212197. }
  212198. }
  212199. delete in;
  212200. }
  212201. return ok;
  212202. }
  212203. const StringArray juce_getFileSystemRoots() throw()
  212204. {
  212205. StringArray s;
  212206. s.add (T("/"));
  212207. return s;
  212208. }
  212209. bool File::isOnCDRomDrive() const throw()
  212210. {
  212211. struct statfs buf;
  212212. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212213. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  212214. // Assume not if this fails for some reason
  212215. return false;
  212216. }
  212217. bool File::isOnHardDisk() const throw()
  212218. {
  212219. struct statfs buf;
  212220. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212221. {
  212222. switch (buf.f_type)
  212223. {
  212224. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  212225. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  212226. case U_NFS_SUPER_MAGIC: // Network NFS
  212227. case U_SMB_SUPER_MAGIC: // Network Samba
  212228. return false;
  212229. default:
  212230. // Assume anything else is a hard-disk (but note it could
  212231. // be a RAM disk. There isn't a good way of determining
  212232. // this for sure)
  212233. return true;
  212234. }
  212235. }
  212236. // Assume so if this fails for some reason
  212237. return true;
  212238. }
  212239. bool File::isOnRemovableDrive() const throw()
  212240. {
  212241. jassertfalse // xxx not implemented for linux!
  212242. return false;
  212243. }
  212244. bool File::isHidden() const throw()
  212245. {
  212246. return getFileName().startsWithChar (T('.'));
  212247. }
  212248. const File File::getSpecialLocation (const SpecialLocationType type)
  212249. {
  212250. switch (type)
  212251. {
  212252. case userHomeDirectory:
  212253. {
  212254. const char* homeDir = getenv ("HOME");
  212255. if (homeDir == 0)
  212256. {
  212257. struct passwd* const pw = getpwuid (getuid());
  212258. if (pw != 0)
  212259. homeDir = pw->pw_dir;
  212260. }
  212261. return File (String::fromUTF8 ((const uint8*) homeDir));
  212262. }
  212263. case userDocumentsDirectory:
  212264. case userMusicDirectory:
  212265. case userMoviesDirectory:
  212266. case userApplicationDataDirectory:
  212267. return File ("~");
  212268. case userDesktopDirectory:
  212269. return File ("~/Desktop");
  212270. case commonApplicationDataDirectory:
  212271. return File ("/var");
  212272. case globalApplicationsDirectory:
  212273. return File ("/usr");
  212274. case tempDirectory:
  212275. {
  212276. File tmp ("/var/tmp");
  212277. if (! tmp.isDirectory())
  212278. {
  212279. tmp = T("/tmp");
  212280. if (! tmp.isDirectory())
  212281. tmp = File::getCurrentWorkingDirectory();
  212282. }
  212283. return tmp;
  212284. }
  212285. case currentExecutableFile:
  212286. case currentApplicationFile:
  212287. return juce_getExecutableFile();
  212288. default:
  212289. jassertfalse // unknown type?
  212290. break;
  212291. }
  212292. return File::nonexistent;
  212293. }
  212294. const File File::getCurrentWorkingDirectory() throw()
  212295. {
  212296. char buf [2048];
  212297. return File (String::fromUTF8 ((const uint8*) getcwd (buf, sizeof (buf))));
  212298. }
  212299. bool File::setAsCurrentWorkingDirectory() const throw()
  212300. {
  212301. return chdir (getFullPathName().toUTF8()) == 0;
  212302. }
  212303. const String File::getVersion() const throw()
  212304. {
  212305. return String::empty; // xxx not yet implemented
  212306. }
  212307. const File File::getLinkedTarget() const throw()
  212308. {
  212309. char buffer [4096];
  212310. size_t numChars = readlink ((const char*) getFullPathName().toUTF8(),
  212311. buffer, sizeof (buffer));
  212312. if (numChars > 0 && numChars <= sizeof (buffer))
  212313. return File (String::fromUTF8 ((const uint8*) buffer, (int) numChars));
  212314. return *this;
  212315. }
  212316. bool File::moveToTrash() const throw()
  212317. {
  212318. if (! exists())
  212319. return true;
  212320. File trashCan (T("~/.Trash"));
  212321. if (! trashCan.isDirectory())
  212322. trashCan = T("~/.local/share/Trash/files");
  212323. if (! trashCan.isDirectory())
  212324. return false;
  212325. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  212326. getFileExtension()));
  212327. }
  212328. struct FindFileStruct
  212329. {
  212330. String parentDir, wildCard;
  212331. DIR* dir;
  212332. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  212333. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  212334. {
  212335. const char* const wildcardUTF8 = wildCard.toUTF8();
  212336. for (;;)
  212337. {
  212338. struct dirent* const de = readdir (dir);
  212339. if (de == 0)
  212340. break;
  212341. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  212342. {
  212343. result = String::fromUTF8 ((const uint8*) de->d_name);
  212344. const String path (parentDir + result);
  212345. if (isDir != 0 || fileSize != 0)
  212346. {
  212347. struct stat info;
  212348. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  212349. if (isDir != 0)
  212350. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  212351. if (isHidden != 0)
  212352. *isHidden = (de->d_name[0] == '.');
  212353. if (fileSize != 0)
  212354. *fileSize = statOk ? info.st_size : 0;
  212355. }
  212356. if (modTime != 0 || creationTime != 0)
  212357. {
  212358. int64 m, a, c;
  212359. juce_getFileTimes (path, m, a, c);
  212360. if (modTime != 0)
  212361. *modTime = m;
  212362. if (creationTime != 0)
  212363. *creationTime = c;
  212364. }
  212365. if (isReadOnly != 0)
  212366. *isReadOnly = ! juce_canWriteToFile (path);
  212367. return true;
  212368. }
  212369. }
  212370. return false;
  212371. }
  212372. };
  212373. // returns 0 on failure
  212374. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  212375. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  212376. Time* creationTime, bool* isReadOnly) throw()
  212377. {
  212378. DIR* d = opendir (directory.toUTF8());
  212379. if (d != 0)
  212380. {
  212381. FindFileStruct* ff = new FindFileStruct();
  212382. ff->parentDir = directory;
  212383. if (!ff->parentDir.endsWithChar (File::separator))
  212384. ff->parentDir += File::separator;
  212385. ff->wildCard = wildCard;
  212386. if (wildCard == T("*.*"))
  212387. ff->wildCard = T("*");
  212388. ff->dir = d;
  212389. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  212390. {
  212391. return ff;
  212392. }
  212393. else
  212394. {
  212395. firstResultFile = String::empty;
  212396. isDir = false;
  212397. isHidden = false;
  212398. closedir (d);
  212399. delete ff;
  212400. }
  212401. }
  212402. return 0;
  212403. }
  212404. bool juce_findFileNext (void* handle, String& resultFile,
  212405. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  212406. {
  212407. FindFileStruct* const ff = (FindFileStruct*) handle;
  212408. if (ff != 0)
  212409. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  212410. return false;
  212411. }
  212412. void juce_findFileClose (void* handle) throw()
  212413. {
  212414. FindFileStruct* const ff = (FindFileStruct*) handle;
  212415. if (ff != 0)
  212416. {
  212417. closedir (ff->dir);
  212418. delete ff;
  212419. }
  212420. }
  212421. bool juce_launchFile (const String& fileName,
  212422. const String& parameters) throw()
  212423. {
  212424. String cmdString (fileName);
  212425. cmdString << " " << parameters;
  212426. if (URL::isProbablyAWebsiteURL (fileName)
  212427. || URL::isProbablyAnEmailAddress (fileName))
  212428. {
  212429. // create a command that tries to launch a bunch of likely browsers
  212430. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  212431. StringArray cmdLines;
  212432. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  212433. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  212434. cmdString = cmdLines.joinIntoString (T(" || "));
  212435. }
  212436. if (cmdString.startsWithIgnoreCase (T("file:")))
  212437. cmdString = cmdString.substring (5);
  212438. const char* const argv[4] = { "/bin/sh", "-c", (const char*) cmdString.toUTF8(), 0 };
  212439. const int cpid = fork();
  212440. if (cpid == 0)
  212441. {
  212442. setsid();
  212443. // Child process
  212444. execve (argv[0], (char**) argv, environ);
  212445. exit (0);
  212446. }
  212447. return cpid >= 0;
  212448. }
  212449. #endif
  212450. /********* End of inlined file: juce_linux_Files.cpp *********/
  212451. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  212452. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  212453. // compiled on its own).
  212454. #if JUCE_INCLUDED_FILE
  212455. struct NamedPipeInternal
  212456. {
  212457. String pipeInName, pipeOutName;
  212458. int pipeIn, pipeOut;
  212459. bool volatile createdPipe, blocked, stopReadOperation;
  212460. static void signalHandler (int) {}
  212461. };
  212462. void NamedPipe::cancelPendingReads()
  212463. {
  212464. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  212465. {
  212466. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  212467. intern->stopReadOperation = true;
  212468. char buffer [1] = { 0 };
  212469. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  212470. (void) bytesWritten;
  212471. int timeout = 2000;
  212472. while (intern->blocked && --timeout >= 0)
  212473. Thread::sleep (2);
  212474. intern->stopReadOperation = false;
  212475. }
  212476. }
  212477. void NamedPipe::close()
  212478. {
  212479. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  212480. if (intern != 0)
  212481. {
  212482. internal = 0;
  212483. if (intern->pipeIn != -1)
  212484. ::close (intern->pipeIn);
  212485. if (intern->pipeOut != -1)
  212486. ::close (intern->pipeOut);
  212487. if (intern->createdPipe)
  212488. {
  212489. unlink (intern->pipeInName);
  212490. unlink (intern->pipeOutName);
  212491. }
  212492. delete intern;
  212493. }
  212494. }
  212495. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  212496. {
  212497. close();
  212498. NamedPipeInternal* const intern = new NamedPipeInternal();
  212499. internal = intern;
  212500. intern->createdPipe = createPipe;
  212501. intern->blocked = false;
  212502. intern->stopReadOperation = false;
  212503. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  212504. siginterrupt (SIGPIPE, 1);
  212505. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  212506. intern->pipeInName = pipePath + T("_in");
  212507. intern->pipeOutName = pipePath + T("_out");
  212508. intern->pipeIn = -1;
  212509. intern->pipeOut = -1;
  212510. if (createPipe)
  212511. {
  212512. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  212513. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  212514. {
  212515. delete intern;
  212516. internal = 0;
  212517. return false;
  212518. }
  212519. }
  212520. return true;
  212521. }
  212522. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  212523. {
  212524. int bytesRead = -1;
  212525. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  212526. if (intern != 0)
  212527. {
  212528. intern->blocked = true;
  212529. if (intern->pipeIn == -1)
  212530. {
  212531. if (intern->createdPipe)
  212532. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  212533. else
  212534. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  212535. if (intern->pipeIn == -1)
  212536. {
  212537. intern->blocked = false;
  212538. return -1;
  212539. }
  212540. }
  212541. bytesRead = 0;
  212542. char* p = (char*) destBuffer;
  212543. while (bytesRead < maxBytesToRead)
  212544. {
  212545. const int bytesThisTime = maxBytesToRead - bytesRead;
  212546. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  212547. if (numRead <= 0 || intern->stopReadOperation)
  212548. {
  212549. bytesRead = -1;
  212550. break;
  212551. }
  212552. bytesRead += numRead;
  212553. p += bytesRead;
  212554. }
  212555. intern->blocked = false;
  212556. }
  212557. return bytesRead;
  212558. }
  212559. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  212560. {
  212561. int bytesWritten = -1;
  212562. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  212563. if (intern != 0)
  212564. {
  212565. if (intern->pipeOut == -1)
  212566. {
  212567. if (intern->createdPipe)
  212568. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  212569. else
  212570. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  212571. if (intern->pipeOut == -1)
  212572. {
  212573. return -1;
  212574. }
  212575. }
  212576. const char* p = (const char*) sourceBuffer;
  212577. bytesWritten = 0;
  212578. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  212579. while (bytesWritten < numBytesToWrite
  212580. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  212581. {
  212582. const int bytesThisTime = numBytesToWrite - bytesWritten;
  212583. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  212584. if (numWritten <= 0)
  212585. {
  212586. bytesWritten = -1;
  212587. break;
  212588. }
  212589. bytesWritten += numWritten;
  212590. p += bytesWritten;
  212591. }
  212592. }
  212593. return bytesWritten;
  212594. }
  212595. #endif
  212596. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  212597. /********* Start of inlined file: juce_linux_Network.cpp *********/
  212598. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212599. // compiled on its own).
  212600. #ifdef JUCE_INCLUDED_FILE
  212601. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  212602. {
  212603. int numResults = 0;
  212604. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  212605. if (s != -1)
  212606. {
  212607. char buf [1024];
  212608. struct ifconf ifc;
  212609. ifc.ifc_len = sizeof (buf);
  212610. ifc.ifc_buf = buf;
  212611. ioctl (s, SIOCGIFCONF, &ifc);
  212612. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  212613. {
  212614. struct ifreq ifr;
  212615. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  212616. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  212617. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  212618. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  212619. && numResults < maxNum)
  212620. {
  212621. int64 a = 0;
  212622. for (int j = 6; --j >= 0;)
  212623. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data[j];
  212624. *addresses++ = a;
  212625. ++numResults;
  212626. }
  212627. }
  212628. close (s);
  212629. }
  212630. return numResults;
  212631. }
  212632. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  212633. const String& emailSubject,
  212634. const String& bodyText,
  212635. const StringArray& filesToAttach)
  212636. {
  212637. jassertfalse // xxx todo
  212638. return false;
  212639. }
  212640. /** A HTTP input stream that uses sockets.
  212641. */
  212642. class JUCE_HTTPSocketStream
  212643. {
  212644. public:
  212645. JUCE_HTTPSocketStream()
  212646. : readPosition (0),
  212647. socketHandle (-1),
  212648. levelsOfRedirection (0),
  212649. timeoutSeconds (15)
  212650. {
  212651. }
  212652. ~JUCE_HTTPSocketStream()
  212653. {
  212654. closeSocket();
  212655. }
  212656. bool open (const String& url,
  212657. const String& headers,
  212658. const MemoryBlock& postData,
  212659. const bool isPost,
  212660. URL::OpenStreamProgressCallback* callback,
  212661. void* callbackContext,
  212662. int timeOutMs)
  212663. {
  212664. closeSocket();
  212665. uint32 timeOutTime = Time::getMillisecondCounter();
  212666. if (timeOutMs == 0)
  212667. timeOutTime += 60000;
  212668. else if (timeOutMs < 0)
  212669. timeOutTime = 0xffffffff;
  212670. else
  212671. timeOutTime += timeOutMs;
  212672. String hostName, hostPath;
  212673. int hostPort;
  212674. if (! decomposeURL (url, hostName, hostPath, hostPort))
  212675. return false;
  212676. const struct hostent* host = 0;
  212677. int port = 0;
  212678. String proxyName, proxyPath;
  212679. int proxyPort = 0;
  212680. String proxyURL (getenv ("http_proxy"));
  212681. if (proxyURL.startsWithIgnoreCase (T("http://")))
  212682. {
  212683. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  212684. return false;
  212685. host = gethostbyname ((const char*) proxyName.toUTF8());
  212686. port = proxyPort;
  212687. }
  212688. else
  212689. {
  212690. host = gethostbyname ((const char*) hostName.toUTF8());
  212691. port = hostPort;
  212692. }
  212693. if (host == 0)
  212694. return false;
  212695. struct sockaddr_in address;
  212696. zerostruct (address);
  212697. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  212698. address.sin_family = host->h_addrtype;
  212699. address.sin_port = htons (port);
  212700. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  212701. if (socketHandle == -1)
  212702. return false;
  212703. int receiveBufferSize = 16384;
  212704. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  212705. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  212706. #if JUCE_MAC
  212707. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  212708. #endif
  212709. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  212710. {
  212711. closeSocket();
  212712. return false;
  212713. }
  212714. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  212715. proxyName, proxyPort,
  212716. hostPath, url,
  212717. headers, postData,
  212718. isPost));
  212719. int totalHeaderSent = 0;
  212720. while (totalHeaderSent < requestHeader.getSize())
  212721. {
  212722. if (Time::getMillisecondCounter() > timeOutTime)
  212723. {
  212724. closeSocket();
  212725. return false;
  212726. }
  212727. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  212728. if (send (socketHandle,
  212729. ((const char*) requestHeader.getData()) + totalHeaderSent,
  212730. numToSend, 0)
  212731. != numToSend)
  212732. {
  212733. closeSocket();
  212734. return false;
  212735. }
  212736. totalHeaderSent += numToSend;
  212737. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  212738. {
  212739. closeSocket();
  212740. return false;
  212741. }
  212742. }
  212743. const String responseHeader (readResponse (timeOutTime));
  212744. if (responseHeader.isNotEmpty())
  212745. {
  212746. //DBG (responseHeader);
  212747. StringArray lines;
  212748. lines.addLines (responseHeader);
  212749. // NB - using charToString() here instead of just T(" "), because that was
  212750. // causing a mysterious gcc internal compiler error...
  212751. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  212752. .substring (0, 3).getIntValue();
  212753. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  212754. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  212755. String location (findHeaderItem (lines, T("Location:")));
  212756. if (statusCode >= 300 && statusCode < 400
  212757. && location.isNotEmpty())
  212758. {
  212759. if (! location.startsWithIgnoreCase (T("http://")))
  212760. location = T("http://") + location;
  212761. if (levelsOfRedirection++ < 3)
  212762. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  212763. }
  212764. else
  212765. {
  212766. levelsOfRedirection = 0;
  212767. return true;
  212768. }
  212769. }
  212770. closeSocket();
  212771. return false;
  212772. }
  212773. int read (void* buffer, int bytesToRead)
  212774. {
  212775. fd_set readbits;
  212776. FD_ZERO (&readbits);
  212777. FD_SET (socketHandle, &readbits);
  212778. struct timeval tv;
  212779. tv.tv_sec = timeoutSeconds;
  212780. tv.tv_usec = 0;
  212781. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  212782. return 0; // (timeout)
  212783. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  212784. readPosition += bytesRead;
  212785. return bytesRead;
  212786. }
  212787. int readPosition;
  212788. juce_UseDebuggingNewOperator
  212789. private:
  212790. int socketHandle, levelsOfRedirection;
  212791. const int timeoutSeconds;
  212792. void closeSocket()
  212793. {
  212794. if (socketHandle >= 0)
  212795. close (socketHandle);
  212796. socketHandle = -1;
  212797. }
  212798. const MemoryBlock createRequestHeader (const String& hostName,
  212799. const int hostPort,
  212800. const String& proxyName,
  212801. const int proxyPort,
  212802. const String& hostPath,
  212803. const String& originalURL,
  212804. const String& headers,
  212805. const MemoryBlock& postData,
  212806. const bool isPost)
  212807. {
  212808. String header (isPost ? "POST " : "GET ");
  212809. if (proxyName.isEmpty())
  212810. {
  212811. header << hostPath << " HTTP/1.0\r\nHost: "
  212812. << hostName << ':' << hostPort;
  212813. }
  212814. else
  212815. {
  212816. header << originalURL << " HTTP/1.0\r\nHost: "
  212817. << proxyName << ':' << proxyPort;
  212818. }
  212819. header << "\r\nUser-Agent: JUCE/"
  212820. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  212821. << "\r\nConnection: Close\r\nContent-Length: "
  212822. << postData.getSize() << "\r\n"
  212823. << headers << "\r\n";
  212824. MemoryBlock mb;
  212825. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  212826. mb.append (postData.getData(), postData.getSize());
  212827. return mb;
  212828. }
  212829. const String readResponse (const uint32 timeOutTime)
  212830. {
  212831. int bytesRead = 0, numConsecutiveLFs = 0;
  212832. MemoryBlock buffer (1024, true);
  212833. while (numConsecutiveLFs < 2 && bytesRead < 32768
  212834. && Time::getMillisecondCounter() <= timeOutTime)
  212835. {
  212836. fd_set readbits;
  212837. FD_ZERO (&readbits);
  212838. FD_SET (socketHandle, &readbits);
  212839. struct timeval tv;
  212840. tv.tv_sec = timeoutSeconds;
  212841. tv.tv_usec = 0;
  212842. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  212843. return String::empty; // (timeout)
  212844. buffer.ensureSize (bytesRead + 8, true);
  212845. char* const dest = (char*) buffer.getData() + bytesRead;
  212846. if (recv (socketHandle, dest, 1, 0) == -1)
  212847. return String::empty;
  212848. const char lastByte = *dest;
  212849. ++bytesRead;
  212850. if (lastByte == '\n')
  212851. ++numConsecutiveLFs;
  212852. else if (lastByte != '\r')
  212853. numConsecutiveLFs = 0;
  212854. }
  212855. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  212856. if (header.startsWithIgnoreCase (T("HTTP/")))
  212857. return header.trimEnd();
  212858. return String::empty;
  212859. }
  212860. static bool decomposeURL (const String& url,
  212861. String& host, String& path, int& port)
  212862. {
  212863. if (! url.startsWithIgnoreCase (T("http://")))
  212864. return false;
  212865. const int nextSlash = url.indexOfChar (7, '/');
  212866. int nextColon = url.indexOfChar (7, ':');
  212867. if (nextColon > nextSlash && nextSlash > 0)
  212868. nextColon = -1;
  212869. if (nextColon >= 0)
  212870. {
  212871. host = url.substring (7, nextColon);
  212872. if (nextSlash >= 0)
  212873. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  212874. else
  212875. port = url.substring (nextColon + 1).getIntValue();
  212876. }
  212877. else
  212878. {
  212879. port = 80;
  212880. if (nextSlash >= 0)
  212881. host = url.substring (7, nextSlash);
  212882. else
  212883. host = url.substring (7);
  212884. }
  212885. if (nextSlash >= 0)
  212886. path = url.substring (nextSlash);
  212887. else
  212888. path = T("/");
  212889. return true;
  212890. }
  212891. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  212892. {
  212893. for (int i = 0; i < lines.size(); ++i)
  212894. if (lines[i].startsWithIgnoreCase (itemName))
  212895. return lines[i].substring (itemName.length()).trim();
  212896. return String::empty;
  212897. }
  212898. };
  212899. bool juce_isOnLine()
  212900. {
  212901. return true;
  212902. }
  212903. void* juce_openInternetFile (const String& url,
  212904. const String& headers,
  212905. const MemoryBlock& postData,
  212906. const bool isPost,
  212907. URL::OpenStreamProgressCallback* callback,
  212908. void* callbackContext,
  212909. int timeOutMs)
  212910. {
  212911. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  212912. if (s->open (url, headers, postData, isPost,
  212913. callback, callbackContext, timeOutMs))
  212914. return s;
  212915. delete s;
  212916. return 0;
  212917. }
  212918. void juce_closeInternetFile (void* handle)
  212919. {
  212920. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  212921. if (s != 0)
  212922. delete s;
  212923. }
  212924. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  212925. {
  212926. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  212927. if (s != 0)
  212928. return s->read (buffer, bytesToRead);
  212929. return 0;
  212930. }
  212931. int64 juce_getInternetFileContentLength (void* handle)
  212932. {
  212933. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  212934. if (s != 0)
  212935. {
  212936. //xxx todo
  212937. jassertfalse
  212938. }
  212939. return -1;
  212940. }
  212941. int juce_seekInInternetFile (void* handle, int newPosition)
  212942. {
  212943. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  212944. if (s != 0)
  212945. return s->readPosition;
  212946. return 0;
  212947. }
  212948. #endif
  212949. /********* End of inlined file: juce_linux_Network.cpp *********/
  212950. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  212951. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212952. // compiled on its own).
  212953. #ifdef JUCE_INCLUDED_FILE
  212954. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  212955. {
  212956. unsigned int cpu = 0;
  212957. unsigned int ext = 0;
  212958. unsigned int family = 0;
  212959. unsigned int dummy = 0;
  212960. #if JUCE_64BIT
  212961. __asm__ ("cpuid"
  212962. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  212963. #else
  212964. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  212965. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  212966. #endif
  212967. if (familyModel != 0)
  212968. *familyModel = family;
  212969. if (extFeatures != 0)
  212970. *extFeatures = ext;
  212971. return cpu;
  212972. }*/
  212973. void Logger::outputDebugString (const String& text) throw()
  212974. {
  212975. fputs (text.toUTF8(), stdout);
  212976. fputs ("\n", stdout);
  212977. }
  212978. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  212979. {
  212980. String text;
  212981. va_list args;
  212982. va_start (args, format);
  212983. text.vprintf(format, args);
  212984. outputDebugString(text);
  212985. }
  212986. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  212987. {
  212988. return Linux;
  212989. }
  212990. const String SystemStats::getOperatingSystemName() throw()
  212991. {
  212992. return T("Linux");
  212993. }
  212994. bool SystemStats::isOperatingSystem64Bit() throw()
  212995. {
  212996. #if JUCE_64BIT
  212997. return true;
  212998. #else
  212999. //xxx not sure how to find this out?..
  213000. return false;
  213001. #endif
  213002. }
  213003. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  213004. {
  213005. String info;
  213006. char buf [256];
  213007. FILE* f = fopen ("/proc/cpuinfo", "r");
  213008. while (f != 0 && fgets (buf, sizeof(buf), f))
  213009. {
  213010. if (strncmp (buf, key, strlen (key)) == 0)
  213011. {
  213012. char* p = buf;
  213013. while (*p && *p != '\n')
  213014. ++p;
  213015. if (*p != 0)
  213016. *p = 0;
  213017. p = buf;
  213018. while (*p != 0 && *p != ':')
  213019. ++p;
  213020. if (*p != 0 && *(p + 1) != 0)
  213021. info = p + 2;
  213022. if (! lastOne)
  213023. break;
  213024. }
  213025. }
  213026. fclose (f);
  213027. return info;
  213028. }
  213029. bool SystemStats::hasMMX() throw()
  213030. {
  213031. return getCpuInfo ("flags").contains (T("mmx"));
  213032. }
  213033. bool SystemStats::hasSSE() throw()
  213034. {
  213035. return getCpuInfo ("flags").contains (T("sse"));
  213036. }
  213037. bool SystemStats::hasSSE2() throw()
  213038. {
  213039. return getCpuInfo ("flags").contains (T("sse2"));
  213040. }
  213041. bool SystemStats::has3DNow() throw()
  213042. {
  213043. return getCpuInfo ("flags").contains (T("3dnow"));
  213044. }
  213045. const String SystemStats::getCpuVendor() throw()
  213046. {
  213047. return getCpuInfo ("vendor_id");
  213048. }
  213049. int SystemStats::getCpuSpeedInMegaherz() throw()
  213050. {
  213051. const String speed (getCpuInfo ("cpu MHz"));
  213052. return (int) (speed.getFloatValue() + 0.5f);
  213053. }
  213054. int SystemStats::getMemorySizeInMegabytes() throw()
  213055. {
  213056. struct sysinfo sysi;
  213057. if (sysinfo (&sysi) == 0)
  213058. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  213059. return 0;
  213060. }
  213061. uint32 juce_millisecondsSinceStartup() throw()
  213062. {
  213063. static unsigned int calibrate = 0;
  213064. static bool calibrated = false;
  213065. timeval t;
  213066. unsigned int ret = 0;
  213067. if (! gettimeofday (&t, 0))
  213068. {
  213069. if (! calibrated)
  213070. {
  213071. struct sysinfo sysi;
  213072. if (sysinfo (&sysi) == 0)
  213073. // Safe to assume system was not brought up earlier than 1970!
  213074. calibrate = t.tv_sec - sysi.uptime;
  213075. calibrated = true;
  213076. }
  213077. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  213078. }
  213079. return ret;
  213080. }
  213081. double Time::getMillisecondCounterHiRes() throw()
  213082. {
  213083. return getHighResolutionTicks() * 0.001;
  213084. }
  213085. int64 Time::getHighResolutionTicks() throw()
  213086. {
  213087. timeval t;
  213088. if (gettimeofday (&t, 0))
  213089. return 0;
  213090. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  213091. }
  213092. int64 Time::getHighResolutionTicksPerSecond() throw()
  213093. {
  213094. // Microseconds
  213095. return 1000000;
  213096. }
  213097. bool Time::setSystemTimeToThisTime() const throw()
  213098. {
  213099. timeval t;
  213100. t.tv_sec = millisSinceEpoch % 1000000;
  213101. t.tv_usec = millisSinceEpoch - t.tv_sec;
  213102. return settimeofday (&t, NULL) ? false : true;
  213103. }
  213104. int SystemStats::getPageSize() throw()
  213105. {
  213106. static int systemPageSize = 0;
  213107. if (systemPageSize == 0)
  213108. systemPageSize = sysconf (_SC_PAGESIZE);
  213109. return systemPageSize;
  213110. }
  213111. int SystemStats::getNumCpus() throw()
  213112. {
  213113. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  213114. return lastCpu + 1;
  213115. }
  213116. void SystemStats::initialiseStats() throw()
  213117. {
  213118. // Process starts off as root when running suid
  213119. Process::lowerPrivilege();
  213120. String s (SystemStats::getJUCEVersion());
  213121. }
  213122. void PlatformUtilities::fpuReset()
  213123. {
  213124. }
  213125. #endif
  213126. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  213127. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  213128. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213129. // compiled on its own).
  213130. #ifdef JUCE_INCLUDED_FILE
  213131. /*
  213132. Note that a lot of methods that you'd expect to find in this file actually
  213133. live in juce_posix_SharedCode.h!
  213134. */
  213135. void JUCE_API juce_threadEntryPoint (void*);
  213136. void* threadEntryProc (void* value) throw()
  213137. {
  213138. // New threads start off as root when running suid
  213139. Process::lowerPrivilege();
  213140. juce_threadEntryPoint (value);
  213141. return 0;
  213142. }
  213143. void* juce_createThread (void* userData) throw()
  213144. {
  213145. pthread_t handle = 0;
  213146. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  213147. {
  213148. pthread_detach (handle);
  213149. return (void*)handle;
  213150. }
  213151. return 0;
  213152. }
  213153. void juce_killThread (void* handle) throw()
  213154. {
  213155. if (handle != 0)
  213156. pthread_cancel ((pthread_t)handle);
  213157. }
  213158. void juce_setCurrentThreadName (const String& /*name*/) throw()
  213159. {
  213160. }
  213161. Thread::ThreadID Thread::getCurrentThreadId() throw()
  213162. {
  213163. return (ThreadID) pthread_self();
  213164. }
  213165. /*
  213166. * This is all a bit non-ideal... the trouble is that on Linux you
  213167. * need to call setpriority to affect the dynamic priority for
  213168. * non-realtime processes, but this requires the pid, which is not
  213169. * accessible from the pthread_t. We could get it by calling getpid
  213170. * once each thread has started, but then we would need a list of
  213171. * running threads etc etc.
  213172. * Also there is no such thing as IDLE priority on Linux.
  213173. * For the moment, map idle, low and normal process priorities to
  213174. * SCHED_OTHER, with the thread priority ignored for these classes.
  213175. * Map high priority processes to the lower half of the SCHED_RR
  213176. * range, and realtime to the upper half
  213177. */
  213178. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  213179. // priority of the current thread
  213180. bool juce_setThreadPriority (void* handle, int priority) throw()
  213181. {
  213182. struct sched_param param;
  213183. int policy, maxp, minp, pri;
  213184. if (handle == 0)
  213185. handle = (void*) pthread_self();
  213186. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  213187. && policy != SCHED_OTHER)
  213188. {
  213189. minp = sched_get_priority_min(policy);
  213190. maxp = sched_get_priority_max(policy);
  213191. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  213192. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  213193. // Realtime process priority
  213194. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  213195. else
  213196. // High process priority
  213197. param.__sched_priority = minp + pri;
  213198. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  213199. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  213200. }
  213201. return false;
  213202. }
  213203. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  213204. {
  213205. #if SUPPORT_AFFINITIES
  213206. cpu_set_t affinity;
  213207. CPU_ZERO (&affinity);
  213208. for (int i = 0; i < 32; ++i)
  213209. if ((affinityMask & (1 << i)) != 0)
  213210. CPU_SET (i, &affinity);
  213211. /*
  213212. N.B. If this line causes a compile error, then you've probably not got the latest
  213213. version of glibc installed.
  213214. If you don't want to update your copy of glibc and don't care about cpu affinities,
  213215. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  213216. from the linuxincludes.h file.
  213217. */
  213218. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  213219. sched_yield();
  213220. #else
  213221. /* affinities aren't supported because either the appropriate header files weren't found,
  213222. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  213223. */
  213224. jassertfalse
  213225. #endif
  213226. }
  213227. void Thread::yield() throw()
  213228. {
  213229. sched_yield();
  213230. }
  213231. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  213232. void Process::setPriority (ProcessPriority prior)
  213233. {
  213234. struct sched_param param;
  213235. int policy, maxp, minp;
  213236. const int p = (int) prior;
  213237. if (p <= 1)
  213238. policy = SCHED_OTHER;
  213239. else
  213240. policy = SCHED_RR;
  213241. minp = sched_get_priority_min (policy);
  213242. maxp = sched_get_priority_max (policy);
  213243. if (p < 2)
  213244. param.__sched_priority = 0;
  213245. else if (p == 2 )
  213246. // Set to middle of lower realtime priority range
  213247. param.__sched_priority = minp + (maxp - minp) / 4;
  213248. else
  213249. // Set to middle of higher realtime priority range
  213250. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  213251. pthread_setschedparam (pthread_self(), policy, &param);
  213252. }
  213253. void Process::terminate()
  213254. {
  213255. exit (0);
  213256. }
  213257. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  213258. {
  213259. static char testResult = 0;
  213260. if (testResult == 0)
  213261. {
  213262. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  213263. if (testResult >= 0)
  213264. {
  213265. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  213266. testResult = 1;
  213267. }
  213268. }
  213269. return testResult < 0;
  213270. }
  213271. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  213272. {
  213273. return juce_isRunningUnderDebugger();
  213274. }
  213275. void Process::raisePrivilege()
  213276. {
  213277. // If running suid root, change effective user
  213278. // to root
  213279. if (geteuid() != 0 && getuid() == 0)
  213280. {
  213281. setreuid (geteuid(), getuid());
  213282. setregid (getegid(), getgid());
  213283. }
  213284. }
  213285. void Process::lowerPrivilege()
  213286. {
  213287. // If runing suid root, change effective user
  213288. // back to real user
  213289. if (geteuid() == 0 && getuid() != 0)
  213290. {
  213291. setreuid (geteuid(), getuid());
  213292. setregid (getegid(), getgid());
  213293. }
  213294. }
  213295. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213296. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  213297. {
  213298. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  213299. }
  213300. void PlatformUtilities::freeDynamicLibrary (void* handle)
  213301. {
  213302. dlclose(handle);
  213303. }
  213304. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  213305. {
  213306. return dlsym (libraryHandle, (const char*) procedureName);
  213307. }
  213308. #endif
  213309. #endif
  213310. /********* End of inlined file: juce_linux_Threads.cpp *********/
  213311. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213312. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  213313. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213314. // compiled on its own).
  213315. #ifdef JUCE_INCLUDED_FILE
  213316. #ifdef JUCE_DEBUG
  213317. #define JUCE_DEBUG_XERRORS 1
  213318. #endif
  213319. Display* display = 0; // This is also referenced from WindowDriver.cpp
  213320. static Window juce_messageWindowHandle = None;
  213321. #define SpecialAtom "JUCESpecialAtom"
  213322. #define BroadcastAtom "JUCEBroadcastAtom"
  213323. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  213324. static Atom specialId;
  213325. static Atom broadcastId;
  213326. static Atom specialCallbackId;
  213327. // This is referenced from WindowDriver.cpp
  213328. XContext improbableNumber;
  213329. // Defined in WindowDriver.cpp
  213330. extern void juce_windowMessageReceive (XEvent* event);
  213331. struct MessageThreadFuncCall
  213332. {
  213333. MessageCallbackFunction* func;
  213334. void* parameter;
  213335. void* result;
  213336. CriticalSection lock;
  213337. WaitableEvent event;
  213338. };
  213339. static bool errorCondition = false;
  213340. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  213341. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  213342. // (defined in another file to avoid problems including certain headers in this one)
  213343. extern bool juce_isRunningAsApplication();
  213344. // Usually happens when client-server connection is broken
  213345. static int ioErrorHandler (Display* display)
  213346. {
  213347. DBG (T("ERROR: connection to X server broken.. terminating."));
  213348. errorCondition = true;
  213349. if (juce_isRunningAsApplication())
  213350. Process::terminate();
  213351. return 0;
  213352. }
  213353. // A protocol error has occurred
  213354. static int errorHandler (Display* display, XErrorEvent* event)
  213355. {
  213356. #ifdef JUCE_DEBUG_XERRORS
  213357. char errorStr[64] = { 0 };
  213358. char requestStr[64] = { 0 };
  213359. XGetErrorText (display, event->error_code, errorStr, 64);
  213360. XGetErrorDatabaseText (display,
  213361. "XRequest",
  213362. (const char*) String (event->request_code),
  213363. "Unknown",
  213364. requestStr,
  213365. 64);
  213366. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  213367. #endif
  213368. return 0;
  213369. }
  213370. static bool breakIn = false;
  213371. // Breakin from keyboard
  213372. static void sig_handler (int sig)
  213373. {
  213374. if (sig == SIGINT)
  213375. {
  213376. breakIn = true;
  213377. return;
  213378. }
  213379. static bool reentrant = false;
  213380. if (reentrant == false)
  213381. {
  213382. reentrant = true;
  213383. // Illegal instruction
  213384. fflush (stdout);
  213385. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  213386. errorCondition = true;
  213387. if (juce_isRunningAsApplication())
  213388. Process::terminate();
  213389. }
  213390. else
  213391. {
  213392. if (juce_isRunningAsApplication())
  213393. exit(0);
  213394. }
  213395. }
  213396. void MessageManager::doPlatformSpecificInitialisation()
  213397. {
  213398. // Initialise xlib for multiple thread support
  213399. static bool initThreadCalled = false;
  213400. if (! initThreadCalled)
  213401. {
  213402. if (! XInitThreads())
  213403. {
  213404. // This is fatal! Print error and closedown
  213405. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  213406. if (juce_isRunningAsApplication())
  213407. Process::terminate();
  213408. return;
  213409. }
  213410. initThreadCalled = true;
  213411. }
  213412. // This is called if the client/server connection is broken
  213413. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  213414. // This is called if a protocol error occurs
  213415. oldErrorHandler = XSetErrorHandler (errorHandler);
  213416. // Install signal handler for break-in
  213417. struct sigaction saction;
  213418. sigset_t maskSet;
  213419. sigemptyset (&maskSet);
  213420. saction.sa_handler = sig_handler;
  213421. saction.sa_mask = maskSet;
  213422. saction.sa_flags = 0;
  213423. sigaction (SIGINT, &saction, NULL);
  213424. #ifndef _DEBUG
  213425. // Setup signal handlers for various fatal errors
  213426. sigaction (SIGILL, &saction, NULL);
  213427. sigaction (SIGBUS, &saction, NULL);
  213428. sigaction (SIGFPE, &saction, NULL);
  213429. sigaction (SIGSEGV, &saction, NULL);
  213430. sigaction (SIGSYS, &saction, NULL);
  213431. #endif
  213432. String displayName (getenv ("DISPLAY"));
  213433. if (displayName.isEmpty())
  213434. displayName = T(":0.0");
  213435. display = XOpenDisplay (displayName);
  213436. if (display == 0)
  213437. {
  213438. // This is fatal! Print error and closedown
  213439. Logger::outputDebugString ("Failed to open the X display.");
  213440. if (juce_isRunningAsApplication())
  213441. Process::terminate();
  213442. return;
  213443. }
  213444. // Get defaults for various properties
  213445. int screen = DefaultScreen (display);
  213446. Window root = RootWindow (display, screen);
  213447. Visual* visual = DefaultVisual (display, screen);
  213448. // Create atoms for our ClientMessages (these cannot be deleted)
  213449. specialId = XInternAtom (display, SpecialAtom, false);
  213450. broadcastId = XInternAtom (display, BroadcastAtom, false);
  213451. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  213452. // Create a context to store user data associated with Windows we
  213453. // create in WindowDriver
  213454. improbableNumber = XUniqueContext();
  213455. // We're only interested in client messages for this window
  213456. // which are always sent
  213457. XSetWindowAttributes swa;
  213458. swa.event_mask = NoEventMask;
  213459. // Create our message window (this will never be mapped)
  213460. juce_messageWindowHandle = XCreateWindow (display, root,
  213461. 0, 0, 1, 1, 0, 0, InputOnly,
  213462. visual, CWEventMask, &swa);
  213463. }
  213464. void MessageManager::doPlatformSpecificShutdown()
  213465. {
  213466. if (errorCondition == false)
  213467. {
  213468. XDestroyWindow (display, juce_messageWindowHandle);
  213469. XCloseDisplay (display);
  213470. // reset pointers
  213471. juce_messageWindowHandle = 0;
  213472. display = 0;
  213473. // Restore original error handlers
  213474. XSetIOErrorHandler (oldIOErrorHandler);
  213475. oldIOErrorHandler = 0;
  213476. XSetErrorHandler (oldErrorHandler);
  213477. oldErrorHandler = 0;
  213478. }
  213479. }
  213480. bool juce_postMessageToSystemQueue (void* message)
  213481. {
  213482. if (errorCondition)
  213483. return false;
  213484. XClientMessageEvent clientMsg;
  213485. clientMsg.display = display;
  213486. clientMsg.window = juce_messageWindowHandle;
  213487. clientMsg.type = ClientMessage;
  213488. clientMsg.format = 32;
  213489. clientMsg.message_type = specialId;
  213490. #if JUCE_64BIT
  213491. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  213492. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  213493. #else
  213494. clientMsg.data.l[0] = (long) message;
  213495. #endif
  213496. XSendEvent (display, juce_messageWindowHandle, false,
  213497. NoEventMask, (XEvent*) &clientMsg);
  213498. XFlush (display); // This is necessary to ensure the event is delivered
  213499. return true;
  213500. }
  213501. void MessageManager::broadcastMessage (const String& value) throw()
  213502. {
  213503. }
  213504. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  213505. void* parameter)
  213506. {
  213507. void* retVal = 0;
  213508. if (! errorCondition)
  213509. {
  213510. if (! isThisTheMessageThread())
  213511. {
  213512. static MessageThreadFuncCall messageFuncCallContext;
  213513. const ScopedLock sl (messageFuncCallContext.lock);
  213514. XClientMessageEvent clientMsg;
  213515. clientMsg.display = display;
  213516. clientMsg.window = juce_messageWindowHandle;
  213517. clientMsg.type = ClientMessage;
  213518. clientMsg.format = 32;
  213519. clientMsg.message_type = specialCallbackId;
  213520. #if JUCE_64BIT
  213521. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  213522. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  213523. #else
  213524. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  213525. #endif
  213526. messageFuncCallContext.func = func;
  213527. messageFuncCallContext.parameter = parameter;
  213528. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  213529. return 0;
  213530. XFlush (display); // This is necessary to ensure the event is delivered
  213531. // Wait for it to complete before continuing
  213532. messageFuncCallContext.event.wait();
  213533. retVal = messageFuncCallContext.result;
  213534. }
  213535. else
  213536. {
  213537. // Just call the function directly
  213538. retVal = func (parameter);
  213539. }
  213540. }
  213541. return retVal;
  213542. }
  213543. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  213544. {
  213545. if (errorCondition)
  213546. return false;
  213547. if (breakIn)
  213548. {
  213549. errorCondition = true;
  213550. if (juce_isRunningAsApplication())
  213551. Process::terminate();
  213552. return false;
  213553. }
  213554. if (returnIfNoPendingMessages && ! XPending (display))
  213555. return false;
  213556. XEvent evt;
  213557. XNextEvent (display, &evt);
  213558. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  213559. {
  213560. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  213561. if (clientMsg->format != 32)
  213562. {
  213563. jassertfalse
  213564. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  213565. }
  213566. else
  213567. {
  213568. JUCE_TRY
  213569. {
  213570. #if JUCE_64BIT
  213571. void* const messagePtr
  213572. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  213573. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  213574. #else
  213575. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  213576. #endif
  213577. if (clientMsg->message_type == specialId)
  213578. {
  213579. MessageManager::getInstance()->deliverMessage (messagePtr);
  213580. }
  213581. else if (clientMsg->message_type == specialCallbackId)
  213582. {
  213583. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  213584. MessageCallbackFunction* func = call->func;
  213585. call->result = (*func) (call->parameter);
  213586. call->event.signal();
  213587. }
  213588. else if (clientMsg->message_type == broadcastId)
  213589. {
  213590. #if 0
  213591. TCHAR buffer[8192];
  213592. zeromem (buffer, sizeof (buffer));
  213593. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  213594. mq->deliverBroadcastMessage (String (buffer));
  213595. #endif
  213596. }
  213597. else
  213598. {
  213599. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  213600. }
  213601. }
  213602. JUCE_CATCH_ALL
  213603. }
  213604. }
  213605. else if (evt.xany.window != juce_messageWindowHandle)
  213606. {
  213607. juce_windowMessageReceive (&evt);
  213608. }
  213609. return true;
  213610. }
  213611. #endif
  213612. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  213613. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  213614. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213615. // compiled on its own).
  213616. #ifdef JUCE_INCLUDED_FILE
  213617. class FreeTypeFontFace
  213618. {
  213619. public:
  213620. enum FontStyle
  213621. {
  213622. Plain = 0,
  213623. Bold = 1,
  213624. Italic = 2
  213625. };
  213626. struct FontNameIndex
  213627. {
  213628. String fileName;
  213629. int faceIndex;
  213630. };
  213631. FreeTypeFontFace (const String& familyName)
  213632. : hasSerif (false),
  213633. monospaced (false)
  213634. {
  213635. family = familyName;
  213636. }
  213637. void setFileName (const String& name,
  213638. const int faceIndex,
  213639. FontStyle style)
  213640. {
  213641. if (names[(int) style].fileName.isEmpty())
  213642. {
  213643. names[(int) style].fileName = name;
  213644. names[(int) style].faceIndex = faceIndex;
  213645. }
  213646. }
  213647. const String& getFamilyName() const throw()
  213648. {
  213649. return family;
  213650. }
  213651. const String& getFileName (int style, int* faceIndex) const throw()
  213652. {
  213653. *faceIndex = names [style].faceIndex;
  213654. return names[style].fileName;
  213655. }
  213656. void setMonospaced (bool mono) { monospaced = mono; }
  213657. bool getMonospaced () const throw() { return monospaced; }
  213658. void setSerif (const bool serif) { hasSerif = serif; }
  213659. bool getSerif () const throw() { return hasSerif; }
  213660. private:
  213661. String family;
  213662. FontNameIndex names[4];
  213663. bool hasSerif, monospaced;
  213664. };
  213665. class FreeTypeInterface : public DeletedAtShutdown
  213666. {
  213667. public:
  213668. FreeTypeInterface() throw()
  213669. : lastFace (0),
  213670. lastBold (false),
  213671. lastItalic (false)
  213672. {
  213673. if (FT_Init_FreeType (&ftLib) != 0)
  213674. {
  213675. ftLib = 0;
  213676. DBG (T("Failed to initialize FreeType"));
  213677. }
  213678. StringArray fontDirs;
  213679. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  213680. fontDirs.removeEmptyStrings (true);
  213681. if (fontDirs.size() == 0)
  213682. {
  213683. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  213684. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  213685. if (fontsInfo != 0)
  213686. {
  213687. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  213688. {
  213689. fontDirs.add (e->getAllSubText().trim());
  213690. }
  213691. delete fontsInfo;
  213692. }
  213693. }
  213694. if (fontDirs.size() == 0)
  213695. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  213696. for (int i = 0; i < fontDirs.size(); ++i)
  213697. enumerateFaces (fontDirs[i]);
  213698. }
  213699. ~FreeTypeInterface() throw()
  213700. {
  213701. if (lastFace != 0)
  213702. FT_Done_Face (lastFace);
  213703. if (ftLib != 0)
  213704. FT_Done_FreeType (ftLib);
  213705. clearSingletonInstance();
  213706. }
  213707. FreeTypeFontFace* findOrCreate (const String& familyName,
  213708. const bool create = false) throw()
  213709. {
  213710. for (int i = 0; i < faces.size(); i++)
  213711. if (faces[i]->getFamilyName() == familyName)
  213712. return faces[i];
  213713. if (! create)
  213714. return NULL;
  213715. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  213716. faces.add (newFace);
  213717. return newFace;
  213718. }
  213719. // Enumerate all font faces available in a given directory
  213720. void enumerateFaces (const String& path) throw()
  213721. {
  213722. File dirPath (path);
  213723. if (path.isEmpty() || ! dirPath.isDirectory())
  213724. return;
  213725. DirectoryIterator di (dirPath, true);
  213726. while (di.next())
  213727. {
  213728. File possible (di.getFile());
  213729. if (possible.hasFileExtension (T("ttf"))
  213730. || possible.hasFileExtension (T("pfb"))
  213731. || possible.hasFileExtension (T("pcf")))
  213732. {
  213733. FT_Face face;
  213734. int faceIndex = 0;
  213735. int numFaces = 0;
  213736. do
  213737. {
  213738. if (FT_New_Face (ftLib,
  213739. possible.getFullPathName(),
  213740. faceIndex,
  213741. &face) == 0)
  213742. {
  213743. if (faceIndex == 0)
  213744. numFaces = face->num_faces;
  213745. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  213746. {
  213747. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  213748. int style = (int) FreeTypeFontFace::Plain;
  213749. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  213750. style |= (int) FreeTypeFontFace::Bold;
  213751. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  213752. style |= (int) FreeTypeFontFace::Italic;
  213753. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  213754. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  213755. newFace->setMonospaced (true);
  213756. else
  213757. newFace->setMonospaced (false);
  213758. // Surely there must be a better way to do this?
  213759. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  213760. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  213761. || String (face->family_name).containsIgnoreCase (T("Arial")))
  213762. {
  213763. newFace->setSerif (false);
  213764. }
  213765. else
  213766. {
  213767. newFace->setSerif (true);
  213768. }
  213769. }
  213770. FT_Done_Face (face);
  213771. }
  213772. ++faceIndex;
  213773. }
  213774. while (faceIndex < numFaces);
  213775. }
  213776. }
  213777. }
  213778. // Create a FreeType face object for a given font
  213779. FT_Face createFT_Face (const String& fontName,
  213780. const bool bold,
  213781. const bool italic) throw()
  213782. {
  213783. FT_Face face = NULL;
  213784. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  213785. {
  213786. face = lastFace;
  213787. }
  213788. else
  213789. {
  213790. if (lastFace)
  213791. {
  213792. FT_Done_Face (lastFace);
  213793. lastFace = NULL;
  213794. }
  213795. lastFontName = fontName;
  213796. lastBold = bold;
  213797. lastItalic = italic;
  213798. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  213799. if (ftFace != 0)
  213800. {
  213801. int style = (int) FreeTypeFontFace::Plain;
  213802. if (bold)
  213803. style |= (int) FreeTypeFontFace::Bold;
  213804. if (italic)
  213805. style |= (int) FreeTypeFontFace::Italic;
  213806. int faceIndex;
  213807. String fileName (ftFace->getFileName (style, &faceIndex));
  213808. if (fileName.isEmpty())
  213809. {
  213810. style ^= (int) FreeTypeFontFace::Bold;
  213811. fileName = ftFace->getFileName (style, &faceIndex);
  213812. if (fileName.isEmpty())
  213813. {
  213814. style ^= (int) FreeTypeFontFace::Bold;
  213815. style ^= (int) FreeTypeFontFace::Italic;
  213816. fileName = ftFace->getFileName (style, &faceIndex);
  213817. if (! fileName.length())
  213818. {
  213819. style ^= (int) FreeTypeFontFace::Bold;
  213820. fileName = ftFace->getFileName (style, &faceIndex);
  213821. }
  213822. }
  213823. }
  213824. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  213825. {
  213826. face = lastFace;
  213827. // If there isn't a unicode charmap then select the first one.
  213828. if (FT_Select_Charmap (face, ft_encoding_unicode))
  213829. FT_Set_Charmap (face, face->charmaps[0]);
  213830. }
  213831. }
  213832. }
  213833. return face;
  213834. }
  213835. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  213836. {
  213837. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  213838. const float height = (float) (face->ascender - face->descender);
  213839. const float scaleX = 1.0f / height;
  213840. const float scaleY = -1.0f / height;
  213841. Path destShape;
  213842. #define CONVERTX(val) (scaleX * (val).x)
  213843. #define CONVERTY(val) (scaleY * (val).y)
  213844. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  213845. | FT_LOAD_NO_BITMAP
  213846. | FT_LOAD_IGNORE_TRANSFORM) != 0
  213847. || face->glyph->format != ft_glyph_format_outline)
  213848. {
  213849. return false;
  213850. }
  213851. const FT_Outline* const outline = &face->glyph->outline;
  213852. const short* const contours = outline->contours;
  213853. const char* const tags = outline->tags;
  213854. FT_Vector* const points = outline->points;
  213855. for (int c = 0; c < outline->n_contours; c++)
  213856. {
  213857. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  213858. const int endPoint = contours[c];
  213859. for (int p = startPoint; p <= endPoint; p++)
  213860. {
  213861. const float x = CONVERTX (points[p]);
  213862. const float y = CONVERTY (points[p]);
  213863. if (p == startPoint)
  213864. {
  213865. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  213866. {
  213867. float x2 = CONVERTX (points [endPoint]);
  213868. float y2 = CONVERTY (points [endPoint]);
  213869. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  213870. {
  213871. x2 = (x + x2) * 0.5f;
  213872. y2 = (y + y2) * 0.5f;
  213873. }
  213874. destShape.startNewSubPath (x2, y2);
  213875. }
  213876. else
  213877. {
  213878. destShape.startNewSubPath (x, y);
  213879. }
  213880. }
  213881. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  213882. {
  213883. if (p != startPoint)
  213884. destShape.lineTo (x, y);
  213885. }
  213886. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  213887. {
  213888. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  213889. float x2 = CONVERTX (points [nextIndex]);
  213890. float y2 = CONVERTY (points [nextIndex]);
  213891. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  213892. {
  213893. x2 = (x + x2) * 0.5f;
  213894. y2 = (y + y2) * 0.5f;
  213895. }
  213896. else
  213897. {
  213898. ++p;
  213899. }
  213900. destShape.quadraticTo (x, y, x2, y2);
  213901. }
  213902. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  213903. {
  213904. if (p >= endPoint)
  213905. return false;
  213906. const int next1 = p + 1;
  213907. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  213908. const float x2 = CONVERTX (points [next1]);
  213909. const float y2 = CONVERTY (points [next1]);
  213910. const float x3 = CONVERTX (points [next2]);
  213911. const float y3 = CONVERTY (points [next2]);
  213912. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  213913. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  213914. return false;
  213915. destShape.cubicTo (x, y, x2, y2, x3, y3);
  213916. p += 2;
  213917. }
  213918. }
  213919. destShape.closeSubPath();
  213920. }
  213921. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  213922. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  213923. addKerning (face, dest, character, glyphIndex);
  213924. return true;
  213925. }
  213926. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  213927. {
  213928. const float height = (float) (face->ascender - face->descender);
  213929. uint32 rightGlyphIndex;
  213930. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  213931. while (rightGlyphIndex != 0)
  213932. {
  213933. FT_Vector kerning;
  213934. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  213935. {
  213936. if (kerning.x != 0)
  213937. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  213938. }
  213939. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  213940. }
  213941. }
  213942. // Add a glyph to a font
  213943. bool addGlyphToFont (const uint32 character,
  213944. const tchar* fontName, bool bold, bool italic,
  213945. Typeface& dest) throw()
  213946. {
  213947. FT_Face face = createFT_Face (fontName, bold, italic);
  213948. if (face != 0)
  213949. return addGlyph (face, dest, character);
  213950. return false;
  213951. }
  213952. // Create a Typeface object for given name/style
  213953. bool createTypeface (const String& fontName,
  213954. const bool bold, const bool italic,
  213955. Typeface& dest,
  213956. const bool addAllGlyphs) throw()
  213957. {
  213958. dest.clear();
  213959. dest.setName (fontName);
  213960. dest.setBold (bold);
  213961. dest.setItalic (italic);
  213962. FT_Face face = createFT_Face (fontName, bold, italic);
  213963. if (face == 0)
  213964. {
  213965. #ifdef JUCE_DEBUG
  213966. String msg (T("Failed to create typeface: "));
  213967. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  213968. DBG (msg);
  213969. #endif
  213970. return face;
  213971. }
  213972. const float height = (float) (face->ascender - face->descender);
  213973. dest.setAscent (face->ascender / height);
  213974. dest.setDefaultCharacter (L' ');
  213975. if (addAllGlyphs)
  213976. {
  213977. uint32 glyphIndex;
  213978. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  213979. while (glyphIndex != 0)
  213980. {
  213981. addGlyph (face, dest, charCode);
  213982. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  213983. }
  213984. }
  213985. return true;
  213986. }
  213987. void getFamilyNames (StringArray& familyNames) const throw()
  213988. {
  213989. for (int i = 0; i < faces.size(); i++)
  213990. familyNames.add (faces[i]->getFamilyName());
  213991. }
  213992. void getMonospacedNames (StringArray& monoSpaced) const throw()
  213993. {
  213994. for (int i = 0; i < faces.size(); i++)
  213995. if (faces[i]->getMonospaced())
  213996. monoSpaced.add (faces[i]->getFamilyName());
  213997. }
  213998. void getSerifNames (StringArray& serif) const throw()
  213999. {
  214000. for (int i = 0; i < faces.size(); i++)
  214001. if (faces[i]->getSerif())
  214002. serif.add (faces[i]->getFamilyName());
  214003. }
  214004. void getSansSerifNames (StringArray& sansSerif) const throw()
  214005. {
  214006. for (int i = 0; i < faces.size(); i++)
  214007. if (! faces[i]->getSerif())
  214008. sansSerif.add (faces[i]->getFamilyName());
  214009. }
  214010. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  214011. private:
  214012. FT_Library ftLib;
  214013. FT_Face lastFace;
  214014. String lastFontName;
  214015. bool lastBold, lastItalic;
  214016. OwnedArray<FreeTypeFontFace> faces;
  214017. };
  214018. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  214019. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  214020. bool bold, bool italic,
  214021. bool addAllGlyphsToFont) throw()
  214022. {
  214023. FreeTypeInterface::getInstance()
  214024. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  214025. }
  214026. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  214027. {
  214028. return FreeTypeInterface::getInstance()
  214029. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  214030. }
  214031. const StringArray Font::findAllTypefaceNames() throw()
  214032. {
  214033. StringArray s;
  214034. FreeTypeInterface::getInstance()->getFamilyNames (s);
  214035. s.sort (true);
  214036. return s;
  214037. }
  214038. static const String pickBestFont (const StringArray& names,
  214039. const char* const choicesString)
  214040. {
  214041. StringArray choices;
  214042. choices.addTokens (String (choicesString), T(","), 0);
  214043. choices.trim();
  214044. choices.removeEmptyStrings();
  214045. int i, j;
  214046. for (j = 0; j < choices.size(); ++j)
  214047. if (names.contains (choices[j], true))
  214048. return choices[j];
  214049. for (j = 0; j < choices.size(); ++j)
  214050. for (i = 0; i < names.size(); i++)
  214051. if (names[i].startsWithIgnoreCase (choices[j]))
  214052. return names[i];
  214053. for (j = 0; j < choices.size(); ++j)
  214054. for (i = 0; i < names.size(); i++)
  214055. if (names[i].containsIgnoreCase (choices[j]))
  214056. return names[i];
  214057. return names[0];
  214058. }
  214059. static const String linux_getDefaultSansSerifFontName()
  214060. {
  214061. StringArray allFonts;
  214062. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  214063. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  214064. }
  214065. static const String linux_getDefaultSerifFontName()
  214066. {
  214067. StringArray allFonts;
  214068. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  214069. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  214070. }
  214071. static const String linux_getDefaultMonospacedFontName()
  214072. {
  214073. StringArray allFonts;
  214074. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  214075. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  214076. }
  214077. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  214078. {
  214079. defaultSans = linux_getDefaultSansSerifFontName();
  214080. defaultSerif = linux_getDefaultSerifFontName();
  214081. defaultFixed = linux_getDefaultMonospacedFontName();
  214082. }
  214083. #endif
  214084. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  214085. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  214086. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214087. // compiled on its own).
  214088. #ifdef JUCE_INCLUDED_FILE
  214089. #define TAKE_FOCUS 0
  214090. #define DELETE_WINDOW 1
  214091. #define SYSTEM_TRAY_REQUEST_DOCK 0
  214092. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  214093. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  214094. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  214095. static Atom wm_ChangeState = None;
  214096. static Atom wm_State = None;
  214097. static Atom wm_Protocols = None;
  214098. static Atom wm_ProtocolList [2] = { None, None };
  214099. static Atom wm_ActiveWin = None;
  214100. #define ourDndVersion 3
  214101. static Atom XA_XdndAware = None;
  214102. static Atom XA_XdndEnter = None;
  214103. static Atom XA_XdndLeave = None;
  214104. static Atom XA_XdndPosition = None;
  214105. static Atom XA_XdndStatus = None;
  214106. static Atom XA_XdndDrop = None;
  214107. static Atom XA_XdndFinished = None;
  214108. static Atom XA_XdndSelection = None;
  214109. static Atom XA_XdndProxy = None;
  214110. static Atom XA_XdndTypeList = None;
  214111. static Atom XA_XdndActionList = None;
  214112. static Atom XA_XdndActionDescription = None;
  214113. static Atom XA_XdndActionCopy = None;
  214114. static Atom XA_XdndActionMove = None;
  214115. static Atom XA_XdndActionLink = None;
  214116. static Atom XA_XdndActionAsk = None;
  214117. static Atom XA_XdndActionPrivate = None;
  214118. static Atom XA_JXSelectionWindowProperty = None;
  214119. static Atom XA_MimeTextPlain = None;
  214120. static Atom XA_MimeTextUriList = None;
  214121. static Atom XA_MimeRootDrop = None;
  214122. static XErrorHandler oldHandler = 0;
  214123. static int trappedErrorCode = 0;
  214124. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  214125. {
  214126. trappedErrorCode = err->error_code;
  214127. return 0;
  214128. }
  214129. static void trapErrors()
  214130. {
  214131. trappedErrorCode = 0;
  214132. oldHandler = XSetErrorHandler (errorTrapHandler);
  214133. }
  214134. static bool untrapErrors()
  214135. {
  214136. XSetErrorHandler (oldHandler);
  214137. return (trappedErrorCode == 0);
  214138. }
  214139. static bool isActiveApplication = false;
  214140. bool Process::isForegroundProcess() throw()
  214141. {
  214142. return isActiveApplication;
  214143. }
  214144. // (used in the messaging code, declared here for build reasons)
  214145. bool juce_isRunningAsApplication()
  214146. {
  214147. return JUCEApplication::getInstance() != 0;
  214148. }
  214149. // These are defined in juce_linux_Messaging.cpp
  214150. extern Display* display;
  214151. extern XContext improbableNumber;
  214152. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  214153. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  214154. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  214155. static int pointerMap[5];
  214156. static int lastMousePosX = 0, lastMousePosY = 0;
  214157. enum MouseButtons
  214158. {
  214159. NoButton = 0,
  214160. LeftButton = 1,
  214161. MiddleButton = 2,
  214162. RightButton = 3,
  214163. WheelUp = 4,
  214164. WheelDown = 5
  214165. };
  214166. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  214167. {
  214168. Window root, child;
  214169. int winx, winy;
  214170. unsigned int mask;
  214171. mouseMods = 0;
  214172. if (XQueryPointer (display,
  214173. RootWindow (display, DefaultScreen (display)),
  214174. &root, &child,
  214175. &x, &y, &winx, &winy, &mask) == False)
  214176. {
  214177. // Pointer not on the default screen
  214178. x = y = -1;
  214179. }
  214180. else
  214181. {
  214182. if ((mask & Button1Mask) != 0)
  214183. mouseMods |= ModifierKeys::leftButtonModifier;
  214184. if ((mask & Button2Mask) != 0)
  214185. mouseMods |= ModifierKeys::middleButtonModifier;
  214186. if ((mask & Button3Mask) != 0)
  214187. mouseMods |= ModifierKeys::rightButtonModifier;
  214188. }
  214189. }
  214190. static int AltMask = 0;
  214191. static int NumLockMask = 0;
  214192. static bool numLock = 0;
  214193. static bool capsLock = 0;
  214194. static char keyStates [32];
  214195. static void updateKeyStates (const int keycode, const bool press) throw()
  214196. {
  214197. const int keybyte = keycode >> 3;
  214198. const int keybit = (1 << (keycode & 7));
  214199. if (press)
  214200. keyStates [keybyte] |= keybit;
  214201. else
  214202. keyStates [keybyte] &= ~keybit;
  214203. }
  214204. static bool keyDown (const int keycode) throw()
  214205. {
  214206. const int keybyte = keycode >> 3;
  214207. const int keybit = (1 << (keycode & 7));
  214208. return (keyStates [keybyte] & keybit) != 0;
  214209. }
  214210. static const int extendedKeyModifier = 0x10000000;
  214211. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  214212. {
  214213. int keysym;
  214214. if (keyCode & extendedKeyModifier)
  214215. {
  214216. keysym = 0xff00 | (keyCode & 0xff);
  214217. }
  214218. else
  214219. {
  214220. keysym = keyCode;
  214221. if (keysym == (XK_Tab & 0xff)
  214222. || keysym == (XK_Return & 0xff)
  214223. || keysym == (XK_Escape & 0xff)
  214224. || keysym == (XK_BackSpace & 0xff))
  214225. {
  214226. keysym |= 0xff00;
  214227. }
  214228. }
  214229. return keyDown (XKeysymToKeycode (display, keysym));
  214230. }
  214231. // Alt and Num lock are not defined by standard X
  214232. // modifier constants: check what they're mapped to
  214233. static void getModifierMapping() throw()
  214234. {
  214235. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  214236. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  214237. AltMask = 0;
  214238. NumLockMask = 0;
  214239. XModifierKeymap* mapping = XGetModifierMapping (display);
  214240. if (mapping)
  214241. {
  214242. for (int i = 0; i < 8; i++)
  214243. {
  214244. if (mapping->modifiermap [i << 1] == altLeftCode)
  214245. AltMask = 1 << i;
  214246. else if (mapping->modifiermap [i << 1] == numLockCode)
  214247. NumLockMask = 1 << i;
  214248. }
  214249. XFreeModifiermap (mapping);
  214250. }
  214251. }
  214252. static int currentModifiers = 0;
  214253. void ModifierKeys::updateCurrentModifiers() throw()
  214254. {
  214255. currentModifierFlags = currentModifiers;
  214256. }
  214257. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  214258. {
  214259. int x, y, mouseMods;
  214260. getMousePos (x, y, mouseMods);
  214261. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  214262. currentModifiers |= mouseMods;
  214263. return ModifierKeys (currentModifiers);
  214264. }
  214265. static void updateKeyModifiers (const int status) throw()
  214266. {
  214267. currentModifiers &= ~(ModifierKeys::shiftModifier
  214268. | ModifierKeys::ctrlModifier
  214269. | ModifierKeys::altModifier);
  214270. if (status & ShiftMask)
  214271. currentModifiers |= ModifierKeys::shiftModifier;
  214272. if (status & ControlMask)
  214273. currentModifiers |= ModifierKeys::ctrlModifier;
  214274. if (status & AltMask)
  214275. currentModifiers |= ModifierKeys::altModifier;
  214276. numLock = ((status & NumLockMask) != 0);
  214277. capsLock = ((status & LockMask) != 0);
  214278. }
  214279. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  214280. {
  214281. int modifier = 0;
  214282. bool isModifier = true;
  214283. switch (sym)
  214284. {
  214285. case XK_Shift_L:
  214286. case XK_Shift_R:
  214287. modifier = ModifierKeys::shiftModifier;
  214288. break;
  214289. case XK_Control_L:
  214290. case XK_Control_R:
  214291. modifier = ModifierKeys::ctrlModifier;
  214292. break;
  214293. case XK_Alt_L:
  214294. case XK_Alt_R:
  214295. modifier = ModifierKeys::altModifier;
  214296. break;
  214297. case XK_Num_Lock:
  214298. if (press)
  214299. numLock = ! numLock;
  214300. break;
  214301. case XK_Caps_Lock:
  214302. if (press)
  214303. capsLock = ! capsLock;
  214304. break;
  214305. case XK_Scroll_Lock:
  214306. break;
  214307. default:
  214308. isModifier = false;
  214309. break;
  214310. }
  214311. if (modifier != 0)
  214312. {
  214313. if (press)
  214314. currentModifiers |= modifier;
  214315. else
  214316. currentModifiers &= ~modifier;
  214317. }
  214318. return isModifier;
  214319. }
  214320. #if JUCE_USE_XSHM
  214321. static bool isShmAvailable() throw()
  214322. {
  214323. static bool isChecked = false;
  214324. static bool isAvailable = false;
  214325. if (! isChecked)
  214326. {
  214327. isChecked = true;
  214328. int major, minor;
  214329. Bool pixmaps;
  214330. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  214331. {
  214332. trapErrors();
  214333. XShmSegmentInfo segmentInfo;
  214334. zerostruct (segmentInfo);
  214335. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  214336. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  214337. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  214338. xImage->bytes_per_line * xImage->height,
  214339. IPC_CREAT | 0777)) >= 0)
  214340. {
  214341. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  214342. if (segmentInfo.shmaddr != (void*) -1)
  214343. {
  214344. segmentInfo.readOnly = False;
  214345. xImage->data = segmentInfo.shmaddr;
  214346. XSync (display, False);
  214347. if (XShmAttach (display, &segmentInfo) != 0)
  214348. {
  214349. XSync (display, False);
  214350. XShmDetach (display, &segmentInfo);
  214351. isAvailable = true;
  214352. }
  214353. }
  214354. XFlush (display);
  214355. XDestroyImage (xImage);
  214356. shmdt (segmentInfo.shmaddr);
  214357. }
  214358. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  214359. isAvailable &= untrapErrors();
  214360. }
  214361. }
  214362. return isAvailable;
  214363. }
  214364. #endif
  214365. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  214366. {
  214367. const int width = image.getWidth();
  214368. const int height = image.getHeight();
  214369. uint32* const colour = (uint32*) juce_malloc (width * height * sizeof (uint32));
  214370. int index = 0;
  214371. for (int y = 0; y < height; ++y)
  214372. for (int x = 0; x < width; ++x)
  214373. colour[index++] = image.getPixelAt (x, y).getARGB();
  214374. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  214375. 0, (char*) colour, width, height, 32, 0);
  214376. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  214377. width, height, 24);
  214378. GC gc = XCreateGC (display, pixmap, 0, 0);
  214379. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  214380. XFreeGC (display, gc);
  214381. juce_free (colour);
  214382. return pixmap;
  214383. }
  214384. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  214385. {
  214386. const int width = image.getWidth();
  214387. const int height = image.getHeight();
  214388. const int stride = (width + 7) >> 3;
  214389. uint8* const mask = (uint8*) juce_calloc (stride * height);
  214390. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  214391. for (int y = 0; y < height; ++y)
  214392. {
  214393. for (int x = 0; x < width; ++x)
  214394. {
  214395. const uint8 bit = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  214396. const int offset = y * stride + (x >> 3);
  214397. if (image.getPixelAt (x, y).getAlpha() >= 128)
  214398. mask[offset] |= bit;
  214399. }
  214400. }
  214401. Pixmap pixmap = XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  214402. (char*) mask, width, height, 1, 0, 1);
  214403. juce_free (mask);
  214404. return pixmap;
  214405. }
  214406. class XBitmapImage : public Image
  214407. {
  214408. public:
  214409. XBitmapImage (const PixelFormat format_, const int w, const int h,
  214410. const bool clearImage, const bool is16Bit_)
  214411. : Image (format_, w, h),
  214412. is16Bit (is16Bit_)
  214413. {
  214414. jassert (format_ == RGB || format_ == ARGB);
  214415. pixelStride = (format_ == RGB) ? 3 : 4;
  214416. lineStride = ((w * pixelStride + 3) & ~3);
  214417. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  214418. #if JUCE_USE_XSHM
  214419. usingXShm = false;
  214420. if ((! is16Bit) && isShmAvailable())
  214421. {
  214422. zerostruct (segmentInfo);
  214423. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  214424. if (xImage != 0)
  214425. {
  214426. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  214427. xImage->bytes_per_line * xImage->height,
  214428. IPC_CREAT | 0777)) >= 0)
  214429. {
  214430. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  214431. if (segmentInfo.shmaddr != (void*) -1)
  214432. {
  214433. segmentInfo.readOnly = False;
  214434. xImage->data = segmentInfo.shmaddr;
  214435. imageData = (uint8*) segmentInfo.shmaddr;
  214436. XSync (display, False);
  214437. if (XShmAttach (display, &segmentInfo) != 0)
  214438. {
  214439. XSync (display, False);
  214440. usingXShm = true;
  214441. }
  214442. else
  214443. {
  214444. jassertfalse
  214445. }
  214446. }
  214447. else
  214448. {
  214449. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  214450. }
  214451. }
  214452. }
  214453. }
  214454. if (! usingXShm)
  214455. #endif
  214456. {
  214457. imageData = (uint8*) juce_malloc (lineStride * h);
  214458. if (format_ == ARGB && clearImage)
  214459. zeromem (imageData, h * lineStride);
  214460. xImage = (XImage*) juce_calloc (sizeof (XImage));
  214461. xImage->width = w;
  214462. xImage->height = h;
  214463. xImage->xoffset = 0;
  214464. xImage->format = ZPixmap;
  214465. xImage->data = (char*) imageData;
  214466. xImage->byte_order = ImageByteOrder (display);
  214467. xImage->bitmap_unit = BitmapUnit (display);
  214468. xImage->bitmap_bit_order = BitmapBitOrder (display);
  214469. xImage->bitmap_pad = 32;
  214470. xImage->depth = pixelStride * 8;
  214471. xImage->bytes_per_line = lineStride;
  214472. xImage->bits_per_pixel = pixelStride * 8;
  214473. xImage->red_mask = 0x00FF0000;
  214474. xImage->green_mask = 0x0000FF00;
  214475. xImage->blue_mask = 0x000000FF;
  214476. if (is16Bit)
  214477. {
  214478. const int pixelStride = 2;
  214479. const int lineStride = ((w * pixelStride + 3) & ~3);
  214480. xImage->data = (char*) juce_malloc (lineStride * h);
  214481. xImage->bitmap_pad = 16;
  214482. xImage->depth = pixelStride * 8;
  214483. xImage->bytes_per_line = lineStride;
  214484. xImage->bits_per_pixel = pixelStride * 8;
  214485. xImage->red_mask = visual->red_mask;
  214486. xImage->green_mask = visual->green_mask;
  214487. xImage->blue_mask = visual->blue_mask;
  214488. }
  214489. if (! XInitImage (xImage))
  214490. {
  214491. jassertfalse
  214492. }
  214493. }
  214494. }
  214495. ~XBitmapImage()
  214496. {
  214497. #if JUCE_USE_XSHM
  214498. if (usingXShm)
  214499. {
  214500. XShmDetach (display, &segmentInfo);
  214501. XFlush (display);
  214502. XDestroyImage (xImage);
  214503. shmdt (segmentInfo.shmaddr);
  214504. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  214505. }
  214506. else
  214507. #endif
  214508. {
  214509. juce_free (xImage->data);
  214510. xImage->data = 0;
  214511. XDestroyImage (xImage);
  214512. }
  214513. if (! is16Bit)
  214514. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  214515. }
  214516. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  214517. {
  214518. static GC gc = 0;
  214519. if (gc == 0)
  214520. gc = DefaultGC (display, DefaultScreen (display));
  214521. if (is16Bit)
  214522. {
  214523. const uint32 rMask = xImage->red_mask;
  214524. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  214525. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  214526. const uint32 gMask = xImage->green_mask;
  214527. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  214528. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  214529. const uint32 bMask = xImage->blue_mask;
  214530. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  214531. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  214532. int ls, ps;
  214533. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  214534. for (int y = sy; y < sy + dh; ++y)
  214535. {
  214536. const uint8* p = pixels + y * ls + sx * ps;
  214537. for (int x = sx; x < sx + dw; ++x)
  214538. {
  214539. const PixelRGB* const pixel = (const PixelRGB*) p;
  214540. p += ps;
  214541. XPutPixel (xImage, x, y,
  214542. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  214543. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  214544. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  214545. }
  214546. }
  214547. releasePixelDataReadOnly (pixels);
  214548. }
  214549. // blit results to screen.
  214550. #if JUCE_USE_XSHM
  214551. if (usingXShm)
  214552. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  214553. else
  214554. #endif
  214555. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  214556. }
  214557. juce_UseDebuggingNewOperator
  214558. private:
  214559. XImage* xImage;
  214560. const bool is16Bit;
  214561. #if JUCE_USE_XSHM
  214562. XShmSegmentInfo segmentInfo;
  214563. bool usingXShm;
  214564. #endif
  214565. static int getShiftNeeded (const uint32 mask) throw()
  214566. {
  214567. for (int i = 32; --i >= 0;)
  214568. if (((mask >> i) & 1) != 0)
  214569. return i - 7;
  214570. jassertfalse
  214571. return 0;
  214572. }
  214573. };
  214574. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  214575. class LinuxComponentPeer : public ComponentPeer
  214576. {
  214577. public:
  214578. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  214579. : ComponentPeer (component, windowStyleFlags),
  214580. windowH (0),
  214581. parentWindow (0),
  214582. wx (0),
  214583. wy (0),
  214584. ww (0),
  214585. wh (0),
  214586. taskbarImage (0),
  214587. fullScreen (false),
  214588. entered (false),
  214589. mapped (false)
  214590. {
  214591. // it's dangerous to create a window on a thread other than the message thread..
  214592. checkMessageManagerIsLocked
  214593. repainter = new LinuxRepaintManager (this);
  214594. createWindow();
  214595. setTitle (component->getName());
  214596. }
  214597. ~LinuxComponentPeer()
  214598. {
  214599. // it's dangerous to delete a window on a thread other than the message thread..
  214600. checkMessageManagerIsLocked
  214601. deleteTaskBarIcon();
  214602. deleteIconPixmaps();
  214603. destroyWindow();
  214604. windowH = 0;
  214605. delete repainter;
  214606. }
  214607. void* getNativeHandle() const
  214608. {
  214609. return (void*) windowH;
  214610. }
  214611. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  214612. {
  214613. XPointer peer = 0;
  214614. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  214615. {
  214616. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  214617. peer = 0;
  214618. }
  214619. return (LinuxComponentPeer*) peer;
  214620. }
  214621. void setVisible (bool shouldBeVisible)
  214622. {
  214623. if (shouldBeVisible)
  214624. XMapWindow (display, windowH);
  214625. else
  214626. XUnmapWindow (display, windowH);
  214627. }
  214628. void setTitle (const String& title)
  214629. {
  214630. setWindowTitle (windowH, title);
  214631. }
  214632. void setPosition (int x, int y)
  214633. {
  214634. setBounds (x, y, ww, wh, false);
  214635. }
  214636. void setSize (int w, int h)
  214637. {
  214638. setBounds (wx, wy, w, h, false);
  214639. }
  214640. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  214641. {
  214642. fullScreen = isNowFullScreen;
  214643. if (windowH != 0)
  214644. {
  214645. const ComponentDeletionWatcher deletionChecker (component);
  214646. wx = x;
  214647. wy = y;
  214648. ww = jmax (1, w);
  214649. wh = jmax (1, h);
  214650. // Make sure the Window manager does what we want
  214651. XSizeHints* hints = XAllocSizeHints();
  214652. hints->flags = USSize | USPosition;
  214653. hints->width = ww;
  214654. hints->height = wh;
  214655. hints->x = wx;
  214656. hints->y = wy;
  214657. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  214658. {
  214659. hints->min_width = hints->max_width = hints->width;
  214660. hints->min_height = hints->max_height = hints->height;
  214661. hints->flags |= PMinSize | PMaxSize;
  214662. }
  214663. XSetWMNormalHints (display, windowH, hints);
  214664. XFree (hints);
  214665. XMoveResizeWindow (display, windowH,
  214666. wx - windowBorder.getLeft(),
  214667. wy - windowBorder.getTop(), ww, wh);
  214668. if (! deletionChecker.hasBeenDeleted())
  214669. {
  214670. updateBorderSize();
  214671. handleMovedOrResized();
  214672. }
  214673. }
  214674. }
  214675. void getBounds (int& x, int& y, int& w, int& h) const
  214676. {
  214677. x = wx;
  214678. y = wy;
  214679. w = ww;
  214680. h = wh;
  214681. }
  214682. int getScreenX() const
  214683. {
  214684. return wx;
  214685. }
  214686. int getScreenY() const
  214687. {
  214688. return wy;
  214689. }
  214690. void relativePositionToGlobal (int& x, int& y)
  214691. {
  214692. x += wx;
  214693. y += wy;
  214694. }
  214695. void globalPositionToRelative (int& x, int& y)
  214696. {
  214697. x -= wx;
  214698. y -= wy;
  214699. }
  214700. void setMinimised (bool shouldBeMinimised)
  214701. {
  214702. if (shouldBeMinimised)
  214703. {
  214704. Window root = RootWindow (display, DefaultScreen (display));
  214705. XClientMessageEvent clientMsg;
  214706. clientMsg.display = display;
  214707. clientMsg.window = windowH;
  214708. clientMsg.type = ClientMessage;
  214709. clientMsg.format = 32;
  214710. clientMsg.message_type = wm_ChangeState;
  214711. clientMsg.data.l[0] = IconicState;
  214712. XSendEvent (display, root, false,
  214713. SubstructureRedirectMask | SubstructureNotifyMask,
  214714. (XEvent*) &clientMsg);
  214715. }
  214716. else
  214717. {
  214718. setVisible (true);
  214719. }
  214720. }
  214721. bool isMinimised() const
  214722. {
  214723. bool minimised = false;
  214724. unsigned char* stateProp;
  214725. unsigned long nitems, bytesLeft;
  214726. Atom actualType;
  214727. int actualFormat;
  214728. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  214729. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  214730. &stateProp) == Success
  214731. && actualType == wm_State
  214732. && actualFormat == 32
  214733. && nitems > 0)
  214734. {
  214735. if (((unsigned long*) stateProp)[0] == IconicState)
  214736. minimised = true;
  214737. XFree (stateProp);
  214738. }
  214739. return minimised;
  214740. }
  214741. void setFullScreen (const bool shouldBeFullScreen)
  214742. {
  214743. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  214744. setMinimised (false);
  214745. if (fullScreen != shouldBeFullScreen)
  214746. {
  214747. if (shouldBeFullScreen)
  214748. r = Desktop::getInstance().getMainMonitorArea();
  214749. if (! r.isEmpty())
  214750. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  214751. getComponent()->repaint();
  214752. }
  214753. }
  214754. bool isFullScreen() const
  214755. {
  214756. return fullScreen;
  214757. }
  214758. bool isChildWindowOf (Window possibleParent) const
  214759. {
  214760. Window* windowList = 0;
  214761. uint32 windowListSize = 0;
  214762. Window parent, root;
  214763. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  214764. {
  214765. if (windowList != 0)
  214766. XFree (windowList);
  214767. return parent == possibleParent;
  214768. }
  214769. return false;
  214770. }
  214771. bool isFrontWindow() const
  214772. {
  214773. Window* windowList = 0;
  214774. uint32 windowListSize = 0;
  214775. bool result = false;
  214776. Window parent, root = RootWindow (display, DefaultScreen (display));
  214777. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  214778. {
  214779. for (int i = windowListSize; --i >= 0;)
  214780. {
  214781. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  214782. if (peer != 0)
  214783. {
  214784. result = (peer == this);
  214785. break;
  214786. }
  214787. }
  214788. }
  214789. if (windowList != 0)
  214790. XFree (windowList);
  214791. return result;
  214792. }
  214793. bool contains (int x, int y, bool trueIfInAChildWindow) const
  214794. {
  214795. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  214796. if (((unsigned int) x) >= (unsigned int) ww
  214797. || ((unsigned int) y) >= (unsigned int) wh)
  214798. return false;
  214799. bool inFront = false;
  214800. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  214801. {
  214802. Component* const c = Desktop::getInstance().getComponent (i);
  214803. if (inFront)
  214804. {
  214805. if (c->contains (x + wx - c->getScreenX(),
  214806. y + wy - c->getScreenY()))
  214807. {
  214808. return false;
  214809. }
  214810. }
  214811. else if (c == getComponent())
  214812. {
  214813. inFront = true;
  214814. }
  214815. }
  214816. if (trueIfInAChildWindow)
  214817. return true;
  214818. ::Window root, child;
  214819. unsigned int bw, depth;
  214820. int wx, wy, w, h;
  214821. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  214822. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  214823. &bw, &depth))
  214824. {
  214825. return false;
  214826. }
  214827. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  214828. return false;
  214829. return child == None;
  214830. }
  214831. const BorderSize getFrameSize() const
  214832. {
  214833. return BorderSize();
  214834. }
  214835. bool setAlwaysOnTop (bool alwaysOnTop)
  214836. {
  214837. if (windowH != 0)
  214838. {
  214839. const bool wasVisible = component->isVisible();
  214840. if (wasVisible)
  214841. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  214842. XSetWindowAttributes swa;
  214843. swa.override_redirect = alwaysOnTop ? True : False;
  214844. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  214845. if (wasVisible)
  214846. setVisible (true);
  214847. }
  214848. return true;
  214849. }
  214850. void toFront (bool makeActive)
  214851. {
  214852. if (makeActive)
  214853. {
  214854. setVisible (true);
  214855. grabFocus();
  214856. }
  214857. XEvent ev;
  214858. ev.xclient.type = ClientMessage;
  214859. ev.xclient.serial = 0;
  214860. ev.xclient.send_event = True;
  214861. ev.xclient.message_type = wm_ActiveWin;
  214862. ev.xclient.window = windowH;
  214863. ev.xclient.format = 32;
  214864. ev.xclient.data.l[0] = 2;
  214865. ev.xclient.data.l[1] = CurrentTime;
  214866. ev.xclient.data.l[2] = 0;
  214867. ev.xclient.data.l[3] = 0;
  214868. ev.xclient.data.l[4] = 0;
  214869. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  214870. False,
  214871. SubstructureRedirectMask | SubstructureNotifyMask,
  214872. &ev);
  214873. XWindowAttributes attr;
  214874. XGetWindowAttributes (display, windowH, &attr);
  214875. if (attr.override_redirect)
  214876. XRaiseWindow (display, windowH);
  214877. XSync (display, False);
  214878. handleBroughtToFront();
  214879. }
  214880. void toBehind (ComponentPeer* other)
  214881. {
  214882. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  214883. jassert (otherPeer != 0); // wrong type of window?
  214884. if (otherPeer != 0)
  214885. {
  214886. setMinimised (false);
  214887. Window newStack[] = { otherPeer->windowH, windowH };
  214888. XRestackWindows (display, newStack, 2);
  214889. }
  214890. }
  214891. bool isFocused() const
  214892. {
  214893. int revert;
  214894. Window focusedWindow = 0;
  214895. XGetInputFocus (display, &focusedWindow, &revert);
  214896. return focusedWindow == windowH;
  214897. }
  214898. void grabFocus()
  214899. {
  214900. XWindowAttributes atts;
  214901. if (windowH != 0
  214902. && XGetWindowAttributes (display, windowH, &atts)
  214903. && atts.map_state == IsViewable
  214904. && ! isFocused())
  214905. {
  214906. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  214907. isActiveApplication = true;
  214908. }
  214909. }
  214910. void textInputRequired (int /*x*/, int /*y*/)
  214911. {
  214912. }
  214913. void repaint (int x, int y, int w, int h)
  214914. {
  214915. if (Rectangle::intersectRectangles (x, y, w, h,
  214916. 0, 0,
  214917. getComponent()->getWidth(),
  214918. getComponent()->getHeight()))
  214919. {
  214920. repainter->repaint (x, y, w, h);
  214921. }
  214922. }
  214923. void performAnyPendingRepaintsNow()
  214924. {
  214925. repainter->performAnyPendingRepaintsNow();
  214926. }
  214927. void setIcon (const Image& newIcon)
  214928. {
  214929. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  214930. unsigned long* const data = (unsigned long*) juce_malloc (dataSize * sizeof (uint32));
  214931. int index = 0;
  214932. data[index++] = newIcon.getWidth();
  214933. data[index++] = newIcon.getHeight();
  214934. for (int y = 0; y < newIcon.getHeight(); ++y)
  214935. for (int x = 0; x < newIcon.getWidth(); ++x)
  214936. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  214937. XChangeProperty (display, windowH,
  214938. XInternAtom (display, "_NET_WM_ICON", False),
  214939. XA_CARDINAL, 32, PropModeReplace,
  214940. (unsigned char*) data, dataSize);
  214941. juce_free (data);
  214942. deleteIconPixmaps();
  214943. XWMHints* wmHints = XGetWMHints (display, windowH);
  214944. if (wmHints == 0)
  214945. wmHints = XAllocWMHints();
  214946. wmHints->flags |= IconPixmapHint | IconMaskHint;
  214947. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  214948. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  214949. XSetWMHints (display, windowH, wmHints);
  214950. XFree (wmHints);
  214951. XSync (display, False);
  214952. }
  214953. void deleteIconPixmaps()
  214954. {
  214955. XWMHints* wmHints = XGetWMHints (display, windowH);
  214956. if (wmHints != 0)
  214957. {
  214958. if ((wmHints->flags & IconPixmapHint) != 0)
  214959. {
  214960. wmHints->flags &= ~IconPixmapHint;
  214961. XFreePixmap (display, wmHints->icon_pixmap);
  214962. }
  214963. if ((wmHints->flags & IconMaskHint) != 0)
  214964. {
  214965. wmHints->flags &= ~IconMaskHint;
  214966. XFreePixmap (display, wmHints->icon_mask);
  214967. }
  214968. XSetWMHints (display, windowH, wmHints);
  214969. XFree (wmHints);
  214970. }
  214971. }
  214972. void handleWindowMessage (XEvent* event)
  214973. {
  214974. switch (event->xany.type)
  214975. {
  214976. case 2: // 'KeyPress'
  214977. {
  214978. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  214979. updateKeyStates (keyEvent->keycode, true);
  214980. char utf8 [64];
  214981. zeromem (utf8, sizeof (utf8));
  214982. KeySym sym;
  214983. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  214984. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  214985. int keyCode = (int) unicodeChar;
  214986. if (keyCode < 0x20)
  214987. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  214988. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  214989. const int oldMods = currentModifiers;
  214990. bool keyPressed = false;
  214991. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  214992. if ((sym & 0xff00) == 0xff00)
  214993. {
  214994. // Translate keypad
  214995. if (sym == XK_KP_Divide)
  214996. keyCode = XK_slash;
  214997. else if (sym == XK_KP_Multiply)
  214998. keyCode = XK_asterisk;
  214999. else if (sym == XK_KP_Subtract)
  215000. keyCode = XK_hyphen;
  215001. else if (sym == XK_KP_Add)
  215002. keyCode = XK_plus;
  215003. else if (sym == XK_KP_Enter)
  215004. keyCode = XK_Return;
  215005. else if (sym == XK_KP_Decimal)
  215006. keyCode = numLock ? XK_period : XK_Delete;
  215007. else if (sym == XK_KP_0)
  215008. keyCode = numLock ? XK_0 : XK_Insert;
  215009. else if (sym == XK_KP_1)
  215010. keyCode = numLock ? XK_1 : XK_End;
  215011. else if (sym == XK_KP_2)
  215012. keyCode = numLock ? XK_2 : XK_Down;
  215013. else if (sym == XK_KP_3)
  215014. keyCode = numLock ? XK_3 : XK_Page_Down;
  215015. else if (sym == XK_KP_4)
  215016. keyCode = numLock ? XK_4 : XK_Left;
  215017. else if (sym == XK_KP_5)
  215018. keyCode = XK_5;
  215019. else if (sym == XK_KP_6)
  215020. keyCode = numLock ? XK_6 : XK_Right;
  215021. else if (sym == XK_KP_7)
  215022. keyCode = numLock ? XK_7 : XK_Home;
  215023. else if (sym == XK_KP_8)
  215024. keyCode = numLock ? XK_8 : XK_Up;
  215025. else if (sym == XK_KP_9)
  215026. keyCode = numLock ? XK_9 : XK_Page_Up;
  215027. switch (sym)
  215028. {
  215029. case XK_Left:
  215030. case XK_Right:
  215031. case XK_Up:
  215032. case XK_Down:
  215033. case XK_Page_Up:
  215034. case XK_Page_Down:
  215035. case XK_End:
  215036. case XK_Home:
  215037. case XK_Delete:
  215038. case XK_Insert:
  215039. keyPressed = true;
  215040. keyCode = (sym & 0xff) | extendedKeyModifier;
  215041. break;
  215042. case XK_Tab:
  215043. case XK_Return:
  215044. case XK_Escape:
  215045. case XK_BackSpace:
  215046. keyPressed = true;
  215047. keyCode &= 0xff;
  215048. break;
  215049. default:
  215050. {
  215051. if (sym >= XK_F1 && sym <= XK_F16)
  215052. {
  215053. keyPressed = true;
  215054. keyCode = (sym & 0xff) | extendedKeyModifier;
  215055. }
  215056. break;
  215057. }
  215058. }
  215059. }
  215060. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  215061. keyPressed = true;
  215062. if (oldMods != currentModifiers)
  215063. handleModifierKeysChange();
  215064. if (keyDownChange)
  215065. handleKeyUpOrDown (true);
  215066. if (keyPressed)
  215067. handleKeyPress (keyCode, unicodeChar);
  215068. break;
  215069. }
  215070. case KeyRelease:
  215071. {
  215072. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  215073. updateKeyStates (keyEvent->keycode, false);
  215074. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  215075. const int oldMods = currentModifiers;
  215076. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  215077. if (oldMods != currentModifiers)
  215078. handleModifierKeysChange();
  215079. if (keyDownChange)
  215080. handleKeyUpOrDown (false);
  215081. break;
  215082. }
  215083. case ButtonPress:
  215084. {
  215085. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  215086. bool buttonMsg = false;
  215087. bool wheelUpMsg = false;
  215088. bool wheelDownMsg = false;
  215089. const int map = pointerMap [buttonPressEvent->button - Button1];
  215090. if (map == LeftButton)
  215091. {
  215092. currentModifiers |= ModifierKeys::leftButtonModifier;
  215093. buttonMsg = true;
  215094. }
  215095. else if (map == RightButton)
  215096. {
  215097. currentModifiers |= ModifierKeys::rightButtonModifier;
  215098. buttonMsg = true;
  215099. }
  215100. else if (map == MiddleButton)
  215101. {
  215102. currentModifiers |= ModifierKeys::middleButtonModifier;
  215103. buttonMsg = true;
  215104. }
  215105. else if (map == WheelUp)
  215106. {
  215107. wheelUpMsg = true;
  215108. }
  215109. else if (map == WheelDown)
  215110. {
  215111. wheelDownMsg = true;
  215112. }
  215113. updateKeyModifiers (buttonPressEvent->state);
  215114. if (buttonMsg)
  215115. {
  215116. toFront (true);
  215117. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  215118. getEventTime (buttonPressEvent->time));
  215119. }
  215120. else if (wheelUpMsg || wheelDownMsg)
  215121. {
  215122. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  215123. getEventTime (buttonPressEvent->time));
  215124. }
  215125. lastMousePosX = lastMousePosY = 0x100000;
  215126. break;
  215127. }
  215128. case ButtonRelease:
  215129. {
  215130. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  215131. const int oldModifiers = currentModifiers;
  215132. const int map = pointerMap [buttonRelEvent->button - Button1];
  215133. if (map == LeftButton)
  215134. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  215135. else if (map == RightButton)
  215136. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  215137. else if (map == MiddleButton)
  215138. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  215139. updateKeyModifiers (buttonRelEvent->state);
  215140. handleMouseUp (oldModifiers,
  215141. buttonRelEvent->x, buttonRelEvent->y,
  215142. getEventTime (buttonRelEvent->time));
  215143. lastMousePosX = lastMousePosY = 0x100000;
  215144. break;
  215145. }
  215146. case MotionNotify:
  215147. {
  215148. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  215149. updateKeyModifiers (movedEvent->state);
  215150. int x, y, mouseMods;
  215151. getMousePos (x, y, mouseMods);
  215152. if (lastMousePosX != x || lastMousePosY != y)
  215153. {
  215154. lastMousePosX = x;
  215155. lastMousePosY = y;
  215156. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  215157. {
  215158. Window wRoot = 0, wParent = 0;
  215159. Window* wChild = 0;
  215160. unsigned int numChildren;
  215161. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  215162. if (wParent != 0
  215163. && wParent != windowH
  215164. && wParent != wRoot)
  215165. {
  215166. parentWindow = wParent;
  215167. updateBounds();
  215168. x -= getScreenX();
  215169. y -= getScreenY();
  215170. }
  215171. else
  215172. {
  215173. parentWindow = 0;
  215174. x -= getScreenX();
  215175. y -= getScreenY();
  215176. }
  215177. }
  215178. else
  215179. {
  215180. x -= getScreenX();
  215181. y -= getScreenY();
  215182. }
  215183. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  215184. handleMouseMove (x, y, getEventTime (movedEvent->time));
  215185. else
  215186. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  215187. }
  215188. break;
  215189. }
  215190. case EnterNotify:
  215191. {
  215192. lastMousePosX = lastMousePosY = 0x100000;
  215193. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  215194. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215195. && ! entered)
  215196. {
  215197. updateKeyModifiers (enterEvent->state);
  215198. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  215199. entered = true;
  215200. }
  215201. break;
  215202. }
  215203. case LeaveNotify:
  215204. {
  215205. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  215206. // Suppress the normal leave if we've got a pointer grab, or if
  215207. // it's a bogus one caused by clicking a mouse button when running
  215208. // in a Window manager
  215209. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215210. && leaveEvent->mode == NotifyNormal)
  215211. || leaveEvent->mode == NotifyUngrab)
  215212. {
  215213. updateKeyModifiers (leaveEvent->state);
  215214. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  215215. entered = false;
  215216. }
  215217. break;
  215218. }
  215219. case FocusIn:
  215220. {
  215221. isActiveApplication = true;
  215222. if (isFocused())
  215223. handleFocusGain();
  215224. break;
  215225. }
  215226. case FocusOut:
  215227. {
  215228. isActiveApplication = false;
  215229. if (! isFocused())
  215230. handleFocusLoss();
  215231. break;
  215232. }
  215233. case Expose:
  215234. {
  215235. // Batch together all pending expose events
  215236. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  215237. XEvent nextEvent;
  215238. if (exposeEvent->window != windowH)
  215239. {
  215240. Window child;
  215241. XTranslateCoordinates (display, exposeEvent->window, windowH,
  215242. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  215243. &child);
  215244. }
  215245. repaint (exposeEvent->x, exposeEvent->y,
  215246. exposeEvent->width, exposeEvent->height);
  215247. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  215248. {
  215249. XPeekEvent (display, (XEvent*) &nextEvent);
  215250. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  215251. break;
  215252. XNextEvent (display, (XEvent*) &nextEvent);
  215253. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  215254. repaint (nextExposeEvent->x, nextExposeEvent->y,
  215255. nextExposeEvent->width, nextExposeEvent->height);
  215256. }
  215257. break;
  215258. }
  215259. case CirculateNotify:
  215260. case CreateNotify:
  215261. case DestroyNotify:
  215262. // Think we can ignore these
  215263. break;
  215264. case ConfigureNotify:
  215265. {
  215266. updateBounds();
  215267. updateBorderSize();
  215268. handleMovedOrResized();
  215269. // if the native title bar is dragged, need to tell any active menus, etc.
  215270. if ((styleFlags & windowHasTitleBar) != 0
  215271. && component->isCurrentlyBlockedByAnotherModalComponent())
  215272. {
  215273. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  215274. if (currentModalComp != 0)
  215275. currentModalComp->inputAttemptWhenModal();
  215276. }
  215277. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  215278. if (confEvent->window == windowH
  215279. && confEvent->above != 0
  215280. && isFrontWindow())
  215281. {
  215282. handleBroughtToFront();
  215283. }
  215284. break;
  215285. }
  215286. case ReparentNotify:
  215287. case GravityNotify:
  215288. {
  215289. parentWindow = 0;
  215290. Window wRoot = 0;
  215291. Window* wChild = 0;
  215292. unsigned int numChildren;
  215293. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  215294. if (parentWindow == windowH || parentWindow == wRoot)
  215295. parentWindow = 0;
  215296. updateBounds();
  215297. updateBorderSize();
  215298. handleMovedOrResized();
  215299. break;
  215300. }
  215301. case MapNotify:
  215302. mapped = true;
  215303. handleBroughtToFront();
  215304. break;
  215305. case UnmapNotify:
  215306. mapped = false;
  215307. break;
  215308. case MappingNotify:
  215309. {
  215310. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  215311. if (mappingEvent->request != MappingPointer)
  215312. {
  215313. // Deal with modifier/keyboard mapping
  215314. XRefreshKeyboardMapping (mappingEvent);
  215315. getModifierMapping();
  215316. }
  215317. break;
  215318. }
  215319. case ClientMessage:
  215320. {
  215321. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  215322. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  215323. {
  215324. const Atom atom = (Atom) clientMsg->data.l[0];
  215325. if (atom == wm_ProtocolList [TAKE_FOCUS])
  215326. {
  215327. XWindowAttributes atts;
  215328. if (clientMsg->window != 0
  215329. && XGetWindowAttributes (display, clientMsg->window, &atts))
  215330. {
  215331. if (atts.map_state == IsViewable)
  215332. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  215333. }
  215334. }
  215335. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  215336. {
  215337. handleUserClosingWindow();
  215338. }
  215339. }
  215340. else if (clientMsg->message_type == XA_XdndEnter)
  215341. {
  215342. handleDragAndDropEnter (clientMsg);
  215343. }
  215344. else if (clientMsg->message_type == XA_XdndLeave)
  215345. {
  215346. resetDragAndDrop();
  215347. }
  215348. else if (clientMsg->message_type == XA_XdndPosition)
  215349. {
  215350. handleDragAndDropPosition (clientMsg);
  215351. }
  215352. else if (clientMsg->message_type == XA_XdndDrop)
  215353. {
  215354. handleDragAndDropDrop (clientMsg);
  215355. }
  215356. else if (clientMsg->message_type == XA_XdndStatus)
  215357. {
  215358. handleDragAndDropStatus (clientMsg);
  215359. }
  215360. else if (clientMsg->message_type == XA_XdndFinished)
  215361. {
  215362. resetDragAndDrop();
  215363. }
  215364. break;
  215365. }
  215366. case SelectionNotify:
  215367. handleDragAndDropSelection (event);
  215368. break;
  215369. case SelectionClear:
  215370. case SelectionRequest:
  215371. break;
  215372. default:
  215373. break;
  215374. }
  215375. }
  215376. void showMouseCursor (Cursor cursor) throw()
  215377. {
  215378. XDefineCursor (display, windowH, cursor);
  215379. }
  215380. void setTaskBarIcon (const Image& image)
  215381. {
  215382. deleteTaskBarIcon();
  215383. taskbarImage = image.createCopy();
  215384. Screen* const screen = XDefaultScreenOfDisplay (display);
  215385. const int screenNumber = XScreenNumberOfScreen (screen);
  215386. char screenAtom[32];
  215387. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  215388. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  215389. XGrabServer (display);
  215390. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  215391. if (managerWin != None)
  215392. XSelectInput (display, managerWin, StructureNotifyMask);
  215393. XUngrabServer (display);
  215394. XFlush (display);
  215395. if (managerWin != None)
  215396. {
  215397. XEvent ev;
  215398. zerostruct (ev);
  215399. ev.xclient.type = ClientMessage;
  215400. ev.xclient.window = managerWin;
  215401. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  215402. ev.xclient.format = 32;
  215403. ev.xclient.data.l[0] = CurrentTime;
  215404. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  215405. ev.xclient.data.l[2] = windowH;
  215406. ev.xclient.data.l[3] = 0;
  215407. ev.xclient.data.l[4] = 0;
  215408. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  215409. XSync (display, False);
  215410. }
  215411. // For older KDE's ...
  215412. long atomData = 1;
  215413. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  215414. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  215415. // For more recent KDE's...
  215416. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  215417. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  215418. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  215419. XSizeHints* hints = XAllocSizeHints();
  215420. hints->flags = PMinSize;
  215421. hints->min_width = 22;
  215422. hints->min_height = 22;
  215423. XSetWMNormalHints (display, windowH, hints);
  215424. XFree (hints);
  215425. }
  215426. void deleteTaskBarIcon()
  215427. {
  215428. deleteAndZero (taskbarImage);
  215429. }
  215430. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  215431. juce_UseDebuggingNewOperator
  215432. bool dontRepaint;
  215433. private:
  215434. class LinuxRepaintManager : public Timer
  215435. {
  215436. public:
  215437. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  215438. : peer (peer_),
  215439. image (0),
  215440. lastTimeImageUsed (0)
  215441. {
  215442. #if JUCE_USE_XSHM
  215443. useARGBImagesForRendering = isShmAvailable();
  215444. if (useARGBImagesForRendering)
  215445. {
  215446. XShmSegmentInfo segmentinfo;
  215447. XImage* const testImage
  215448. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  215449. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  215450. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  215451. XDestroyImage (testImage);
  215452. }
  215453. #endif
  215454. }
  215455. ~LinuxRepaintManager()
  215456. {
  215457. delete image;
  215458. }
  215459. void timerCallback()
  215460. {
  215461. if (! regionsNeedingRepaint.isEmpty())
  215462. {
  215463. stopTimer();
  215464. performAnyPendingRepaintsNow();
  215465. }
  215466. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  215467. {
  215468. stopTimer();
  215469. deleteAndZero (image);
  215470. }
  215471. }
  215472. void repaint (int x, int y, int w, int h)
  215473. {
  215474. if (! isTimerRunning())
  215475. startTimer (repaintTimerPeriod);
  215476. regionsNeedingRepaint.add (x, y, w, h);
  215477. }
  215478. void performAnyPendingRepaintsNow()
  215479. {
  215480. peer->clearMaskedRegion();
  215481. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  215482. if (! totalArea.isEmpty())
  215483. {
  215484. if (image == 0 || image->getWidth() < totalArea.getWidth()
  215485. || image->getHeight() < totalArea.getHeight())
  215486. {
  215487. delete image;
  215488. #if JUCE_USE_XSHM
  215489. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  215490. : Image::RGB,
  215491. #else
  215492. image = new XBitmapImage (Image::RGB,
  215493. #endif
  215494. (totalArea.getWidth() + 31) & ~31,
  215495. (totalArea.getHeight() + 31) & ~31,
  215496. false,
  215497. peer->depthIs16Bit);
  215498. }
  215499. startTimer (repaintTimerPeriod);
  215500. LowLevelGraphicsSoftwareRenderer context (*image);
  215501. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  215502. if (context.reduceClipRegion (regionsNeedingRepaint))
  215503. peer->handlePaint (context);
  215504. if (! peer->maskedRegion.isEmpty())
  215505. regionsNeedingRepaint.subtract (peer->maskedRegion);
  215506. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  215507. {
  215508. const Rectangle& r = *i.getRectangle();
  215509. image->blitToWindow (peer->windowH,
  215510. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  215511. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  215512. }
  215513. }
  215514. regionsNeedingRepaint.clear();
  215515. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  215516. startTimer (repaintTimerPeriod);
  215517. }
  215518. private:
  215519. LinuxComponentPeer* const peer;
  215520. XBitmapImage* image;
  215521. uint32 lastTimeImageUsed;
  215522. RectangleList regionsNeedingRepaint;
  215523. #if JUCE_USE_XSHM
  215524. bool useARGBImagesForRendering;
  215525. #endif
  215526. LinuxRepaintManager (const LinuxRepaintManager&);
  215527. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  215528. };
  215529. LinuxRepaintManager* repainter;
  215530. friend class LinuxRepaintManager;
  215531. Window windowH, parentWindow;
  215532. int wx, wy, ww, wh;
  215533. Image* taskbarImage;
  215534. bool fullScreen, entered, mapped, depthIs16Bit;
  215535. BorderSize windowBorder;
  215536. void removeWindowDecorations (Window wndH)
  215537. {
  215538. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  215539. if (hints != None)
  215540. {
  215541. typedef struct
  215542. {
  215543. unsigned long flags;
  215544. unsigned long functions;
  215545. unsigned long decorations;
  215546. long input_mode;
  215547. unsigned long status;
  215548. } MotifWmHints;
  215549. MotifWmHints motifHints;
  215550. zerostruct (motifHints);
  215551. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  215552. motifHints.decorations = 0;
  215553. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  215554. (unsigned char*) &motifHints, 4);
  215555. }
  215556. hints = XInternAtom (display, "_WIN_HINTS", True);
  215557. if (hints != None)
  215558. {
  215559. long gnomeHints = 0;
  215560. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  215561. (unsigned char*) &gnomeHints, 1);
  215562. }
  215563. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  215564. if (hints != None)
  215565. {
  215566. long kwmHints = 2; /*KDE_tinyDecoration*/
  215567. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  215568. (unsigned char*) &kwmHints, 1);
  215569. }
  215570. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  215571. if (hints != None)
  215572. {
  215573. int netHints [2];
  215574. int numHints = 0;
  215575. if ((styleFlags & windowIsTemporary) != 0)
  215576. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  215577. else
  215578. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  215579. if (netHints [numHints] != 0)
  215580. ++numHints;
  215581. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  215582. if (netHints [numHints] != 0)
  215583. ++numHints;
  215584. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  215585. (unsigned char*) &netHints, numHints);
  215586. }
  215587. }
  215588. void addWindowButtons (Window wndH)
  215589. {
  215590. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  215591. if (hints != None)
  215592. {
  215593. typedef struct
  215594. {
  215595. unsigned long flags;
  215596. unsigned long functions;
  215597. unsigned long decorations;
  215598. long input_mode;
  215599. unsigned long status;
  215600. } MotifWmHints;
  215601. MotifWmHints motifHints;
  215602. zerostruct (motifHints);
  215603. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  215604. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  215605. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  215606. if ((styleFlags & windowHasCloseButton) != 0)
  215607. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  215608. if ((styleFlags & windowHasMinimiseButton) != 0)
  215609. {
  215610. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  215611. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  215612. }
  215613. if ((styleFlags & windowHasMaximiseButton) != 0)
  215614. {
  215615. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  215616. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  215617. }
  215618. if ((styleFlags & windowIsResizable) != 0)
  215619. {
  215620. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  215621. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  215622. }
  215623. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  215624. }
  215625. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  215626. if (hints != None)
  215627. {
  215628. int netHints [6];
  215629. int num = 0;
  215630. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  215631. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  215632. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  215633. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  215634. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  215635. (unsigned char*) &netHints, num);
  215636. }
  215637. }
  215638. void createWindow()
  215639. {
  215640. static bool atomsInitialised = false;
  215641. if (! atomsInitialised)
  215642. {
  215643. atomsInitialised = true;
  215644. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  215645. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  215646. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  215647. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  215648. wm_State = XInternAtom (display, "WM_STATE", 1);
  215649. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  215650. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  215651. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  215652. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  215653. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  215654. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  215655. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  215656. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  215657. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  215658. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  215659. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  215660. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  215661. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  215662. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  215663. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  215664. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  215665. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  215666. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  215667. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  215668. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  215669. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  215670. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  215671. }
  215672. resetDragAndDrop();
  215673. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  215674. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  215675. allowedMimeTypeAtoms [1] = XA_OtherMime;
  215676. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  215677. allowedActions [0] = XA_XdndActionMove;
  215678. allowedActions [1] = XA_XdndActionCopy;
  215679. allowedActions [2] = XA_XdndActionLink;
  215680. allowedActions [3] = XA_XdndActionAsk;
  215681. allowedActions [4] = XA_XdndActionPrivate;
  215682. // Get defaults for various properties
  215683. const int screen = DefaultScreen (display);
  215684. Window root = RootWindow (display, screen);
  215685. // Attempt to create a 24-bit window on the default screen. If this is not
  215686. // possible then exit
  215687. XVisualInfo desiredVisual;
  215688. desiredVisual.screen = screen;
  215689. desiredVisual.depth = 24;
  215690. depthIs16Bit = false;
  215691. int numVisuals;
  215692. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  215693. &desiredVisual, &numVisuals);
  215694. if (numVisuals < 1 || visuals == 0)
  215695. {
  215696. XFree (visuals);
  215697. desiredVisual.depth = 16;
  215698. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  215699. &desiredVisual, &numVisuals);
  215700. if (numVisuals < 1 || visuals == 0)
  215701. {
  215702. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  215703. Process::terminate();
  215704. }
  215705. depthIs16Bit = true;
  215706. }
  215707. XFree (visuals);
  215708. // Set up the window attributes
  215709. XSetWindowAttributes swa;
  215710. swa.border_pixel = 0;
  215711. swa.background_pixmap = None;
  215712. swa.colormap = DefaultColormap (display, screen);
  215713. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  215714. swa.event_mask = eventMask;
  215715. Window wndH = XCreateWindow (display, root,
  215716. 0, 0, 1, 1,
  215717. 0, 0, InputOutput, (Visual*) CopyFromParent,
  215718. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  215719. &swa);
  215720. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  215721. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  215722. GrabModeAsync, GrabModeAsync, None, None);
  215723. // Set the window context to identify the window handle object
  215724. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  215725. {
  215726. // Failed
  215727. jassertfalse
  215728. Logger::outputDebugString ("Failed to create context information for window.\n");
  215729. XDestroyWindow (display, wndH);
  215730. wndH = 0;
  215731. }
  215732. // Set window manager hints
  215733. XWMHints* wmHints = XAllocWMHints();
  215734. wmHints->flags = InputHint | StateHint;
  215735. wmHints->input = True; // Locally active input model
  215736. wmHints->initial_state = NormalState;
  215737. XSetWMHints (display, wndH, wmHints);
  215738. XFree (wmHints);
  215739. if ((styleFlags & windowIsSemiTransparent) != 0)
  215740. {
  215741. //xxx
  215742. }
  215743. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  215744. {
  215745. //xxx
  215746. }
  215747. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  215748. if ((styleFlags & windowHasTitleBar) == 0)
  215749. removeWindowDecorations (wndH);
  215750. else
  215751. addWindowButtons (wndH);
  215752. // Set window manager protocols
  215753. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  215754. (unsigned char*) wm_ProtocolList, 2);
  215755. // Set drag and drop flags
  215756. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  215757. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  215758. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  215759. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  215760. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  215761. (const unsigned char*) "", 0);
  215762. unsigned long dndVersion = ourDndVersion;
  215763. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  215764. (const unsigned char*) &dndVersion, 1);
  215765. // Set window name
  215766. setWindowTitle (wndH, getComponent()->getName());
  215767. // Initialise the pointer and keyboard mapping
  215768. // This is not the same as the logical pointer mapping the X server uses:
  215769. // we don't mess with this.
  215770. static bool mappingInitialised = false;
  215771. if (! mappingInitialised)
  215772. {
  215773. mappingInitialised = true;
  215774. const int numButtons = XGetPointerMapping (display, 0, 0);
  215775. if (numButtons == 2)
  215776. {
  215777. pointerMap[0] = LeftButton;
  215778. pointerMap[1] = RightButton;
  215779. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  215780. }
  215781. else if (numButtons >= 3)
  215782. {
  215783. pointerMap[0] = LeftButton;
  215784. pointerMap[1] = MiddleButton;
  215785. pointerMap[2] = RightButton;
  215786. if (numButtons >= 5)
  215787. {
  215788. pointerMap[3] = WheelUp;
  215789. pointerMap[4] = WheelDown;
  215790. }
  215791. }
  215792. getModifierMapping();
  215793. }
  215794. windowH = wndH;
  215795. }
  215796. void destroyWindow()
  215797. {
  215798. XPointer handlePointer;
  215799. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  215800. XDeleteContext (display, (XID) windowH, improbableNumber);
  215801. XDestroyWindow (display, windowH);
  215802. // Wait for it to complete and then remove any events for this
  215803. // window from the event queue.
  215804. XSync (display, false);
  215805. XEvent event;
  215806. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  215807. {}
  215808. }
  215809. static int64 getEventTime (::Time t) throw()
  215810. {
  215811. static int64 eventTimeOffset = 0x12345678;
  215812. const int64 thisMessageTime = t;
  215813. if (eventTimeOffset == 0x12345678)
  215814. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  215815. return eventTimeOffset + thisMessageTime;
  215816. }
  215817. static void setWindowTitle (Window xwin, const char* const title) throw()
  215818. {
  215819. XTextProperty nameProperty;
  215820. char* strings[] = { (char*) title };
  215821. if (XStringListToTextProperty (strings, 1, &nameProperty))
  215822. {
  215823. XSetWMName (display, xwin, &nameProperty);
  215824. XSetWMIconName (display, xwin, &nameProperty);
  215825. XFree (nameProperty.value);
  215826. }
  215827. }
  215828. void updateBorderSize()
  215829. {
  215830. if ((styleFlags & windowHasTitleBar) == 0)
  215831. {
  215832. windowBorder = BorderSize (0);
  215833. }
  215834. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  215835. {
  215836. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  215837. if (hints != None)
  215838. {
  215839. unsigned char* data = 0;
  215840. unsigned long nitems, bytesLeft;
  215841. Atom actualType;
  215842. int actualFormat;
  215843. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  215844. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  215845. &data) == Success)
  215846. {
  215847. const unsigned long* const sizes = (const unsigned long*) data;
  215848. if (actualFormat == 32)
  215849. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  215850. (int) sizes[3], (int) sizes[1]);
  215851. XFree (data);
  215852. }
  215853. }
  215854. }
  215855. }
  215856. void updateBounds()
  215857. {
  215858. jassert (windowH != 0);
  215859. if (windowH != 0)
  215860. {
  215861. Window root, child;
  215862. unsigned int bw, depth;
  215863. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  215864. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  215865. &bw, &depth))
  215866. {
  215867. wx = wy = ww = wh = 0;
  215868. }
  215869. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  215870. {
  215871. wx = wy = 0;
  215872. }
  215873. }
  215874. }
  215875. void resetDragAndDrop()
  215876. {
  215877. dragAndDropFiles.clear();
  215878. lastDropX = lastDropY = -1;
  215879. dragAndDropCurrentMimeType = 0;
  215880. dragAndDropSourceWindow = 0;
  215881. srcMimeTypeAtomList.clear();
  215882. }
  215883. void sendDragAndDropMessage (XClientMessageEvent& msg)
  215884. {
  215885. msg.type = ClientMessage;
  215886. msg.display = display;
  215887. msg.window = dragAndDropSourceWindow;
  215888. msg.format = 32;
  215889. msg.data.l[0] = windowH;
  215890. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  215891. }
  215892. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  215893. {
  215894. XClientMessageEvent msg;
  215895. zerostruct (msg);
  215896. msg.message_type = XA_XdndStatus;
  215897. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  215898. msg.data.l[4] = dropAction;
  215899. sendDragAndDropMessage (msg);
  215900. }
  215901. void sendDragAndDropLeave()
  215902. {
  215903. XClientMessageEvent msg;
  215904. zerostruct (msg);
  215905. msg.message_type = XA_XdndLeave;
  215906. sendDragAndDropMessage (msg);
  215907. }
  215908. void sendDragAndDropFinish()
  215909. {
  215910. XClientMessageEvent msg;
  215911. zerostruct (msg);
  215912. msg.message_type = XA_XdndFinished;
  215913. sendDragAndDropMessage (msg);
  215914. }
  215915. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  215916. {
  215917. if ((clientMsg->data.l[1] & 1) == 0)
  215918. {
  215919. sendDragAndDropLeave();
  215920. if (dragAndDropFiles.size() > 0)
  215921. handleFileDragExit (dragAndDropFiles);
  215922. dragAndDropFiles.clear();
  215923. }
  215924. }
  215925. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  215926. {
  215927. if (dragAndDropSourceWindow == 0)
  215928. return;
  215929. dragAndDropSourceWindow = clientMsg->data.l[0];
  215930. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  215931. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  215932. if (lastDropX != dropX || lastDropY != dropY)
  215933. {
  215934. lastDropX = dropX;
  215935. lastDropY = dropY;
  215936. dragAndDropTimestamp = clientMsg->data.l[3];
  215937. Atom targetAction = XA_XdndActionCopy;
  215938. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  215939. {
  215940. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  215941. {
  215942. targetAction = allowedActions[i];
  215943. break;
  215944. }
  215945. }
  215946. sendDragAndDropStatus (true, targetAction);
  215947. if (dragAndDropFiles.size() == 0)
  215948. updateDraggedFileList (clientMsg);
  215949. if (dragAndDropFiles.size() > 0)
  215950. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  215951. }
  215952. }
  215953. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  215954. {
  215955. if (dragAndDropFiles.size() == 0)
  215956. updateDraggedFileList (clientMsg);
  215957. const StringArray files (dragAndDropFiles);
  215958. const int lastX = lastDropX, lastY = lastDropY;
  215959. sendDragAndDropFinish();
  215960. resetDragAndDrop();
  215961. if (files.size() > 0)
  215962. handleFileDragDrop (files, lastX, lastY);
  215963. }
  215964. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  215965. {
  215966. dragAndDropFiles.clear();
  215967. srcMimeTypeAtomList.clear();
  215968. dragAndDropCurrentMimeType = 0;
  215969. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  215970. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  215971. {
  215972. dragAndDropSourceWindow = 0;
  215973. return;
  215974. }
  215975. dragAndDropSourceWindow = clientMsg->data.l[0];
  215976. if ((clientMsg->data.l[1] & 1) != 0)
  215977. {
  215978. Atom actual;
  215979. int format;
  215980. unsigned long count = 0, remaining = 0;
  215981. unsigned char* data = 0;
  215982. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  215983. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  215984. &count, &remaining, &data);
  215985. if (data != 0)
  215986. {
  215987. if (actual == XA_ATOM && format == 32 && count != 0)
  215988. {
  215989. const unsigned long* const types = (const unsigned long*) data;
  215990. for (unsigned int i = 0; i < count; ++i)
  215991. if (types[i] != None)
  215992. srcMimeTypeAtomList.add (types[i]);
  215993. }
  215994. XFree (data);
  215995. }
  215996. }
  215997. if (srcMimeTypeAtomList.size() == 0)
  215998. {
  215999. for (int i = 2; i < 5; ++i)
  216000. if (clientMsg->data.l[i] != None)
  216001. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  216002. if (srcMimeTypeAtomList.size() == 0)
  216003. {
  216004. dragAndDropSourceWindow = 0;
  216005. return;
  216006. }
  216007. }
  216008. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  216009. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  216010. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  216011. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  216012. handleDragAndDropPosition (clientMsg);
  216013. }
  216014. void handleDragAndDropSelection (const XEvent* const evt)
  216015. {
  216016. dragAndDropFiles.clear();
  216017. if (evt->xselection.property != 0)
  216018. {
  216019. StringArray lines;
  216020. {
  216021. MemoryBlock dropData;
  216022. for (;;)
  216023. {
  216024. Atom actual;
  216025. uint8* data = 0;
  216026. unsigned long count = 0, remaining = 0;
  216027. int format = 0;
  216028. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  216029. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  216030. &format, &count, &remaining, &data) == Success)
  216031. {
  216032. dropData.append (data, count * format / 8);
  216033. XFree (data);
  216034. if (remaining == 0)
  216035. break;
  216036. }
  216037. else
  216038. {
  216039. XFree (data);
  216040. break;
  216041. }
  216042. }
  216043. lines.addLines (dropData.toString());
  216044. }
  216045. for (int i = 0; i < lines.size(); ++i)
  216046. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  216047. dragAndDropFiles.trim();
  216048. dragAndDropFiles.removeEmptyStrings();
  216049. }
  216050. }
  216051. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  216052. {
  216053. dragAndDropFiles.clear();
  216054. if (dragAndDropSourceWindow != None
  216055. && dragAndDropCurrentMimeType != 0)
  216056. {
  216057. dragAndDropTimestamp = clientMsg->data.l[2];
  216058. XConvertSelection (display,
  216059. XA_XdndSelection,
  216060. dragAndDropCurrentMimeType,
  216061. XA_JXSelectionWindowProperty,
  216062. windowH,
  216063. dragAndDropTimestamp);
  216064. }
  216065. }
  216066. StringArray dragAndDropFiles;
  216067. int dragAndDropTimestamp, lastDropX, lastDropY;
  216068. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  216069. Window dragAndDropSourceWindow;
  216070. unsigned int allowedActions [5];
  216071. unsigned int allowedMimeTypeAtoms [3];
  216072. Array <Atom> srcMimeTypeAtomList;
  216073. };
  216074. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  216075. {
  216076. if (enableOrDisable)
  216077. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  216078. }
  216079. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  216080. {
  216081. return new LinuxComponentPeer (this, styleFlags);
  216082. }
  216083. // (this callback is hooked up in the messaging code)
  216084. void juce_windowMessageReceive (XEvent* event)
  216085. {
  216086. if (event->xany.window != None)
  216087. {
  216088. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  216089. if (ComponentPeer::isValidPeer (peer))
  216090. peer->handleWindowMessage (event);
  216091. }
  216092. else
  216093. {
  216094. switch (event->xany.type)
  216095. {
  216096. case KeymapNotify:
  216097. {
  216098. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  216099. memcpy (keyStates, keymapEvent->key_vector, 32);
  216100. break;
  216101. }
  216102. default:
  216103. break;
  216104. }
  216105. }
  216106. }
  216107. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  216108. {
  216109. #if JUCE_USE_XINERAMA
  216110. int major_opcode, first_event, first_error;
  216111. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  216112. && XineramaIsActive (display))
  216113. {
  216114. int numMonitors = 0;
  216115. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  216116. if (screens != 0)
  216117. {
  216118. for (int i = numMonitors; --i >= 0;)
  216119. {
  216120. int index = screens[i].screen_number;
  216121. if (index >= 0)
  216122. {
  216123. while (monitorCoords.size() < index)
  216124. monitorCoords.add (Rectangle (0, 0, 0, 0));
  216125. monitorCoords.set (index, Rectangle (screens[i].x_org,
  216126. screens[i].y_org,
  216127. screens[i].width,
  216128. screens[i].height));
  216129. }
  216130. }
  216131. XFree (screens);
  216132. }
  216133. }
  216134. if (monitorCoords.size() == 0)
  216135. #endif
  216136. {
  216137. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  216138. if (hints != None)
  216139. {
  216140. const int numMonitors = ScreenCount (display);
  216141. for (int i = 0; i < numMonitors; ++i)
  216142. {
  216143. Window root = RootWindow (display, i);
  216144. unsigned long nitems, bytesLeft;
  216145. Atom actualType;
  216146. int actualFormat;
  216147. unsigned char* data = 0;
  216148. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  216149. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216150. &data) == Success)
  216151. {
  216152. const long* const position = (const long*) data;
  216153. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  216154. monitorCoords.add (Rectangle (position[0], position[1],
  216155. position[2], position[3]));
  216156. XFree (data);
  216157. }
  216158. }
  216159. }
  216160. if (monitorCoords.size() == 0)
  216161. {
  216162. monitorCoords.add (Rectangle (0, 0,
  216163. DisplayWidth (display, DefaultScreen (display)),
  216164. DisplayHeight (display, DefaultScreen (display))));
  216165. }
  216166. }
  216167. }
  216168. bool Desktop::canUseSemiTransparentWindows() throw()
  216169. {
  216170. return false;
  216171. }
  216172. void Desktop::getMousePosition (int& x, int& y) throw()
  216173. {
  216174. int mouseMods;
  216175. getMousePos (x, y, mouseMods);
  216176. }
  216177. void Desktop::setMousePosition (int x, int y) throw()
  216178. {
  216179. Window root = RootWindow (display, DefaultScreen (display));
  216180. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  216181. }
  216182. static bool screenSaverAllowed = true;
  216183. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  216184. {
  216185. if (screenSaverAllowed != isEnabled)
  216186. {
  216187. screenSaverAllowed = isEnabled;
  216188. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  216189. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  216190. if (xScreenSaverSuspend == 0)
  216191. {
  216192. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  216193. if (h != 0)
  216194. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  216195. }
  216196. if (xScreenSaverSuspend != 0)
  216197. xScreenSaverSuspend (display, ! isEnabled);
  216198. }
  216199. }
  216200. bool Desktop::isScreenSaverEnabled() throw()
  216201. {
  216202. return screenSaverAllowed;
  216203. }
  216204. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  216205. {
  216206. Window root = RootWindow (display, DefaultScreen (display));
  216207. const unsigned int imageW = image.getWidth();
  216208. const unsigned int imageH = image.getHeight();
  216209. unsigned int cursorW, cursorH;
  216210. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  216211. return 0;
  216212. Image im (Image::ARGB, cursorW, cursorH, true);
  216213. Graphics g (im);
  216214. if (imageW > cursorW || imageH > cursorH)
  216215. {
  216216. hotspotX = (hotspotX * cursorW) / imageW;
  216217. hotspotY = (hotspotY * cursorH) / imageH;
  216218. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  216219. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  216220. false);
  216221. }
  216222. else
  216223. {
  216224. g.drawImageAt (&image, 0, 0);
  216225. }
  216226. const int stride = (cursorW + 7) >> 3;
  216227. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  216228. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  216229. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216230. for (int y = cursorH; --y >= 0;)
  216231. {
  216232. for (int x = cursorW; --x >= 0;)
  216233. {
  216234. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216235. const int offset = y * stride + (x >> 3);
  216236. const Colour c (im.getPixelAt (x, y));
  216237. if (c.getAlpha() >= 128)
  216238. maskPlane[offset] |= mask;
  216239. if (c.getBrightness() >= 0.5f)
  216240. sourcePlane[offset] |= mask;
  216241. }
  216242. }
  216243. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  216244. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  216245. juce_free (maskPlane);
  216246. juce_free (sourcePlane);
  216247. XColor white, black;
  216248. black.red = black.green = black.blue = 0;
  216249. white.red = white.green = white.blue = 0xffff;
  216250. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  216251. XFreePixmap (display, sourcePixmap);
  216252. XFreePixmap (display, maskPixmap);
  216253. return result;
  216254. }
  216255. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  216256. {
  216257. if (cursorHandle != None)
  216258. XFreeCursor (display, (Cursor) cursorHandle);
  216259. }
  216260. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  216261. {
  216262. unsigned int shape;
  216263. switch (type)
  216264. {
  216265. case MouseCursor::NoCursor:
  216266. {
  216267. const Image im (Image::ARGB, 16, 16, true);
  216268. return juce_createMouseCursorFromImage (im, 0, 0);
  216269. }
  216270. case MouseCursor::NormalCursor:
  216271. return (void*) None; // Use parent cursor
  216272. case MouseCursor::DraggingHandCursor:
  216273. {
  216274. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  216275. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  216276. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  216277. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  216278. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  216279. const int dragHandDataSize = 99;
  216280. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  216281. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  216282. delete im;
  216283. return dragHandCursor;
  216284. }
  216285. case MouseCursor::CopyingCursor:
  216286. {
  216287. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  216288. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  216289. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  216290. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  216291. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  216292. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  216293. const int copyCursorSize = 119;
  216294. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  216295. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  216296. delete im;
  216297. return copyCursor;
  216298. }
  216299. case MouseCursor::WaitCursor:
  216300. shape = XC_watch;
  216301. break;
  216302. case MouseCursor::IBeamCursor:
  216303. shape = XC_xterm;
  216304. break;
  216305. case MouseCursor::PointingHandCursor:
  216306. shape = XC_hand2;
  216307. break;
  216308. case MouseCursor::LeftRightResizeCursor:
  216309. shape = XC_sb_h_double_arrow;
  216310. break;
  216311. case MouseCursor::UpDownResizeCursor:
  216312. shape = XC_sb_v_double_arrow;
  216313. break;
  216314. case MouseCursor::UpDownLeftRightResizeCursor:
  216315. shape = XC_fleur;
  216316. break;
  216317. case MouseCursor::TopEdgeResizeCursor:
  216318. shape = XC_top_side;
  216319. break;
  216320. case MouseCursor::BottomEdgeResizeCursor:
  216321. shape = XC_bottom_side;
  216322. break;
  216323. case MouseCursor::LeftEdgeResizeCursor:
  216324. shape = XC_left_side;
  216325. break;
  216326. case MouseCursor::RightEdgeResizeCursor:
  216327. shape = XC_right_side;
  216328. break;
  216329. case MouseCursor::TopLeftCornerResizeCursor:
  216330. shape = XC_top_left_corner;
  216331. break;
  216332. case MouseCursor::TopRightCornerResizeCursor:
  216333. shape = XC_top_right_corner;
  216334. break;
  216335. case MouseCursor::BottomLeftCornerResizeCursor:
  216336. shape = XC_bottom_left_corner;
  216337. break;
  216338. case MouseCursor::BottomRightCornerResizeCursor:
  216339. shape = XC_bottom_right_corner;
  216340. break;
  216341. case MouseCursor::CrosshairCursor:
  216342. shape = XC_crosshair;
  216343. break;
  216344. default:
  216345. return (void*) None; // Use parent cursor
  216346. }
  216347. return (void*) XCreateFontCursor (display, shape);
  216348. }
  216349. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  216350. {
  216351. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  216352. if (lp != 0)
  216353. lp->showMouseCursor ((Cursor) getHandle());
  216354. }
  216355. void MouseCursor::showInAllWindows() const throw()
  216356. {
  216357. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  216358. showInWindow (ComponentPeer::getPeer (i));
  216359. }
  216360. Image* juce_createIconForFile (const File& file)
  216361. {
  216362. return 0;
  216363. }
  216364. #if JUCE_OPENGL
  216365. class WindowedGLContext : public OpenGLContext
  216366. {
  216367. public:
  216368. WindowedGLContext (Component* const component,
  216369. const OpenGLPixelFormat& pixelFormat_,
  216370. GLXContext sharedContext)
  216371. : renderContext (0),
  216372. embeddedWindow (0),
  216373. pixelFormat (pixelFormat_)
  216374. {
  216375. jassert (component != 0);
  216376. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  216377. if (peer == 0)
  216378. return;
  216379. XSync (display, False);
  216380. GLint attribs [64];
  216381. int n = 0;
  216382. attribs[n++] = GLX_RGBA;
  216383. attribs[n++] = GLX_DOUBLEBUFFER;
  216384. attribs[n++] = GLX_RED_SIZE;
  216385. attribs[n++] = pixelFormat.redBits;
  216386. attribs[n++] = GLX_GREEN_SIZE;
  216387. attribs[n++] = pixelFormat.greenBits;
  216388. attribs[n++] = GLX_BLUE_SIZE;
  216389. attribs[n++] = pixelFormat.blueBits;
  216390. attribs[n++] = GLX_ALPHA_SIZE;
  216391. attribs[n++] = pixelFormat.alphaBits;
  216392. attribs[n++] = GLX_DEPTH_SIZE;
  216393. attribs[n++] = pixelFormat.depthBufferBits;
  216394. attribs[n++] = GLX_STENCIL_SIZE;
  216395. attribs[n++] = pixelFormat.stencilBufferBits;
  216396. attribs[n++] = GLX_ACCUM_RED_SIZE;
  216397. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  216398. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  216399. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  216400. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  216401. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  216402. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  216403. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  216404. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  216405. attribs[n++] = None;
  216406. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  216407. if (bestVisual == 0)
  216408. return;
  216409. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  216410. Window windowH = (Window) peer->getNativeHandle();
  216411. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  216412. XSetWindowAttributes swa;
  216413. swa.colormap = colourMap;
  216414. swa.border_pixel = 0;
  216415. swa.event_mask = ExposureMask | StructureNotifyMask;
  216416. embeddedWindow = XCreateWindow (display, windowH,
  216417. 0, 0, 1, 1, 0,
  216418. bestVisual->depth,
  216419. InputOutput,
  216420. bestVisual->visual,
  216421. CWBorderPixel | CWColormap | CWEventMask,
  216422. &swa);
  216423. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  216424. XMapWindow (display, embeddedWindow);
  216425. XFreeColormap (display, colourMap);
  216426. XFree (bestVisual);
  216427. XSync (display, False);
  216428. }
  216429. ~WindowedGLContext()
  216430. {
  216431. makeInactive();
  216432. glXDestroyContext (display, renderContext);
  216433. XUnmapWindow (display, embeddedWindow);
  216434. XDestroyWindow (display, embeddedWindow);
  216435. }
  216436. bool makeActive() const throw()
  216437. {
  216438. jassert (renderContext != 0);
  216439. return glXMakeCurrent (display, embeddedWindow, renderContext)
  216440. && XSync (display, False);
  216441. }
  216442. bool makeInactive() const throw()
  216443. {
  216444. return (! isActive()) || glXMakeCurrent (display, None, 0);
  216445. }
  216446. bool isActive() const throw()
  216447. {
  216448. return glXGetCurrentContext() == renderContext;
  216449. }
  216450. const OpenGLPixelFormat getPixelFormat() const
  216451. {
  216452. return pixelFormat;
  216453. }
  216454. void* getRawContext() const throw()
  216455. {
  216456. return renderContext;
  216457. }
  216458. void updateWindowPosition (int x, int y, int w, int h, int)
  216459. {
  216460. XMoveResizeWindow (display, embeddedWindow,
  216461. x, y, jmax (1, w), jmax (1, h));
  216462. }
  216463. void swapBuffers()
  216464. {
  216465. glXSwapBuffers (display, embeddedWindow);
  216466. }
  216467. bool setSwapInterval (const int numFramesPerSwap)
  216468. {
  216469. // xxx needs doing..
  216470. return false;
  216471. }
  216472. int getSwapInterval() const
  216473. {
  216474. // xxx needs doing..
  216475. return 0;
  216476. }
  216477. void repaint()
  216478. {
  216479. }
  216480. juce_UseDebuggingNewOperator
  216481. GLXContext renderContext;
  216482. private:
  216483. Window embeddedWindow;
  216484. OpenGLPixelFormat pixelFormat;
  216485. WindowedGLContext (const WindowedGLContext&);
  216486. const WindowedGLContext& operator= (const WindowedGLContext&);
  216487. };
  216488. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  216489. const OpenGLPixelFormat& pixelFormat,
  216490. const OpenGLContext* const contextToShareWith)
  216491. {
  216492. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  216493. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  216494. if (c->renderContext == 0)
  216495. deleteAndZero (c);
  216496. return c;
  216497. }
  216498. void juce_glViewport (const int w, const int h)
  216499. {
  216500. glViewport (0, 0, w, h);
  216501. }
  216502. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  216503. OwnedArray <OpenGLPixelFormat>& results)
  216504. {
  216505. results.add (new OpenGLPixelFormat()); // xxx
  216506. }
  216507. #endif
  216508. static void initClipboard (Window root, Atom* cutBuffers) throw()
  216509. {
  216510. static bool init = false;
  216511. if (! init)
  216512. {
  216513. init = true;
  216514. // Make sure all cut buffers exist before use
  216515. for (int i = 0; i < 8; i++)
  216516. {
  216517. XChangeProperty (display, root, cutBuffers[i],
  216518. XA_STRING, 8, PropModeAppend, NULL, 0);
  216519. }
  216520. }
  216521. }
  216522. // Clipboard implemented currently using cut buffers
  216523. // rather than the more powerful selection method
  216524. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  216525. {
  216526. Window root = RootWindow (display, DefaultScreen (display));
  216527. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  216528. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  216529. initClipboard (root, cutBuffers);
  216530. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  216531. XChangeProperty (display, root, cutBuffers[0],
  216532. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  216533. clipText.length());
  216534. }
  216535. const String SystemClipboard::getTextFromClipboard() throw()
  216536. {
  216537. const int bufSize = 64; // in words
  216538. String returnData;
  216539. int byteOffset = 0;
  216540. Window root = RootWindow (display, DefaultScreen (display));
  216541. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  216542. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  216543. initClipboard (root, cutBuffers);
  216544. for (;;)
  216545. {
  216546. unsigned long bytesLeft = 0, nitems = 0;
  216547. unsigned char* clipData = 0;
  216548. int actualFormat = 0;
  216549. Atom actualType;
  216550. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  216551. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  216552. &clipData) == Success)
  216553. {
  216554. if (actualType == XA_STRING && actualFormat == 8)
  216555. {
  216556. byteOffset += nitems;
  216557. returnData += String ((const char*) clipData, nitems);
  216558. }
  216559. else
  216560. {
  216561. bytesLeft = 0;
  216562. }
  216563. if (clipData != 0)
  216564. XFree (clipData);
  216565. }
  216566. if (bytesLeft == 0)
  216567. break;
  216568. }
  216569. return returnData;
  216570. }
  216571. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  216572. {
  216573. jassertfalse // not implemented!
  216574. return false;
  216575. }
  216576. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  216577. {
  216578. jassertfalse // not implemented!
  216579. return false;
  216580. }
  216581. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  216582. {
  216583. if (! isOnDesktop ())
  216584. addToDesktop (0);
  216585. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  216586. if (wp != 0)
  216587. {
  216588. wp->setTaskBarIcon (newImage);
  216589. setVisible (true);
  216590. toFront (false);
  216591. repaint();
  216592. }
  216593. }
  216594. void SystemTrayIconComponent::paint (Graphics& g)
  216595. {
  216596. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  216597. if (wp != 0)
  216598. {
  216599. const Image* const image = wp->getTaskbarIcon();
  216600. if (image != 0)
  216601. {
  216602. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  216603. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  216604. false);
  216605. }
  216606. }
  216607. }
  216608. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  216609. {
  216610. // xxx not yet implemented!
  216611. }
  216612. void PlatformUtilities::beep()
  216613. {
  216614. fprintf (stdout, "\a");
  216615. fflush (stdout);
  216616. }
  216617. bool AlertWindow::showNativeDialogBox (const String& title,
  216618. const String& bodyText,
  216619. bool isOkCancel)
  216620. {
  216621. // xxx this is supposed to pop up an alert!
  216622. Logger::outputDebugString (title + ": " + bodyText);
  216623. // use a non-native one for the time being..
  216624. if (isOkCancel)
  216625. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  216626. else
  216627. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  216628. return true;
  216629. }
  216630. const int KeyPress::spaceKey = XK_space & 0xff;
  216631. const int KeyPress::returnKey = XK_Return & 0xff;
  216632. const int KeyPress::escapeKey = XK_Escape & 0xff;
  216633. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  216634. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  216635. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  216636. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  216637. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  216638. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  216639. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  216640. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  216641. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  216642. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  216643. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  216644. const int KeyPress::tabKey = XK_Tab & 0xff;
  216645. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  216646. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  216647. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  216648. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  216649. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  216650. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  216651. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  216652. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  216653. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  216654. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  216655. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  216656. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  216657. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  216658. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  216659. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  216660. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  216661. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  216662. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  216663. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  216664. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  216665. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  216666. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  216667. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  216668. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  216669. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  216670. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  216671. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  216672. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  216673. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  216674. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  216675. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  216676. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  216677. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  216678. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  216679. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  216680. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  216681. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  216682. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  216683. #endif
  216684. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  216685. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  216686. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216687. // compiled on its own).
  216688. #ifdef JUCE_INCLUDED_FILE && JUCE_ALSA
  216689. static const int maxNumChans = 64;
  216690. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  216691. {
  216692. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  216693. snd_pcm_hw_params_t* hwParams;
  216694. snd_pcm_hw_params_alloca (&hwParams);
  216695. for (int i = 0; ratesToTry[i] != 0; ++i)
  216696. {
  216697. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  216698. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  216699. {
  216700. rates.addIfNotAlreadyThere (ratesToTry[i]);
  216701. }
  216702. }
  216703. }
  216704. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  216705. {
  216706. snd_pcm_hw_params_t *params;
  216707. snd_pcm_hw_params_alloca (&params);
  216708. if (snd_pcm_hw_params_any (handle, params) >= 0)
  216709. {
  216710. snd_pcm_hw_params_get_channels_min (params, minChans);
  216711. snd_pcm_hw_params_get_channels_max (params, maxChans);
  216712. }
  216713. }
  216714. static void getDeviceProperties (const String& id,
  216715. unsigned int& minChansOut,
  216716. unsigned int& maxChansOut,
  216717. unsigned int& minChansIn,
  216718. unsigned int& maxChansIn,
  216719. Array <int>& rates)
  216720. {
  216721. if (id.isEmpty())
  216722. return;
  216723. snd_ctl_t* handle;
  216724. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  216725. {
  216726. snd_pcm_info_t* info;
  216727. snd_pcm_info_alloca (&info);
  216728. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  216729. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  216730. snd_pcm_info_set_subdevice (info, 0);
  216731. if (snd_ctl_pcm_info (handle, info) >= 0)
  216732. {
  216733. snd_pcm_t* pcmHandle;
  216734. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  216735. {
  216736. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  216737. getDeviceSampleRates (pcmHandle, rates);
  216738. snd_pcm_close (pcmHandle);
  216739. }
  216740. }
  216741. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  216742. if (snd_ctl_pcm_info (handle, info) >= 0)
  216743. {
  216744. snd_pcm_t* pcmHandle;
  216745. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  216746. {
  216747. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  216748. if (rates.size() == 0)
  216749. getDeviceSampleRates (pcmHandle, rates);
  216750. snd_pcm_close (pcmHandle);
  216751. }
  216752. }
  216753. snd_ctl_close (handle);
  216754. }
  216755. }
  216756. class ALSADevice
  216757. {
  216758. public:
  216759. ALSADevice (const String& id,
  216760. const bool forInput)
  216761. : handle (0),
  216762. bitDepth (16),
  216763. numChannelsRunning (0),
  216764. isInput (forInput),
  216765. sampleFormat (AudioDataConverters::int16LE)
  216766. {
  216767. failed (snd_pcm_open (&handle, id,
  216768. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  216769. SND_PCM_ASYNC));
  216770. }
  216771. ~ALSADevice()
  216772. {
  216773. if (handle != 0)
  216774. snd_pcm_close (handle);
  216775. }
  216776. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  216777. {
  216778. if (handle == 0)
  216779. return false;
  216780. snd_pcm_hw_params_t* hwParams;
  216781. snd_pcm_hw_params_alloca (&hwParams);
  216782. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  216783. return false;
  216784. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  216785. isInterleaved = false;
  216786. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  216787. isInterleaved = true;
  216788. else
  216789. {
  216790. jassertfalse
  216791. return false;
  216792. }
  216793. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  216794. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  216795. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  216796. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  216797. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  216798. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  216799. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  216800. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  216801. bitDepth = 0;
  216802. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  216803. {
  216804. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  216805. {
  216806. bitDepth = formatsToTry [i + 1];
  216807. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  216808. break;
  216809. }
  216810. }
  216811. if (bitDepth == 0)
  216812. {
  216813. error = "device doesn't support a compatible PCM format";
  216814. DBG (T("ALSA error: ") + error + T("\n"));
  216815. return false;
  216816. }
  216817. int dir = 0;
  216818. unsigned int periods = 4;
  216819. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  216820. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  216821. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  216822. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  216823. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  216824. || failed (snd_pcm_hw_params (handle, hwParams)))
  216825. {
  216826. return false;
  216827. }
  216828. snd_pcm_sw_params_t* swParams;
  216829. snd_pcm_sw_params_alloca (&swParams);
  216830. snd_pcm_uframes_t boundary;
  216831. if (failed (snd_pcm_sw_params_current (handle, swParams))
  216832. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  216833. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  216834. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  216835. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  216836. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  216837. || failed (snd_pcm_sw_params (handle, swParams)))
  216838. {
  216839. return false;
  216840. }
  216841. /*
  216842. #ifdef JUCE_DEBUG
  216843. // enable this to dump the config of the devices that get opened
  216844. snd_output_t* out;
  216845. snd_output_stdio_attach (&out, stderr, 0);
  216846. snd_pcm_hw_params_dump (hwParams, out);
  216847. snd_pcm_sw_params_dump (swParams, out);
  216848. #endif
  216849. */
  216850. numChannelsRunning = numChannels;
  216851. return true;
  216852. }
  216853. bool write (float** const data, const int numSamples)
  216854. {
  216855. if (isInterleaved)
  216856. {
  216857. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  216858. float* interleaved = (float*) scratch;
  216859. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  216860. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  216861. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  216862. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  216863. return false;
  216864. }
  216865. else
  216866. {
  216867. for (int i = 0; i < numChannelsRunning; ++i)
  216868. if (data[i] != 0)
  216869. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  216870. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  216871. if (failed (num))
  216872. {
  216873. if (num == -EPIPE)
  216874. {
  216875. if (failed (snd_pcm_prepare (handle)))
  216876. return false;
  216877. }
  216878. else if (num != -ESTRPIPE)
  216879. return false;
  216880. }
  216881. }
  216882. return true;
  216883. }
  216884. bool read (float** const data, const int numSamples)
  216885. {
  216886. if (isInterleaved)
  216887. {
  216888. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  216889. float* interleaved = (float*) scratch;
  216890. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  216891. if (failed (num))
  216892. {
  216893. if (num == -EPIPE)
  216894. {
  216895. if (failed (snd_pcm_prepare (handle)))
  216896. return false;
  216897. }
  216898. else if (num != -ESTRPIPE)
  216899. return false;
  216900. }
  216901. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  216902. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  216903. }
  216904. else
  216905. {
  216906. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  216907. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  216908. return false;
  216909. for (int i = 0; i < numChannelsRunning; ++i)
  216910. if (data[i] != 0)
  216911. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  216912. }
  216913. return true;
  216914. }
  216915. juce_UseDebuggingNewOperator
  216916. snd_pcm_t* handle;
  216917. String error;
  216918. int bitDepth, numChannelsRunning;
  216919. private:
  216920. const bool isInput;
  216921. bool isInterleaved;
  216922. MemoryBlock scratch;
  216923. AudioDataConverters::DataFormat sampleFormat;
  216924. bool failed (const int errorNum)
  216925. {
  216926. if (errorNum >= 0)
  216927. return false;
  216928. error = snd_strerror (errorNum);
  216929. DBG (T("ALSA error: ") + error + T("\n"));
  216930. return true;
  216931. }
  216932. };
  216933. class ALSAThread : public Thread
  216934. {
  216935. public:
  216936. ALSAThread (const String& inputId_,
  216937. const String& outputId_)
  216938. : Thread ("Juce ALSA"),
  216939. sampleRate (0),
  216940. bufferSize (0),
  216941. callback (0),
  216942. inputId (inputId_),
  216943. outputId (outputId_),
  216944. outputDevice (0),
  216945. inputDevice (0),
  216946. numCallbacks (0),
  216947. totalNumInputChannels (0),
  216948. totalNumOutputChannels (0)
  216949. {
  216950. zeromem (outputChannelData, sizeof (outputChannelData));
  216951. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  216952. zeromem (inputChannelData, sizeof (inputChannelData));
  216953. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  216954. initialiseRatesAndChannels();
  216955. }
  216956. ~ALSAThread()
  216957. {
  216958. close();
  216959. }
  216960. void open (BitArray inputChannels,
  216961. BitArray outputChannels,
  216962. const double sampleRate_,
  216963. const int bufferSize_)
  216964. {
  216965. close();
  216966. error = String::empty;
  216967. sampleRate = sampleRate_;
  216968. bufferSize = bufferSize_;
  216969. currentInputChans.clear();
  216970. currentOutputChans.clear();
  216971. if (inputChannels.getHighestBit() >= 0)
  216972. {
  216973. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), minChansIn); ++i)
  216974. {
  216975. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  216976. if (inputChannels[i])
  216977. {
  216978. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  216979. currentInputChans.setBit (i);
  216980. }
  216981. }
  216982. }
  216983. if (outputChannels.getHighestBit() >= 0)
  216984. {
  216985. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), minChansOut); ++i)
  216986. {
  216987. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  216988. if (outputChannels[i])
  216989. {
  216990. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  216991. currentOutputChans.setBit (i);
  216992. }
  216993. }
  216994. }
  216995. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  216996. {
  216997. outputDevice = new ALSADevice (outputId, false);
  216998. if (outputDevice->error.isNotEmpty())
  216999. {
  217000. error = outputDevice->error;
  217001. deleteAndZero (outputDevice);
  217002. return;
  217003. }
  217004. currentOutputChans.setRange (0, minChansOut, true);
  217005. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  217006. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  217007. bufferSize))
  217008. {
  217009. error = outputDevice->error;
  217010. deleteAndZero (outputDevice);
  217011. return;
  217012. }
  217013. }
  217014. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  217015. {
  217016. inputDevice = new ALSADevice (inputId, true);
  217017. if (inputDevice->error.isNotEmpty())
  217018. {
  217019. error = inputDevice->error;
  217020. deleteAndZero (inputDevice);
  217021. return;
  217022. }
  217023. currentInputChans.setRange (0, minChansIn, true);
  217024. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  217025. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  217026. bufferSize))
  217027. {
  217028. error = inputDevice->error;
  217029. deleteAndZero (inputDevice);
  217030. return;
  217031. }
  217032. }
  217033. if (outputDevice == 0 && inputDevice == 0)
  217034. {
  217035. error = "no channels";
  217036. return;
  217037. }
  217038. if (outputDevice != 0 && inputDevice != 0)
  217039. {
  217040. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  217041. }
  217042. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  217043. return;
  217044. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  217045. return;
  217046. startThread (9);
  217047. int count = 1000;
  217048. while (numCallbacks == 0)
  217049. {
  217050. sleep (5);
  217051. if (--count < 0 || ! isThreadRunning())
  217052. {
  217053. error = "device didn't start";
  217054. break;
  217055. }
  217056. }
  217057. }
  217058. void close()
  217059. {
  217060. stopThread (6000);
  217061. deleteAndZero (inputDevice);
  217062. deleteAndZero (outputDevice);
  217063. for (int i = 0; i < maxNumChans; ++i)
  217064. {
  217065. juce_free (inputChannelData [i]);
  217066. juce_free (outputChannelData [i]);
  217067. }
  217068. zeromem (outputChannelData, sizeof (outputChannelData));
  217069. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217070. zeromem (inputChannelData, sizeof (inputChannelData));
  217071. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217072. totalNumOutputChannels = 0;
  217073. totalNumInputChannels = 0;
  217074. numCallbacks = 0;
  217075. }
  217076. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  217077. {
  217078. const ScopedLock sl (callbackLock);
  217079. callback = newCallback;
  217080. }
  217081. void run()
  217082. {
  217083. while (! threadShouldExit())
  217084. {
  217085. if (inputDevice != 0)
  217086. {
  217087. if (! inputDevice->read (inputChannelData, bufferSize))
  217088. {
  217089. DBG ("ALSA: read failure");
  217090. break;
  217091. }
  217092. }
  217093. if (threadShouldExit())
  217094. break;
  217095. {
  217096. const ScopedLock sl (callbackLock);
  217097. ++numCallbacks;
  217098. if (callback != 0)
  217099. {
  217100. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  217101. totalNumInputChannels,
  217102. outputChannelDataForCallback,
  217103. totalNumOutputChannels,
  217104. bufferSize);
  217105. }
  217106. else
  217107. {
  217108. for (int i = 0; i < totalNumOutputChannels; ++i)
  217109. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  217110. }
  217111. }
  217112. if (outputDevice != 0)
  217113. {
  217114. failed (snd_pcm_wait (outputDevice->handle, 2000));
  217115. if (threadShouldExit())
  217116. break;
  217117. failed (snd_pcm_avail_update (outputDevice->handle));
  217118. if (! outputDevice->write (outputChannelData, bufferSize))
  217119. {
  217120. DBG ("ALSA: write failure");
  217121. break;
  217122. }
  217123. }
  217124. }
  217125. }
  217126. int getBitDepth() const throw()
  217127. {
  217128. if (outputDevice != 0)
  217129. return outputDevice->bitDepth;
  217130. if (inputDevice != 0)
  217131. return inputDevice->bitDepth;
  217132. return 16;
  217133. }
  217134. juce_UseDebuggingNewOperator
  217135. String error;
  217136. double sampleRate;
  217137. int bufferSize;
  217138. BitArray currentInputChans, currentOutputChans;
  217139. Array <int> sampleRates;
  217140. StringArray channelNamesOut, channelNamesIn;
  217141. AudioIODeviceCallback* callback;
  217142. private:
  217143. const String inputId, outputId;
  217144. ALSADevice* outputDevice;
  217145. ALSADevice* inputDevice;
  217146. int numCallbacks;
  217147. CriticalSection callbackLock;
  217148. float* outputChannelData [maxNumChans];
  217149. float* outputChannelDataForCallback [maxNumChans];
  217150. int totalNumInputChannels;
  217151. float* inputChannelData [maxNumChans];
  217152. float* inputChannelDataForCallback [maxNumChans];
  217153. int totalNumOutputChannels;
  217154. unsigned int minChansOut, maxChansOut;
  217155. unsigned int minChansIn, maxChansIn;
  217156. bool failed (const int errorNum) throw()
  217157. {
  217158. if (errorNum >= 0)
  217159. return false;
  217160. error = snd_strerror (errorNum);
  217161. DBG (T("ALSA error: ") + error + T("\n"));
  217162. return true;
  217163. }
  217164. void initialiseRatesAndChannels() throw()
  217165. {
  217166. sampleRates.clear();
  217167. channelNamesOut.clear();
  217168. channelNamesIn.clear();
  217169. minChansOut = 0;
  217170. maxChansOut = 0;
  217171. minChansIn = 0;
  217172. maxChansIn = 0;
  217173. unsigned int dummy = 0;
  217174. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  217175. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  217176. unsigned int i;
  217177. for (i = 0; i < maxChansOut; ++i)
  217178. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  217179. for (i = 0; i < maxChansIn; ++i)
  217180. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  217181. }
  217182. };
  217183. class ALSAAudioIODevice : public AudioIODevice
  217184. {
  217185. public:
  217186. ALSAAudioIODevice (const String& deviceName,
  217187. const String& inputId_,
  217188. const String& outputId_)
  217189. : AudioIODevice (deviceName, T("ALSA")),
  217190. inputId (inputId_),
  217191. outputId (outputId_),
  217192. isOpen_ (false),
  217193. isStarted (false),
  217194. internal (0)
  217195. {
  217196. internal = new ALSAThread (inputId, outputId);
  217197. }
  217198. ~ALSAAudioIODevice()
  217199. {
  217200. delete internal;
  217201. }
  217202. const StringArray getOutputChannelNames()
  217203. {
  217204. return internal->channelNamesOut;
  217205. }
  217206. const StringArray getInputChannelNames()
  217207. {
  217208. return internal->channelNamesIn;
  217209. }
  217210. int getNumSampleRates()
  217211. {
  217212. return internal->sampleRates.size();
  217213. }
  217214. double getSampleRate (int index)
  217215. {
  217216. return internal->sampleRates [index];
  217217. }
  217218. int getNumBufferSizesAvailable()
  217219. {
  217220. return 50;
  217221. }
  217222. int getBufferSizeSamples (int index)
  217223. {
  217224. int n = 16;
  217225. for (int i = 0; i < index; ++i)
  217226. n += n < 64 ? 16
  217227. : (n < 512 ? 32
  217228. : (n < 1024 ? 64
  217229. : (n < 2048 ? 128 : 256)));
  217230. return n;
  217231. }
  217232. int getDefaultBufferSize()
  217233. {
  217234. return 512;
  217235. }
  217236. const String open (const BitArray& inputChannels,
  217237. const BitArray& outputChannels,
  217238. double sampleRate,
  217239. int bufferSizeSamples)
  217240. {
  217241. close();
  217242. if (bufferSizeSamples <= 0)
  217243. bufferSizeSamples = getDefaultBufferSize();
  217244. if (sampleRate <= 0)
  217245. {
  217246. for (int i = 0; i < getNumSampleRates(); ++i)
  217247. {
  217248. if (getSampleRate (i) >= 44100)
  217249. {
  217250. sampleRate = getSampleRate (i);
  217251. break;
  217252. }
  217253. }
  217254. }
  217255. internal->open (inputChannels, outputChannels,
  217256. sampleRate, bufferSizeSamples);
  217257. isOpen_ = internal->error.isEmpty();
  217258. return internal->error;
  217259. }
  217260. void close()
  217261. {
  217262. stop();
  217263. internal->close();
  217264. isOpen_ = false;
  217265. }
  217266. bool isOpen()
  217267. {
  217268. return isOpen_;
  217269. }
  217270. int getCurrentBufferSizeSamples()
  217271. {
  217272. return internal->bufferSize;
  217273. }
  217274. double getCurrentSampleRate()
  217275. {
  217276. return internal->sampleRate;
  217277. }
  217278. int getCurrentBitDepth()
  217279. {
  217280. return internal->getBitDepth();
  217281. }
  217282. const BitArray getActiveOutputChannels() const
  217283. {
  217284. return internal->currentOutputChans;
  217285. }
  217286. const BitArray getActiveInputChannels() const
  217287. {
  217288. return internal->currentInputChans;
  217289. }
  217290. int getOutputLatencyInSamples()
  217291. {
  217292. return 0;
  217293. }
  217294. int getInputLatencyInSamples()
  217295. {
  217296. return 0;
  217297. }
  217298. void start (AudioIODeviceCallback* callback)
  217299. {
  217300. if (! isOpen_)
  217301. callback = 0;
  217302. internal->setCallback (callback);
  217303. if (callback != 0)
  217304. callback->audioDeviceAboutToStart (this);
  217305. isStarted = (callback != 0);
  217306. }
  217307. void stop()
  217308. {
  217309. AudioIODeviceCallback* const oldCallback = internal->callback;
  217310. start (0);
  217311. if (oldCallback != 0)
  217312. oldCallback->audioDeviceStopped();
  217313. }
  217314. bool isPlaying()
  217315. {
  217316. return isStarted && internal->error.isEmpty();
  217317. }
  217318. const String getLastError()
  217319. {
  217320. return internal->error;
  217321. }
  217322. String inputId, outputId;
  217323. private:
  217324. bool isOpen_, isStarted;
  217325. ALSAThread* internal;
  217326. };
  217327. class ALSAAudioIODeviceType : public AudioIODeviceType
  217328. {
  217329. public:
  217330. ALSAAudioIODeviceType()
  217331. : AudioIODeviceType (T("ALSA")),
  217332. hasScanned (false)
  217333. {
  217334. }
  217335. ~ALSAAudioIODeviceType()
  217336. {
  217337. }
  217338. void scanForDevices()
  217339. {
  217340. if (hasScanned)
  217341. return;
  217342. hasScanned = true;
  217343. inputNames.clear();
  217344. inputIds.clear();
  217345. outputNames.clear();
  217346. outputIds.clear();
  217347. snd_ctl_t* handle;
  217348. snd_ctl_card_info_t* info;
  217349. snd_ctl_card_info_alloca (&info);
  217350. int cardNum = -1;
  217351. while (outputIds.size() + inputIds.size() <= 32)
  217352. {
  217353. snd_card_next (&cardNum);
  217354. if (cardNum < 0)
  217355. break;
  217356. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  217357. {
  217358. if (snd_ctl_card_info (handle, info) >= 0)
  217359. {
  217360. String cardId (snd_ctl_card_info_get_id (info));
  217361. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  217362. cardId = String (cardNum);
  217363. int device = -1;
  217364. for (;;)
  217365. {
  217366. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  217367. break;
  217368. String id, name;
  217369. id << "hw:" << cardId << ',' << device;
  217370. bool isInput, isOutput;
  217371. if (testDevice (id, isInput, isOutput))
  217372. {
  217373. name << snd_ctl_card_info_get_name (info);
  217374. if (name.isEmpty())
  217375. name = id;
  217376. if (isInput)
  217377. {
  217378. inputNames.add (name);
  217379. inputIds.add (id);
  217380. }
  217381. if (isOutput)
  217382. {
  217383. outputNames.add (name);
  217384. outputIds.add (id);
  217385. }
  217386. }
  217387. }
  217388. }
  217389. snd_ctl_close (handle);
  217390. }
  217391. }
  217392. inputNames.appendNumbersToDuplicates (false, true);
  217393. outputNames.appendNumbersToDuplicates (false, true);
  217394. }
  217395. const StringArray getDeviceNames (const bool wantInputNames) const
  217396. {
  217397. jassert (hasScanned); // need to call scanForDevices() before doing this
  217398. return wantInputNames ? inputNames : outputNames;
  217399. }
  217400. int getDefaultDeviceIndex (const bool forInput) const
  217401. {
  217402. jassert (hasScanned); // need to call scanForDevices() before doing this
  217403. return 0;
  217404. }
  217405. bool hasSeparateInputsAndOutputs() const { return true; }
  217406. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  217407. {
  217408. jassert (hasScanned); // need to call scanForDevices() before doing this
  217409. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  217410. if (d == 0)
  217411. return -1;
  217412. return asInput ? inputIds.indexOf (d->inputId)
  217413. : outputIds.indexOf (d->outputId);
  217414. }
  217415. AudioIODevice* createDevice (const String& outputDeviceName,
  217416. const String& inputDeviceName)
  217417. {
  217418. jassert (hasScanned); // need to call scanForDevices() before doing this
  217419. const int inputIndex = inputNames.indexOf (inputDeviceName);
  217420. const int outputIndex = outputNames.indexOf (outputDeviceName);
  217421. String deviceName (outputDeviceName);
  217422. if (deviceName.isEmpty())
  217423. deviceName = inputDeviceName;
  217424. if (index >= 0)
  217425. return new ALSAAudioIODevice (deviceName,
  217426. inputIds [inputIndex],
  217427. outputIds [outputIndex]);
  217428. return 0;
  217429. }
  217430. juce_UseDebuggingNewOperator
  217431. private:
  217432. StringArray inputNames, outputNames, inputIds, outputIds;
  217433. bool hasScanned;
  217434. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  217435. {
  217436. unsigned int minChansOut = 0, maxChansOut = 0;
  217437. unsigned int minChansIn = 0, maxChansIn = 0;
  217438. Array <int> rates;
  217439. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  217440. DBG (T("ALSA device: ") + id
  217441. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  217442. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  217443. + T(" rates=") + String (rates.size()));
  217444. isInput = maxChansIn > 0;
  217445. isOutput = maxChansOut > 0;
  217446. return (isInput || isOutput) && rates.size() > 0;
  217447. }
  217448. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  217449. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  217450. };
  217451. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  217452. {
  217453. return new ALSAAudioIODeviceType();
  217454. }
  217455. #endif
  217456. /********* End of inlined file: juce_linux_Audio.cpp *********/
  217457. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  217458. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217459. // compiled on its own).
  217460. #ifdef JUCE_INCLUDED_FILE
  217461. #if JUCE_ALSA
  217462. static snd_seq_t* iterateDevices (const bool forInput,
  217463. StringArray& deviceNamesFound,
  217464. const int deviceIndexToOpen)
  217465. {
  217466. snd_seq_t* returnedHandle = 0;
  217467. snd_seq_t* seqHandle;
  217468. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  217469. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  217470. {
  217471. snd_seq_system_info_t* systemInfo;
  217472. snd_seq_client_info_t* clientInfo;
  217473. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  217474. {
  217475. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  217476. && snd_seq_client_info_malloc (&clientInfo) == 0)
  217477. {
  217478. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  217479. while (--numClients >= 0 && returnedHandle == 0)
  217480. {
  217481. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  217482. {
  217483. snd_seq_port_info_t* portInfo;
  217484. if (snd_seq_port_info_malloc (&portInfo) == 0)
  217485. {
  217486. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  217487. const int client = snd_seq_client_info_get_client (clientInfo);
  217488. snd_seq_port_info_set_client (portInfo, client);
  217489. snd_seq_port_info_set_port (portInfo, -1);
  217490. while (--numPorts >= 0)
  217491. {
  217492. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  217493. && (snd_seq_port_info_get_capability (portInfo)
  217494. & (forInput ? SND_SEQ_PORT_CAP_READ
  217495. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  217496. {
  217497. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  217498. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  217499. {
  217500. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  217501. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  217502. if (sourcePort != -1)
  217503. {
  217504. snd_seq_set_client_name (seqHandle,
  217505. forInput ? "Juce Midi Input"
  217506. : "Juce Midi Output");
  217507. const int portId
  217508. = snd_seq_create_simple_port (seqHandle,
  217509. forInput ? "Juce Midi In Port"
  217510. : "Juce Midi Out Port",
  217511. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  217512. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  217513. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  217514. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  217515. returnedHandle = seqHandle;
  217516. }
  217517. }
  217518. }
  217519. }
  217520. snd_seq_port_info_free (portInfo);
  217521. }
  217522. }
  217523. }
  217524. snd_seq_client_info_free (clientInfo);
  217525. }
  217526. snd_seq_system_info_free (systemInfo);
  217527. }
  217528. if (returnedHandle == 0)
  217529. snd_seq_close (seqHandle);
  217530. }
  217531. deviceNamesFound.appendNumbersToDuplicates (true, true);
  217532. return returnedHandle;
  217533. }
  217534. static snd_seq_t* createDevice (const bool forInput,
  217535. const String& deviceNameToOpen)
  217536. {
  217537. snd_seq_t* seqHandle = 0;
  217538. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  217539. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  217540. {
  217541. snd_seq_set_client_name (seqHandle,
  217542. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  217543. : (deviceNameToOpen + T(" Output"))));
  217544. const int portId
  217545. = snd_seq_create_simple_port (seqHandle,
  217546. forInput ? "in"
  217547. : "out",
  217548. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  217549. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  217550. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  217551. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  217552. if (portId < 0)
  217553. {
  217554. snd_seq_close (seqHandle);
  217555. seqHandle = 0;
  217556. }
  217557. }
  217558. return seqHandle;
  217559. }
  217560. class MidiOutputDevice
  217561. {
  217562. public:
  217563. MidiOutputDevice (MidiOutput* const midiOutput_,
  217564. snd_seq_t* const seqHandle_)
  217565. :
  217566. midiOutput (midiOutput_),
  217567. seqHandle (seqHandle_),
  217568. maxEventSize (16 * 1024)
  217569. {
  217570. jassert (seqHandle != 0 && midiOutput != 0);
  217571. snd_midi_event_new (maxEventSize, &midiParser);
  217572. }
  217573. ~MidiOutputDevice()
  217574. {
  217575. snd_midi_event_free (midiParser);
  217576. snd_seq_close (seqHandle);
  217577. }
  217578. void sendMessageNow (const MidiMessage& message)
  217579. {
  217580. if (message.getRawDataSize() > maxEventSize)
  217581. {
  217582. maxEventSize = message.getRawDataSize();
  217583. snd_midi_event_free (midiParser);
  217584. snd_midi_event_new (maxEventSize, &midiParser);
  217585. }
  217586. snd_seq_event_t event;
  217587. snd_seq_ev_clear (&event);
  217588. snd_midi_event_encode (midiParser,
  217589. message.getRawData(),
  217590. message.getRawDataSize(),
  217591. &event);
  217592. snd_midi_event_reset_encode (midiParser);
  217593. snd_seq_ev_set_source (&event, 0);
  217594. snd_seq_ev_set_subs (&event);
  217595. snd_seq_ev_set_direct (&event);
  217596. snd_seq_event_output (seqHandle, &event);
  217597. snd_seq_drain_output (seqHandle);
  217598. }
  217599. juce_UseDebuggingNewOperator
  217600. private:
  217601. MidiOutput* const midiOutput;
  217602. snd_seq_t* const seqHandle;
  217603. snd_midi_event_t* midiParser;
  217604. int maxEventSize;
  217605. };
  217606. const StringArray MidiOutput::getDevices()
  217607. {
  217608. StringArray devices;
  217609. iterateDevices (false, devices, -1);
  217610. return devices;
  217611. }
  217612. int MidiOutput::getDefaultDeviceIndex()
  217613. {
  217614. return 0;
  217615. }
  217616. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  217617. {
  217618. MidiOutput* newDevice = 0;
  217619. StringArray devices;
  217620. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  217621. if (handle != 0)
  217622. {
  217623. newDevice = new MidiOutput();
  217624. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  217625. }
  217626. return newDevice;
  217627. }
  217628. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  217629. {
  217630. MidiOutput* newDevice = 0;
  217631. snd_seq_t* const handle = createDevice (false, deviceName);
  217632. if (handle != 0)
  217633. {
  217634. newDevice = new MidiOutput();
  217635. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  217636. }
  217637. return newDevice;
  217638. }
  217639. MidiOutput::~MidiOutput()
  217640. {
  217641. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  217642. delete device;
  217643. }
  217644. void MidiOutput::reset()
  217645. {
  217646. }
  217647. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  217648. {
  217649. return false;
  217650. }
  217651. void MidiOutput::setVolume (float leftVol, float rightVol)
  217652. {
  217653. }
  217654. void MidiOutput::sendMessageNow (const MidiMessage& message)
  217655. {
  217656. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  217657. }
  217658. class MidiInputThread : public Thread
  217659. {
  217660. public:
  217661. MidiInputThread (MidiInput* const midiInput_,
  217662. snd_seq_t* const seqHandle_,
  217663. MidiInputCallback* const callback_)
  217664. : Thread (T("Juce MIDI Input")),
  217665. midiInput (midiInput_),
  217666. seqHandle (seqHandle_),
  217667. callback (callback_)
  217668. {
  217669. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  217670. }
  217671. ~MidiInputThread()
  217672. {
  217673. snd_seq_close (seqHandle);
  217674. }
  217675. void run()
  217676. {
  217677. const int maxEventSize = 16 * 1024;
  217678. snd_midi_event_t* midiParser;
  217679. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  217680. {
  217681. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  217682. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  217683. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  217684. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  217685. while (! threadShouldExit())
  217686. {
  217687. if (poll (pfd, numPfds, 500) > 0)
  217688. {
  217689. snd_seq_event_t* inputEvent = 0;
  217690. snd_seq_nonblock (seqHandle, 1);
  217691. do
  217692. {
  217693. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  217694. {
  217695. // xxx what about SYSEXes that are too big for the buffer?
  217696. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  217697. snd_midi_event_reset_decode (midiParser);
  217698. if (numBytes > 0)
  217699. {
  217700. const MidiMessage message ((const uint8*) buffer,
  217701. numBytes,
  217702. Time::getMillisecondCounter() * 0.001);
  217703. callback->handleIncomingMidiMessage (midiInput, message);
  217704. }
  217705. snd_seq_free_event (inputEvent);
  217706. }
  217707. }
  217708. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  217709. snd_seq_free_event (inputEvent);
  217710. }
  217711. }
  217712. snd_midi_event_free (midiParser);
  217713. juce_free (buffer);
  217714. }
  217715. };
  217716. juce_UseDebuggingNewOperator
  217717. private:
  217718. MidiInput* const midiInput;
  217719. snd_seq_t* const seqHandle;
  217720. MidiInputCallback* const callback;
  217721. };
  217722. MidiInput::MidiInput (const String& name_)
  217723. : name (name_),
  217724. internal (0)
  217725. {
  217726. }
  217727. MidiInput::~MidiInput()
  217728. {
  217729. stop();
  217730. MidiInputThread* const thread = (MidiInputThread*) internal;
  217731. delete thread;
  217732. }
  217733. void MidiInput::start()
  217734. {
  217735. ((MidiInputThread*) internal)->startThread();
  217736. }
  217737. void MidiInput::stop()
  217738. {
  217739. ((MidiInputThread*) internal)->stopThread (3000);
  217740. }
  217741. int MidiInput::getDefaultDeviceIndex()
  217742. {
  217743. return 0;
  217744. }
  217745. const StringArray MidiInput::getDevices()
  217746. {
  217747. StringArray devices;
  217748. iterateDevices (true, devices, -1);
  217749. return devices;
  217750. }
  217751. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  217752. {
  217753. MidiInput* newDevice = 0;
  217754. StringArray devices;
  217755. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  217756. if (handle != 0)
  217757. {
  217758. newDevice = new MidiInput (devices [deviceIndex]);
  217759. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  217760. }
  217761. return newDevice;
  217762. }
  217763. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  217764. {
  217765. MidiInput* newDevice = 0;
  217766. snd_seq_t* const handle = createDevice (true, deviceName);
  217767. if (handle != 0)
  217768. {
  217769. newDevice = new MidiInput (deviceName);
  217770. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  217771. }
  217772. return newDevice;
  217773. }
  217774. #else
  217775. // (These are just stub functions if ALSA is unavailable...)
  217776. const StringArray MidiOutput::getDevices() { return StringArray(); }
  217777. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  217778. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  217779. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  217780. MidiOutput::~MidiOutput() {}
  217781. void MidiOutput::reset() {}
  217782. bool MidiOutput::getVolume (float&, float&) { return false; }
  217783. void MidiOutput::setVolume (float, float) {}
  217784. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  217785. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  217786. MidiInput::~MidiInput() {}
  217787. void MidiInput::start() {}
  217788. void MidiInput::stop() {}
  217789. int MidiInput::getDefaultDeviceIndex() { return 0; }
  217790. const StringArray MidiInput::getDevices() { return StringArray(); }
  217791. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  217792. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  217793. #endif
  217794. #endif
  217795. /********* End of inlined file: juce_linux_Midi.cpp *********/
  217796. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  217797. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217798. // compiled on its own).
  217799. #ifdef JUCE_INCLUDED_FILE
  217800. AudioCDReader::AudioCDReader()
  217801. : AudioFormatReader (0, T("CD Audio"))
  217802. {
  217803. }
  217804. const StringArray AudioCDReader::getAvailableCDNames()
  217805. {
  217806. StringArray names;
  217807. return names;
  217808. }
  217809. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  217810. {
  217811. return 0;
  217812. }
  217813. AudioCDReader::~AudioCDReader()
  217814. {
  217815. }
  217816. void AudioCDReader::refreshTrackLengths()
  217817. {
  217818. }
  217819. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  217820. int64 startSampleInFile, int numSamples)
  217821. {
  217822. return false;
  217823. }
  217824. bool AudioCDReader::isCDStillPresent() const
  217825. {
  217826. return false;
  217827. }
  217828. int AudioCDReader::getNumTracks() const
  217829. {
  217830. return 0;
  217831. }
  217832. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  217833. {
  217834. return 0;
  217835. }
  217836. bool AudioCDReader::isTrackAudio (int trackNum) const
  217837. {
  217838. return false;
  217839. }
  217840. void AudioCDReader::enableIndexScanning (bool b)
  217841. {
  217842. }
  217843. int AudioCDReader::getLastIndex() const
  217844. {
  217845. return 0;
  217846. }
  217847. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  217848. {
  217849. return Array<int>();
  217850. }
  217851. int AudioCDReader::getCDDBId()
  217852. {
  217853. return 0;
  217854. }
  217855. #endif
  217856. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  217857. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  217858. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217859. // compiled on its own).
  217860. #ifdef JUCE_INCLUDED_FILE
  217861. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  217862. const String& title,
  217863. const File& file,
  217864. const String& filters,
  217865. bool isDirectory,
  217866. bool isSave,
  217867. bool warnAboutOverwritingExistingFiles,
  217868. bool selectMultipleFiles,
  217869. FilePreviewComponent* previewComponent)
  217870. {
  217871. //xxx ain't got one!
  217872. jassertfalse
  217873. }
  217874. #endif
  217875. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  217876. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  217877. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217878. // compiled on its own).
  217879. #ifdef JUCE_INCLUDED_FILE
  217880. #if JUCE_WEB_BROWSER
  217881. /*
  217882. Sorry.. This class isn't implemented on Linux!
  217883. */
  217884. WebBrowserComponent::WebBrowserComponent()
  217885. : browser (0),
  217886. blankPageShown (false)
  217887. {
  217888. setOpaque (true);
  217889. }
  217890. WebBrowserComponent::~WebBrowserComponent()
  217891. {
  217892. }
  217893. void WebBrowserComponent::goToURL (const String& url,
  217894. const StringArray* headers,
  217895. const MemoryBlock* postData)
  217896. {
  217897. lastURL = url;
  217898. lastHeaders.clear();
  217899. if (headers != 0)
  217900. lastHeaders = *headers;
  217901. lastPostData.setSize (0);
  217902. if (postData != 0)
  217903. lastPostData = *postData;
  217904. blankPageShown = false;
  217905. }
  217906. void WebBrowserComponent::stop()
  217907. {
  217908. }
  217909. void WebBrowserComponent::goBack()
  217910. {
  217911. lastURL = String::empty;
  217912. blankPageShown = false;
  217913. }
  217914. void WebBrowserComponent::goForward()
  217915. {
  217916. lastURL = String::empty;
  217917. }
  217918. void WebBrowserComponent::refresh()
  217919. {
  217920. }
  217921. void WebBrowserComponent::paint (Graphics& g)
  217922. {
  217923. g.fillAll (Colours::white);
  217924. }
  217925. void WebBrowserComponent::checkWindowAssociation()
  217926. {
  217927. }
  217928. void WebBrowserComponent::reloadLastURL()
  217929. {
  217930. if (lastURL.isNotEmpty())
  217931. {
  217932. goToURL (lastURL, &lastHeaders, &lastPostData);
  217933. lastURL = String::empty;
  217934. }
  217935. }
  217936. void WebBrowserComponent::parentHierarchyChanged()
  217937. {
  217938. checkWindowAssociation();
  217939. }
  217940. void WebBrowserComponent::resized()
  217941. {
  217942. }
  217943. void WebBrowserComponent::visibilityChanged()
  217944. {
  217945. checkWindowAssociation();
  217946. }
  217947. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  217948. {
  217949. return true;
  217950. }
  217951. #endif
  217952. #endif
  217953. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  217954. #endif
  217955. END_JUCE_NAMESPACE
  217956. /********* End of inlined file: juce_linux_NativeCode.cpp *********/
  217957. #endif
  217958. #if JUCE_MAC
  217959. /********* Start of inlined file: juce_mac_NativeCode.mm *********/
  217960. /*
  217961. This file wraps together all the mac-specific code, so that
  217962. we can include all the native headers just once, and compile all our
  217963. platform-specific stuff in one big lump, keeping it out of the way of
  217964. the rest of the codebase.
  217965. */
  217966. BEGIN_JUCE_NAMESPACE
  217967. #undef Point
  217968. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  217969. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  217970. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  217971. cross-linked so that when you make a call to a class that you thought was private, it ends up
  217972. actually calling into a similarly named class in the other module's address space.
  217973. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  217974. have unique names, and should avoid this problem.
  217975. If you're using the amalgamated version, you can just set this macro to something unique before
  217976. you include juce_amalgamated.cpp.
  217977. */
  217978. #ifndef JUCE_ObjCExtraSuffix
  217979. #define JUCE_ObjCExtraSuffix 3
  217980. #endif
  217981. #define appendMacro1(a, b, c, d) a ## _ ## b ## _ ## c ## _ ## d
  217982. #define appendMacro2(a, b, c, d) appendMacro1(a, b, c, d)
  217983. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_ObjCExtraSuffix)
  217984. #define JUCE_INCLUDED_FILE 1
  217985. // Now include the actual code files..
  217986. /********* Start of inlined file: juce_mac_Strings.mm *********/
  217987. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217988. // compiled on its own).
  217989. #ifdef JUCE_INCLUDED_FILE
  217990. static const String nsStringToJuce (NSString* s)
  217991. {
  217992. return String::fromUTF8 ((uint8*) [s UTF8String]);
  217993. }
  217994. static NSString* juceStringToNS (const String& s)
  217995. {
  217996. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  217997. }
  217998. static const String convertUTF16ToString (const UniChar* utf16)
  217999. {
  218000. String s;
  218001. while (*utf16 != 0)
  218002. s += (juce_wchar) *utf16++;
  218003. return s;
  218004. }
  218005. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  218006. {
  218007. String result;
  218008. if (cfString != 0)
  218009. {
  218010. #if JUCE_STRINGS_ARE_UNICODE
  218011. CFRange range = { 0, CFStringGetLength (cfString) };
  218012. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  218013. CFStringGetCharacters (cfString, range, u);
  218014. u[range.length] = 0;
  218015. result = convertUTF16ToString (u);
  218016. juce_free (u);
  218017. #else
  218018. const int len = CFStringGetLength (cfString);
  218019. char* buffer = (char*) juce_malloc (len + 1);
  218020. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  218021. result = buffer;
  218022. juce_free (buffer);
  218023. #endif
  218024. }
  218025. return result;
  218026. }
  218027. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  218028. {
  218029. #if JUCE_STRINGS_ARE_UNICODE
  218030. const int len = s.length();
  218031. const juce_wchar* t = (const juce_wchar*) s;
  218032. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  218033. for (int i = 0; i <= len; ++i)
  218034. temp[i] = t[i];
  218035. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  218036. juce_free (temp);
  218037. return result;
  218038. #else
  218039. return CFStringCreateWithCString (kCFAllocatorDefault,
  218040. (const char*) s,
  218041. CFStringGetSystemEncoding());
  218042. #endif
  218043. }
  218044. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  218045. {
  218046. UnicodeMapping map;
  218047. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218048. kUnicodeNoSubset,
  218049. kTextEncodingDefaultFormat);
  218050. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218051. kUnicodeCanonicalCompVariant,
  218052. kTextEncodingDefaultFormat);
  218053. map.mappingVersion = kUnicodeUseLatestMapping;
  218054. UnicodeToTextInfo conversionInfo = 0;
  218055. String result;
  218056. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  218057. {
  218058. const int len = s.length();
  218059. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218060. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218061. for (int i = 0; i <= len; ++i)
  218062. tempIn[i] = s[i];
  218063. ByteCount bytesRead = 0;
  218064. ByteCount outputBufferSize = 0;
  218065. if (ConvertFromUnicodeToText (conversionInfo,
  218066. len * sizeof (UniChar), tempIn,
  218067. kUnicodeDefaultDirectionMask,
  218068. 0, 0, 0, 0,
  218069. len * sizeof (UniChar), &bytesRead,
  218070. &outputBufferSize, tempOut) == noErr)
  218071. {
  218072. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  218073. tchar* t = const_cast <tchar*> ((const tchar*) result);
  218074. unsigned int i;
  218075. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  218076. t[i] = (tchar) tempOut[i];
  218077. t[i] = 0;
  218078. }
  218079. juce_free (tempIn);
  218080. juce_free (tempOut);
  218081. DisposeUnicodeToTextInfo (&conversionInfo);
  218082. }
  218083. return result;
  218084. }
  218085. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218086. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  218087. {
  218088. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  218089. owner: nil];
  218090. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  218091. forType: NSStringPboardType];
  218092. }
  218093. const String SystemClipboard::getTextFromClipboard() throw()
  218094. {
  218095. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  218096. return text == 0 ? String::empty
  218097. : nsStringToJuce (text);
  218098. }
  218099. #endif
  218100. #endif
  218101. /********* End of inlined file: juce_mac_Strings.mm *********/
  218102. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  218103. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218104. // compiled on its own).
  218105. #ifdef JUCE_INCLUDED_FILE
  218106. static int64 highResTimerFrequency;
  218107. #if JUCE_INTEL
  218108. static void juce_getCpuVendor (char* const v) throw()
  218109. {
  218110. int vendor[4];
  218111. zerostruct (vendor);
  218112. int dummy = 0;
  218113. asm ("mov %%ebx, %%esi \n\t"
  218114. "cpuid \n\t"
  218115. "xchg %%esi, %%ebx"
  218116. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  218117. memcpy (v, vendor, 16);
  218118. }
  218119. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  218120. {
  218121. unsigned int cpu = 0;
  218122. unsigned int ext = 0;
  218123. unsigned int family = 0;
  218124. unsigned int dummy = 0;
  218125. asm ("mov %%ebx, %%esi \n\t"
  218126. "cpuid \n\t"
  218127. "xchg %%esi, %%ebx"
  218128. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  218129. familyModel = family;
  218130. extFeatures = ext;
  218131. return cpu;
  218132. }
  218133. struct CPUFlags
  218134. {
  218135. bool hasMMX : 1;
  218136. bool hasSSE : 1;
  218137. bool hasSSE2 : 1;
  218138. bool has3DNow : 1;
  218139. };
  218140. static CPUFlags cpuFlags;
  218141. #endif
  218142. void SystemStats::initialiseStats() throw()
  218143. {
  218144. static bool initialised = false;
  218145. if (! initialised)
  218146. {
  218147. initialised = true;
  218148. // extremely annoying: adding this line stops the apple menu items from working. Of
  218149. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  218150. // any events.
  218151. //NSApplicationLoad();
  218152. [NSApplication sharedApplication];
  218153. #if JUCE_INTEL
  218154. {
  218155. unsigned int familyModel, extFeatures;
  218156. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  218157. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  218158. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  218159. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  218160. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  218161. }
  218162. #endif
  218163. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  218164. String s (SystemStats::getJUCEVersion());
  218165. rlimit lim;
  218166. getrlimit (RLIMIT_NOFILE, &lim);
  218167. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  218168. setrlimit (RLIMIT_NOFILE, &lim);
  218169. }
  218170. }
  218171. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  218172. {
  218173. return MacOSX;
  218174. }
  218175. const String SystemStats::getOperatingSystemName() throw()
  218176. {
  218177. return T("Mac OS X");
  218178. }
  218179. bool SystemStats::isOperatingSystem64Bit() throw()
  218180. {
  218181. #if JUCE_64BIT
  218182. return true;
  218183. #else
  218184. //xxx not sure how to find this out?..
  218185. return false;
  218186. #endif
  218187. }
  218188. int SystemStats::getMemorySizeInMegabytes() throw()
  218189. {
  218190. uint64 mem = 0;
  218191. size_t memSize = sizeof (mem);
  218192. int mib[] = { CTL_HW, HW_MEMSIZE };
  218193. sysctl (mib, 2, &mem, &memSize, 0, 0);
  218194. return mem / (1024 * 1024);
  218195. }
  218196. bool SystemStats::hasMMX() throw()
  218197. {
  218198. #if JUCE_INTEL
  218199. return cpuFlags.hasMMX;
  218200. #else
  218201. return false;
  218202. #endif
  218203. }
  218204. bool SystemStats::hasSSE() throw()
  218205. {
  218206. #if JUCE_INTEL
  218207. return cpuFlags.hasSSE;
  218208. #else
  218209. return false;
  218210. #endif
  218211. }
  218212. bool SystemStats::hasSSE2() throw()
  218213. {
  218214. #if JUCE_INTEL
  218215. return cpuFlags.hasSSE2;
  218216. #else
  218217. return false;
  218218. #endif
  218219. }
  218220. bool SystemStats::has3DNow() throw()
  218221. {
  218222. #if JUCE_INTEL
  218223. return cpuFlags.has3DNow;
  218224. #else
  218225. return false;
  218226. #endif
  218227. }
  218228. const String SystemStats::getCpuVendor() throw()
  218229. {
  218230. #if JUCE_INTEL
  218231. char v [16];
  218232. juce_getCpuVendor (v);
  218233. return String (v, 16);
  218234. #else
  218235. return String::empty;
  218236. #endif
  218237. }
  218238. int SystemStats::getCpuSpeedInMegaherz() throw()
  218239. {
  218240. uint64 speedHz = 0;
  218241. size_t speedSize = sizeof (speedHz);
  218242. int mib[] = { CTL_HW, HW_CPU_FREQ };
  218243. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  218244. #if JUCE_BIG_ENDIAN
  218245. if (speedSize == 4)
  218246. speedHz >>= 32;
  218247. #endif
  218248. return speedHz / 1000000;
  218249. }
  218250. int SystemStats::getNumCpus() throw()
  218251. {
  218252. #if MACOS_10_4_OR_EARLIER
  218253. return MPProcessors();
  218254. #else
  218255. return [[NSProcessInfo processInfo] activeProcessorCount];
  218256. #endif
  218257. }
  218258. static int64 juce_getMicroseconds() throw()
  218259. {
  218260. UnsignedWide t;
  218261. Microseconds (&t);
  218262. return (((int64) t.hi) << 32) | t.lo;
  218263. }
  218264. uint32 juce_millisecondsSinceStartup() throw()
  218265. {
  218266. return (uint32) (juce_getMicroseconds() / 1000);
  218267. }
  218268. double Time::getMillisecondCounterHiRes() throw()
  218269. {
  218270. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  218271. return juce_getMicroseconds() * 0.001;
  218272. }
  218273. int64 Time::getHighResolutionTicks() throw()
  218274. {
  218275. return (int64) AudioGetCurrentHostTime();
  218276. }
  218277. int64 Time::getHighResolutionTicksPerSecond() throw()
  218278. {
  218279. return highResTimerFrequency;
  218280. }
  218281. int64 SystemStats::getClockCycleCounter() throw()
  218282. {
  218283. return (int64) AudioGetCurrentHostTime();
  218284. }
  218285. bool Time::setSystemTimeToThisTime() const throw()
  218286. {
  218287. jassertfalse
  218288. return false;
  218289. }
  218290. int SystemStats::getPageSize() throw()
  218291. {
  218292. return NSPageSize();
  218293. }
  218294. void PlatformUtilities::fpuReset()
  218295. {
  218296. }
  218297. #endif
  218298. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  218299. /********* Start of inlined file: juce_mac_Network.mm *********/
  218300. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218301. // compiled on its own).
  218302. #if JUCE_INCLUDED_FILE
  218303. static bool getEthernetIterator (io_iterator_t* matchingServices) throw()
  218304. {
  218305. mach_port_t masterPort;
  218306. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  218307. {
  218308. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  218309. if (dict != 0)
  218310. {
  218311. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  218312. 0,
  218313. &kCFTypeDictionaryKeyCallBacks,
  218314. &kCFTypeDictionaryValueCallBacks);
  218315. if (propDict != 0)
  218316. {
  218317. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  218318. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  218319. CFRelease (propDict);
  218320. }
  218321. }
  218322. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  218323. }
  218324. return false;
  218325. }
  218326. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  218327. {
  218328. int numResults = 0;
  218329. io_iterator_t it;
  218330. if (getEthernetIterator (&it))
  218331. {
  218332. io_object_t i;
  218333. while ((i = IOIteratorNext (it)) != 0)
  218334. {
  218335. io_object_t controller;
  218336. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  218337. {
  218338. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  218339. CFSTR (kIOMACAddress),
  218340. kCFAllocatorDefault,
  218341. 0);
  218342. if (data != 0)
  218343. {
  218344. UInt8 addr [kIOEthernetAddressSize];
  218345. zeromem (addr, sizeof (addr));
  218346. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  218347. CFRelease (data);
  218348. int64 a = 0;
  218349. for (int i = 6; --i >= 0;)
  218350. a = (a << 8) | addr[i];
  218351. if (! littleEndian)
  218352. a = (int64) swapByteOrder ((uint64) a);
  218353. if (numResults < maxNum)
  218354. {
  218355. *addresses++ = a;
  218356. ++numResults;
  218357. }
  218358. }
  218359. IOObjectRelease (controller);
  218360. }
  218361. IOObjectRelease (i);
  218362. }
  218363. IOObjectRelease (it);
  218364. }
  218365. return numResults;
  218366. }
  218367. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218368. const String& emailSubject,
  218369. const String& bodyText,
  218370. const StringArray& filesToAttach)
  218371. {
  218372. const ScopedAutoReleasePool pool;
  218373. String script;
  218374. script << "tell application \"Mail\"\r\n"
  218375. "set newMessage to make new outgoing message with properties {subject:\""
  218376. << emailSubject.replace (T("\""), T("\\\""))
  218377. << "\", content:\""
  218378. << bodyText.replace (T("\""), T("\\\""))
  218379. << "\" & return & return}\r\n"
  218380. "tell newMessage\r\n"
  218381. "set visible to true\r\n"
  218382. "set sender to \"sdfsdfsdfewf\"\r\n"
  218383. "make new to recipient at end of to recipients with properties {address:\""
  218384. << targetEmailAddress
  218385. << "\"}\r\n";
  218386. for (int i = 0; i < filesToAttach.size(); ++i)
  218387. {
  218388. script << "tell content\r\n"
  218389. "make new attachment with properties {file name:\""
  218390. << filesToAttach[i].replace (T("\""), T("\\\""))
  218391. << "\"} at after the last paragraph\r\n"
  218392. "end tell\r\n";
  218393. }
  218394. script << "end tell\r\n"
  218395. "end tell\r\n";
  218396. NSAppleScript* s = [[NSAppleScript alloc]
  218397. initWithSource: juceStringToNS (script)];
  218398. NSDictionary* error = 0;
  218399. const bool ok = [s executeAndReturnError: &error] != nil;
  218400. [s release];
  218401. return ok;
  218402. }
  218403. END_JUCE_NAMESPACE
  218404. using namespace JUCE_NAMESPACE;
  218405. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  218406. @interface JuceURLConnection : NSObject
  218407. {
  218408. @public
  218409. NSURLRequest* request;
  218410. NSURLConnection* connection;
  218411. NSMutableData* data;
  218412. Thread* runLoopThread;
  218413. bool initialised, hasFailed, hasFinished;
  218414. int position;
  218415. int64 contentLength;
  218416. NSLock* dataLock;
  218417. }
  218418. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  218419. - (void) dealloc;
  218420. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  218421. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  218422. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  218423. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  218424. - (BOOL) isOpen;
  218425. - (int) read: (char*) dest numBytes: (int) num;
  218426. - (int) readPosition;
  218427. - (void) stop;
  218428. - (void) createConnection;
  218429. @end
  218430. class JuceURLConnectionMessageThread : public Thread
  218431. {
  218432. JuceURLConnection* owner;
  218433. public:
  218434. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  218435. : Thread (T("http connection")),
  218436. owner (owner_)
  218437. {
  218438. }
  218439. ~JuceURLConnectionMessageThread()
  218440. {
  218441. stopThread (10000);
  218442. }
  218443. void run()
  218444. {
  218445. [owner createConnection];
  218446. while (! threadShouldExit())
  218447. {
  218448. const ScopedAutoReleasePool pool;
  218449. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  218450. }
  218451. }
  218452. };
  218453. @implementation JuceURLConnection
  218454. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  218455. withCallback: (URL::OpenStreamProgressCallback*) callback
  218456. withContext: (void*) context;
  218457. {
  218458. [super init];
  218459. request = req;
  218460. [request retain];
  218461. data = [[NSMutableData data] retain];
  218462. dataLock = [[NSLock alloc] init];
  218463. connection = 0;
  218464. initialised = false;
  218465. hasFailed = false;
  218466. hasFinished = false;
  218467. contentLength = -1;
  218468. runLoopThread = new JuceURLConnectionMessageThread (self);
  218469. runLoopThread->startThread();
  218470. while (runLoopThread->isThreadRunning() && ! initialised)
  218471. {
  218472. if (callback != 0)
  218473. callback (context, -1, [[request HTTPBody] length]);
  218474. Thread::sleep (1);
  218475. }
  218476. return self;
  218477. }
  218478. - (void) dealloc
  218479. {
  218480. [self stop];
  218481. delete runLoopThread;
  218482. [connection release];
  218483. [data release];
  218484. [dataLock release];
  218485. [request release];
  218486. [super dealloc];
  218487. }
  218488. - (void) createConnection
  218489. {
  218490. connection = [[NSURLConnection alloc] initWithRequest: request
  218491. delegate: [self retain]];
  218492. if (connection == nil)
  218493. runLoopThread->signalThreadShouldExit();
  218494. }
  218495. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
  218496. {
  218497. [dataLock lock];
  218498. [data setLength: 0];
  218499. [dataLock unlock];
  218500. initialised = true;
  218501. contentLength = [response expectedContentLength];
  218502. }
  218503. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
  218504. {
  218505. DBG (nsStringToJuce ([error description]));
  218506. hasFailed = true;
  218507. initialised = true;
  218508. runLoopThread->signalThreadShouldExit();
  218509. }
  218510. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) newData
  218511. {
  218512. [dataLock lock];
  218513. [data appendData: newData];
  218514. [dataLock unlock];
  218515. initialised = true;
  218516. }
  218517. - (void) connectionDidFinishLoading: (NSURLConnection*) connection
  218518. {
  218519. hasFinished = true;
  218520. initialised = true;
  218521. runLoopThread->signalThreadShouldExit();
  218522. }
  218523. - (BOOL) isOpen
  218524. {
  218525. return connection != 0 && ! hasFailed;
  218526. }
  218527. - (int) readPosition
  218528. {
  218529. return position;
  218530. }
  218531. - (int) read: (char*) dest numBytes: (int) numNeeded
  218532. {
  218533. int numDone = 0;
  218534. while (numNeeded > 0)
  218535. {
  218536. int available = jmin (numNeeded, [data length]);
  218537. if (available > 0)
  218538. {
  218539. [dataLock lock];
  218540. [data getBytes: dest length: available];
  218541. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  218542. [dataLock unlock];
  218543. numDone += available;
  218544. numNeeded -= available;
  218545. dest += available;
  218546. }
  218547. else
  218548. {
  218549. if (hasFailed || hasFinished)
  218550. break;
  218551. Thread::sleep (1);
  218552. }
  218553. }
  218554. position += numDone;
  218555. return numDone;
  218556. }
  218557. - (void) stop
  218558. {
  218559. [connection cancel];
  218560. runLoopThread->stopThread (10000);
  218561. }
  218562. @end
  218563. BEGIN_JUCE_NAMESPACE
  218564. bool juce_isOnLine()
  218565. {
  218566. return true;
  218567. }
  218568. void* juce_openInternetFile (const String& url,
  218569. const String& headers,
  218570. const MemoryBlock& postData,
  218571. const bool isPost,
  218572. URL::OpenStreamProgressCallback* callback,
  218573. void* callbackContext,
  218574. int timeOutMs)
  218575. {
  218576. const ScopedAutoReleasePool pool;
  218577. NSMutableURLRequest* req = [NSMutableURLRequest
  218578. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  218579. cachePolicy: NSURLRequestUseProtocolCachePolicy
  218580. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  218581. if (req == nil)
  218582. return 0;
  218583. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  218584. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  218585. StringArray headerLines;
  218586. headerLines.addLines (headers);
  218587. headerLines.removeEmptyStrings (true);
  218588. for (int i = 0; i < headerLines.size(); ++i)
  218589. {
  218590. const String key (headerLines[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  218591. const String value (headerLines[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  218592. if (key.isNotEmpty() && value.isNotEmpty())
  218593. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  218594. }
  218595. if (isPost && postData.getSize() > 0)
  218596. {
  218597. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  218598. length: postData.getSize()]];
  218599. }
  218600. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  218601. withCallback: callback
  218602. withContext: callbackContext];
  218603. if ([s isOpen])
  218604. return s;
  218605. [s release];
  218606. return 0;
  218607. }
  218608. void juce_closeInternetFile (void* handle)
  218609. {
  218610. JuceURLConnection* const s = (JuceURLConnection*) handle;
  218611. if (s != 0)
  218612. {
  218613. const ScopedAutoReleasePool pool;
  218614. [s stop];
  218615. [s release];
  218616. }
  218617. }
  218618. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218619. {
  218620. JuceURLConnection* const s = (JuceURLConnection*) handle;
  218621. if (s != 0)
  218622. {
  218623. const ScopedAutoReleasePool pool;
  218624. return [s read: (char*) buffer numBytes: bytesToRead];
  218625. }
  218626. return 0;
  218627. }
  218628. int64 juce_getInternetFileContentLength (void* handle)
  218629. {
  218630. JuceURLConnection* const s = (JuceURLConnection*) handle;
  218631. if (s != 0)
  218632. return s->contentLength;
  218633. return -1;
  218634. }
  218635. int juce_seekInInternetFile (void* handle, int newPosition)
  218636. {
  218637. JuceURLConnection* const s = (JuceURLConnection*) handle;
  218638. if (s != 0)
  218639. return [s readPosition];
  218640. return 0;
  218641. }
  218642. #endif
  218643. /********* End of inlined file: juce_mac_Network.mm *********/
  218644. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  218645. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218646. // compiled on its own).
  218647. #if JUCE_INCLUDED_FILE
  218648. struct NamedPipeInternal
  218649. {
  218650. String pipeInName, pipeOutName;
  218651. int pipeIn, pipeOut;
  218652. bool volatile createdPipe, blocked, stopReadOperation;
  218653. static void signalHandler (int) {}
  218654. };
  218655. void NamedPipe::cancelPendingReads()
  218656. {
  218657. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  218658. {
  218659. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  218660. intern->stopReadOperation = true;
  218661. char buffer [1] = { 0 };
  218662. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  218663. (void) bytesWritten;
  218664. int timeout = 2000;
  218665. while (intern->blocked && --timeout >= 0)
  218666. Thread::sleep (2);
  218667. intern->stopReadOperation = false;
  218668. }
  218669. }
  218670. void NamedPipe::close()
  218671. {
  218672. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  218673. if (intern != 0)
  218674. {
  218675. internal = 0;
  218676. if (intern->pipeIn != -1)
  218677. ::close (intern->pipeIn);
  218678. if (intern->pipeOut != -1)
  218679. ::close (intern->pipeOut);
  218680. if (intern->createdPipe)
  218681. {
  218682. unlink (intern->pipeInName);
  218683. unlink (intern->pipeOutName);
  218684. }
  218685. delete intern;
  218686. }
  218687. }
  218688. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  218689. {
  218690. close();
  218691. NamedPipeInternal* const intern = new NamedPipeInternal();
  218692. internal = intern;
  218693. intern->createdPipe = createPipe;
  218694. intern->blocked = false;
  218695. intern->stopReadOperation = false;
  218696. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  218697. siginterrupt (SIGPIPE, 1);
  218698. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  218699. intern->pipeInName = pipePath + T("_in");
  218700. intern->pipeOutName = pipePath + T("_out");
  218701. intern->pipeIn = -1;
  218702. intern->pipeOut = -1;
  218703. if (createPipe)
  218704. {
  218705. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  218706. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  218707. {
  218708. delete intern;
  218709. internal = 0;
  218710. return false;
  218711. }
  218712. }
  218713. return true;
  218714. }
  218715. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  218716. {
  218717. int bytesRead = -1;
  218718. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  218719. if (intern != 0)
  218720. {
  218721. intern->blocked = true;
  218722. if (intern->pipeIn == -1)
  218723. {
  218724. if (intern->createdPipe)
  218725. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  218726. else
  218727. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  218728. if (intern->pipeIn == -1)
  218729. {
  218730. intern->blocked = false;
  218731. return -1;
  218732. }
  218733. }
  218734. bytesRead = 0;
  218735. char* p = (char*) destBuffer;
  218736. while (bytesRead < maxBytesToRead)
  218737. {
  218738. const int bytesThisTime = maxBytesToRead - bytesRead;
  218739. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  218740. if (numRead <= 0 || intern->stopReadOperation)
  218741. {
  218742. bytesRead = -1;
  218743. break;
  218744. }
  218745. bytesRead += numRead;
  218746. p += bytesRead;
  218747. }
  218748. intern->blocked = false;
  218749. }
  218750. return bytesRead;
  218751. }
  218752. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218753. {
  218754. int bytesWritten = -1;
  218755. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  218756. if (intern != 0)
  218757. {
  218758. if (intern->pipeOut == -1)
  218759. {
  218760. if (intern->createdPipe)
  218761. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  218762. else
  218763. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  218764. if (intern->pipeOut == -1)
  218765. {
  218766. return -1;
  218767. }
  218768. }
  218769. const char* p = (const char*) sourceBuffer;
  218770. bytesWritten = 0;
  218771. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218772. while (bytesWritten < numBytesToWrite
  218773. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218774. {
  218775. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218776. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  218777. if (numWritten <= 0)
  218778. {
  218779. bytesWritten = -1;
  218780. break;
  218781. }
  218782. bytesWritten += numWritten;
  218783. p += bytesWritten;
  218784. }
  218785. }
  218786. return bytesWritten;
  218787. }
  218788. #endif
  218789. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  218790. /********* Start of inlined file: juce_mac_Threads.mm *********/
  218791. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218792. // compiled on its own).
  218793. #ifdef JUCE_INCLUDED_FILE
  218794. /*
  218795. Note that a lot of methods that you'd expect to find in this file actually
  218796. live in juce_posix_SharedCode.h!
  218797. */
  218798. void JUCE_API juce_threadEntryPoint (void*);
  218799. void* threadEntryProc (void* userData) throw()
  218800. {
  218801. const ScopedAutoReleasePool pool;
  218802. juce_threadEntryPoint (userData);
  218803. return 0;
  218804. }
  218805. void* juce_createThread (void* userData) throw()
  218806. {
  218807. pthread_t handle = 0;
  218808. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  218809. {
  218810. pthread_detach (handle);
  218811. return (void*) handle;
  218812. }
  218813. return 0;
  218814. }
  218815. void juce_killThread (void* handle) throw()
  218816. {
  218817. if (handle != 0)
  218818. pthread_cancel ((pthread_t) handle);
  218819. }
  218820. void juce_setCurrentThreadName (const String& /*name*/) throw()
  218821. {
  218822. }
  218823. Thread::ThreadID Thread::getCurrentThreadId() throw()
  218824. {
  218825. return (ThreadID) pthread_self();
  218826. }
  218827. bool juce_setThreadPriority (void* handle, int priority) throw()
  218828. {
  218829. if (handle == 0)
  218830. handle = (void*) pthread_self();
  218831. struct sched_param param;
  218832. int policy;
  218833. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  218834. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  218835. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  218836. }
  218837. void Thread::yield() throw()
  218838. {
  218839. sched_yield();
  218840. }
  218841. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  218842. {
  218843. // xxx
  218844. jassertfalse
  218845. }
  218846. bool Process::isForegroundProcess() throw()
  218847. {
  218848. return [NSApp isActive];
  218849. }
  218850. void Process::raisePrivilege()
  218851. {
  218852. jassertfalse
  218853. }
  218854. void Process::lowerPrivilege()
  218855. {
  218856. jassertfalse
  218857. }
  218858. void Process::terminate()
  218859. {
  218860. exit (0);
  218861. }
  218862. void Process::setPriority (ProcessPriority p)
  218863. {
  218864. // xxx
  218865. }
  218866. #endif
  218867. /********* End of inlined file: juce_mac_Threads.mm *********/
  218868. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  218869. /*
  218870. This file contains posix routines that are common to both the Linux and Mac builds.
  218871. It gets included directly in the cpp files for these platforms.
  218872. */
  218873. CriticalSection::CriticalSection() throw()
  218874. {
  218875. pthread_mutexattr_t atts;
  218876. pthread_mutexattr_init (&atts);
  218877. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  218878. pthread_mutex_init (&internal, &atts);
  218879. }
  218880. CriticalSection::~CriticalSection() throw()
  218881. {
  218882. pthread_mutex_destroy (&internal);
  218883. }
  218884. void CriticalSection::enter() const throw()
  218885. {
  218886. pthread_mutex_lock (&internal);
  218887. }
  218888. bool CriticalSection::tryEnter() const throw()
  218889. {
  218890. return pthread_mutex_trylock (&internal) == 0;
  218891. }
  218892. void CriticalSection::exit() const throw()
  218893. {
  218894. pthread_mutex_unlock (&internal);
  218895. }
  218896. struct EventStruct
  218897. {
  218898. pthread_cond_t condition;
  218899. pthread_mutex_t mutex;
  218900. bool triggered;
  218901. };
  218902. WaitableEvent::WaitableEvent() throw()
  218903. {
  218904. EventStruct* const es = new EventStruct();
  218905. es->triggered = false;
  218906. pthread_cond_init (&es->condition, 0);
  218907. pthread_mutex_init (&es->mutex, 0);
  218908. internal = es;
  218909. }
  218910. WaitableEvent::~WaitableEvent() throw()
  218911. {
  218912. EventStruct* const es = (EventStruct*) internal;
  218913. pthread_cond_destroy (&es->condition);
  218914. pthread_mutex_destroy (&es->mutex);
  218915. delete es;
  218916. }
  218917. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  218918. {
  218919. EventStruct* const es = (EventStruct*) internal;
  218920. bool ok = true;
  218921. pthread_mutex_lock (&es->mutex);
  218922. if (timeOutMillisecs < 0)
  218923. {
  218924. while (! es->triggered)
  218925. pthread_cond_wait (&es->condition, &es->mutex);
  218926. }
  218927. else
  218928. {
  218929. while (! es->triggered)
  218930. {
  218931. struct timeval t;
  218932. gettimeofday (&t, 0);
  218933. struct timespec time;
  218934. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  218935. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  218936. if (time.tv_nsec >= 1000000000)
  218937. {
  218938. time.tv_nsec -= 1000000000;
  218939. time.tv_sec++;
  218940. }
  218941. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  218942. {
  218943. ok = false;
  218944. break;
  218945. }
  218946. }
  218947. }
  218948. es->triggered = false;
  218949. pthread_mutex_unlock (&es->mutex);
  218950. return ok;
  218951. }
  218952. void WaitableEvent::signal() const throw()
  218953. {
  218954. EventStruct* const es = (EventStruct*) internal;
  218955. pthread_mutex_lock (&es->mutex);
  218956. es->triggered = true;
  218957. pthread_cond_broadcast (&es->condition);
  218958. pthread_mutex_unlock (&es->mutex);
  218959. }
  218960. void WaitableEvent::reset() const throw()
  218961. {
  218962. EventStruct* const es = (EventStruct*) internal;
  218963. pthread_mutex_lock (&es->mutex);
  218964. es->triggered = false;
  218965. pthread_mutex_unlock (&es->mutex);
  218966. }
  218967. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  218968. {
  218969. struct timespec time;
  218970. time.tv_sec = millisecs / 1000;
  218971. time.tv_nsec = (millisecs % 1000) * 1000000;
  218972. nanosleep (&time, 0);
  218973. }
  218974. const tchar File::separator = T('/');
  218975. const tchar* File::separatorString = T("/");
  218976. bool juce_copyFile (const String& s, const String& d) throw();
  218977. static bool juce_stat (const String& fileName, struct stat& info) throw()
  218978. {
  218979. return fileName.isNotEmpty()
  218980. && (stat (fileName.toUTF8(), &info) == 0);
  218981. }
  218982. bool juce_isDirectory (const String& fileName) throw()
  218983. {
  218984. struct stat info;
  218985. return fileName.isEmpty()
  218986. || (juce_stat (fileName, info)
  218987. && ((info.st_mode & S_IFDIR) != 0));
  218988. }
  218989. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  218990. {
  218991. if (fileName.isEmpty())
  218992. return false;
  218993. const char* const fileNameUTF8 = fileName.toUTF8();
  218994. bool exists = access (fileNameUTF8, F_OK) == 0;
  218995. if (exists && dontCountDirectories)
  218996. {
  218997. struct stat info;
  218998. const int res = stat (fileNameUTF8, &info);
  218999. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  219000. exists = false;
  219001. }
  219002. return exists;
  219003. }
  219004. int64 juce_getFileSize (const String& fileName) throw()
  219005. {
  219006. struct stat info;
  219007. return juce_stat (fileName, info) ? info.st_size : 0;
  219008. }
  219009. bool juce_canWriteToFile (const String& fileName) throw()
  219010. {
  219011. return access (fileName.toUTF8(), W_OK) == 0;
  219012. }
  219013. bool juce_deleteFile (const String& fileName) throw()
  219014. {
  219015. if (juce_isDirectory (fileName))
  219016. return rmdir ((const char*) fileName.toUTF8()) == 0;
  219017. else
  219018. return remove ((const char*) fileName.toUTF8()) == 0;
  219019. }
  219020. bool juce_moveFile (const String& source, const String& dest) throw()
  219021. {
  219022. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  219023. return true;
  219024. if (juce_canWriteToFile (source)
  219025. && juce_copyFile (source, dest))
  219026. {
  219027. if (juce_deleteFile (source))
  219028. return true;
  219029. juce_deleteFile (dest);
  219030. }
  219031. return false;
  219032. }
  219033. void juce_createDirectory (const String& fileName) throw()
  219034. {
  219035. mkdir (fileName.toUTF8(), 0777);
  219036. }
  219037. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  219038. {
  219039. int flags = O_RDONLY;
  219040. if (forWriting)
  219041. {
  219042. if (juce_fileExists (fileName, false))
  219043. {
  219044. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  219045. if (f != -1)
  219046. lseek (f, 0, SEEK_END);
  219047. return (void*) f;
  219048. }
  219049. else
  219050. {
  219051. flags = O_RDWR + O_CREAT;
  219052. }
  219053. }
  219054. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  219055. }
  219056. void juce_fileClose (void* handle) throw()
  219057. {
  219058. if (handle != 0)
  219059. close ((int) (pointer_sized_int) handle);
  219060. }
  219061. int juce_fileRead (void* handle, void* buffer, int size) throw()
  219062. {
  219063. if (handle != 0)
  219064. return read ((int) (pointer_sized_int) handle, buffer, size);
  219065. return 0;
  219066. }
  219067. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  219068. {
  219069. if (handle != 0)
  219070. return write ((int) (pointer_sized_int) handle, buffer, size);
  219071. return 0;
  219072. }
  219073. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  219074. {
  219075. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  219076. return pos;
  219077. return -1;
  219078. }
  219079. int64 juce_fileGetPosition (void* handle) throw()
  219080. {
  219081. if (handle != 0)
  219082. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  219083. else
  219084. return -1;
  219085. }
  219086. void juce_fileFlush (void* handle) throw()
  219087. {
  219088. if (handle != 0)
  219089. fsync ((int) (pointer_sized_int) handle);
  219090. }
  219091. const File juce_getExecutableFile()
  219092. {
  219093. Dl_info exeInfo;
  219094. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  219095. return File (exeInfo.dli_fname);
  219096. }
  219097. // if this file doesn't exist, find a parent of it that does..
  219098. static bool doStatFS (const File* file, struct statfs& result) throw()
  219099. {
  219100. File f (*file);
  219101. for (int i = 5; --i >= 0;)
  219102. {
  219103. if (f.exists())
  219104. break;
  219105. f = f.getParentDirectory();
  219106. }
  219107. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  219108. }
  219109. int64 File::getBytesFreeOnVolume() const throw()
  219110. {
  219111. struct statfs buf;
  219112. if (doStatFS (this, buf))
  219113. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  219114. return 0;
  219115. }
  219116. int64 File::getVolumeTotalSize() const throw()
  219117. {
  219118. struct statfs buf;
  219119. if (doStatFS (this, buf))
  219120. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  219121. return 0;
  219122. }
  219123. const String juce_getVolumeLabel (const String& filenameOnVolume,
  219124. int& volumeSerialNumber) throw()
  219125. {
  219126. volumeSerialNumber = 0;
  219127. #if JUCE_MAC
  219128. struct VolAttrBuf
  219129. {
  219130. u_int32_t length;
  219131. attrreference_t mountPointRef;
  219132. char mountPointSpace [MAXPATHLEN];
  219133. } attrBuf;
  219134. struct attrlist attrList;
  219135. zerostruct (attrList);
  219136. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  219137. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  219138. File f (filenameOnVolume);
  219139. for (;;)
  219140. {
  219141. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  219142. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  219143. {
  219144. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  219145. (int) attrBuf.mountPointRef.attr_length);
  219146. }
  219147. const File parent (f.getParentDirectory());
  219148. if (f == parent)
  219149. break;
  219150. f = parent;
  219151. }
  219152. #endif
  219153. return String::empty;
  219154. }
  219155. void juce_runSystemCommand (const String& command)
  219156. {
  219157. int result = system ((const char*) command.toUTF8());
  219158. (void) result;
  219159. }
  219160. const String juce_getOutputFromCommand (const String& command)
  219161. {
  219162. // slight bodge here, as we just pipe the output into a temp file and read it...
  219163. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  219164. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  219165. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  219166. String result (tempFile.loadFileAsString());
  219167. tempFile.deleteFile();
  219168. return result;
  219169. }
  219170. #if JUCE_64BIT
  219171. #define filedesc ((long long) internal)
  219172. #else
  219173. #define filedesc ((int) internal)
  219174. #endif
  219175. InterProcessLock::InterProcessLock (const String& name_) throw()
  219176. : internal (0),
  219177. name (name_),
  219178. reentrancyLevel (0)
  219179. {
  219180. #if JUCE_MAC
  219181. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  219182. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  219183. #else
  219184. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  219185. #endif
  219186. temp.create();
  219187. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  219188. }
  219189. InterProcessLock::~InterProcessLock() throw()
  219190. {
  219191. while (reentrancyLevel > 0)
  219192. this->exit();
  219193. close (filedesc);
  219194. }
  219195. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  219196. {
  219197. if (internal == 0)
  219198. return false;
  219199. if (reentrancyLevel != 0)
  219200. return true;
  219201. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  219202. struct flock fl;
  219203. zerostruct (fl);
  219204. fl.l_whence = SEEK_SET;
  219205. fl.l_type = F_WRLCK;
  219206. for (;;)
  219207. {
  219208. const int result = fcntl (filedesc, F_SETLK, &fl);
  219209. if (result >= 0)
  219210. {
  219211. ++reentrancyLevel;
  219212. return true;
  219213. }
  219214. if (errno != EINTR)
  219215. {
  219216. if (timeOutMillisecs == 0
  219217. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  219218. break;
  219219. Thread::sleep (10);
  219220. }
  219221. }
  219222. return false;
  219223. }
  219224. void InterProcessLock::exit() throw()
  219225. {
  219226. if (reentrancyLevel > 0 && internal != 0)
  219227. {
  219228. --reentrancyLevel;
  219229. struct flock fl;
  219230. zerostruct (fl);
  219231. fl.l_whence = SEEK_SET;
  219232. fl.l_type = F_UNLCK;
  219233. for (;;)
  219234. {
  219235. const int result = fcntl (filedesc, F_SETLKW, &fl);
  219236. if (result >= 0 || errno != EINTR)
  219237. break;
  219238. }
  219239. }
  219240. }
  219241. /********* End of inlined file: juce_posix_SharedCode.h *********/
  219242. /********* Start of inlined file: juce_mac_Files.mm *********/
  219243. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219244. // compiled on its own).
  219245. #ifdef JUCE_INCLUDED_FILE
  219246. /*
  219247. Note that a lot of methods that you'd expect to find in this file actually
  219248. live in juce_posix_SharedCode.h!
  219249. */
  219250. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  219251. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  219252. {
  219253. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  219254. return 0;
  219255. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  219256. + ((d.fraction * 1000) >> 16)
  219257. - 2082844800000ll;
  219258. }
  219259. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  219260. {
  219261. if (t != 0)
  219262. t += 2082844800000ll;
  219263. d.highSeconds = (t / 1000) >> 32;
  219264. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  219265. d.fraction = ((t % 1000) << 16) / 1000;
  219266. }
  219267. void juce_getFileTimes (const String& fileName,
  219268. int64& modificationTime,
  219269. int64& accessTime,
  219270. int64& creationTime) throw()
  219271. {
  219272. modificationTime = 0;
  219273. accessTime = 0;
  219274. creationTime = 0;
  219275. FSRef fileRef;
  219276. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  219277. {
  219278. FSRefParam info;
  219279. zerostruct (info);
  219280. info.ref = &fileRef;
  219281. info.whichInfo = kFSCatInfoAllDates;
  219282. FSCatalogInfo catInfo;
  219283. info.catInfo = &catInfo;
  219284. if (PBGetCatalogInfoSync (&info) == noErr)
  219285. {
  219286. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  219287. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  219288. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  219289. }
  219290. }
  219291. }
  219292. bool juce_setFileTimes (const String& fileName,
  219293. int64 modificationTime,
  219294. int64 accessTime,
  219295. int64 creationTime) throw()
  219296. {
  219297. FSRef fileRef;
  219298. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  219299. {
  219300. FSRefParam info;
  219301. zerostruct (info);
  219302. info.ref = &fileRef;
  219303. info.whichInfo = kFSCatInfoAllDates;
  219304. FSCatalogInfo catInfo;
  219305. info.catInfo = &catInfo;
  219306. if (PBGetCatalogInfoSync (&info) == noErr)
  219307. {
  219308. if (creationTime != 0)
  219309. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  219310. if (modificationTime != 0)
  219311. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  219312. if (accessTime != 0)
  219313. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  219314. return PBSetCatalogInfoSync (&info) == noErr;
  219315. }
  219316. }
  219317. return false;
  219318. }
  219319. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  219320. {
  219321. const char* const fileNameUTF8 = fileName.toUTF8();
  219322. struct stat info;
  219323. const int res = stat (fileNameUTF8, &info);
  219324. bool ok = false;
  219325. if (res == 0)
  219326. {
  219327. info.st_mode &= 0777; // Just permissions
  219328. if (isReadOnly)
  219329. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  219330. else
  219331. // Give everybody write permission?
  219332. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  219333. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  219334. }
  219335. return ok;
  219336. }
  219337. bool juce_copyFile (const String& src, const String& dst) throw()
  219338. {
  219339. const ScopedAutoReleasePool pool;
  219340. NSFileManager* fm = [NSFileManager defaultManager];
  219341. return [fm fileExistsAtPath: juceStringToNS (src)]
  219342. && [fm copyPath: juceStringToNS (src)
  219343. toPath: juceStringToNS (dst)
  219344. handler: nil];
  219345. }
  219346. const StringArray juce_getFileSystemRoots() throw()
  219347. {
  219348. StringArray s;
  219349. s.add (T("/"));
  219350. return s;
  219351. }
  219352. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  219353. {
  219354. struct statfs buf;
  219355. if (doStatFS (f, buf))
  219356. {
  219357. const String type (buf.f_fstypename);
  219358. while (*types != 0)
  219359. if (type.equalsIgnoreCase (*types++))
  219360. return true;
  219361. }
  219362. return false;
  219363. }
  219364. bool File::isOnCDRomDrive() const throw()
  219365. {
  219366. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  219367. return isFileOnDriveType (this, (const char**) cdTypes);
  219368. }
  219369. bool File::isOnHardDisk() const throw()
  219370. {
  219371. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  219372. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  219373. }
  219374. bool File::isOnRemovableDrive() const throw()
  219375. {
  219376. const ScopedAutoReleasePool pool;
  219377. BOOL removable = false;
  219378. [[NSWorkspace sharedWorkspace]
  219379. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  219380. isRemovable: &removable
  219381. isWritable: nil
  219382. isUnmountable: nil
  219383. description: nil
  219384. type: nil];
  219385. return removable;
  219386. }
  219387. static bool juce_isHiddenFile (const String& path) throw()
  219388. {
  219389. FSRef ref;
  219390. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  219391. return false;
  219392. FSCatalogInfo info;
  219393. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  219394. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  219395. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  219396. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  219397. }
  219398. bool File::isHidden() const throw()
  219399. {
  219400. return juce_isHiddenFile (getFullPathName());
  219401. }
  219402. const File File::getSpecialLocation (const SpecialLocationType type)
  219403. {
  219404. const ScopedAutoReleasePool pool;
  219405. String resultPath;
  219406. switch (type)
  219407. {
  219408. case userHomeDirectory:
  219409. resultPath = nsStringToJuce (NSHomeDirectory());
  219410. break;
  219411. case userDocumentsDirectory:
  219412. resultPath = "~/Documents";
  219413. break;
  219414. case userDesktopDirectory:
  219415. resultPath = "~/Desktop";
  219416. break;
  219417. case userApplicationDataDirectory:
  219418. resultPath = "~/Library";
  219419. break;
  219420. case commonApplicationDataDirectory:
  219421. resultPath = "/Library";
  219422. break;
  219423. case globalApplicationsDirectory:
  219424. resultPath = "/Applications";
  219425. break;
  219426. case userMusicDirectory:
  219427. resultPath = "~/Music";
  219428. break;
  219429. case userMoviesDirectory:
  219430. resultPath = "~/Movies";
  219431. break;
  219432. case tempDirectory:
  219433. {
  219434. File tmp (T("~/Library/Caches/") + juce_getExecutableFile().getFileNameWithoutExtension());
  219435. tmp.createDirectory();
  219436. return tmp.getFullPathName();
  219437. }
  219438. case currentExecutableFile:
  219439. return juce_getExecutableFile();
  219440. case currentApplicationFile:
  219441. {
  219442. const File exe (juce_getExecutableFile());
  219443. const File parent (exe.getParentDirectory());
  219444. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  219445. ? parent.getParentDirectory().getParentDirectory()
  219446. : exe;
  219447. }
  219448. default:
  219449. jassertfalse // unknown type?
  219450. break;
  219451. }
  219452. if (resultPath != 0)
  219453. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  219454. return File::nonexistent;
  219455. }
  219456. const File File::getCurrentWorkingDirectory() throw()
  219457. {
  219458. char buf [2048];
  219459. getcwd (buf, sizeof(buf));
  219460. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  219461. }
  219462. bool File::setAsCurrentWorkingDirectory() const throw()
  219463. {
  219464. return chdir (getFullPathName().toUTF8()) == 0;
  219465. }
  219466. const String File::getVersion() const throw()
  219467. {
  219468. const ScopedAutoReleasePool pool;
  219469. String result;
  219470. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  219471. if (bundle != 0)
  219472. {
  219473. NSDictionary* info = [bundle infoDictionary];
  219474. if (info != 0)
  219475. {
  219476. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  219477. if (name != nil)
  219478. result = nsStringToJuce (name);
  219479. }
  219480. }
  219481. return result;
  219482. }
  219483. const File File::getLinkedTarget() const throw()
  219484. {
  219485. FSRef ref;
  219486. Boolean targetIsAFolder, wasAliased;
  219487. if (PlatformUtilities::makeFSRefFromPath (&ref, getFullPathName())
  219488. && (FSResolveAliasFileWithMountFlags (&ref, true, &targetIsAFolder, &wasAliased, 0) == noErr)
  219489. && wasAliased)
  219490. {
  219491. return File (PlatformUtilities::makePathFromFSRef (&ref));
  219492. }
  219493. return *this;
  219494. }
  219495. bool File::moveToTrash() const throw()
  219496. {
  219497. if (! exists())
  219498. return true;
  219499. const ScopedAutoReleasePool pool;
  219500. NSString* p = juceStringToNS (getFullPathName());
  219501. return [[NSWorkspace sharedWorkspace]
  219502. performFileOperation: NSWorkspaceRecycleOperation
  219503. source: [p stringByDeletingLastPathComponent]
  219504. destination: @""
  219505. files: [NSArray arrayWithObject: [p lastPathComponent]]
  219506. tag: nil ];
  219507. }
  219508. struct FindFileStruct
  219509. {
  219510. String parentDir, wildCard;
  219511. DIR* dir;
  219512. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  219513. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  219514. {
  219515. const char* const wildCardUTF8 = wildCard.toUTF8();
  219516. for (;;)
  219517. {
  219518. struct dirent* const de = readdir (dir);
  219519. if (de == 0)
  219520. break;
  219521. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  219522. {
  219523. result = String::fromUTF8 ((const uint8*) de->d_name);
  219524. const String path (parentDir + result);
  219525. if (isDir != 0 || fileSize != 0)
  219526. {
  219527. struct stat info;
  219528. const bool statOk = juce_stat (path, info);
  219529. if (isDir != 0)
  219530. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  219531. if (isHidden != 0)
  219532. *isHidden = (de->d_name[0] == '.')
  219533. || juce_isHiddenFile (path);
  219534. if (fileSize != 0)
  219535. *fileSize = statOk ? info.st_size : 0;
  219536. }
  219537. if (modTime != 0 || creationTime != 0)
  219538. {
  219539. int64 m, a, c;
  219540. juce_getFileTimes (path, m, a, c);
  219541. if (modTime != 0)
  219542. *modTime = m;
  219543. if (creationTime != 0)
  219544. *creationTime = c;
  219545. }
  219546. if (isReadOnly != 0)
  219547. *isReadOnly = ! juce_canWriteToFile (path);
  219548. return true;
  219549. }
  219550. }
  219551. return false;
  219552. }
  219553. };
  219554. // returns 0 on failure
  219555. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  219556. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  219557. Time* creationTime, bool* isReadOnly) throw()
  219558. {
  219559. DIR* const d = opendir (directory.toUTF8());
  219560. if (d != 0)
  219561. {
  219562. FindFileStruct* const ff = new FindFileStruct();
  219563. ff->parentDir = directory;
  219564. if (!ff->parentDir.endsWithChar (File::separator))
  219565. ff->parentDir += File::separator;
  219566. ff->wildCard = wildCard;
  219567. ff->dir = d;
  219568. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  219569. {
  219570. return ff;
  219571. }
  219572. else
  219573. {
  219574. firstResultFile = String::empty;
  219575. isDir = false;
  219576. closedir (d);
  219577. delete ff;
  219578. }
  219579. }
  219580. return 0;
  219581. }
  219582. bool juce_findFileNext (void* handle, String& resultFile,
  219583. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  219584. {
  219585. FindFileStruct* const ff = (FindFileStruct*) handle;
  219586. if (ff != 0)
  219587. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  219588. return false;
  219589. }
  219590. void juce_findFileClose (void* handle) throw()
  219591. {
  219592. FindFileStruct* const ff = (FindFileStruct*)handle;
  219593. if (ff != 0)
  219594. {
  219595. closedir (ff->dir);
  219596. delete ff;
  219597. }
  219598. }
  219599. bool juce_launchExecutable (const String& pathAndArguments) throw()
  219600. {
  219601. const char* const argv[4] = { "/bin/sh", "-c", (const char*) pathAndArguments, 0 };
  219602. const int cpid = fork();
  219603. if (cpid == 0)
  219604. {
  219605. // Child process
  219606. if (execve (argv[0], (char**) argv, 0) < 0)
  219607. exit (0);
  219608. }
  219609. else
  219610. {
  219611. if (cpid < 0)
  219612. return false;
  219613. }
  219614. return true;
  219615. }
  219616. bool juce_launchFile (const String& fileName,
  219617. const String& parameters) throw()
  219618. {
  219619. const ScopedAutoReleasePool pool;
  219620. if (parameters.isEmpty())
  219621. {
  219622. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  219623. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  219624. }
  219625. bool ok = false;
  219626. FSRef ref;
  219627. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  219628. {
  219629. if (PlatformUtilities::isBundle (fileName))
  219630. {
  219631. NSMutableArray* urls = [NSMutableArray array];
  219632. StringArray docs;
  219633. docs.addTokens (parameters, true);
  219634. for (int i = 0; i < docs.size(); ++i)
  219635. [urls addObject: juceStringToNS (docs[i])];
  219636. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  219637. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  219638. options: nil
  219639. additionalEventParamDescriptor: nil
  219640. launchIdentifiers: nil];
  219641. }
  219642. else
  219643. {
  219644. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  219645. }
  219646. }
  219647. return ok;
  219648. }
  219649. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  219650. {
  219651. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  219652. }
  219653. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  219654. {
  219655. uint8 path [2048];
  219656. zeromem (path, sizeof (path));
  219657. String result;
  219658. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  219659. result = String::fromUTF8 (path);
  219660. return PlatformUtilities::convertToPrecomposedUnicode (result);
  219661. }
  219662. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  219663. {
  219664. const ScopedAutoReleasePool pool;
  219665. return NSHFSTypeCodeFromFileType (NSHFSTypeOfFile (juceStringToNS (filename)));
  219666. }
  219667. bool PlatformUtilities::isBundle (const String& filename)
  219668. {
  219669. const ScopedAutoReleasePool pool;
  219670. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  219671. }
  219672. #endif
  219673. /********* End of inlined file: juce_mac_Files.mm *********/
  219674. /********* Start of inlined file: juce_mac_MiscUtilities.mm *********/
  219675. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219676. // compiled on its own).
  219677. #ifdef JUCE_INCLUDED_FILE
  219678. ScopedAutoReleasePool::ScopedAutoReleasePool()
  219679. {
  219680. pool = [[NSAutoreleasePool alloc] init];
  219681. }
  219682. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  219683. {
  219684. [((NSAutoreleasePool*) pool) release];
  219685. }
  219686. void PlatformUtilities::beep()
  219687. {
  219688. NSBeep();
  219689. }
  219690. void PlatformUtilities::addItemToDock (const File& file)
  219691. {
  219692. // check that it's not already there...
  219693. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  219694. .containsIgnoreCase (file.getFullPathName()))
  219695. {
  219696. 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>"
  219697. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  219698. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  219699. }
  219700. }
  219701. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  219702. bool AlertWindow::showNativeDialogBox (const String& title,
  219703. const String& bodyText,
  219704. bool isOkCancel)
  219705. {
  219706. const ScopedAutoReleasePool pool;
  219707. return NSRunAlertPanel (juceStringToNS (title),
  219708. juceStringToNS (bodyText),
  219709. @"Ok",
  219710. isOkCancel ? @"Cancel" : nil,
  219711. nil) == NSAlertDefaultReturn;
  219712. }
  219713. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  219714. {
  219715. if (files.size() == 0)
  219716. return false;
  219717. Component* sourceComp = Component::getComponentUnderMouse();
  219718. if (sourceComp == 0)
  219719. {
  219720. jassertfalse // this method must be called in response to a
  219721. // component's mouseDrag event!
  219722. return false;
  219723. }
  219724. const ScopedAutoReleasePool pool;
  219725. NSView* view = (NSView*) sourceComp->getWindowHandle();
  219726. if (view == 0)
  219727. return false;
  219728. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  219729. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  219730. owner: nil];
  219731. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  219732. for (int i = 0; i < files.size(); ++i)
  219733. [filesArray addObject: juceStringToNS (files[i])];
  219734. [pboard setPropertyList: filesArray
  219735. forType: NSFilenamesPboardType];
  219736. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  219737. fromView: nil];
  219738. dragPosition.x -= 16;
  219739. dragPosition.y -= 16;
  219740. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  219741. at: dragPosition
  219742. offset: NSMakeSize (0, 0)
  219743. event: [[view window] currentEvent]
  219744. pasteboard: pboard
  219745. source: view
  219746. slideBack: YES];
  219747. return true;
  219748. }
  219749. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  219750. {
  219751. jassertfalse // not implemented!
  219752. return false;
  219753. }
  219754. bool Desktop::canUseSemiTransparentWindows() throw()
  219755. {
  219756. return true;
  219757. }
  219758. void Desktop::getMousePosition (int& x, int& y) throw()
  219759. {
  219760. const ScopedAutoReleasePool pool;
  219761. const NSPoint p ([NSEvent mouseLocation]);
  219762. x = roundFloatToInt (p.x);
  219763. y = roundFloatToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y);
  219764. }
  219765. void Desktop::setMousePosition (int x, int y) throw()
  219766. {
  219767. // this rubbish needs to be done around the warp call, to avoid causing a
  219768. // bizarre glitch..
  219769. CGAssociateMouseAndMouseCursorPosition (false);
  219770. CGSetLocalEventsSuppressionInterval (0);
  219771. CGPoint pos = { x, y };
  219772. CGWarpMouseCursorPosition (pos);
  219773. CGAssociateMouseAndMouseCursorPosition (true);
  219774. }
  219775. #if MACOS_10_4_OR_EARLIER
  219776. class ScreenSaverDefeater : public Timer,
  219777. public DeletedAtShutdown
  219778. {
  219779. public:
  219780. ScreenSaverDefeater() throw()
  219781. {
  219782. startTimer (10000);
  219783. timerCallback();
  219784. }
  219785. ~ScreenSaverDefeater() {}
  219786. void timerCallback()
  219787. {
  219788. if (Process::isForegroundProcess())
  219789. UpdateSystemActivity (UsrActivity);
  219790. }
  219791. };
  219792. static ScreenSaverDefeater* screenSaverDefeater = 0;
  219793. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  219794. {
  219795. if (isEnabled)
  219796. {
  219797. deleteAndZero (screenSaverDefeater);
  219798. }
  219799. else if (screenSaverDefeater == 0)
  219800. {
  219801. screenSaverDefeater = new ScreenSaverDefeater();
  219802. }
  219803. }
  219804. bool Desktop::isScreenSaverEnabled() throw()
  219805. {
  219806. return screenSaverDefeater == 0;
  219807. }
  219808. #else
  219809. static IOPMAssertionID screenSaverDisablerID = 0;
  219810. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  219811. {
  219812. if (isEnabled)
  219813. {
  219814. if (screenSaverDisablerID != 0)
  219815. {
  219816. IOPMAssertionRelease (screenSaverDisablerID);
  219817. screenSaverDisablerID = 0;
  219818. }
  219819. }
  219820. else
  219821. {
  219822. if (screenSaverDisablerID == 0)
  219823. {
  219824. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep,
  219825. kIOPMAssertionLevelOn, &screenSaverDisablerID);
  219826. }
  219827. }
  219828. }
  219829. bool Desktop::isScreenSaverEnabled() throw()
  219830. {
  219831. return screenSaverDisablerID == 0;
  219832. }
  219833. #endif
  219834. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  219835. {
  219836. const ScopedAutoReleasePool pool;
  219837. monitorCoords.clear();
  219838. NSArray* screens = [NSScreen screens];
  219839. const float mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  219840. for (unsigned int i = 0; i < [screens count]; ++i)
  219841. {
  219842. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  219843. NSRect r = clipToWorkArea ? [s visibleFrame]
  219844. : [s frame];
  219845. monitorCoords.add (Rectangle ((int) r.origin.x,
  219846. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  219847. (int) r.size.width,
  219848. (int) r.size.height));
  219849. }
  219850. jassert (monitorCoords.size() > 0);
  219851. }
  219852. #endif
  219853. #endif
  219854. /********* End of inlined file: juce_mac_MiscUtilities.mm *********/
  219855. /********* Start of inlined file: juce_mac_Debugging.mm *********/
  219856. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219857. // compiled on its own).
  219858. #ifdef JUCE_INCLUDED_FILE
  219859. void Logger::outputDebugString (const String& text) throw()
  219860. {
  219861. fputs (text.toUTF8(), stderr);
  219862. fputs ("\n", stderr);
  219863. }
  219864. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  219865. {
  219866. String text;
  219867. va_list args;
  219868. va_start (args, format);
  219869. text.vprintf (format, args);
  219870. outputDebugString (text);
  219871. }
  219872. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  219873. {
  219874. static char testResult = 0;
  219875. if (testResult == 0)
  219876. {
  219877. struct kinfo_proc info;
  219878. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  219879. size_t sz = sizeof (info);
  219880. sysctl (m, 4, &info, &sz, 0, 0);
  219881. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  219882. }
  219883. return testResult > 0;
  219884. }
  219885. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  219886. {
  219887. return juce_isRunningUnderDebugger();
  219888. }
  219889. #endif
  219890. /********* End of inlined file: juce_mac_Debugging.mm *********/
  219891. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  219892. /********* Start of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  219893. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219894. // compiled on its own).
  219895. #ifdef JUCE_INCLUDED_FILE
  219896. class NSViewComponentPeer;
  219897. END_JUCE_NAMESPACE
  219898. #define JuceNSView MakeObjCClassName(JuceNSView)
  219899. @interface JuceNSView : NSView
  219900. {
  219901. @public
  219902. NSViewComponentPeer* owner;
  219903. NSNotificationCenter* notificationCenter;
  219904. }
  219905. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  219906. - (void) dealloc;
  219907. - (BOOL) isOpaque;
  219908. - (void) drawRect: (NSRect) r;
  219909. - (void) mouseDown: (NSEvent*) ev;
  219910. - (void) asyncMouseDown: (NSEvent*) ev;
  219911. - (void) mouseUp: (NSEvent*) ev;
  219912. - (void) asyncMouseUp: (NSEvent*) ev;
  219913. - (void) mouseDragged: (NSEvent*) ev;
  219914. - (void) mouseMoved: (NSEvent*) ev;
  219915. - (void) mouseEntered: (NSEvent*) ev;
  219916. - (void) mouseExited: (NSEvent*) ev;
  219917. - (void) rightMouseDown: (NSEvent*) ev;
  219918. - (void) rightMouseDragged: (NSEvent*) ev;
  219919. - (void) rightMouseUp: (NSEvent*) ev;
  219920. - (void) otherMouseDown: (NSEvent*) ev;
  219921. - (void) otherMouseDragged: (NSEvent*) ev;
  219922. - (void) otherMouseUp: (NSEvent*) ev;
  219923. - (void) scrollWheel: (NSEvent*) ev;
  219924. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  219925. - (void) frameChanged: (NSNotification*) n;
  219926. - (void) keyDown: (NSEvent*) ev;
  219927. - (void) keyUp: (NSEvent*) ev;
  219928. - (void) flagsChanged: (NSEvent*) ev;
  219929. #if MACOS_10_4_OR_EARLIER
  219930. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  219931. #endif
  219932. - (BOOL) becomeFirstResponder;
  219933. - (BOOL) resignFirstResponder;
  219934. - (BOOL) acceptsFirstResponder;
  219935. - (NSArray*) getSupportedDragTypes;
  219936. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  219937. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  219938. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  219939. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  219940. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  219941. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  219942. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  219943. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  219944. @end
  219945. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  219946. @interface JuceNSWindow : NSWindow
  219947. {
  219948. @private
  219949. NSViewComponentPeer* owner;
  219950. bool isZooming;
  219951. }
  219952. - (void) setOwner: (NSViewComponentPeer*) owner;
  219953. - (BOOL) canBecomeKeyWindow;
  219954. - (void) becomeKeyWindow;
  219955. - (BOOL) windowShouldClose: (id) window;
  219956. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  219957. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  219958. - (void) zoom: (id) sender;
  219959. @end
  219960. BEGIN_JUCE_NAMESPACE
  219961. class NSViewComponentPeer : public ComponentPeer
  219962. {
  219963. public:
  219964. NSViewComponentPeer (Component* const component,
  219965. const int windowStyleFlags,
  219966. NSView* viewToAttachTo);
  219967. ~NSViewComponentPeer();
  219968. void* getNativeHandle() const;
  219969. void setVisible (bool shouldBeVisible);
  219970. void setTitle (const String& title);
  219971. void setPosition (int x, int y);
  219972. void setSize (int w, int h);
  219973. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  219974. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  219975. void getBounds (int& x, int& y, int& w, int& h) const;
  219976. int getScreenX() const;
  219977. int getScreenY() const;
  219978. void relativePositionToGlobal (int& x, int& y);
  219979. void globalPositionToRelative (int& x, int& y);
  219980. void setMinimised (bool shouldBeMinimised);
  219981. bool isMinimised() const;
  219982. void setFullScreen (bool shouldBeFullScreen);
  219983. bool isFullScreen() const;
  219984. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  219985. const BorderSize getFrameSize() const;
  219986. bool setAlwaysOnTop (bool alwaysOnTop);
  219987. void toFront (bool makeActiveWindow);
  219988. void toBehind (ComponentPeer* other);
  219989. void setIcon (const Image& newIcon);
  219990. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  219991. for example having more than one juce plugin loaded into a host, then when a
  219992. method is called, the actual code that runs might actually be in a different module
  219993. than the one you expect... So any calls to library functions or statics that are
  219994. made inside obj-c methods will probably end up getting executed in a different DLL's
  219995. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  219996. To work around this insanity, I'm only allowing obj-c methods to make calls to
  219997. virtual methods of an object that's known to live inside the right module's space.
  219998. */
  219999. virtual void redirectMouseDown (NSEvent* ev);
  220000. virtual void redirectMouseUp (NSEvent* ev);
  220001. virtual void redirectMouseDrag (NSEvent* ev);
  220002. virtual void redirectMouseMove (NSEvent* ev);
  220003. virtual void redirectMouseEnter (NSEvent* ev);
  220004. virtual void redirectMouseExit (NSEvent* ev);
  220005. virtual void redirectMouseWheel (NSEvent* ev);
  220006. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  220007. virtual bool redirectKeyDown (NSEvent* ev);
  220008. virtual bool redirectKeyUp (NSEvent* ev);
  220009. virtual void redirectModKeyChange (NSEvent* ev);
  220010. #if MACOS_10_4_OR_EARLIER
  220011. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  220012. #endif
  220013. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  220014. virtual bool isOpaque();
  220015. virtual void drawRect (NSRect r);
  220016. virtual bool canBecomeKeyWindow();
  220017. virtual bool windowShouldClose();
  220018. virtual void redirectMovedOrResized();
  220019. virtual NSRect constrainRect (NSRect r);
  220020. static void showArrowCursorIfNeeded();
  220021. virtual void viewFocusGain();
  220022. virtual void viewFocusLoss();
  220023. bool isFocused() const;
  220024. void grabFocus();
  220025. void textInputRequired (int x, int y);
  220026. void repaint (int x, int y, int w, int h);
  220027. void performAnyPendingRepaintsNow();
  220028. juce_UseDebuggingNewOperator
  220029. NSWindow* window;
  220030. JuceNSView* view;
  220031. bool isSharedWindow, fullScreen;
  220032. };
  220033. END_JUCE_NAMESPACE
  220034. @implementation JuceNSView
  220035. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  220036. withFrame: (NSRect) frame
  220037. {
  220038. [super initWithFrame: frame];
  220039. owner = owner_;
  220040. notificationCenter = [NSNotificationCenter defaultCenter];
  220041. [notificationCenter addObserver: self
  220042. selector: @selector (frameChanged:)
  220043. name: NSViewFrameDidChangeNotification
  220044. object: self];
  220045. if (! owner_->isSharedWindow)
  220046. {
  220047. [notificationCenter addObserver: self
  220048. selector: @selector (frameChanged:)
  220049. name: NSWindowDidMoveNotification
  220050. object: owner_->window];
  220051. }
  220052. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  220053. return self;
  220054. }
  220055. - (void) dealloc
  220056. {
  220057. [notificationCenter removeObserver: self];
  220058. [super dealloc];
  220059. }
  220060. - (void) drawRect: (NSRect) r
  220061. {
  220062. if (owner != 0)
  220063. owner->drawRect (r);
  220064. }
  220065. - (BOOL) isOpaque
  220066. {
  220067. return owner == 0 || owner->isOpaque();
  220068. }
  220069. - (void) mouseDown: (NSEvent*) ev
  220070. {
  220071. // In some host situations, the host will stop modal loops from working
  220072. // correctly if they're called from a mouse event, so we'll trigger
  220073. // the event asynchronously..
  220074. if (JUCEApplication::getInstance() == 0)
  220075. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  220076. withObject: ev
  220077. waitUntilDone: NO];
  220078. else
  220079. [self asyncMouseDown: ev];
  220080. }
  220081. - (void) asyncMouseDown: (NSEvent*) ev
  220082. {
  220083. if (owner != 0)
  220084. owner->redirectMouseDown (ev);
  220085. }
  220086. - (void) mouseUp: (NSEvent*) ev
  220087. {
  220088. // In some host situations, the host will stop modal loops from working
  220089. // correctly if they're called from a mouse event, so we'll trigger
  220090. // the event asynchronously..
  220091. if (JUCEApplication::getInstance() == 0)
  220092. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  220093. withObject: ev
  220094. waitUntilDone: NO];
  220095. else
  220096. [self asyncMouseUp: ev];
  220097. }
  220098. - (void) asyncMouseUp: (NSEvent*) ev
  220099. {
  220100. if (owner != 0)
  220101. owner->redirectMouseUp (ev);
  220102. }
  220103. - (void) mouseDragged: (NSEvent*) ev
  220104. {
  220105. if (owner != 0)
  220106. owner->redirectMouseDrag (ev);
  220107. }
  220108. - (void) mouseMoved: (NSEvent*) ev
  220109. {
  220110. if (owner != 0)
  220111. owner->redirectMouseMove (ev);
  220112. }
  220113. - (void) mouseEntered: (NSEvent*) ev
  220114. {
  220115. if (owner != 0)
  220116. owner->redirectMouseEnter (ev);
  220117. }
  220118. - (void) mouseExited: (NSEvent*) ev
  220119. {
  220120. if (owner != 0)
  220121. owner->redirectMouseExit (ev);
  220122. }
  220123. - (void) rightMouseDown: (NSEvent*) ev
  220124. {
  220125. [self mouseDown: ev];
  220126. }
  220127. - (void) rightMouseDragged: (NSEvent*) ev
  220128. {
  220129. [self mouseDragged: ev];
  220130. }
  220131. - (void) rightMouseUp: (NSEvent*) ev
  220132. {
  220133. [self mouseUp: ev];
  220134. }
  220135. - (void) otherMouseDown: (NSEvent*) ev
  220136. {
  220137. [self mouseDown: ev];
  220138. }
  220139. - (void) otherMouseDragged: (NSEvent*) ev
  220140. {
  220141. [self mouseDragged: ev];
  220142. }
  220143. - (void) otherMouseUp: (NSEvent*) ev
  220144. {
  220145. [self mouseUp: ev];
  220146. }
  220147. - (void) scrollWheel: (NSEvent*) ev
  220148. {
  220149. if (owner != 0)
  220150. owner->redirectMouseWheel (ev);
  220151. }
  220152. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  220153. {
  220154. return YES;
  220155. }
  220156. - (void) frameChanged: (NSNotification*) n
  220157. {
  220158. if (owner != 0)
  220159. owner->redirectMovedOrResized();
  220160. }
  220161. - (void) keyDown: (NSEvent*) ev
  220162. {
  220163. if (owner == 0 || ! owner->redirectKeyDown (ev))
  220164. [super keyDown: ev];
  220165. }
  220166. - (void) keyUp: (NSEvent*) ev
  220167. {
  220168. if (owner == 0 || ! owner->redirectKeyUp (ev))
  220169. [super keyUp: ev];
  220170. }
  220171. - (void) flagsChanged: (NSEvent*) ev
  220172. {
  220173. if (owner != 0)
  220174. owner->redirectModKeyChange (ev);
  220175. }
  220176. #if MACOS_10_4_OR_EARLIER
  220177. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  220178. {
  220179. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  220180. return true;
  220181. return [super performKeyEquivalent: ev];
  220182. }
  220183. #endif
  220184. - (BOOL) becomeFirstResponder
  220185. {
  220186. if (owner != 0)
  220187. owner->viewFocusGain();
  220188. return true;
  220189. }
  220190. - (BOOL) resignFirstResponder
  220191. {
  220192. if (owner != 0)
  220193. owner->viewFocusLoss();
  220194. return true;
  220195. }
  220196. - (BOOL) acceptsFirstResponder
  220197. {
  220198. return owner != 0 && owner->canBecomeKeyWindow();
  220199. }
  220200. - (NSArray*) getSupportedDragTypes
  220201. {
  220202. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  220203. }
  220204. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  220205. {
  220206. return owner != 0 && owner->sendDragCallback (type, sender);
  220207. }
  220208. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  220209. {
  220210. if ([self sendDragCallback: 0 sender: sender])
  220211. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  220212. else
  220213. return NSDragOperationNone;
  220214. }
  220215. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  220216. {
  220217. if ([self sendDragCallback: 0 sender: sender])
  220218. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  220219. else
  220220. return NSDragOperationNone;
  220221. }
  220222. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  220223. {
  220224. [self sendDragCallback: 1 sender: sender];
  220225. }
  220226. - (void) draggingExited: (id <NSDraggingInfo>) sender
  220227. {
  220228. [self sendDragCallback: 1 sender: sender];
  220229. }
  220230. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  220231. {
  220232. return YES;
  220233. }
  220234. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  220235. {
  220236. return [self sendDragCallback: 2 sender: sender];
  220237. }
  220238. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  220239. {
  220240. }
  220241. @end
  220242. @implementation JuceNSWindow
  220243. - (void) setOwner: (NSViewComponentPeer*) owner_
  220244. {
  220245. owner = owner_;
  220246. isZooming = false;
  220247. }
  220248. - (BOOL) canBecomeKeyWindow
  220249. {
  220250. return owner != 0 && owner->canBecomeKeyWindow();
  220251. }
  220252. - (void) becomeKeyWindow
  220253. {
  220254. [super becomeKeyWindow];
  220255. if (owner != 0)
  220256. owner->grabFocus();
  220257. }
  220258. - (BOOL) windowShouldClose: (id) window
  220259. {
  220260. return owner == 0 || owner->windowShouldClose();
  220261. }
  220262. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  220263. {
  220264. if (owner != 0)
  220265. frameRect = owner->constrainRect (frameRect);
  220266. return frameRect;
  220267. }
  220268. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  220269. {
  220270. if (isZooming)
  220271. return proposedFrameSize;
  220272. NSRect frameRect = [self frame];
  220273. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  220274. frameRect.size = proposedFrameSize;
  220275. if (owner != 0)
  220276. frameRect = owner->constrainRect (frameRect);
  220277. return frameRect.size;
  220278. }
  220279. - (void) zoom: (id) sender
  220280. {
  220281. isZooming = true;
  220282. [super zoom: sender];
  220283. isZooming = false;
  220284. }
  220285. - (void) windowWillMove: (NSNotification*) notification
  220286. {
  220287. if (juce::Component::getCurrentlyModalComponent() != 0
  220288. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  220289. && (owner->getStyleFlags() & juce::ComponentPeer::windowHasTitleBar) != 0)
  220290. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  220291. }
  220292. @end
  220293. BEGIN_JUCE_NAMESPACE
  220294. class JuceNSImage
  220295. {
  220296. public:
  220297. JuceNSImage (const int width, const int height, const bool hasAlpha)
  220298. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  220299. width, height, hasAlpha)
  220300. {
  220301. lineStride = 0;
  220302. pixelStride = 0;
  220303. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  220304. lineStride, pixelStride);
  220305. imageRep = [[NSBitmapImageRep alloc]
  220306. initWithBitmapDataPlanes: &imageData
  220307. pixelsWide: width
  220308. pixelsHigh: height
  220309. bitsPerSample: 8
  220310. samplesPerPixel: pixelStride
  220311. hasAlpha: hasAlpha
  220312. isPlanar: NO
  220313. colorSpaceName: NSCalibratedRGBColorSpace
  220314. bitmapFormat: /*NSAlphaFirstBitmapFormat*/ (NSBitmapFormat) 0
  220315. bytesPerRow: lineStride
  220316. bitsPerPixel: 8 * pixelStride ];
  220317. juceImage.releasePixelDataReadWrite (imageData);
  220318. }
  220319. ~JuceNSImage()
  220320. {
  220321. [imageRep release];
  220322. }
  220323. Image& getJuceImage() throw() { return juceImage; }
  220324. void draw (const float x, const float y,
  220325. const RectangleList& clip,
  220326. const int originX, const int originY) const
  220327. {
  220328. // Our data is BGRA and the damned image rep only takes RGBA, so
  220329. // we need to byte-swap the active areas if there's an alpha channel...
  220330. if (juceImage.hasAlphaChannel())
  220331. {
  220332. RectangleList::Iterator iter (clip);
  220333. while (iter.next())
  220334. {
  220335. const Rectangle* const r = iter.getRectangle();
  220336. swapRGBOrder (r->getX() + originX,
  220337. r->getY() + originY,
  220338. r->getWidth(),
  220339. r->getHeight());
  220340. }
  220341. }
  220342. NSPoint p;
  220343. p.x = x;
  220344. p.y = y;
  220345. [imageRep drawAtPoint: p];
  220346. }
  220347. void drawNSImage (NSImage* imageToDraw)
  220348. {
  220349. const ScopedAutoReleasePool pool;
  220350. [NSGraphicsContext saveGraphicsState];
  220351. [NSGraphicsContext setCurrentContext:
  220352. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  220353. [imageToDraw drawAtPoint: NSZeroPoint
  220354. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  220355. operation: NSCompositeSourceOver
  220356. fraction: 1.0f];
  220357. [[NSGraphicsContext currentContext] flushGraphics];
  220358. [NSGraphicsContext restoreGraphicsState];
  220359. if (juceImage.hasAlphaChannel())
  220360. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());
  220361. }
  220362. private:
  220363. Image juceImage;
  220364. NSBitmapImageRep* imageRep;
  220365. uint8* imageData;
  220366. int pixelStride, lineStride;
  220367. void swapRGBOrder (const int x, const int y, const int w, int h) const
  220368. {
  220369. #if JUCE_BIG_ENDIAN
  220370. jassert (pixelStride == 4);
  220371. #endif
  220372. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  220373. .contains (Rectangle (x, y, w, h)));
  220374. uint8* start = imageData + x * pixelStride + y * lineStride;
  220375. while (--h >= 0)
  220376. {
  220377. uint8* p = start;
  220378. start += lineStride;
  220379. for (int i = w; --i >= 0;)
  220380. {
  220381. #if JUCE_BIG_ENDIAN
  220382. const uint8 oldp3 = p[3];
  220383. const uint8 oldp1 = p[1];
  220384. p[3] = p[0];
  220385. p[0] = oldp1;
  220386. p[1] = p[2];
  220387. p[2] = oldp3;
  220388. #else
  220389. const uint8 oldp0 = p[0];
  220390. p[0] = p[2];
  220391. p[2] = oldp0;
  220392. #endif
  220393. p += pixelStride;
  220394. }
  220395. }
  220396. }
  220397. };
  220398. static ComponentPeer* currentlyFocusedPeer = 0;
  220399. static VoidArray keysCurrentlyDown;
  220400. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  220401. {
  220402. if (keysCurrentlyDown.contains ((void*) keyCode))
  220403. return true;
  220404. if (keyCode >= 'A' && keyCode <= 'Z'
  220405. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  220406. return true;
  220407. if (keyCode >= 'a' && keyCode <= 'z'
  220408. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  220409. return true;
  220410. return false;
  220411. }
  220412. static int getKeyCodeFromEvent (NSEvent* ev)
  220413. {
  220414. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  220415. int keyCode = unmodified[0];
  220416. if (keyCode == 0x19) // (backwards-tab)
  220417. keyCode = '\t';
  220418. else if (keyCode == 0x03) // (enter)
  220419. keyCode = '\r';
  220420. return keyCode;
  220421. }
  220422. static int currentModifiers = 0;
  220423. static void updateModifiers (NSEvent* e)
  220424. {
  220425. int m = currentModifiers & ~(ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  220426. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  220427. if (([e modifierFlags] & NSShiftKeyMask) != 0)
  220428. m |= ModifierKeys::shiftModifier;
  220429. if (([e modifierFlags] & NSControlKeyMask) != 0)
  220430. m |= ModifierKeys::ctrlModifier;
  220431. if (([e modifierFlags] & NSAlternateKeyMask) != 0)
  220432. m |= ModifierKeys::altModifier;
  220433. if (([e modifierFlags] & NSCommandKeyMask) != 0)
  220434. m |= ModifierKeys::commandModifier;
  220435. currentModifiers = m;
  220436. }
  220437. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  220438. {
  220439. updateModifiers (ev);
  220440. int keyCode = getKeyCodeFromEvent (ev);
  220441. if (keyCode != 0)
  220442. {
  220443. if (isKeyDown)
  220444. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  220445. else
  220446. keysCurrentlyDown.removeValue ((void*) keyCode);
  220447. }
  220448. }
  220449. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220450. {
  220451. return ModifierKeys (currentModifiers);
  220452. }
  220453. void ModifierKeys::updateCurrentModifiers() throw()
  220454. {
  220455. currentModifierFlags = currentModifiers;
  220456. }
  220457. static int64 getMouseTime (NSEvent* e) { return (int64) [e timestamp] * 1000.0; }
  220458. static void getMousePos (NSEvent* e, NSView* view, int& x, int& y)
  220459. {
  220460. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  220461. x = roundFloatToInt (p.x);
  220462. y = roundFloatToInt ([view frame].size.height - p.y);
  220463. }
  220464. static int getModifierForButtonNumber (const int num) throw()
  220465. {
  220466. return num == 0 ? ModifierKeys::leftButtonModifier
  220467. : (num == 1 ? ModifierKeys::rightButtonModifier
  220468. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  220469. }
  220470. NSViewComponentPeer::NSViewComponentPeer (Component* const component,
  220471. const int windowStyleFlags,
  220472. NSView* viewToAttachTo)
  220473. : ComponentPeer (component, windowStyleFlags),
  220474. window (0),
  220475. view (0)
  220476. {
  220477. NSRect r;
  220478. r.origin.x = 0;
  220479. r.origin.y = 0;
  220480. r.size.width = (float) component->getWidth();
  220481. r.size.height = (float) component->getHeight();
  220482. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  220483. [view setPostsFrameChangedNotifications: YES];
  220484. if (viewToAttachTo != 0)
  220485. {
  220486. window = [viewToAttachTo window];
  220487. [viewToAttachTo addSubview: view];
  220488. isSharedWindow = true;
  220489. setVisible (component->isVisible());
  220490. }
  220491. else
  220492. {
  220493. isSharedWindow = false;
  220494. r.origin.x = (float) component->getX();
  220495. r.origin.y = (float) component->getY();
  220496. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  220497. unsigned int style = 0;
  220498. if ((windowStyleFlags & windowHasTitleBar) == 0)
  220499. style = NSBorderlessWindowMask;
  220500. else
  220501. style = NSTitledWindowMask;
  220502. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  220503. style |= NSMiniaturizableWindowMask;
  220504. if ((windowStyleFlags & windowHasCloseButton) != 0)
  220505. style |= NSClosableWindowMask;
  220506. if ((windowStyleFlags & windowIsResizable) != 0)
  220507. style |= NSResizableWindowMask;
  220508. window = [[JuceNSWindow alloc] initWithContentRect: r
  220509. styleMask: style
  220510. backing: NSBackingStoreBuffered
  220511. defer: YES];
  220512. [((JuceNSWindow*) window) setOwner: this];
  220513. [window orderOut: nil];
  220514. [window setDelegate: (JuceNSWindow*) window];
  220515. [window setOpaque: component->isOpaque()];
  220516. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  220517. if (component->isAlwaysOnTop())
  220518. [window setLevel: NSFloatingWindowLevel];
  220519. [window setContentView: view];
  220520. [window setAutodisplay: YES];
  220521. [window setAcceptsMouseMovedEvents: YES];
  220522. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  220523. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  220524. [window setReleasedWhenClosed: YES];
  220525. [window retain];
  220526. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  220527. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  220528. }
  220529. setTitle (component->getName());
  220530. }
  220531. NSViewComponentPeer::~NSViewComponentPeer()
  220532. {
  220533. view->owner = 0;
  220534. [view removeFromSuperview];
  220535. [view release];
  220536. if (! isSharedWindow)
  220537. {
  220538. [((JuceNSWindow*) window) setOwner: 0];
  220539. [window close];
  220540. [window release];
  220541. }
  220542. }
  220543. void* NSViewComponentPeer::getNativeHandle() const
  220544. {
  220545. return view;
  220546. }
  220547. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  220548. {
  220549. if (isSharedWindow)
  220550. {
  220551. [view setHidden: ! shouldBeVisible];
  220552. }
  220553. else
  220554. {
  220555. if (shouldBeVisible)
  220556. [window orderFront: nil];
  220557. else
  220558. [window orderOut: nil];
  220559. }
  220560. }
  220561. void NSViewComponentPeer::setTitle (const String& title)
  220562. {
  220563. const ScopedAutoReleasePool pool;
  220564. if (! isSharedWindow)
  220565. [window setTitle: juceStringToNS (title)];
  220566. }
  220567. void NSViewComponentPeer::setPosition (int x, int y)
  220568. {
  220569. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  220570. }
  220571. void NSViewComponentPeer::setSize (int w, int h)
  220572. {
  220573. setBounds (component->getX(), component->getY(), w, h, false);
  220574. }
  220575. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  220576. {
  220577. fullScreen = isNowFullScreen;
  220578. w = jmax (0, w);
  220579. h = jmax (0, h);
  220580. NSRect r;
  220581. r.origin.x = (float) x;
  220582. r.origin.y = (float) y;
  220583. r.size.width = (float) w;
  220584. r.size.height = (float) h;
  220585. if (isSharedWindow)
  220586. {
  220587. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  220588. if ([view frame].size.width != r.size.width
  220589. || [view frame].size.height != r.size.height)
  220590. [view setNeedsDisplay: true];
  220591. [view setFrame: r];
  220592. }
  220593. else
  220594. {
  220595. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  220596. [window setFrame: [window frameRectForContentRect: r]
  220597. display: true];
  220598. }
  220599. }
  220600. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  220601. {
  220602. NSRect r = [view frame];
  220603. if (global && [view window] != 0)
  220604. {
  220605. r = [view convertRect: r toView: nil];
  220606. NSRect wr = [[view window] frame];
  220607. r.origin.x += wr.origin.x;
  220608. r.origin.y += wr.origin.y;
  220609. y = (int) ([[[NSScreen screens] objectAtIndex:0] frame].size.height - r.origin.y - r.size.height);
  220610. }
  220611. else
  220612. {
  220613. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  220614. }
  220615. x = (int) r.origin.x;
  220616. w = (int) r.size.width;
  220617. h = (int) r.size.height;
  220618. }
  220619. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  220620. {
  220621. getBounds (x, y, w, h, ! isSharedWindow);
  220622. }
  220623. int NSViewComponentPeer::getScreenX() const
  220624. {
  220625. int x, y, w, h;
  220626. getBounds (x, y, w, h, true);
  220627. return x;
  220628. }
  220629. int NSViewComponentPeer::getScreenY() const
  220630. {
  220631. int x, y, w, h;
  220632. getBounds (x, y, w, h, true);
  220633. return y;
  220634. }
  220635. void NSViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  220636. {
  220637. int wx, wy, ww, wh;
  220638. getBounds (wx, wy, ww, wh, true);
  220639. x += wx;
  220640. y += wy;
  220641. }
  220642. void NSViewComponentPeer::globalPositionToRelative (int& x, int& y)
  220643. {
  220644. int wx, wy, ww, wh;
  220645. getBounds (wx, wy, ww, wh, true);
  220646. x -= wx;
  220647. y -= wy;
  220648. }
  220649. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  220650. {
  220651. if (constrainer != 0)
  220652. {
  220653. NSRect current = [window frame];
  220654. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  220655. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  220656. int x = (int) r.origin.x;
  220657. int y = (int) r.origin.y;
  220658. int w = (int) r.size.width;
  220659. int h = (int) r.size.height;
  220660. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  220661. (int) current.size.width, (int) current.size.height);
  220662. constrainer->checkBounds (x, y, w, h,
  220663. original,
  220664. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  220665. y != original.getY() && y + h == original.getBottom(),
  220666. x != original.getX() && x + w == original.getRight(),
  220667. y == original.getY() && y + h != original.getBottom(),
  220668. x == original.getX() && x + w != original.getRight());
  220669. r.origin.x = x;
  220670. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - y;
  220671. r.size.width = w;
  220672. r.size.height = h;
  220673. }
  220674. return r;
  220675. }
  220676. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  220677. {
  220678. if (! isSharedWindow)
  220679. {
  220680. if (shouldBeMinimised)
  220681. [window miniaturize: nil];
  220682. else
  220683. [window deminiaturize: nil];
  220684. }
  220685. }
  220686. bool NSViewComponentPeer::isMinimised() const
  220687. {
  220688. return window != 0 && [window isMiniaturized];
  220689. }
  220690. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  220691. {
  220692. if (! isSharedWindow)
  220693. {
  220694. Rectangle r (lastNonFullscreenBounds);
  220695. setMinimised (false);
  220696. if (fullScreen != shouldBeFullScreen)
  220697. {
  220698. if (shouldBeFullScreen)
  220699. r = Desktop::getInstance().getMainMonitorArea();
  220700. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  220701. if (r != getComponent()->getBounds() && ! r.isEmpty())
  220702. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220703. }
  220704. }
  220705. }
  220706. bool NSViewComponentPeer::isFullScreen() const
  220707. {
  220708. return fullScreen;
  220709. }
  220710. bool NSViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  220711. {
  220712. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  220713. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  220714. return false;
  220715. NSPoint p;
  220716. p.x = (float) x;
  220717. p.y = (float) y;
  220718. NSView* v = [view hitTest: p];
  220719. if (trueIfInAChildWindow)
  220720. return v != nil;
  220721. return v == view;
  220722. }
  220723. const BorderSize NSViewComponentPeer::getFrameSize() const
  220724. {
  220725. BorderSize b;
  220726. if (! isSharedWindow)
  220727. {
  220728. NSRect v = [view convertRect: [view frame] toView: nil];
  220729. NSRect w = [window frame];
  220730. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  220731. b.setBottom ((int) v.origin.y);
  220732. b.setLeft ((int) v.origin.x);
  220733. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  220734. }
  220735. return b;
  220736. }
  220737. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  220738. {
  220739. if (! isSharedWindow)
  220740. {
  220741. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  220742. : NSNormalWindowLevel];
  220743. }
  220744. return true;
  220745. }
  220746. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  220747. {
  220748. if (isSharedWindow)
  220749. {
  220750. [[view superview] addSubview: view
  220751. positioned: NSWindowAbove
  220752. relativeTo: nil];
  220753. }
  220754. if (window != 0 && component->isVisible())
  220755. {
  220756. if (makeActiveWindow)
  220757. [window makeKeyAndOrderFront: nil];
  220758. else
  220759. [window orderFront: nil];
  220760. }
  220761. }
  220762. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  220763. {
  220764. NSViewComponentPeer* o = (NSViewComponentPeer*) other;
  220765. if (isSharedWindow)
  220766. {
  220767. [[view superview] addSubview: view
  220768. positioned: NSWindowBelow
  220769. relativeTo: o->view];
  220770. }
  220771. else
  220772. {
  220773. [window orderWindow: NSWindowBelow
  220774. relativeTo: o->window != 0 ? [o->window windowNumber]
  220775. : nil ];
  220776. }
  220777. }
  220778. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  220779. {
  220780. // to do..
  220781. }
  220782. void NSViewComponentPeer::viewFocusGain()
  220783. {
  220784. if (currentlyFocusedPeer != this)
  220785. {
  220786. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  220787. currentlyFocusedPeer->handleFocusLoss();
  220788. currentlyFocusedPeer = this;
  220789. handleFocusGain();
  220790. }
  220791. }
  220792. void NSViewComponentPeer::viewFocusLoss()
  220793. {
  220794. if (currentlyFocusedPeer == this)
  220795. {
  220796. currentlyFocusedPeer = 0;
  220797. handleFocusLoss();
  220798. }
  220799. }
  220800. void juce_HandleProcessFocusChange()
  220801. {
  220802. keysCurrentlyDown.clear();
  220803. if (NSViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  220804. {
  220805. if (Process::isForegroundProcess())
  220806. {
  220807. currentlyFocusedPeer->handleFocusGain();
  220808. ComponentPeer::bringModalComponentToFront();
  220809. }
  220810. else
  220811. {
  220812. currentlyFocusedPeer->handleFocusLoss();
  220813. // turn kiosk mode off if we lose focus..
  220814. Desktop::getInstance().setKioskModeComponent (0);
  220815. }
  220816. }
  220817. }
  220818. bool NSViewComponentPeer::isFocused() const
  220819. {
  220820. return isSharedWindow ? this == currentlyFocusedPeer
  220821. : (window != 0 && [window isKeyWindow]);
  220822. }
  220823. void NSViewComponentPeer::grabFocus()
  220824. {
  220825. if (window != 0)
  220826. {
  220827. [window makeKeyWindow];
  220828. [window makeFirstResponder: view];
  220829. viewFocusGain();
  220830. }
  220831. }
  220832. void NSViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  220833. {
  220834. }
  220835. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  220836. {
  220837. String unicode (nsStringToJuce ([ev characters]));
  220838. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  220839. int keyCode = getKeyCodeFromEvent (ev);
  220840. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  220841. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  220842. if (unicode.isNotEmpty() || keyCode != 0)
  220843. {
  220844. if (isKeyDown)
  220845. {
  220846. bool used = false;
  220847. while (unicode.length() > 0)
  220848. {
  220849. juce_wchar textCharacter = unicode[0];
  220850. unicode = unicode.substring (1);
  220851. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  220852. textCharacter = 0;
  220853. used = handleKeyUpOrDown (true) || used;
  220854. used = handleKeyPress (keyCode, textCharacter) || used;
  220855. }
  220856. return used;
  220857. }
  220858. else
  220859. {
  220860. if (handleKeyUpOrDown (false))
  220861. return true;
  220862. }
  220863. }
  220864. return false;
  220865. }
  220866. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  220867. {
  220868. updateKeysDown (ev, true);
  220869. bool used = handleKeyEvent (ev, true);
  220870. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  220871. {
  220872. // for command keys, the key-up event is thrown away, so simulate one..
  220873. updateKeysDown (ev, false);
  220874. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  220875. }
  220876. // (If we're running modally, don't allow unused keystrokes to be passed
  220877. // along to other blocked views..)
  220878. if (Component::getCurrentlyModalComponent() != 0)
  220879. used = true;
  220880. return used;
  220881. }
  220882. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  220883. {
  220884. updateKeysDown (ev, false);
  220885. return handleKeyEvent (ev, false)
  220886. || Component::getCurrentlyModalComponent() != 0;
  220887. }
  220888. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  220889. {
  220890. updateModifiers (ev);
  220891. handleModifierKeysChange();
  220892. }
  220893. #if MACOS_10_4_OR_EARLIER
  220894. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  220895. {
  220896. if ([ev type] == NSKeyDown)
  220897. return redirectKeyDown (ev);
  220898. else if ([ev type] == NSKeyUp)
  220899. return redirectKeyUp (ev);
  220900. return false;
  220901. }
  220902. #endif
  220903. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  220904. {
  220905. updateModifiers (ev);
  220906. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  220907. int x, y;
  220908. getMousePos (ev, view, x, y);
  220909. handleMouseDown (x, y, getMouseTime (ev));
  220910. }
  220911. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  220912. {
  220913. const int oldMods = currentModifiers;
  220914. updateModifiers (ev);
  220915. currentModifiers &= ~getModifierForButtonNumber ([ev buttonNumber]);
  220916. int x, y;
  220917. getMousePos (ev, view, x, y);
  220918. handleMouseUp (oldMods, x, y, getMouseTime (ev));
  220919. showArrowCursorIfNeeded();
  220920. }
  220921. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  220922. {
  220923. updateModifiers (ev);
  220924. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  220925. int x, y;
  220926. getMousePos (ev, view, x, y);
  220927. handleMouseDrag (x, y, getMouseTime (ev));
  220928. }
  220929. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  220930. {
  220931. updateModifiers (ev);
  220932. int x, y;
  220933. getMousePos (ev, view, x, y);
  220934. handleMouseMove (x, y, getMouseTime (ev));
  220935. showArrowCursorIfNeeded();
  220936. }
  220937. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  220938. {
  220939. updateModifiers (ev);
  220940. int x, y;
  220941. getMousePos (ev, view, x, y);
  220942. handleMouseEnter (x, y, getMouseTime (ev));
  220943. }
  220944. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  220945. {
  220946. updateModifiers (ev);
  220947. int x, y;
  220948. getMousePos (ev, view, x, y);
  220949. handleMouseExit (x, y, getMouseTime (ev));
  220950. }
  220951. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  220952. {
  220953. updateModifiers (ev);
  220954. handleMouseWheel (roundFloatToInt ([ev deltaX] * 10.0f),
  220955. roundFloatToInt ([ev deltaY] * 10.0f),
  220956. getMouseTime (ev));
  220957. }
  220958. void NSViewComponentPeer::showArrowCursorIfNeeded()
  220959. {
  220960. if (Component::getComponentUnderMouse() == 0)
  220961. {
  220962. int mx, my;
  220963. Desktop::getInstance().getMousePosition (mx, my);
  220964. if (Desktop::getInstance().findComponentAt (mx, my) == 0)
  220965. [[NSCursor arrowCursor] set];
  220966. }
  220967. }
  220968. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  220969. {
  220970. NSString* bestType
  220971. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  220972. if (bestType == nil)
  220973. return false;
  220974. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  220975. int x = (int) p.x;
  220976. int y = (int) ([view frame].size.height - p.y);
  220977. StringArray files;
  220978. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  220979. if (list == nil)
  220980. return false;
  220981. if ([list isKindOfClass: [NSArray class]])
  220982. {
  220983. NSArray* items = (NSArray*) list;
  220984. for (unsigned int i = 0; i < [items count]; ++i)
  220985. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  220986. }
  220987. if (files.size() == 0)
  220988. return false;
  220989. if (type == 0)
  220990. handleFileDragMove (files, x, y);
  220991. else if (type == 1)
  220992. handleFileDragExit (files);
  220993. else if (type == 2)
  220994. handleFileDragDrop (files, x, y);
  220995. return true;
  220996. }
  220997. bool NSViewComponentPeer::isOpaque()
  220998. {
  220999. if (! getComponent()->isValidComponent())
  221000. return true;
  221001. return getComponent()->isOpaque();
  221002. }
  221003. void NSViewComponentPeer::drawRect (NSRect r)
  221004. {
  221005. if (r.size.width < 1.0f || r.size.height < 1.0f)
  221006. return;
  221007. const float y = [view frame].size.height - (r.origin.y + r.size.height);
  221008. JuceNSImage temp ((int) (r.size.width + 0.5f),
  221009. (int) (r.size.height + 0.5f),
  221010. ! getComponent()->isOpaque());
  221011. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  221012. const int originX = -roundFloatToInt (r.origin.x);
  221013. const int originY = -roundFloatToInt (y);
  221014. context.setOrigin (originX, originY);
  221015. const NSRect* rects = 0;
  221016. NSInteger numRects = 0;
  221017. [view getRectsBeingDrawn: &rects count: &numRects];
  221018. RectangleList clip;
  221019. for (int i = 0; i < numRects; ++i)
  221020. {
  221021. clip.addWithoutMerging (Rectangle (roundFloatToInt (rects[i].origin.x),
  221022. roundFloatToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  221023. roundFloatToInt (rects[i].size.width),
  221024. roundFloatToInt (rects[i].size.height)));
  221025. }
  221026. if (context.reduceClipRegion (clip))
  221027. {
  221028. handlePaint (context);
  221029. temp.draw (r.origin.x, r.origin.y, clip, originX, originY);
  221030. }
  221031. }
  221032. bool NSViewComponentPeer::canBecomeKeyWindow()
  221033. {
  221034. // If running as a plugin, let the component decide whether it's going to allow the window to get focused.
  221035. return ((getStyleFlags() & juce::ComponentPeer::windowIsTemporary) == 0)
  221036. && (JUCEApplication::getInstance() != 0
  221037. || (isValidPeer (this)
  221038. && ! getComponent()->getComponentPropertyBool ("juce_disallowFocus", false, false)));
  221039. }
  221040. bool NSViewComponentPeer::windowShouldClose()
  221041. {
  221042. if (! isValidPeer (this))
  221043. return YES;
  221044. handleUserClosingWindow();
  221045. return NO;
  221046. }
  221047. void NSViewComponentPeer::redirectMovedOrResized()
  221048. {
  221049. handleMovedOrResized();
  221050. }
  221051. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221052. {
  221053. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  221054. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  221055. // is apparently still available in 64-bit apps..
  221056. if (enableOrDisable)
  221057. {
  221058. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  221059. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221060. }
  221061. else
  221062. {
  221063. SetSystemUIMode (kUIModeNormal, 0);
  221064. }
  221065. }
  221066. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  221067. {
  221068. [view setNeedsDisplayInRect:
  221069. NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  221070. (float) w, (float) h)];
  221071. }
  221072. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  221073. {
  221074. [view displayIfNeeded];
  221075. }
  221076. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  221077. {
  221078. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  221079. }
  221080. static Image* NSImageToJuceImage (NSImage* image)
  221081. {
  221082. JuceNSImage juceIm ((int) [image size].width,
  221083. (int) [image size].height,
  221084. true);
  221085. juceIm.drawNSImage (image);
  221086. return juceIm.getJuceImage().createCopy();
  221087. }
  221088. Image* juce_createIconForFile (const File& file)
  221089. {
  221090. const ScopedAutoReleasePool pool;
  221091. NSImage* im = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  221092. return NSImageToJuceImage (im);
  221093. }
  221094. const int KeyPress::spaceKey = ' ';
  221095. const int KeyPress::returnKey = 0x0d;
  221096. const int KeyPress::escapeKey = 0x1b;
  221097. const int KeyPress::backspaceKey = 0x7f;
  221098. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  221099. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  221100. const int KeyPress::upKey = NSUpArrowFunctionKey;
  221101. const int KeyPress::downKey = NSDownArrowFunctionKey;
  221102. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  221103. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  221104. const int KeyPress::endKey = NSEndFunctionKey;
  221105. const int KeyPress::homeKey = NSHomeFunctionKey;
  221106. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  221107. const int KeyPress::insertKey = -1;
  221108. const int KeyPress::tabKey = 9;
  221109. const int KeyPress::F1Key = NSF1FunctionKey;
  221110. const int KeyPress::F2Key = NSF2FunctionKey;
  221111. const int KeyPress::F3Key = NSF3FunctionKey;
  221112. const int KeyPress::F4Key = NSF4FunctionKey;
  221113. const int KeyPress::F5Key = NSF5FunctionKey;
  221114. const int KeyPress::F6Key = NSF6FunctionKey;
  221115. const int KeyPress::F7Key = NSF7FunctionKey;
  221116. const int KeyPress::F8Key = NSF8FunctionKey;
  221117. const int KeyPress::F9Key = NSF9FunctionKey;
  221118. const int KeyPress::F10Key = NSF10FunctionKey;
  221119. const int KeyPress::F11Key = NSF1FunctionKey;
  221120. const int KeyPress::F12Key = NSF12FunctionKey;
  221121. const int KeyPress::F13Key = NSF13FunctionKey;
  221122. const int KeyPress::F14Key = NSF14FunctionKey;
  221123. const int KeyPress::F15Key = NSF15FunctionKey;
  221124. const int KeyPress::F16Key = NSF16FunctionKey;
  221125. const int KeyPress::numberPad0 = 0x30020;
  221126. const int KeyPress::numberPad1 = 0x30021;
  221127. const int KeyPress::numberPad2 = 0x30022;
  221128. const int KeyPress::numberPad3 = 0x30023;
  221129. const int KeyPress::numberPad4 = 0x30024;
  221130. const int KeyPress::numberPad5 = 0x30025;
  221131. const int KeyPress::numberPad6 = 0x30026;
  221132. const int KeyPress::numberPad7 = 0x30027;
  221133. const int KeyPress::numberPad8 = 0x30028;
  221134. const int KeyPress::numberPad9 = 0x30029;
  221135. const int KeyPress::numberPadAdd = 0x3002a;
  221136. const int KeyPress::numberPadSubtract = 0x3002b;
  221137. const int KeyPress::numberPadMultiply = 0x3002c;
  221138. const int KeyPress::numberPadDivide = 0x3002d;
  221139. const int KeyPress::numberPadSeparator = 0x3002e;
  221140. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  221141. const int KeyPress::numberPadEquals = 0x30030;
  221142. const int KeyPress::numberPadDelete = 0x30031;
  221143. const int KeyPress::playKey = 0x30000;
  221144. const int KeyPress::stopKey = 0x30001;
  221145. const int KeyPress::fastForwardKey = 0x30002;
  221146. const int KeyPress::rewindKey = 0x30003;
  221147. #endif
  221148. /********* End of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  221149. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  221150. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221151. // compiled on its own).
  221152. #ifdef JUCE_INCLUDED_FILE
  221153. static NSImage* juceImageToNSImage (const Image& image)
  221154. {
  221155. const ScopedAutoReleasePool pool;
  221156. int lineStride, pixelStride;
  221157. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  221158. lineStride, pixelStride);
  221159. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  221160. initWithBitmapDataPlanes: NULL
  221161. pixelsWide: image.getWidth()
  221162. pixelsHigh: image.getHeight()
  221163. bitsPerSample: 8
  221164. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  221165. hasAlpha: image.hasAlphaChannel()
  221166. isPlanar: NO
  221167. colorSpaceName: NSCalibratedRGBColorSpace
  221168. bitmapFormat: (NSBitmapFormat) 0
  221169. bytesPerRow: lineStride
  221170. bitsPerPixel: pixelStride * 8];
  221171. unsigned char* newData = [rep bitmapData];
  221172. memcpy (newData, pixels, lineStride * image.getHeight());
  221173. image.releasePixelDataReadOnly (pixels);
  221174. NSImage* im = [[NSImage alloc] init];
  221175. [im addRepresentation: rep];
  221176. [rep release];
  221177. return im;
  221178. }
  221179. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  221180. {
  221181. NSImage* im = juceImageToNSImage (image);
  221182. NSCursor* c = [[NSCursor alloc] initWithImage: im
  221183. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  221184. [im release];
  221185. return (void*) c;
  221186. }
  221187. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  221188. {
  221189. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  221190. jassert (im != 0);
  221191. if (im == 0)
  221192. return 0;
  221193. void* const curs = juce_createMouseCursorFromImage (*im,
  221194. (int) (hx * im->getWidth()),
  221195. (int) (hy * im->getHeight()));
  221196. delete im;
  221197. return curs;
  221198. }
  221199. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  221200. {
  221201. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  221202. MemoryBlock mb;
  221203. if (f.getChildFile (filename).loadFileAsData (mb))
  221204. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  221205. return 0;
  221206. }
  221207. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  221208. {
  221209. const ScopedAutoReleasePool pool;
  221210. NSCursor* c = 0;
  221211. switch (type)
  221212. {
  221213. case MouseCursor::NormalCursor:
  221214. c = [NSCursor arrowCursor];
  221215. break;
  221216. case MouseCursor::NoCursor:
  221217. {
  221218. Image blank (Image::ARGB, 8, 8, true);
  221219. return juce_createMouseCursorFromImage (blank, 0, 0);
  221220. }
  221221. case MouseCursor::DraggingHandCursor:
  221222. c = [NSCursor openHandCursor];
  221223. break;
  221224. case MouseCursor::CopyingCursor:
  221225. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  221226. case MouseCursor::WaitCursor:
  221227. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  221228. break;
  221229. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  221230. case MouseCursor::IBeamCursor:
  221231. c = [NSCursor IBeamCursor];
  221232. break;
  221233. case MouseCursor::PointingHandCursor:
  221234. c = [NSCursor pointingHandCursor];
  221235. break;
  221236. case MouseCursor::LeftRightResizeCursor:
  221237. c = [NSCursor resizeLeftRightCursor];
  221238. break;
  221239. case MouseCursor::LeftEdgeResizeCursor:
  221240. c = [NSCursor resizeLeftCursor];
  221241. break;
  221242. case MouseCursor::RightEdgeResizeCursor:
  221243. c = [NSCursor resizeRightCursor];
  221244. break;
  221245. case MouseCursor::UpDownResizeCursor:
  221246. case MouseCursor::TopEdgeResizeCursor:
  221247. case MouseCursor::BottomEdgeResizeCursor:
  221248. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  221249. case MouseCursor::TopLeftCornerResizeCursor:
  221250. case MouseCursor::BottomRightCornerResizeCursor:
  221251. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  221252. case MouseCursor::TopRightCornerResizeCursor:
  221253. case MouseCursor::BottomLeftCornerResizeCursor:
  221254. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  221255. case MouseCursor::UpDownLeftRightResizeCursor:
  221256. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  221257. case MouseCursor::CrosshairCursor:
  221258. c = [NSCursor crosshairCursor];
  221259. break;
  221260. }
  221261. [c retain];
  221262. return (void*) c;
  221263. }
  221264. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  221265. {
  221266. NSCursor* c = (NSCursor*) cursorHandle;
  221267. [c release];
  221268. }
  221269. void MouseCursor::showInAllWindows() const throw()
  221270. {
  221271. showInWindow (0);
  221272. }
  221273. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  221274. {
  221275. NSCursor* const c = (NSCursor*) getHandle();
  221276. [c set];
  221277. }
  221278. #endif
  221279. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  221280. /********* Start of inlined file: juce_mac_NSViewComponent.mm *********/
  221281. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221282. // compiled on its own).
  221283. #ifdef JUCE_INCLUDED_FILE
  221284. class NSViewComponentInternal : public ComponentMovementWatcher
  221285. {
  221286. Component* const owner;
  221287. NSViewComponentPeer* currentPeer;
  221288. bool wasShowing;
  221289. public:
  221290. NSView* const view;
  221291. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  221292. : ComponentMovementWatcher (owner_),
  221293. owner (owner_),
  221294. currentPeer (0),
  221295. wasShowing (false),
  221296. view (view_)
  221297. {
  221298. [view_ retain];
  221299. if (owner_->isShowing())
  221300. componentPeerChanged();
  221301. }
  221302. ~NSViewComponentInternal()
  221303. {
  221304. [view removeFromSuperview];
  221305. [view release];
  221306. }
  221307. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  221308. {
  221309. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  221310. // The ComponentMovementWatcher version of this method avoids calling
  221311. // us when the top-level comp is resized, but for an NSView we need to know this
  221312. // because with inverted co-ords, we need to update the position even if the
  221313. // top-left pos hasn't changed
  221314. if (comp.isOnDesktop() && wasResized)
  221315. componentMovedOrResized (wasMoved, wasResized);
  221316. }
  221317. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  221318. {
  221319. Component* const topComp = owner->getTopLevelComponent();
  221320. if (topComp->getPeer() != 0)
  221321. {
  221322. int x = 0, y = 0;
  221323. owner->relativePositionToOtherComponent (topComp, x, y);
  221324. NSRect r;
  221325. r.origin.x = (float) x;
  221326. r.origin.y = (float) y;
  221327. r.size.width = (float) owner->getWidth();
  221328. r.size.height = (float) owner->getHeight();
  221329. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  221330. [view setFrame: r];
  221331. }
  221332. }
  221333. void componentPeerChanged()
  221334. {
  221335. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  221336. if (currentPeer != peer)
  221337. {
  221338. [view removeFromSuperview];
  221339. currentPeer = peer;
  221340. if (peer != 0)
  221341. {
  221342. [peer->view addSubview: view];
  221343. componentMovedOrResized (false, false);
  221344. }
  221345. }
  221346. [view setHidden: ! owner->isShowing()];
  221347. }
  221348. void componentVisibilityChanged (Component&)
  221349. {
  221350. componentPeerChanged();
  221351. }
  221352. juce_UseDebuggingNewOperator
  221353. private:
  221354. NSViewComponentInternal (const NSViewComponentInternal&);
  221355. const NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  221356. };
  221357. NSViewComponent::NSViewComponent()
  221358. : info (0)
  221359. {
  221360. }
  221361. NSViewComponent::~NSViewComponent()
  221362. {
  221363. delete info;
  221364. }
  221365. void NSViewComponent::setView (void* view)
  221366. {
  221367. if (view != getView())
  221368. {
  221369. deleteAndZero (info);
  221370. if (view != 0)
  221371. info = new NSViewComponentInternal ((NSView*) view, this);
  221372. }
  221373. }
  221374. void* NSViewComponent::getView() const
  221375. {
  221376. return info == 0 ? 0 : info->view;
  221377. }
  221378. void NSViewComponent::paint (Graphics& g)
  221379. {
  221380. }
  221381. #endif
  221382. /********* End of inlined file: juce_mac_NSViewComponent.mm *********/
  221383. /********* Start of inlined file: juce_mac_AppleRemote.mm *********/
  221384. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221385. // compiled on its own).
  221386. #ifdef JUCE_INCLUDED_FILE
  221387. AppleRemoteDevice::AppleRemoteDevice()
  221388. : device (0),
  221389. queue (0),
  221390. remoteId (0)
  221391. {
  221392. }
  221393. AppleRemoteDevice::~AppleRemoteDevice()
  221394. {
  221395. stop();
  221396. }
  221397. static io_object_t getAppleRemoteDevice() throw()
  221398. {
  221399. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  221400. io_iterator_t iter = 0;
  221401. io_object_t iod = 0;
  221402. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  221403. && iter != 0)
  221404. {
  221405. iod = IOIteratorNext (iter);
  221406. }
  221407. IOObjectRelease (iter);
  221408. return iod;
  221409. }
  221410. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  221411. {
  221412. jassert (*device == 0);
  221413. io_name_t classname;
  221414. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  221415. {
  221416. IOCFPlugInInterface** cfPlugInInterface = 0;
  221417. SInt32 score = 0;
  221418. if (IOCreatePlugInInterfaceForService (iod,
  221419. kIOHIDDeviceUserClientTypeID,
  221420. kIOCFPlugInInterfaceID,
  221421. &cfPlugInInterface,
  221422. &score) == kIOReturnSuccess)
  221423. {
  221424. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  221425. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  221426. device);
  221427. (void) hr;
  221428. (*cfPlugInInterface)->Release (cfPlugInInterface);
  221429. }
  221430. }
  221431. return *device != 0;
  221432. }
  221433. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  221434. {
  221435. if (queue != 0)
  221436. return true;
  221437. stop();
  221438. bool result = false;
  221439. io_object_t iod = getAppleRemoteDevice();
  221440. if (iod != 0)
  221441. {
  221442. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  221443. result = true;
  221444. else
  221445. stop();
  221446. IOObjectRelease (iod);
  221447. }
  221448. return result;
  221449. }
  221450. void AppleRemoteDevice::stop() throw()
  221451. {
  221452. if (queue != 0)
  221453. {
  221454. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  221455. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  221456. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  221457. queue = 0;
  221458. }
  221459. if (device != 0)
  221460. {
  221461. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  221462. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  221463. device = 0;
  221464. }
  221465. }
  221466. bool AppleRemoteDevice::isActive() const throw()
  221467. {
  221468. return queue != 0;
  221469. }
  221470. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  221471. {
  221472. if (result == kIOReturnSuccess)
  221473. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  221474. }
  221475. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  221476. {
  221477. Array <int> cookies;
  221478. CFArrayRef elements;
  221479. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  221480. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  221481. return false;
  221482. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  221483. {
  221484. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  221485. // get the cookie
  221486. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  221487. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  221488. continue;
  221489. long number;
  221490. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  221491. continue;
  221492. cookies.add ((int) number);
  221493. }
  221494. CFRelease (elements);
  221495. if ((*(IOHIDDeviceInterface**) device)
  221496. ->open ((IOHIDDeviceInterface**) device,
  221497. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  221498. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  221499. {
  221500. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  221501. if (queue != 0)
  221502. {
  221503. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  221504. for (int i = 0; i < cookies.size(); ++i)
  221505. {
  221506. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  221507. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  221508. }
  221509. CFRunLoopSourceRef eventSource;
  221510. if ((*(IOHIDQueueInterface**) queue)
  221511. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  221512. {
  221513. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  221514. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  221515. {
  221516. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  221517. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  221518. return true;
  221519. }
  221520. }
  221521. }
  221522. }
  221523. return false;
  221524. }
  221525. void AppleRemoteDevice::handleCallbackInternal()
  221526. {
  221527. int totalValues = 0;
  221528. AbsoluteTime nullTime = { 0, 0 };
  221529. char cookies [12];
  221530. int numCookies = 0;
  221531. while (numCookies < numElementsInArray (cookies))
  221532. {
  221533. IOHIDEventStruct e;
  221534. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  221535. break;
  221536. if ((int) e.elementCookie == 19)
  221537. {
  221538. remoteId = e.value;
  221539. buttonPressed (switched, false);
  221540. }
  221541. else
  221542. {
  221543. totalValues += e.value;
  221544. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  221545. }
  221546. }
  221547. cookies [numCookies++] = 0;
  221548. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  221549. static const char buttonPatterns[] =
  221550. {
  221551. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  221552. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  221553. 0x1f, 0x1d, 0x1c, 0x12, 0,
  221554. 0x1f, 0x1e, 0x1c, 0x12, 0,
  221555. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  221556. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  221557. 0x1f, 0x12, 0x04, 0x02, 0,
  221558. 0x1f, 0x12, 0x03, 0x02, 0,
  221559. 0x1f, 0x12, 0x1f, 0x12, 0,
  221560. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  221561. 19, 0
  221562. };
  221563. int buttonNum = (int) menuButton;
  221564. int i = 0;
  221565. while (i < numElementsInArray (buttonPatterns))
  221566. {
  221567. if (strcmp (cookies, buttonPatterns + i) == 0)
  221568. {
  221569. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  221570. break;
  221571. }
  221572. i += strlen (buttonPatterns + i) + 1;
  221573. ++buttonNum;
  221574. }
  221575. }
  221576. #endif
  221577. /********* End of inlined file: juce_mac_AppleRemote.mm *********/
  221578. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  221579. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221580. // compiled on its own).
  221581. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  221582. END_JUCE_NAMESPACE
  221583. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  221584. {
  221585. CriticalSection* contextLock;
  221586. bool needsUpdate;
  221587. }
  221588. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  221589. - (bool) makeActive;
  221590. - (void) makeInactive;
  221591. - (void) reshape;
  221592. @end
  221593. @implementation ThreadSafeNSOpenGLView
  221594. - (id) initWithFrame: (NSRect) frameRect
  221595. pixelFormat: (NSOpenGLPixelFormat*) format
  221596. {
  221597. contextLock = new CriticalSection();
  221598. self = [super initWithFrame: frameRect pixelFormat: format];
  221599. if (self != nil)
  221600. [[NSNotificationCenter defaultCenter] addObserver: self
  221601. selector: @selector (_surfaceNeedsUpdate:)
  221602. name: NSViewGlobalFrameDidChangeNotification
  221603. object: self];
  221604. return self;
  221605. }
  221606. - (void) dealloc
  221607. {
  221608. [[NSNotificationCenter defaultCenter] removeObserver: self];
  221609. delete contextLock;
  221610. [super dealloc];
  221611. }
  221612. - (bool) makeActive
  221613. {
  221614. const ScopedLock sl (*contextLock);
  221615. if ([self openGLContext] == 0)
  221616. return false;
  221617. [[self openGLContext] makeCurrentContext];
  221618. if (needsUpdate)
  221619. {
  221620. [super update];
  221621. needsUpdate = false;
  221622. }
  221623. return true;
  221624. }
  221625. - (void) makeInactive
  221626. {
  221627. const ScopedLock sl (*contextLock);
  221628. [NSOpenGLContext clearCurrentContext];
  221629. }
  221630. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  221631. {
  221632. const ScopedLock sl (*contextLock);
  221633. needsUpdate = true;
  221634. }
  221635. - (void) update
  221636. {
  221637. const ScopedLock sl (*contextLock);
  221638. needsUpdate = true;
  221639. }
  221640. - (void) reshape
  221641. {
  221642. const ScopedLock sl (*contextLock);
  221643. needsUpdate = true;
  221644. }
  221645. @end
  221646. BEGIN_JUCE_NAMESPACE
  221647. class WindowedGLContext : public OpenGLContext
  221648. {
  221649. public:
  221650. WindowedGLContext (Component* const component,
  221651. const OpenGLPixelFormat& pixelFormat_,
  221652. NSOpenGLContext* sharedContext)
  221653. : renderContext (0),
  221654. pixelFormat (pixelFormat_)
  221655. {
  221656. jassert (component != 0);
  221657. NSOpenGLPixelFormatAttribute attribs [64];
  221658. int n = 0;
  221659. attribs[n++] = NSOpenGLPFADoubleBuffer;
  221660. attribs[n++] = NSOpenGLPFAAccelerated;
  221661. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  221662. attribs[n++] = NSOpenGLPFAColorSize;
  221663. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  221664. pixelFormat.greenBits,
  221665. pixelFormat.blueBits);
  221666. attribs[n++] = NSOpenGLPFAAlphaSize;
  221667. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  221668. attribs[n++] = NSOpenGLPFADepthSize;
  221669. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  221670. attribs[n++] = NSOpenGLPFAStencilSize;
  221671. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  221672. attribs[n++] = NSOpenGLPFAAccumSize;
  221673. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  221674. pixelFormat.accumulationBufferGreenBits,
  221675. pixelFormat.accumulationBufferBlueBits,
  221676. pixelFormat.accumulationBufferAlphaBits);
  221677. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  221678. attribs[n++] = NSOpenGLPFASampleBuffers;
  221679. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  221680. attribs[n++] = NSOpenGLPFAClosestPolicy;
  221681. attribs[n++] = NSOpenGLPFANoRecovery;
  221682. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  221683. NSOpenGLPixelFormat* format
  221684. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  221685. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  221686. pixelFormat: format];
  221687. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  221688. shareContext: sharedContext] autorelease];
  221689. const GLint swapInterval = 1;
  221690. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  221691. [view setOpenGLContext: renderContext];
  221692. [renderContext setView: view];
  221693. [format release];
  221694. viewHolder = new NSViewComponentInternal (view, component);
  221695. }
  221696. ~WindowedGLContext()
  221697. {
  221698. makeInactive();
  221699. [renderContext setView: nil];
  221700. delete viewHolder;
  221701. }
  221702. bool makeActive() const throw()
  221703. {
  221704. jassert (renderContext != 0);
  221705. [view makeActive];
  221706. return isActive();
  221707. }
  221708. bool makeInactive() const throw()
  221709. {
  221710. [view makeInactive];
  221711. return true;
  221712. }
  221713. bool isActive() const throw()
  221714. {
  221715. return [NSOpenGLContext currentContext] == renderContext;
  221716. }
  221717. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  221718. void* getRawContext() const throw() { return renderContext; }
  221719. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  221720. {
  221721. }
  221722. void swapBuffers()
  221723. {
  221724. [renderContext flushBuffer];
  221725. }
  221726. bool setSwapInterval (const int numFramesPerSwap)
  221727. {
  221728. [renderContext setValues: (const GLint*) &numFramesPerSwap
  221729. forParameter: NSOpenGLCPSwapInterval];
  221730. return true;
  221731. }
  221732. int getSwapInterval() const
  221733. {
  221734. GLint numFrames = 0;
  221735. [renderContext getValues: &numFrames
  221736. forParameter: NSOpenGLCPSwapInterval];
  221737. return numFrames;
  221738. }
  221739. void repaint()
  221740. {
  221741. // we need to invalidate the juce view that holds this gl view, to make it
  221742. // cause a repaint callback
  221743. NSView* v = (NSView*) viewHolder->view;
  221744. NSRect r = [v frame];
  221745. // bit of a bodge here.. if we only invalidate the area of the gl component,
  221746. // it's completely covered by the NSOpenGLView, so the OS throws away the
  221747. // repaint message, thus never causing our paint() callback, and never repainting
  221748. // the comp. So invalidating just a little bit around the edge helps..
  221749. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  221750. }
  221751. void* getNativeWindowHandle() const { return viewHolder->view; }
  221752. juce_UseDebuggingNewOperator
  221753. NSOpenGLContext* renderContext;
  221754. ThreadSafeNSOpenGLView* view;
  221755. private:
  221756. OpenGLPixelFormat pixelFormat;
  221757. NSViewComponentInternal* viewHolder;
  221758. WindowedGLContext (const WindowedGLContext&);
  221759. const WindowedGLContext& operator= (const WindowedGLContext&);
  221760. };
  221761. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  221762. const OpenGLPixelFormat& pixelFormat,
  221763. const OpenGLContext* const contextToShareWith)
  221764. {
  221765. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  221766. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  221767. if (c->renderContext == 0)
  221768. deleteAndZero (c);
  221769. return c;
  221770. }
  221771. void* OpenGLComponent::getNativeWindowHandle() const
  221772. {
  221773. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  221774. : 0;
  221775. }
  221776. void juce_glViewport (const int w, const int h)
  221777. {
  221778. glViewport (0, 0, w, h);
  221779. }
  221780. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  221781. OwnedArray <OpenGLPixelFormat>& results)
  221782. {
  221783. /* GLint attribs [64];
  221784. int n = 0;
  221785. attribs[n++] = AGL_RGBA;
  221786. attribs[n++] = AGL_DOUBLEBUFFER;
  221787. attribs[n++] = AGL_ACCELERATED;
  221788. attribs[n++] = AGL_NO_RECOVERY;
  221789. attribs[n++] = AGL_NONE;
  221790. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  221791. while (p != 0)
  221792. {
  221793. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  221794. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  221795. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  221796. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  221797. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  221798. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  221799. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  221800. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  221801. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  221802. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  221803. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  221804. results.add (pf);
  221805. p = aglNextPixelFormat (p);
  221806. }*/
  221807. //jassertfalse //xxx can't see how you do this in cocoa!
  221808. }
  221809. #endif
  221810. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  221811. /********* Start of inlined file: juce_mac_MainMenu.mm *********/
  221812. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221813. // compiled on its own).
  221814. #ifdef JUCE_INCLUDED_FILE
  221815. class JuceMainMenuHandler;
  221816. END_JUCE_NAMESPACE
  221817. using namespace JUCE_NAMESPACE;
  221818. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  221819. @interface JuceMenuCallback : NSObject
  221820. {
  221821. JuceMainMenuHandler* owner;
  221822. }
  221823. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  221824. - (void) dealloc;
  221825. - (void) menuItemInvoked: (id) menu;
  221826. - (void) menuNeedsUpdate: (NSMenu*) menu;
  221827. @end
  221828. BEGIN_JUCE_NAMESPACE
  221829. class JuceMainMenuHandler : private MenuBarModelListener,
  221830. private DeletedAtShutdown
  221831. {
  221832. public:
  221833. static JuceMainMenuHandler* instance;
  221834. JuceMainMenuHandler() throw()
  221835. : currentModel (0),
  221836. lastUpdateTime (0)
  221837. {
  221838. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  221839. }
  221840. ~JuceMainMenuHandler() throw()
  221841. {
  221842. setMenu (0);
  221843. jassert (instance == this);
  221844. instance = 0;
  221845. [callback release];
  221846. }
  221847. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  221848. {
  221849. if (currentModel != newMenuBarModel)
  221850. {
  221851. if (currentModel != 0)
  221852. currentModel->removeListener (this);
  221853. currentModel = newMenuBarModel;
  221854. if (currentModel != 0)
  221855. currentModel->addListener (this);
  221856. menuBarItemsChanged (0);
  221857. }
  221858. }
  221859. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  221860. const String& name, const int menuId, const int tag)
  221861. {
  221862. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  221863. action: nil
  221864. keyEquivalent: @""];
  221865. [item setTag: tag];
  221866. NSMenu* sub = createMenu (child, name, menuId, tag);
  221867. [parent setSubmenu: sub forItem: item];
  221868. [sub setAutoenablesItems: false];
  221869. [sub release];
  221870. }
  221871. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  221872. const String& name, const int menuId, const int tag)
  221873. {
  221874. [parentItem setTag: tag];
  221875. NSMenu* menu = [parentItem submenu];
  221876. [menu setTitle: juceStringToNS (name)];
  221877. while ([menu numberOfItems] > 0)
  221878. [menu removeItemAtIndex: 0];
  221879. PopupMenu::MenuItemIterator iter (menuToCopy);
  221880. while (iter.next())
  221881. addMenuItem (iter, menu, menuId, tag);
  221882. [menu setAutoenablesItems: false];
  221883. [menu update];
  221884. }
  221885. void menuBarItemsChanged (MenuBarModel*)
  221886. {
  221887. lastUpdateTime = Time::getMillisecondCounter();
  221888. StringArray menuNames;
  221889. if (currentModel != 0)
  221890. menuNames = currentModel->getMenuBarNames();
  221891. NSMenu* menuBar = [NSApp mainMenu];
  221892. while ([menuBar numberOfItems] > 1 + menuNames.size())
  221893. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  221894. int menuId = 1;
  221895. for (int i = 0; i < menuNames.size(); ++i)
  221896. {
  221897. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  221898. if (i >= [menuBar numberOfItems] - 1)
  221899. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  221900. else
  221901. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  221902. }
  221903. }
  221904. static void flashMenuBar (NSMenu* menu)
  221905. {
  221906. const unichar f35Key = NSF35FunctionKey;
  221907. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  221908. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  221909. action: nil
  221910. keyEquivalent: f35String];
  221911. [item setTarget: nil];
  221912. [menu insertItem: item atIndex: [menu numberOfItems]];
  221913. [item release];
  221914. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  221915. location: NSZeroPoint
  221916. modifierFlags: NSCommandKeyMask
  221917. timestamp: 0
  221918. windowNumber: 0
  221919. context: [NSGraphicsContext currentContext]
  221920. characters: f35String
  221921. charactersIgnoringModifiers: f35String
  221922. isARepeat: NO
  221923. keyCode: 0];
  221924. [menu performKeyEquivalent: f35Event];
  221925. [menu removeItem: item];
  221926. }
  221927. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  221928. {
  221929. for (int i = [menu numberOfItems]; --i >= 0;)
  221930. {
  221931. NSMenuItem* m = [menu itemAtIndex: i];
  221932. if ([m tag] == info.commandID)
  221933. return m;
  221934. if ([m submenu] != 0)
  221935. {
  221936. NSMenuItem* found = findMenuItem ([m submenu], info);
  221937. if (found != 0)
  221938. return found;
  221939. }
  221940. }
  221941. return 0;
  221942. }
  221943. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  221944. {
  221945. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  221946. if (item != 0)
  221947. flashMenuBar ([item menu]);
  221948. }
  221949. void updateMenus()
  221950. {
  221951. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  221952. menuBarItemsChanged (0);
  221953. }
  221954. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  221955. {
  221956. if (currentModel != 0)
  221957. {
  221958. if (commandManager != 0)
  221959. {
  221960. ApplicationCommandTarget::InvocationInfo info (commandId);
  221961. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  221962. commandManager->invoke (info, true);
  221963. }
  221964. currentModel->menuItemSelected (commandId, topLevelIndex);
  221965. }
  221966. }
  221967. MenuBarModel* currentModel;
  221968. uint32 lastUpdateTime;
  221969. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  221970. const int topLevelMenuId, const int topLevelIndex)
  221971. {
  221972. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  221973. if (text == 0)
  221974. text = @"";
  221975. if (iter.isSeparator)
  221976. {
  221977. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  221978. }
  221979. else if (iter.isSectionHeader)
  221980. {
  221981. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  221982. action: nil
  221983. keyEquivalent: @""];
  221984. [item setEnabled: false];
  221985. }
  221986. else if (iter.subMenu != 0)
  221987. {
  221988. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  221989. action: nil
  221990. keyEquivalent: @""];
  221991. [item setTag: iter.itemId];
  221992. [item setEnabled: iter.isEnabled];
  221993. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  221994. [sub setDelegate: nil];
  221995. [menuToAddTo setSubmenu: sub forItem: item];
  221996. }
  221997. else
  221998. {
  221999. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  222000. action: @selector (menuItemInvoked:)
  222001. keyEquivalent: @""];
  222002. [item setTag: iter.itemId];
  222003. [item setEnabled: iter.isEnabled];
  222004. [item setState: iter.isTicked ? NSOnState : NSOffState];
  222005. [item setTarget: (id) callback];
  222006. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  222007. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  222008. [item setRepresentedObject: info];
  222009. if (iter.commandManager != 0)
  222010. {
  222011. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  222012. ->getKeyPressesAssignedToCommand (iter.itemId));
  222013. if (keyPresses.size() > 0)
  222014. {
  222015. const KeyPress& kp = keyPresses.getReference(0);
  222016. juce_wchar key = kp.getTextCharacter();
  222017. if (kp.getKeyCode() == KeyPress::backspaceKey)
  222018. key = NSBackspaceCharacter;
  222019. else if (kp.getKeyCode() == KeyPress::deleteKey)
  222020. key = NSDeleteCharacter;
  222021. else if (key == 0)
  222022. key = (juce_wchar) kp.getKeyCode();
  222023. unsigned int mods = 0;
  222024. if (kp.getModifiers().isShiftDown())
  222025. mods |= NSShiftKeyMask;
  222026. if (kp.getModifiers().isCtrlDown())
  222027. mods |= NSControlKeyMask;
  222028. if (kp.getModifiers().isAltDown())
  222029. mods |= NSAlternateKeyMask;
  222030. if (kp.getModifiers().isCommandDown())
  222031. mods |= NSCommandKeyMask;
  222032. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  222033. [item setKeyEquivalentModifierMask: mods];
  222034. }
  222035. }
  222036. }
  222037. }
  222038. JuceMenuCallback* callback;
  222039. private:
  222040. NSMenu* createMenu (const PopupMenu menu,
  222041. const String& menuName,
  222042. const int topLevelMenuId,
  222043. const int topLevelIndex)
  222044. {
  222045. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  222046. [m setAutoenablesItems: false];
  222047. [m setDelegate: callback];
  222048. PopupMenu::MenuItemIterator iter (menu);
  222049. while (iter.next())
  222050. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  222051. [m update];
  222052. return m;
  222053. }
  222054. };
  222055. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  222056. END_JUCE_NAMESPACE
  222057. @implementation JuceMenuCallback
  222058. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  222059. {
  222060. [super init];
  222061. owner = owner_;
  222062. return self;
  222063. }
  222064. - (void) dealloc
  222065. {
  222066. [super dealloc];
  222067. }
  222068. - (void) menuItemInvoked: (id) menu
  222069. {
  222070. NSMenuItem* item = (NSMenuItem*) menu;
  222071. if ([[item representedObject] isKindOfClass: [NSArray class]])
  222072. {
  222073. NSArray* info = (NSArray*) [item representedObject];
  222074. owner->invoke ([item tag],
  222075. (ApplicationCommandManager*) (pointer_sized_int)
  222076. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  222077. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  222078. }
  222079. }
  222080. - (void) menuNeedsUpdate: (NSMenu*) menu;
  222081. {
  222082. if (JuceMainMenuHandler::instance != 0)
  222083. JuceMainMenuHandler::instance->updateMenus();
  222084. }
  222085. @end
  222086. BEGIN_JUCE_NAMESPACE
  222087. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  222088. const PopupMenu* extraItems)
  222089. {
  222090. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  222091. {
  222092. PopupMenu::MenuItemIterator iter (*extraItems);
  222093. while (iter.next())
  222094. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  222095. [menu addItem: [NSMenuItem separatorItem]];
  222096. }
  222097. NSMenuItem* item;
  222098. // Services...
  222099. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  222100. action: nil keyEquivalent: @""];
  222101. [menu addItem: item];
  222102. [item release];
  222103. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  222104. [menu setSubmenu: servicesMenu forItem: item];
  222105. [NSApp setServicesMenu: servicesMenu];
  222106. [servicesMenu release];
  222107. [menu addItem: [NSMenuItem separatorItem]];
  222108. // Hide + Show stuff...
  222109. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  222110. action: @selector (hide:) keyEquivalent: @"h"];
  222111. [item setTarget: NSApp];
  222112. [menu addItem: item];
  222113. [item release];
  222114. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  222115. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  222116. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  222117. [item setTarget: NSApp];
  222118. [menu addItem: item];
  222119. [item release];
  222120. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  222121. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  222122. [item setTarget: NSApp];
  222123. [menu addItem: item];
  222124. [item release];
  222125. [menu addItem: [NSMenuItem separatorItem]];
  222126. // Quit item....
  222127. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  222128. action: @selector (terminate:) keyEquivalent: @"q"];
  222129. [item setTarget: NSApp];
  222130. [menu addItem: item];
  222131. [item release];
  222132. return menu;
  222133. }
  222134. // Since our app has no NIB, this initialises a standard app menu...
  222135. static void rebuildMainMenu (const PopupMenu* extraItems)
  222136. {
  222137. // this can't be used in a plugin!
  222138. jassert (JUCEApplication::getInstance() != 0);
  222139. if (JUCEApplication::getInstance() != 0)
  222140. {
  222141. const ScopedAutoReleasePool pool;
  222142. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  222143. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  222144. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  222145. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  222146. [mainMenu setSubmenu: appMenu forItem: item];
  222147. [NSApp setMainMenu: mainMenu];
  222148. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  222149. [appMenu release];
  222150. [mainMenu release];
  222151. }
  222152. }
  222153. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  222154. const PopupMenu* extraAppleMenuItems) throw()
  222155. {
  222156. if (getMacMainMenu() != newMenuBarModel)
  222157. {
  222158. const ScopedAutoReleasePool pool;
  222159. if (newMenuBarModel == 0)
  222160. {
  222161. delete JuceMainMenuHandler::instance;
  222162. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  222163. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  222164. extraAppleMenuItems = 0;
  222165. }
  222166. else
  222167. {
  222168. if (JuceMainMenuHandler::instance == 0)
  222169. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  222170. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  222171. }
  222172. }
  222173. rebuildMainMenu (extraAppleMenuItems);
  222174. if (newMenuBarModel != 0)
  222175. newMenuBarModel->menuItemsChanged();
  222176. }
  222177. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  222178. {
  222179. return JuceMainMenuHandler::instance != 0
  222180. ? JuceMainMenuHandler::instance->currentModel : 0;
  222181. }
  222182. void initialiseMainMenu()
  222183. {
  222184. if (JUCEApplication::getInstance() != 0) // only needed in an app
  222185. rebuildMainMenu (0);
  222186. }
  222187. #endif
  222188. /********* End of inlined file: juce_mac_MainMenu.mm *********/
  222189. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  222190. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222191. // compiled on its own).
  222192. #ifdef JUCE_INCLUDED_FILE
  222193. END_JUCE_NAMESPACE
  222194. using namespace JUCE_NAMESPACE;
  222195. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  222196. @interface JuceFileChooserDelegate : NSObject
  222197. {
  222198. StringArray* filters;
  222199. }
  222200. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  222201. - (void) dealloc;
  222202. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  222203. @end
  222204. @implementation JuceFileChooserDelegate
  222205. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  222206. {
  222207. [super init];
  222208. filters = filters_;
  222209. return self;
  222210. }
  222211. - (void) dealloc
  222212. {
  222213. delete filters;
  222214. [super dealloc];
  222215. }
  222216. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  222217. {
  222218. const String fname (nsStringToJuce (filename));
  222219. for (int i = filters->size(); --i >= 0;)
  222220. if (fname.matchesWildcard ((*filters)[i], true))
  222221. return true;
  222222. return File (fname).isDirectory();
  222223. }
  222224. @end
  222225. BEGIN_JUCE_NAMESPACE
  222226. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  222227. const String& title,
  222228. const File& currentFileOrDirectory,
  222229. const String& filter,
  222230. bool selectsDirectory,
  222231. bool isSaveDialogue,
  222232. bool warnAboutOverwritingExistingFiles,
  222233. bool selectMultipleFiles,
  222234. FilePreviewComponent* extraInfoComponent)
  222235. {
  222236. const ScopedAutoReleasePool pool;
  222237. StringArray* filters = new StringArray();
  222238. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  222239. filters->trim();
  222240. filters->removeEmptyStrings();
  222241. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  222242. [delegate autorelease];
  222243. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  222244. : [NSOpenPanel openPanel];
  222245. [panel setTitle: juceStringToNS (title)];
  222246. if (! isSaveDialogue)
  222247. {
  222248. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  222249. [openPanel setCanChooseDirectories: selectsDirectory];
  222250. [openPanel setCanChooseFiles: ! selectsDirectory];
  222251. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  222252. }
  222253. [panel setDelegate: delegate];
  222254. String directory, filename;
  222255. if (currentFileOrDirectory.isDirectory())
  222256. {
  222257. directory = currentFileOrDirectory.getFullPathName();
  222258. }
  222259. else
  222260. {
  222261. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  222262. filename = currentFileOrDirectory.getFileName();
  222263. }
  222264. if ([panel runModalForDirectory: juceStringToNS (directory)
  222265. file: juceStringToNS (filename)]
  222266. == NSOKButton)
  222267. {
  222268. if (isSaveDialogue)
  222269. {
  222270. results.add (new File (nsStringToJuce ([panel filename])));
  222271. }
  222272. else
  222273. {
  222274. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  222275. NSArray* urls = [openPanel filenames];
  222276. for (unsigned int i = 0; i < [urls count]; ++i)
  222277. {
  222278. NSString* f = [urls objectAtIndex: i];
  222279. results.add (new File (nsStringToJuce (f)));
  222280. }
  222281. }
  222282. }
  222283. [panel setDelegate: nil];
  222284. }
  222285. #endif
  222286. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  222287. /********* Start of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  222288. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222289. // compiled on its own).
  222290. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  222291. #define theMovie ((QTMovie*) movie)
  222292. QuickTimeMovieComponent::QuickTimeMovieComponent()
  222293. : movie (0)
  222294. {
  222295. setOpaque (true);
  222296. setVisible (true);
  222297. QTMovieView* view = [[QTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  222298. setView (view);
  222299. }
  222300. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  222301. {
  222302. closeMovie();
  222303. setView (0);
  222304. }
  222305. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  222306. {
  222307. return true;
  222308. }
  222309. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  222310. {
  222311. // unfortunately, QTMovie objects can only be created on the main thread..
  222312. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  222313. QTMovie* movie = 0;
  222314. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  222315. if (fin != 0)
  222316. {
  222317. movieFile = fin->getFile();
  222318. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  222319. error: nil];
  222320. }
  222321. else
  222322. {
  222323. MemoryBlock temp;
  222324. movieStream->readIntoMemoryBlock (temp);
  222325. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  222326. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  222327. {
  222328. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  222329. length: temp.getSize()]
  222330. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  222331. MIMEType: @""]
  222332. error: nil];
  222333. if (movie != 0)
  222334. break;
  222335. }
  222336. }
  222337. return movie;
  222338. }
  222339. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  222340. const bool controllerVisible)
  222341. {
  222342. closeMovie();
  222343. if (getPeer() == 0)
  222344. {
  222345. // To open a movie, this component must be visible inside a functioning window, so that
  222346. // the QT control can be assigned to the window.
  222347. jassertfalse
  222348. return false;
  222349. }
  222350. movie = openMovieFromStream (movieStream, movieFile);
  222351. [theMovie retain];
  222352. QTMovieView* view = (QTMovieView*) getView();
  222353. [view setMovie: theMovie];
  222354. [view setControllerVisible: controllerVisible];
  222355. setLooping (looping);
  222356. return movie != nil;
  222357. }
  222358. void QuickTimeMovieComponent::closeMovie()
  222359. {
  222360. stop();
  222361. QTMovieView* view = (QTMovieView*) getView();
  222362. [view setMovie: nil];
  222363. [theMovie release];
  222364. movie = 0;
  222365. movieFile = File::nonexistent;
  222366. }
  222367. bool QuickTimeMovieComponent::isMovieOpen() const
  222368. {
  222369. return movie != nil;
  222370. }
  222371. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  222372. {
  222373. return movieFile;
  222374. }
  222375. void QuickTimeMovieComponent::play()
  222376. {
  222377. [theMovie play];
  222378. }
  222379. void QuickTimeMovieComponent::stop()
  222380. {
  222381. [theMovie stop];
  222382. }
  222383. bool QuickTimeMovieComponent::isPlaying() const
  222384. {
  222385. return movie != 0 && [theMovie rate] != 0;
  222386. }
  222387. void QuickTimeMovieComponent::setPosition (const double seconds)
  222388. {
  222389. if (movie != 0)
  222390. {
  222391. QTTime t;
  222392. t.timeValue = (uint64) (100000.0 * seconds);
  222393. t.timeScale = 100000;
  222394. t.flags = 0;
  222395. [theMovie setCurrentTime: t];
  222396. }
  222397. }
  222398. double QuickTimeMovieComponent::getPosition() const
  222399. {
  222400. if (movie == 0)
  222401. return 0.0;
  222402. QTTime t = [theMovie currentTime];
  222403. return t.timeValue / (double) t.timeScale;
  222404. }
  222405. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  222406. {
  222407. [theMovie setRate: newSpeed];
  222408. }
  222409. double QuickTimeMovieComponent::getMovieDuration() const
  222410. {
  222411. if (movie == 0)
  222412. return 0.0;
  222413. QTTime t = [theMovie duration];
  222414. return t.timeValue / (double) t.timeScale;
  222415. }
  222416. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  222417. {
  222418. looping = shouldLoop;
  222419. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  222420. forKey: QTMovieLoopsAttribute];
  222421. }
  222422. bool QuickTimeMovieComponent::isLooping() const
  222423. {
  222424. return looping;
  222425. }
  222426. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  222427. {
  222428. [theMovie setVolume: newVolume];
  222429. }
  222430. float QuickTimeMovieComponent::getMovieVolume() const
  222431. {
  222432. return movie != 0 ? [theMovie volume] : 0.0f;
  222433. }
  222434. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  222435. {
  222436. width = 0;
  222437. height = 0;
  222438. if (movie != 0)
  222439. {
  222440. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  222441. width = s.width;
  222442. height = s.height;
  222443. }
  222444. }
  222445. void QuickTimeMovieComponent::paint (Graphics& g)
  222446. {
  222447. if (movie == 0)
  222448. g.fillAll (Colours::black);
  222449. }
  222450. bool QuickTimeMovieComponent::isControllerVisible() const
  222451. {
  222452. return controllerVisible;
  222453. }
  222454. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  222455. const bool isControllerVisible)
  222456. {
  222457. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  222458. movieFile = movieFile_;
  222459. return ok;
  222460. }
  222461. void QuickTimeMovieComponent::goToStart()
  222462. {
  222463. setPosition (0.0);
  222464. }
  222465. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  222466. const RectanglePlacement& placement)
  222467. {
  222468. int normalWidth, normalHeight;
  222469. getMovieNormalSize (normalWidth, normalHeight);
  222470. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  222471. {
  222472. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  222473. placement.applyTo (x, y, w, h,
  222474. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  222475. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  222476. if (w > 0 && h > 0)
  222477. {
  222478. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  222479. roundDoubleToInt (w), roundDoubleToInt (h));
  222480. }
  222481. }
  222482. else
  222483. {
  222484. setBounds (spaceToFitWithin);
  222485. }
  222486. }
  222487. #if ! (JUCE_MAC && JUCE_64BIT)
  222488. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  222489. {
  222490. if (movieStream == 0)
  222491. return false;
  222492. File file;
  222493. QTMovie* movie = openMovieFromStream (movieStream, file);
  222494. if (movie != nil)
  222495. result = [movie quickTimeMovie];
  222496. return movie != nil;
  222497. }
  222498. #endif
  222499. #endif
  222500. /********* End of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  222501. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  222502. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222503. // compiled on its own).
  222504. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  222505. END_JUCE_NAMESPACE
  222506. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  222507. @interface OpenDiskDevice : NSObject
  222508. {
  222509. DRDevice* device;
  222510. NSMutableArray* tracks;
  222511. }
  222512. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  222513. - (void) dealloc;
  222514. - (bool) isDiskPresent;
  222515. - (int) getNumAvailableAudioBlocks;
  222516. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  222517. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  222518. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  222519. @end
  222520. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  222521. @interface AudioTrackProducer : NSObject
  222522. {
  222523. JUCE_NAMESPACE::AudioSource* source;
  222524. int readPosition, lengthInFrames;
  222525. }
  222526. - (AudioTrackProducer*) init: (int) lengthInFrames;
  222527. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  222528. - (void) dealloc;
  222529. - (void) setupTrackProperties: (DRTrack*) track;
  222530. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  222531. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  222532. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  222533. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  222534. toMedia:(NSDictionary*)mediaInfo;
  222535. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  222536. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  222537. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  222538. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  222539. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  222540. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  222541. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  222542. ioFlags:(uint32_t*)flags;
  222543. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  222544. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  222545. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  222546. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  222547. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  222548. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  222549. ioFlags:(uint32_t*)flags;
  222550. @end
  222551. @implementation OpenDiskDevice
  222552. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  222553. {
  222554. [super init];
  222555. device = device_;
  222556. tracks = [[NSMutableArray alloc] init];
  222557. return self;
  222558. }
  222559. - (void) dealloc
  222560. {
  222561. [tracks release];
  222562. [super dealloc];
  222563. }
  222564. - (bool) isDiskPresent
  222565. {
  222566. return [device isValid]
  222567. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  222568. isEqualTo: DRDeviceMediaStateMediaPresent];
  222569. }
  222570. - (int) getNumAvailableAudioBlocks
  222571. {
  222572. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  222573. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  222574. }
  222575. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  222576. {
  222577. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  222578. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  222579. [p setupTrackProperties: t];
  222580. [tracks addObject: t];
  222581. [t release];
  222582. [p release];
  222583. }
  222584. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  222585. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  222586. {
  222587. DRBurn* burn = [DRBurn burnForDevice: device];
  222588. if (! [device acquireExclusiveAccess])
  222589. {
  222590. *error = "Couldn't open or write to the CD device";
  222591. return;
  222592. }
  222593. [device acquireMediaReservation];
  222594. NSMutableDictionary* d = [[burn properties] mutableCopy];
  222595. [d autorelease];
  222596. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  222597. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  222598. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  222599. forKey: DRBurnCompletionActionKey];
  222600. [burn setProperties: d];
  222601. [burn writeLayout: tracks];
  222602. for (;;)
  222603. {
  222604. JUCE_NAMESPACE::Thread::sleep (300);
  222605. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  222606. if (listener != 0 && listener->audioCDBurnProgress (progress))
  222607. {
  222608. [burn abort];
  222609. *error = "User cancelled the write operation";
  222610. break;
  222611. }
  222612. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  222613. {
  222614. *error = "Write operation failed";
  222615. break;
  222616. }
  222617. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  222618. {
  222619. break;
  222620. }
  222621. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  222622. objectForKey: DRErrorStatusErrorStringKey];
  222623. if ([err length] > 0)
  222624. {
  222625. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  222626. break;
  222627. }
  222628. }
  222629. [device releaseMediaReservation];
  222630. [device releaseExclusiveAccess];
  222631. }
  222632. @end
  222633. @implementation AudioTrackProducer
  222634. - (AudioTrackProducer*) init: (int) lengthInFrames_
  222635. {
  222636. lengthInFrames = lengthInFrames_;
  222637. readPosition = 0;
  222638. return self;
  222639. }
  222640. - (void) setupTrackProperties: (DRTrack*) track
  222641. {
  222642. NSMutableDictionary* p = [[track properties] mutableCopy];
  222643. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  222644. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  222645. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  222646. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  222647. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  222648. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  222649. [track setProperties: p];
  222650. [p release];
  222651. }
  222652. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  222653. {
  222654. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  222655. if (s != nil)
  222656. s->source = source_;
  222657. return s;
  222658. }
  222659. - (void) dealloc
  222660. {
  222661. if (source != 0)
  222662. {
  222663. source->releaseResources();
  222664. delete source;
  222665. }
  222666. [super dealloc];
  222667. }
  222668. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  222669. {
  222670. }
  222671. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  222672. {
  222673. return true;
  222674. }
  222675. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  222676. {
  222677. return lengthInFrames;
  222678. }
  222679. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  222680. toMedia: (NSDictionary*) mediaInfo
  222681. {
  222682. if (source != 0)
  222683. source->prepareToPlay (44100 / 75, 44100);
  222684. readPosition = 0;
  222685. return true;
  222686. }
  222687. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  222688. {
  222689. if (source != 0)
  222690. source->prepareToPlay (44100 / 75, 44100);
  222691. return true;
  222692. }
  222693. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  222694. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  222695. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  222696. {
  222697. if (source != 0)
  222698. {
  222699. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  222700. if (numSamples > 0)
  222701. {
  222702. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  222703. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  222704. info.buffer = &tempBuffer;
  222705. info.startSample = 0;
  222706. info.numSamples = numSamples;
  222707. source->getNextAudioBlock (info);
  222708. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  222709. buffer, numSamples, 4);
  222710. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  222711. buffer + 2, numSamples, 4);
  222712. readPosition += numSamples;
  222713. }
  222714. return numSamples * 4;
  222715. }
  222716. return 0;
  222717. }
  222718. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  222719. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  222720. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  222721. ioFlags: (uint32_t*) flags
  222722. {
  222723. zeromem (buffer, bufferLength);
  222724. return bufferLength;
  222725. }
  222726. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  222727. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  222728. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  222729. {
  222730. return true;
  222731. }
  222732. @end
  222733. BEGIN_JUCE_NAMESPACE
  222734. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  222735. : internal (0)
  222736. {
  222737. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  222738. internal = (void*) dev;
  222739. }
  222740. AudioCDBurner::~AudioCDBurner()
  222741. {
  222742. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  222743. if (dev != 0)
  222744. [dev release];
  222745. }
  222746. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  222747. {
  222748. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  222749. if (b->internal == 0)
  222750. deleteAndZero (b);
  222751. return b;
  222752. }
  222753. static NSArray* findDiskBurnerDevices()
  222754. {
  222755. NSMutableArray* results = [NSMutableArray array];
  222756. NSArray* devs = [DRDevice devices];
  222757. if (devs != 0)
  222758. {
  222759. int num = [devs count];
  222760. int i;
  222761. for (i = 0; i < num; ++i)
  222762. {
  222763. NSDictionary* dic = [[devs objectAtIndex: i] info];
  222764. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  222765. if (name != nil)
  222766. [results addObject: name];
  222767. }
  222768. }
  222769. return results;
  222770. }
  222771. const StringArray AudioCDBurner::findAvailableDevices()
  222772. {
  222773. NSArray* names = findDiskBurnerDevices();
  222774. StringArray s;
  222775. for (unsigned int i = 0; i < [names count]; ++i)
  222776. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  222777. return s;
  222778. }
  222779. bool AudioCDBurner::isDiskPresent() const
  222780. {
  222781. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  222782. return dev != 0 && [dev isDiskPresent];
  222783. }
  222784. int AudioCDBurner::getNumAvailableAudioBlocks() const
  222785. {
  222786. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  222787. return [dev getNumAvailableAudioBlocks];
  222788. }
  222789. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  222790. {
  222791. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  222792. if (dev != 0)
  222793. {
  222794. [dev addSourceTrack: source numSamples: numSamps];
  222795. return true;
  222796. }
  222797. return false;
  222798. }
  222799. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  222800. const bool ejectDiscAfterwards,
  222801. const bool peformFakeBurnForTesting)
  222802. {
  222803. String error ("Couldn't open or write to the CD device");
  222804. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  222805. if (dev != 0)
  222806. {
  222807. error = String::empty;
  222808. [dev burn: listener
  222809. errorString: &error
  222810. ejectAfterwards: ejectDiscAfterwards
  222811. isFake: peformFakeBurnForTesting];
  222812. }
  222813. return error;
  222814. }
  222815. void AudioCDReader::ejectDisk()
  222816. {
  222817. const ScopedAutoReleasePool p;
  222818. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  222819. }
  222820. #endif
  222821. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  222822. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  222823. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222824. // compiled on its own).
  222825. #ifdef JUCE_INCLUDED_FILE
  222826. class FontHelper
  222827. {
  222828. NSFont* font;
  222829. public:
  222830. String name;
  222831. bool isBold, isItalic, needsItalicTransform;
  222832. float fontSize, totalSize, ascent;
  222833. int refCount;
  222834. NSMutableDictionary* attributes;
  222835. FontHelper (const String& name_,
  222836. const bool bold_,
  222837. const bool italic_,
  222838. const float size_)
  222839. : font (0),
  222840. name (name_),
  222841. isBold (bold_),
  222842. isItalic (italic_),
  222843. needsItalicTransform (false),
  222844. fontSize (size_),
  222845. refCount (1)
  222846. {
  222847. attributes = [[NSMutableDictionary dictionaryWithObject: [NSNumber numberWithInt: 0]
  222848. forKey: NSLigatureAttributeName] retain];
  222849. font = [NSFont fontWithName: juceStringToNS (name_) size: size_];
  222850. if (italic_)
  222851. {
  222852. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSItalicFontMask];
  222853. if (newFont == font)
  222854. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  222855. font = newFont;
  222856. }
  222857. if (bold_)
  222858. font = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSBoldFontMask];
  222859. [font retain];
  222860. ascent = fabsf ([font ascender]);
  222861. totalSize = ascent + fabsf ([font descender]);
  222862. }
  222863. ~FontHelper()
  222864. {
  222865. [font release];
  222866. [attributes release];
  222867. }
  222868. bool getPathAndKerning (const juce_wchar char1,
  222869. const juce_wchar char2,
  222870. Path* path,
  222871. float& kerning,
  222872. float* ascent,
  222873. float* descent)
  222874. {
  222875. const ScopedAutoReleasePool pool;
  222876. if (font == 0
  222877. || ! [[font coveredCharacterSet] longCharacterIsMember: (UTF32Char) char1])
  222878. return false;
  222879. String chars;
  222880. chars << ' ' << char1 << char2;
  222881. NSTextStorage* textStorage = [[[NSTextStorage alloc] initWithString: juceStringToNS (chars)
  222882. attributes: attributes] autorelease];
  222883. NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
  222884. NSTextContainer* textContainer = [[[NSTextContainer alloc] init] autorelease];
  222885. [layoutManager addTextContainer: textContainer];
  222886. [textStorage addLayoutManager: layoutManager];
  222887. [textStorage setFont: font];
  222888. unsigned int glyphIndex = [layoutManager glyphRangeForCharacterRange: NSMakeRange (1, 1)
  222889. actualCharacterRange: 0].location;
  222890. NSPoint p1 = [layoutManager locationForGlyphAtIndex: glyphIndex];
  222891. NSPoint p2 = [layoutManager locationForGlyphAtIndex: glyphIndex + 1];
  222892. kerning = p2.x - p1.x;
  222893. if (ascent != 0)
  222894. *ascent = this->ascent;
  222895. if (descent != 0)
  222896. *descent = fabsf ([font descender]);
  222897. if (path != 0)
  222898. {
  222899. NSBezierPath* bez = [NSBezierPath bezierPath];
  222900. [bez moveToPoint: NSMakePoint (0, 0)];
  222901. [bez appendBezierPathWithGlyph: [layoutManager glyphAtIndex: glyphIndex]
  222902. inFont: font];
  222903. for (int i = 0; i < [bez elementCount]; ++i)
  222904. {
  222905. NSPoint p[3];
  222906. switch ([bez elementAtIndex: i associatedPoints: p])
  222907. {
  222908. case NSMoveToBezierPathElement:
  222909. path->startNewSubPath (p[0].x, -p[0].y);
  222910. break;
  222911. case NSLineToBezierPathElement:
  222912. path->lineTo (p[0].x, -p[0].y);
  222913. break;
  222914. case NSCurveToBezierPathElement:
  222915. path->cubicTo (p[0].x, -p[0].y, p[1].x, -p[1].y, p[2].x, -p[2].y);
  222916. break;
  222917. case NSClosePathBezierPathElement:
  222918. path->closeSubPath();
  222919. break;
  222920. default:
  222921. jassertfalse
  222922. break;
  222923. }
  222924. }
  222925. if (needsItalicTransform)
  222926. path->applyTransform (AffineTransform::identity.sheared (-0.15, 0));
  222927. }
  222928. return kerning != 0;
  222929. }
  222930. juce_wchar getDefaultChar()
  222931. {
  222932. return 0;
  222933. }
  222934. };
  222935. class FontHelperCache : public Timer,
  222936. public DeletedAtShutdown
  222937. {
  222938. VoidArray cache;
  222939. public:
  222940. FontHelperCache()
  222941. {
  222942. }
  222943. ~FontHelperCache()
  222944. {
  222945. for (int i = cache.size(); --i >= 0;)
  222946. {
  222947. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  222948. delete f;
  222949. }
  222950. clearSingletonInstance();
  222951. }
  222952. FontHelper* getFont (const String& name,
  222953. const bool bold,
  222954. const bool italic,
  222955. const float size = 1024)
  222956. {
  222957. for (int i = cache.size(); --i >= 0;)
  222958. {
  222959. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  222960. if (f->name == name
  222961. && f->isBold == bold
  222962. && f->isItalic == italic
  222963. && f->fontSize == size)
  222964. {
  222965. f->refCount++;
  222966. return f;
  222967. }
  222968. }
  222969. FontHelper* const f = new FontHelper (name, bold, italic, size);
  222970. cache.add (f);
  222971. return f;
  222972. }
  222973. void releaseFont (FontHelper* f)
  222974. {
  222975. for (int i = cache.size(); --i >= 0;)
  222976. {
  222977. FontHelper* const f2 = (FontHelper*) cache.getUnchecked(i);
  222978. if (f == f2)
  222979. {
  222980. f->refCount--;
  222981. if (f->refCount == 0)
  222982. startTimer (5000);
  222983. break;
  222984. }
  222985. }
  222986. }
  222987. void timerCallback()
  222988. {
  222989. stopTimer();
  222990. for (int i = cache.size(); --i >= 0;)
  222991. {
  222992. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  222993. if (f->refCount == 0)
  222994. {
  222995. cache.remove (i);
  222996. delete f;
  222997. }
  222998. }
  222999. if (cache.size() == 0)
  223000. delete this;
  223001. }
  223002. juce_DeclareSingleton_SingleThreaded_Minimal (FontHelperCache)
  223003. };
  223004. juce_ImplementSingleton_SingleThreaded (FontHelperCache)
  223005. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  223006. bool bold,
  223007. bool italic,
  223008. bool addAllGlyphsToFont) throw()
  223009. {
  223010. // This method is only safe to be called from the normal UI thread..
  223011. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  223012. FontHelper* const helper = FontHelperCache::getInstance()
  223013. ->getFont (fontName, bold, italic);
  223014. clear();
  223015. setAscent (helper->ascent / helper->totalSize);
  223016. setName (fontName);
  223017. setDefaultCharacter (helper->getDefaultChar());
  223018. setBold (bold);
  223019. setItalic (italic);
  223020. if (addAllGlyphsToFont)
  223021. {
  223022. //xxx
  223023. jassertfalse
  223024. }
  223025. FontHelperCache::getInstance()->releaseFont (helper);
  223026. }
  223027. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  223028. {
  223029. // This method is only safe to be called from the normal UI thread..
  223030. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  223031. if (character == 0)
  223032. return false;
  223033. FontHelper* const helper = FontHelperCache::getInstance()
  223034. ->getFont (getName(), isBold(), isItalic());
  223035. Path path;
  223036. float width;
  223037. bool foundOne = false;
  223038. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  223039. {
  223040. path.applyTransform (AffineTransform::scale (1.0f / helper->totalSize,
  223041. 1.0f / helper->totalSize));
  223042. addGlyph (character, path, width / helper->totalSize);
  223043. for (int i = 0; i < glyphs.size(); ++i)
  223044. {
  223045. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  223046. float kerning;
  223047. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  223048. {
  223049. kerning = (kerning - width) / helper->totalSize;
  223050. if (kerning != 0)
  223051. addKerningPair (character, g->getCharacter(), kerning);
  223052. }
  223053. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  223054. {
  223055. kerning = kerning / helper->totalSize - g->width;
  223056. if (kerning != 0)
  223057. addKerningPair (g->getCharacter(), character, kerning);
  223058. }
  223059. }
  223060. foundOne = true;
  223061. }
  223062. FontHelperCache::getInstance()->releaseFont (helper);
  223063. return foundOne;
  223064. }
  223065. const StringArray Font::findAllTypefaceNames() throw()
  223066. {
  223067. StringArray names;
  223068. const ScopedAutoReleasePool pool;
  223069. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  223070. for (unsigned int i = 0; i < [fonts count]; ++i)
  223071. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  223072. names.sort (true);
  223073. return names;
  223074. }
  223075. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  223076. {
  223077. defaultSans = "Lucida Grande";
  223078. defaultSerif = "Times New Roman";
  223079. defaultFixed = "Monaco";
  223080. }
  223081. #endif
  223082. /********* End of inlined file: juce_mac_Fonts.mm *********/
  223083. /********* Start of inlined file: juce_mac_MessageManager.mm *********/
  223084. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223085. // compiled on its own).
  223086. #ifdef JUCE_INCLUDED_FILE
  223087. struct CallbackMessagePayload
  223088. {
  223089. MessageCallbackFunction* function;
  223090. void* parameter;
  223091. void* volatile result;
  223092. bool volatile hasBeenExecuted;
  223093. };
  223094. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  223095. for example having more than one juce plugin loaded into a host, then when a
  223096. method is called, the actual code that runs might actually be in a different module
  223097. than the one you expect... So any calls to library functions or statics that are
  223098. made inside obj-c methods will probably end up getting executed in a different DLL's
  223099. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  223100. To work around this insanity, I'm only allowing obj-c methods to make calls to
  223101. virtual methods of an object that's known to live inside the right module's space.
  223102. */
  223103. class AppDelegateRedirector
  223104. {
  223105. public:
  223106. AppDelegateRedirector() {}
  223107. virtual ~AppDelegateRedirector() {}
  223108. virtual NSApplicationTerminateReply shouldTerminate()
  223109. {
  223110. if (JUCEApplication::getInstance() != 0)
  223111. {
  223112. JUCEApplication::getInstance()->systemRequestedQuit();
  223113. return NSTerminateCancel;
  223114. }
  223115. return NSTerminateNow;
  223116. }
  223117. virtual BOOL openFile (const NSString* filename)
  223118. {
  223119. if (JUCEApplication::getInstance() != 0)
  223120. {
  223121. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  223122. return YES;
  223123. }
  223124. return NO;
  223125. }
  223126. virtual void openFiles (NSArray* filenames)
  223127. {
  223128. StringArray files;
  223129. for (unsigned int i = 0; i < [filenames count]; ++i)
  223130. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  223131. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  223132. {
  223133. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  223134. }
  223135. }
  223136. virtual void focusChanged()
  223137. {
  223138. juce_HandleProcessFocusChange();
  223139. }
  223140. virtual void deliverMessage (void* message)
  223141. {
  223142. // no need for an mm lock here - deliverMessage locks it
  223143. MessageManager::getInstance()->deliverMessage (message);
  223144. }
  223145. virtual void performCallback (CallbackMessagePayload* pl)
  223146. {
  223147. pl->result = (*pl->function) (pl->parameter);
  223148. pl->hasBeenExecuted = true;
  223149. }
  223150. virtual void deleteSelf()
  223151. {
  223152. delete this;
  223153. }
  223154. };
  223155. END_JUCE_NAMESPACE
  223156. using namespace JUCE_NAMESPACE;
  223157. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  223158. static int numPendingMessages = 0;
  223159. @interface JuceAppDelegate : NSObject
  223160. {
  223161. @private
  223162. id oldDelegate;
  223163. AppDelegateRedirector* redirector;
  223164. @public
  223165. bool flushingMessages;
  223166. }
  223167. - (JuceAppDelegate*) init;
  223168. - (void) dealloc;
  223169. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  223170. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  223171. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  223172. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  223173. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  223174. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  223175. - (void) customEvent: (id) data;
  223176. - (void) performCallback: (id) info;
  223177. - (void) dummyMethod;
  223178. @end
  223179. @implementation JuceAppDelegate
  223180. - (JuceAppDelegate*) init
  223181. {
  223182. [super init];
  223183. redirector = new AppDelegateRedirector();
  223184. numPendingMessages = 0;
  223185. flushingMessages = false;
  223186. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  223187. if (JUCEApplication::getInstance() != 0)
  223188. {
  223189. oldDelegate = [NSApp delegate];
  223190. [NSApp setDelegate: self];
  223191. }
  223192. else
  223193. {
  223194. oldDelegate = 0;
  223195. [center addObserver: self selector: @selector (applicationDidResignActive:)
  223196. name: NSApplicationDidResignActiveNotification object: NSApp];
  223197. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  223198. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  223199. [center addObserver: self selector: @selector (applicationWillUnhide:)
  223200. name: NSApplicationWillUnhideNotification object: NSApp];
  223201. }
  223202. return self;
  223203. }
  223204. - (void) dealloc
  223205. {
  223206. if (oldDelegate != 0)
  223207. [NSApp setDelegate: oldDelegate];
  223208. redirector->deleteSelf();
  223209. [super dealloc];
  223210. }
  223211. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  223212. {
  223213. return redirector->shouldTerminate();
  223214. }
  223215. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  223216. {
  223217. return redirector->openFile (filename);
  223218. }
  223219. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  223220. {
  223221. return redirector->openFiles (filenames);
  223222. }
  223223. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  223224. {
  223225. redirector->focusChanged();
  223226. }
  223227. - (void) applicationDidResignActive: (NSNotification*) aNotification
  223228. {
  223229. redirector->focusChanged();
  223230. }
  223231. - (void) applicationWillUnhide: (NSNotification*) aNotification
  223232. {
  223233. redirector->focusChanged();
  223234. }
  223235. - (void) customEvent: (id) n
  223236. {
  223237. atomicDecrement (numPendingMessages);
  223238. NSData* data = (NSData*) n;
  223239. void* message = 0;
  223240. [data getBytes: &message length: sizeof (message)];
  223241. [data release];
  223242. if (message != 0 && ! flushingMessages)
  223243. redirector->deliverMessage (message);
  223244. }
  223245. - (void) performCallback: (id) info
  223246. {
  223247. if ([info isKindOfClass: [NSData class]])
  223248. {
  223249. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  223250. if (pl != 0)
  223251. redirector->performCallback (pl);
  223252. }
  223253. else
  223254. {
  223255. jassertfalse // should never get here!
  223256. }
  223257. }
  223258. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  223259. @end
  223260. BEGIN_JUCE_NAMESPACE
  223261. static JuceAppDelegate* juceAppDelegate = 0;
  223262. void MessageManager::runDispatchLoop()
  223263. {
  223264. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  223265. {
  223266. const ScopedAutoReleasePool pool;
  223267. // must only be called by the message thread!
  223268. jassert (isThisTheMessageThread());
  223269. [NSApp run];
  223270. }
  223271. }
  223272. void MessageManager::stopDispatchLoop()
  223273. {
  223274. quitMessagePosted = true;
  223275. [NSApp stop: nil];
  223276. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  223277. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  223278. }
  223279. static bool isEventBlockedByModalComps (NSEvent* e)
  223280. {
  223281. if (Component::getNumCurrentlyModalComponents() == 0)
  223282. return false;
  223283. NSWindow* const w = [e window];
  223284. if (w == 0 || [w worksWhenModal])
  223285. return false;
  223286. bool isKey = false, isInputAttempt = false;
  223287. switch ([e type])
  223288. {
  223289. case NSKeyDown:
  223290. case NSKeyUp:
  223291. isKey = isInputAttempt = true;
  223292. break;
  223293. case NSLeftMouseDown:
  223294. case NSRightMouseDown:
  223295. case NSOtherMouseDown:
  223296. isInputAttempt = true;
  223297. break;
  223298. case NSLeftMouseDragged:
  223299. case NSRightMouseDragged:
  223300. case NSLeftMouseUp:
  223301. case NSRightMouseUp:
  223302. case NSOtherMouseUp:
  223303. case NSOtherMouseDragged:
  223304. if (Component::getComponentUnderMouse() != 0)
  223305. return false;
  223306. break;
  223307. case NSMouseMoved:
  223308. case NSMouseEntered:
  223309. case NSMouseExited:
  223310. case NSCursorUpdate:
  223311. case NSScrollWheel:
  223312. case NSTabletPoint:
  223313. case NSTabletProximity:
  223314. break;
  223315. default:
  223316. return false;
  223317. }
  223318. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  223319. {
  223320. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  223321. NSView* const compView = (NSView*) peer->getNativeHandle();
  223322. if ([compView window] == w)
  223323. {
  223324. if (isKey)
  223325. {
  223326. if (compView == [w firstResponder])
  223327. return false;
  223328. }
  223329. else
  223330. {
  223331. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  223332. [compView bounds]))
  223333. return false;
  223334. }
  223335. }
  223336. }
  223337. if (isInputAttempt)
  223338. {
  223339. if (! [NSApp isActive])
  223340. [NSApp activateIgnoringOtherApps: YES];
  223341. Component* const modal = Component::getCurrentlyModalComponent (0);
  223342. if (modal != 0)
  223343. modal->inputAttemptWhenModal();
  223344. }
  223345. return true;
  223346. }
  223347. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  223348. {
  223349. const ScopedAutoReleasePool pool;
  223350. jassert (isThisTheMessageThread()); // must only be called by the message thread
  223351. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  223352. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  223353. while (! quitMessagePosted)
  223354. {
  223355. const ScopedAutoReleasePool pool;
  223356. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  223357. beforeDate: endDate];
  223358. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  223359. untilDate: endDate
  223360. inMode: NSDefaultRunLoopMode
  223361. dequeue: YES];
  223362. if (e != 0 && ! isEventBlockedByModalComps (e))
  223363. [NSApp sendEvent: e];
  223364. if (Time::getMillisecondCounter() >= endTime)
  223365. break;
  223366. }
  223367. return ! quitMessagePosted;
  223368. }
  223369. void MessageManager::doPlatformSpecificInitialisation()
  223370. {
  223371. if (juceAppDelegate == 0)
  223372. juceAppDelegate = [[JuceAppDelegate alloc] init];
  223373. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  223374. // correctly (needed prior to 10.5)
  223375. if (! [NSThread isMultiThreaded])
  223376. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  223377. toTarget: juceAppDelegate
  223378. withObject: nil];
  223379. initialiseMainMenu();
  223380. }
  223381. void MessageManager::doPlatformSpecificShutdown()
  223382. {
  223383. if (juceAppDelegate != 0)
  223384. {
  223385. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  223386. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  223387. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  223388. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  223389. juceAppDelegate->flushingMessages = true;
  223390. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  223391. {
  223392. const ScopedAutoReleasePool pool;
  223393. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  223394. beforeDate: [NSDate dateWithTimeIntervalSinceNow: 5 * 0.001]];
  223395. }
  223396. [juceAppDelegate release];
  223397. juceAppDelegate = 0;
  223398. }
  223399. }
  223400. bool juce_postMessageToSystemQueue (void* message)
  223401. {
  223402. atomicIncrement (numPendingMessages);
  223403. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  223404. withObject: (id) [[NSData alloc] initWithBytes: &message length: (int) sizeof (message)]
  223405. waitUntilDone: NO];
  223406. return true;
  223407. }
  223408. void MessageManager::broadcastMessage (const String& value) throw()
  223409. {
  223410. }
  223411. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  223412. void* data)
  223413. {
  223414. if (isThisTheMessageThread())
  223415. {
  223416. return (*callback) (data);
  223417. }
  223418. else
  223419. {
  223420. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  223421. // deadlock because the message manager is blocked from running, so can never
  223422. // call your function..
  223423. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  223424. const ScopedAutoReleasePool pool;
  223425. CallbackMessagePayload cmp;
  223426. cmp.function = callback;
  223427. cmp.parameter = data;
  223428. cmp.result = 0;
  223429. cmp.hasBeenExecuted = false;
  223430. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  223431. withObject: [NSData dataWithBytesNoCopy: &cmp
  223432. length: sizeof (cmp)
  223433. freeWhenDone: NO]
  223434. waitUntilDone: YES];
  223435. return cmp.result;
  223436. }
  223437. }
  223438. #endif
  223439. /********* End of inlined file: juce_mac_MessageManager.mm *********/
  223440. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  223441. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223442. // compiled on its own).
  223443. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223444. END_JUCE_NAMESPACE
  223445. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  223446. @interface DownloadClickDetector : NSObject
  223447. {
  223448. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  223449. }
  223450. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  223451. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  223452. request: (NSURLRequest*) request
  223453. frame: (WebFrame*) frame
  223454. decisionListener: (id<WebPolicyDecisionListener>) listener;
  223455. @end
  223456. @implementation DownloadClickDetector
  223457. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  223458. {
  223459. [super init];
  223460. ownerComponent = ownerComponent_;
  223461. return self;
  223462. }
  223463. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  223464. request: (NSURLRequest*) request
  223465. frame: (WebFrame*) frame
  223466. decisionListener: (id <WebPolicyDecisionListener>) listener
  223467. {
  223468. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  223469. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  223470. [listener use];
  223471. else
  223472. [listener ignore];
  223473. }
  223474. @end
  223475. BEGIN_JUCE_NAMESPACE
  223476. class WebBrowserComponentInternal : public NSViewComponent
  223477. {
  223478. public:
  223479. WebBrowserComponentInternal (WebBrowserComponent* owner)
  223480. {
  223481. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  223482. frameName: @""
  223483. groupName: @""];
  223484. setView (webView);
  223485. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  223486. [webView setPolicyDelegate: clickListener];
  223487. }
  223488. ~WebBrowserComponentInternal()
  223489. {
  223490. [webView setPolicyDelegate: nil];
  223491. [clickListener release];
  223492. setView (0);
  223493. }
  223494. void goToURL (const String& url,
  223495. const StringArray* headers,
  223496. const MemoryBlock* postData)
  223497. {
  223498. NSMutableURLRequest* r
  223499. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  223500. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223501. timeoutInterval: 30.0];
  223502. if (postData != 0 && postData->getSize() > 0)
  223503. {
  223504. [r setHTTPMethod: @"POST"];
  223505. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  223506. length: postData->getSize()]];
  223507. }
  223508. if (headers != 0)
  223509. {
  223510. for (int i = 0; i < headers->size(); ++i)
  223511. {
  223512. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  223513. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  223514. [r setValue: juceStringToNS (headerValue)
  223515. forHTTPHeaderField: juceStringToNS (headerName)];
  223516. }
  223517. }
  223518. stop();
  223519. [[webView mainFrame] loadRequest: r];
  223520. }
  223521. void goBack()
  223522. {
  223523. [webView goBack];
  223524. }
  223525. void goForward()
  223526. {
  223527. [webView goForward];
  223528. }
  223529. void stop()
  223530. {
  223531. [webView stopLoading: nil];
  223532. }
  223533. void refresh()
  223534. {
  223535. [webView reload: nil];
  223536. }
  223537. private:
  223538. WebView* webView;
  223539. DownloadClickDetector* clickListener;
  223540. };
  223541. WebBrowserComponent::WebBrowserComponent()
  223542. : browser (0),
  223543. blankPageShown (false)
  223544. {
  223545. setOpaque (true);
  223546. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  223547. }
  223548. WebBrowserComponent::~WebBrowserComponent()
  223549. {
  223550. deleteAndZero (browser);
  223551. }
  223552. void WebBrowserComponent::goToURL (const String& url,
  223553. const StringArray* headers,
  223554. const MemoryBlock* postData)
  223555. {
  223556. lastURL = url;
  223557. lastHeaders.clear();
  223558. if (headers != 0)
  223559. lastHeaders = *headers;
  223560. lastPostData.setSize (0);
  223561. if (postData != 0)
  223562. lastPostData = *postData;
  223563. blankPageShown = false;
  223564. browser->goToURL (url, headers, postData);
  223565. }
  223566. void WebBrowserComponent::stop()
  223567. {
  223568. browser->stop();
  223569. }
  223570. void WebBrowserComponent::goBack()
  223571. {
  223572. lastURL = String::empty;
  223573. blankPageShown = false;
  223574. browser->goBack();
  223575. }
  223576. void WebBrowserComponent::goForward()
  223577. {
  223578. lastURL = String::empty;
  223579. browser->goForward();
  223580. }
  223581. void WebBrowserComponent::refresh()
  223582. {
  223583. browser->refresh();
  223584. }
  223585. void WebBrowserComponent::paint (Graphics& g)
  223586. {
  223587. }
  223588. void WebBrowserComponent::checkWindowAssociation()
  223589. {
  223590. // when the component becomes invisible, some stuff like flash
  223591. // carries on playing audio, so we need to force it onto a blank
  223592. // page to avoid this, (and send it back when it's made visible again).
  223593. if (isShowing())
  223594. {
  223595. if (blankPageShown)
  223596. goBack();
  223597. }
  223598. else
  223599. {
  223600. if (! blankPageShown)
  223601. {
  223602. blankPageShown = true;
  223603. browser->goToURL ("about:blank", 0, 0);
  223604. }
  223605. }
  223606. }
  223607. void WebBrowserComponent::reloadLastURL()
  223608. {
  223609. if (lastURL.isNotEmpty())
  223610. {
  223611. goToURL (lastURL, &lastHeaders, &lastPostData);
  223612. lastURL = String::empty;
  223613. }
  223614. }
  223615. void WebBrowserComponent::parentHierarchyChanged()
  223616. {
  223617. checkWindowAssociation();
  223618. }
  223619. void WebBrowserComponent::resized()
  223620. {
  223621. browser->setSize (getWidth(), getHeight());
  223622. }
  223623. void WebBrowserComponent::visibilityChanged()
  223624. {
  223625. checkWindowAssociation();
  223626. }
  223627. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223628. {
  223629. return true;
  223630. }
  223631. #endif
  223632. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  223633. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  223634. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223635. // compiled on its own).
  223636. #ifdef JUCE_INCLUDED_FILE
  223637. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  223638. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  223639. #endif
  223640. #undef log
  223641. #if JUCE_COREAUDIO_LOGGING_ENABLED
  223642. #define log(a) Logger::writeToLog (a)
  223643. #else
  223644. #define log(a)
  223645. #endif
  223646. #undef OK
  223647. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  223648. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  223649. {
  223650. if (err == noErr)
  223651. return true;
  223652. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  223653. jassertfalse
  223654. return false;
  223655. }
  223656. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  223657. #else
  223658. #define OK(a) (a == noErr)
  223659. #endif
  223660. class CoreAudioInternal : public Timer
  223661. {
  223662. public:
  223663. CoreAudioInternal (AudioDeviceID id)
  223664. : inputLatency (0),
  223665. outputLatency (0),
  223666. callback (0),
  223667. #if ! MACOS_10_4_OR_EARLIER
  223668. audioProcID (0),
  223669. #endif
  223670. inputDevice (0),
  223671. isSlaveDevice (false),
  223672. deviceID (id),
  223673. started (false),
  223674. audioBuffer (0),
  223675. numInputChans (0),
  223676. numOutputChans (0),
  223677. callbacksAllowed (true),
  223678. numInputChannelInfos (0),
  223679. numOutputChannelInfos (0),
  223680. tempInputBuffers (0),
  223681. tempOutputBuffers (0),
  223682. inputChannelInfo (0),
  223683. outputChannelInfo (0)
  223684. {
  223685. sampleRate = 0;
  223686. bufferSize = 512;
  223687. if (deviceID == 0)
  223688. {
  223689. error = TRANS("can't open device");
  223690. }
  223691. else
  223692. {
  223693. updateDetailsFromDevice();
  223694. AudioDeviceAddPropertyListener (deviceID,
  223695. kAudioPropertyWildcardChannel,
  223696. kAudioPropertyWildcardSection,
  223697. kAudioPropertyWildcardPropertyID,
  223698. deviceListenerProc, this);
  223699. }
  223700. }
  223701. ~CoreAudioInternal()
  223702. {
  223703. AudioDeviceRemovePropertyListener (deviceID,
  223704. kAudioPropertyWildcardChannel,
  223705. kAudioPropertyWildcardSection,
  223706. kAudioPropertyWildcardPropertyID,
  223707. deviceListenerProc);
  223708. stop (false);
  223709. juce_free (audioBuffer);
  223710. juce_free (tempInputBuffers);
  223711. juce_free (tempOutputBuffers);
  223712. juce_free (inputChannelInfo);
  223713. juce_free (outputChannelInfo);
  223714. delete inputDevice;
  223715. }
  223716. void allocateTempBuffers()
  223717. {
  223718. const int tempBufSize = bufferSize + 4;
  223719. juce_free (audioBuffer);
  223720. audioBuffer = (float*) juce_calloc ((numInputChans + numOutputChans) * tempBufSize * sizeof (float));
  223721. juce_free (tempInputBuffers);
  223722. tempInputBuffers = (float**) juce_calloc (sizeof (float*) * (numInputChans + 2));
  223723. juce_free (tempOutputBuffers);
  223724. tempOutputBuffers = (float**) juce_calloc (sizeof (float*) * (numOutputChans + 2));
  223725. int i, count = 0;
  223726. for (i = 0; i < numInputChans; ++i)
  223727. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  223728. for (i = 0; i < numOutputChans; ++i)
  223729. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  223730. }
  223731. // returns the number of actual available channels
  223732. void fillInChannelInfo (const bool input)
  223733. {
  223734. int chanNum = 0;
  223735. UInt32 size;
  223736. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  223737. {
  223738. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  223739. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  223740. {
  223741. const int numStreams = bufList->mNumberBuffers;
  223742. for (int i = 0; i < numStreams; ++i)
  223743. {
  223744. const AudioBuffer& b = bufList->mBuffers[i];
  223745. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  223746. {
  223747. String name;
  223748. {
  223749. uint8 channelName [256];
  223750. zerostruct (channelName);
  223751. UInt32 nameSize = sizeof (channelName);
  223752. if (AudioDeviceGetProperty (deviceID, chanNum + 1, input, kAudioDevicePropertyChannelName,
  223753. &nameSize, &channelName) == noErr)
  223754. name = String::fromUTF8 (channelName, nameSize);
  223755. }
  223756. if (input)
  223757. {
  223758. if (activeInputChans[chanNum])
  223759. {
  223760. inputChannelInfo [numInputChannelInfos].streamNum = i;
  223761. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  223762. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  223763. ++numInputChannelInfos;
  223764. }
  223765. if (name.isEmpty())
  223766. name << "Input " << (chanNum + 1);
  223767. inChanNames.add (name);
  223768. }
  223769. else
  223770. {
  223771. if (activeOutputChans[chanNum])
  223772. {
  223773. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  223774. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  223775. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  223776. ++numOutputChannelInfos;
  223777. }
  223778. if (name.isEmpty())
  223779. name << "Output " << (chanNum + 1);
  223780. outChanNames.add (name);
  223781. }
  223782. ++chanNum;
  223783. }
  223784. }
  223785. }
  223786. juce_free (bufList);
  223787. }
  223788. }
  223789. void updateDetailsFromDevice()
  223790. {
  223791. stopTimer();
  223792. if (deviceID == 0)
  223793. return;
  223794. const ScopedLock sl (callbackLock);
  223795. Float64 sr;
  223796. UInt32 size = sizeof (Float64);
  223797. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  223798. sampleRate = sr;
  223799. UInt32 framesPerBuf;
  223800. size = sizeof (framesPerBuf);
  223801. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  223802. {
  223803. bufferSize = framesPerBuf;
  223804. allocateTempBuffers();
  223805. }
  223806. bufferSizes.clear();
  223807. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  223808. {
  223809. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  223810. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  223811. {
  223812. bufferSizes.add ((int) ranges[0].mMinimum);
  223813. for (int i = 32; i < 8192; i += 32)
  223814. {
  223815. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  223816. {
  223817. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  223818. {
  223819. bufferSizes.addIfNotAlreadyThere (i);
  223820. break;
  223821. }
  223822. }
  223823. }
  223824. if (bufferSize > 0)
  223825. bufferSizes.addIfNotAlreadyThere (bufferSize);
  223826. }
  223827. juce_free (ranges);
  223828. }
  223829. if (bufferSizes.size() == 0 && bufferSize > 0)
  223830. bufferSizes.add (bufferSize);
  223831. sampleRates.clear();
  223832. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  223833. String rates;
  223834. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  223835. {
  223836. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  223837. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  223838. {
  223839. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  223840. {
  223841. bool ok = false;
  223842. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  223843. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  223844. ok = true;
  223845. if (ok)
  223846. {
  223847. sampleRates.add (possibleRates[i]);
  223848. rates << possibleRates[i] << T(" ");
  223849. }
  223850. }
  223851. }
  223852. juce_free (ranges);
  223853. }
  223854. if (sampleRates.size() == 0 && sampleRate > 0)
  223855. {
  223856. sampleRates.add (sampleRate);
  223857. rates << sampleRate;
  223858. }
  223859. log (T("sr: ") + rates);
  223860. inputLatency = 0;
  223861. outputLatency = 0;
  223862. UInt32 lat;
  223863. size = sizeof (UInt32);
  223864. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  223865. inputLatency = (int) lat;
  223866. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  223867. outputLatency = (int) lat;
  223868. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  223869. inChanNames.clear();
  223870. outChanNames.clear();
  223871. juce_free (inputChannelInfo);
  223872. inputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numInputChans + 2));
  223873. numInputChannelInfos = 0;
  223874. juce_free (outputChannelInfo);
  223875. outputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numOutputChans + 2));
  223876. numOutputChannelInfos = 0;
  223877. fillInChannelInfo (true);
  223878. fillInChannelInfo (false);
  223879. }
  223880. const StringArray getSources (bool input)
  223881. {
  223882. StringArray s;
  223883. int num = 0;
  223884. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  223885. if (types != 0)
  223886. {
  223887. for (int i = 0; i < num; ++i)
  223888. {
  223889. AudioValueTranslation avt;
  223890. char buffer[256];
  223891. avt.mInputData = (void*) &(types[i]);
  223892. avt.mInputDataSize = sizeof (UInt32);
  223893. avt.mOutputData = buffer;
  223894. avt.mOutputDataSize = 256;
  223895. UInt32 transSize = sizeof (avt);
  223896. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  223897. {
  223898. DBG (buffer);
  223899. s.add (buffer);
  223900. }
  223901. }
  223902. juce_free (types);
  223903. }
  223904. return s;
  223905. }
  223906. int getCurrentSourceIndex (bool input) const
  223907. {
  223908. OSType currentSourceID = 0;
  223909. UInt32 size = 0;
  223910. int result = -1;
  223911. if (deviceID != 0
  223912. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  223913. {
  223914. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  223915. {
  223916. int num = 0;
  223917. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  223918. if (types != 0)
  223919. {
  223920. for (int i = 0; i < num; ++i)
  223921. {
  223922. if (types[num] == currentSourceID)
  223923. {
  223924. result = i;
  223925. break;
  223926. }
  223927. }
  223928. juce_free (types);
  223929. }
  223930. }
  223931. }
  223932. return result;
  223933. }
  223934. void setCurrentSourceIndex (int index, bool input)
  223935. {
  223936. if (deviceID != 0)
  223937. {
  223938. int num = 0;
  223939. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  223940. if (types != 0)
  223941. {
  223942. if (((unsigned int) index) < (unsigned int) num)
  223943. {
  223944. OSType typeId = types[index];
  223945. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  223946. }
  223947. juce_free (types);
  223948. }
  223949. }
  223950. }
  223951. const String reopen (const BitArray& inputChannels,
  223952. const BitArray& outputChannels,
  223953. double newSampleRate,
  223954. int bufferSizeSamples)
  223955. {
  223956. error = String::empty;
  223957. log ("CoreAudio reopen");
  223958. callbacksAllowed = false;
  223959. stopTimer();
  223960. stop (false);
  223961. activeInputChans = inputChannels;
  223962. activeOutputChans = outputChannels;
  223963. activeInputChans.setRange (inChanNames.size(),
  223964. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  223965. false);
  223966. activeOutputChans.setRange (outChanNames.size(),
  223967. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  223968. false);
  223969. numInputChans = activeInputChans.countNumberOfSetBits();
  223970. numOutputChans = activeOutputChans.countNumberOfSetBits();
  223971. // set sample rate
  223972. Float64 sr = newSampleRate;
  223973. UInt32 size = sizeof (sr);
  223974. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  223975. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  223976. // change buffer size
  223977. UInt32 framesPerBuf = bufferSizeSamples;
  223978. size = sizeof (framesPerBuf);
  223979. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  223980. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  223981. // wait for the changes to happen (on some devices)
  223982. int i = 30;
  223983. while (--i >= 0)
  223984. {
  223985. updateDetailsFromDevice();
  223986. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  223987. break;
  223988. Thread::sleep (100);
  223989. }
  223990. if (i < 0)
  223991. error = "Couldn't change sample rate/buffer size";
  223992. if (sampleRates.size() == 0)
  223993. error = "Device has no available sample-rates";
  223994. if (bufferSizes.size() == 0)
  223995. error = "Device has no available buffer-sizes";
  223996. if (inputDevice != 0 && error.isEmpty())
  223997. error = inputDevice->reopen (inputChannels,
  223998. outputChannels,
  223999. newSampleRate,
  224000. bufferSizeSamples);
  224001. callbacksAllowed = true;
  224002. return error;
  224003. }
  224004. bool start (AudioIODeviceCallback* cb)
  224005. {
  224006. if (! started)
  224007. {
  224008. callback = 0;
  224009. if (deviceID != 0)
  224010. {
  224011. #if MACOS_10_4_OR_EARLIER
  224012. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  224013. #else
  224014. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, (void*) this, &audioProcID)))
  224015. #endif
  224016. {
  224017. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  224018. {
  224019. started = true;
  224020. }
  224021. else
  224022. {
  224023. #if MACOS_10_4_OR_EARLIER
  224024. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  224025. #else
  224026. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  224027. audioProcID = 0;
  224028. #endif
  224029. }
  224030. }
  224031. }
  224032. }
  224033. if (started)
  224034. {
  224035. const ScopedLock sl (callbackLock);
  224036. callback = cb;
  224037. }
  224038. if (inputDevice != 0)
  224039. return started && inputDevice->start (cb);
  224040. else
  224041. return started;
  224042. }
  224043. void stop (bool leaveInterruptRunning)
  224044. {
  224045. callbackLock.enter();
  224046. callback = 0;
  224047. callbackLock.exit();
  224048. if (started
  224049. && (deviceID != 0)
  224050. && ! leaveInterruptRunning)
  224051. {
  224052. OK (AudioDeviceStop (deviceID, audioIOProc));
  224053. #if MACOS_10_4_OR_EARLIER
  224054. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  224055. #else
  224056. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  224057. audioProcID = 0;
  224058. #endif
  224059. started = false;
  224060. callbackLock.enter();
  224061. callbackLock.exit();
  224062. // wait until it's definately stopped calling back..
  224063. for (int i = 40; --i >= 0;)
  224064. {
  224065. Thread::sleep (50);
  224066. UInt32 running = 0;
  224067. UInt32 size = sizeof (running);
  224068. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  224069. if (running == 0)
  224070. break;
  224071. }
  224072. callbackLock.enter();
  224073. callbackLock.exit();
  224074. }
  224075. if (inputDevice != 0)
  224076. inputDevice->stop (leaveInterruptRunning);
  224077. }
  224078. double getSampleRate() const
  224079. {
  224080. return sampleRate;
  224081. }
  224082. int getBufferSize() const
  224083. {
  224084. return bufferSize;
  224085. }
  224086. void audioCallback (const AudioBufferList* inInputData,
  224087. AudioBufferList* outOutputData)
  224088. {
  224089. int i;
  224090. const ScopedLock sl (callbackLock);
  224091. if (callback != 0)
  224092. {
  224093. if (inputDevice == 0)
  224094. {
  224095. for (i = numInputChans; --i >= 0;)
  224096. {
  224097. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  224098. float* dest = tempInputBuffers [i];
  224099. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  224100. + info.dataOffsetSamples;
  224101. const int stride = info.dataStrideSamples;
  224102. if (stride != 0) // if this is zero, info is invalid
  224103. {
  224104. for (int j = bufferSize; --j >= 0;)
  224105. {
  224106. *dest++ = *src;
  224107. src += stride;
  224108. }
  224109. }
  224110. }
  224111. }
  224112. if (! isSlaveDevice)
  224113. {
  224114. if (inputDevice == 0)
  224115. {
  224116. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  224117. numInputChans,
  224118. tempOutputBuffers,
  224119. numOutputChans,
  224120. bufferSize);
  224121. }
  224122. else
  224123. {
  224124. jassert (inputDevice->bufferSize == bufferSize);
  224125. // Sometimes the two linked devices seem to get their callbacks in
  224126. // parallel, so we need to lock both devices to stop the input data being
  224127. // changed while inside our callback..
  224128. const ScopedLock sl (inputDevice->callbackLock);
  224129. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  224130. inputDevice->numInputChans,
  224131. tempOutputBuffers,
  224132. numOutputChans,
  224133. bufferSize);
  224134. }
  224135. for (i = numOutputChans; --i >= 0;)
  224136. {
  224137. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  224138. const float* src = tempOutputBuffers [i];
  224139. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  224140. + info.dataOffsetSamples;
  224141. const int stride = info.dataStrideSamples;
  224142. if (stride != 0) // if this is zero, info is invalid
  224143. {
  224144. for (int j = bufferSize; --j >= 0;)
  224145. {
  224146. *dest = *src++;
  224147. dest += stride;
  224148. }
  224149. }
  224150. }
  224151. }
  224152. }
  224153. else
  224154. {
  224155. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  224156. {
  224157. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  224158. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  224159. + info.dataOffsetSamples;
  224160. const int stride = info.dataStrideSamples;
  224161. if (stride != 0) // if this is zero, info is invalid
  224162. {
  224163. for (int j = bufferSize; --j >= 0;)
  224164. {
  224165. *dest = 0.0f;
  224166. dest += stride;
  224167. }
  224168. }
  224169. }
  224170. }
  224171. }
  224172. // called by callbacks
  224173. void deviceDetailsChanged()
  224174. {
  224175. if (callbacksAllowed)
  224176. startTimer (100);
  224177. }
  224178. void timerCallback()
  224179. {
  224180. stopTimer();
  224181. log ("CoreAudio device changed callback");
  224182. const double oldSampleRate = sampleRate;
  224183. const int oldBufferSize = bufferSize;
  224184. updateDetailsFromDevice();
  224185. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  224186. {
  224187. callbacksAllowed = false;
  224188. stop (false);
  224189. updateDetailsFromDevice();
  224190. callbacksAllowed = true;
  224191. }
  224192. }
  224193. CoreAudioInternal* getRelatedDevice() const
  224194. {
  224195. UInt32 size = 0;
  224196. CoreAudioInternal* result = 0;
  224197. if (deviceID != 0
  224198. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  224199. && size > 0)
  224200. {
  224201. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  224202. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  224203. {
  224204. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  224205. {
  224206. if (devs[i] != deviceID && devs[i] != 0)
  224207. {
  224208. result = new CoreAudioInternal (devs[i]);
  224209. if (result->error.isEmpty())
  224210. {
  224211. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  224212. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  224213. if (thisIsInput != otherIsInput
  224214. || (inChanNames.size() + outChanNames.size() == 0)
  224215. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  224216. break;
  224217. }
  224218. deleteAndZero (result);
  224219. }
  224220. }
  224221. }
  224222. juce_free (devs);
  224223. }
  224224. return result;
  224225. }
  224226. juce_UseDebuggingNewOperator
  224227. String error;
  224228. int inputLatency, outputLatency;
  224229. BitArray activeInputChans, activeOutputChans;
  224230. StringArray inChanNames, outChanNames;
  224231. Array <double> sampleRates;
  224232. Array <int> bufferSizes;
  224233. AudioIODeviceCallback* callback;
  224234. #if ! MACOS_10_4_OR_EARLIER
  224235. AudioDeviceIOProcID audioProcID;
  224236. #endif
  224237. CoreAudioInternal* inputDevice;
  224238. bool isSlaveDevice;
  224239. private:
  224240. CriticalSection callbackLock;
  224241. AudioDeviceID deviceID;
  224242. bool started;
  224243. double sampleRate;
  224244. int bufferSize;
  224245. float* audioBuffer;
  224246. int numInputChans, numOutputChans;
  224247. bool callbacksAllowed;
  224248. struct CallbackDetailsForChannel
  224249. {
  224250. int streamNum;
  224251. int dataOffsetSamples;
  224252. int dataStrideSamples;
  224253. };
  224254. int numInputChannelInfos, numOutputChannelInfos;
  224255. CallbackDetailsForChannel* inputChannelInfo;
  224256. CallbackDetailsForChannel* outputChannelInfo;
  224257. float** tempInputBuffers;
  224258. float** tempOutputBuffers;
  224259. CoreAudioInternal (const CoreAudioInternal&);
  224260. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  224261. static OSStatus audioIOProc (AudioDeviceID inDevice,
  224262. const AudioTimeStamp* inNow,
  224263. const AudioBufferList* inInputData,
  224264. const AudioTimeStamp* inInputTime,
  224265. AudioBufferList* outOutputData,
  224266. const AudioTimeStamp* inOutputTime,
  224267. void* device)
  224268. {
  224269. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  224270. return noErr;
  224271. }
  224272. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  224273. UInt32 inLine,
  224274. Boolean isInput,
  224275. AudioDevicePropertyID inPropertyID,
  224276. void* inClientData)
  224277. {
  224278. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  224279. switch (inPropertyID)
  224280. {
  224281. case kAudioDevicePropertyBufferSize:
  224282. case kAudioDevicePropertyBufferFrameSize:
  224283. case kAudioDevicePropertyNominalSampleRate:
  224284. case kAudioDevicePropertyStreamFormat:
  224285. case kAudioDevicePropertyDeviceIsAlive:
  224286. intern->deviceDetailsChanged();
  224287. break;
  224288. case kAudioDevicePropertyBufferSizeRange:
  224289. case kAudioDevicePropertyVolumeScalar:
  224290. case kAudioDevicePropertyMute:
  224291. case kAudioDevicePropertyPlayThru:
  224292. case kAudioDevicePropertyDataSource:
  224293. case kAudioDevicePropertyDeviceIsRunning:
  224294. break;
  224295. }
  224296. return noErr;
  224297. }
  224298. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  224299. {
  224300. OSType* types = 0;
  224301. UInt32 size = 0;
  224302. num = 0;
  224303. if (deviceID != 0
  224304. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  224305. {
  224306. types = (OSType*) juce_calloc (size);
  224307. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  224308. {
  224309. num = size / sizeof (OSType);
  224310. }
  224311. else
  224312. {
  224313. juce_free (types);
  224314. types = 0;
  224315. }
  224316. }
  224317. return types;
  224318. }
  224319. };
  224320. class CoreAudioIODevice : public AudioIODevice
  224321. {
  224322. public:
  224323. CoreAudioIODevice (const String& deviceName,
  224324. AudioDeviceID inputDeviceId,
  224325. const int inputIndex_,
  224326. AudioDeviceID outputDeviceId,
  224327. const int outputIndex_)
  224328. : AudioIODevice (deviceName, "CoreAudio"),
  224329. inputIndex (inputIndex_),
  224330. outputIndex (outputIndex_),
  224331. isOpen_ (false),
  224332. isStarted (false)
  224333. {
  224334. internal = 0;
  224335. CoreAudioInternal* device = 0;
  224336. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  224337. {
  224338. jassert (inputDeviceId != 0);
  224339. device = new CoreAudioInternal (inputDeviceId);
  224340. lastError = device->error;
  224341. if (lastError.isNotEmpty())
  224342. deleteAndZero (device);
  224343. }
  224344. else
  224345. {
  224346. device = new CoreAudioInternal (outputDeviceId);
  224347. lastError = device->error;
  224348. if (lastError.isNotEmpty())
  224349. {
  224350. deleteAndZero (device);
  224351. }
  224352. else if (inputDeviceId != 0)
  224353. {
  224354. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  224355. lastError = device->error;
  224356. if (lastError.isNotEmpty())
  224357. {
  224358. delete secondDevice;
  224359. }
  224360. else
  224361. {
  224362. device->inputDevice = secondDevice;
  224363. secondDevice->isSlaveDevice = true;
  224364. }
  224365. }
  224366. }
  224367. internal = device;
  224368. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  224369. hardwareListenerProc, internal);
  224370. }
  224371. ~CoreAudioIODevice()
  224372. {
  224373. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  224374. hardwareListenerProc);
  224375. delete internal;
  224376. }
  224377. const StringArray getOutputChannelNames()
  224378. {
  224379. return internal->outChanNames;
  224380. }
  224381. const StringArray getInputChannelNames()
  224382. {
  224383. if (internal->inputDevice != 0)
  224384. return internal->inputDevice->inChanNames;
  224385. else
  224386. return internal->inChanNames;
  224387. }
  224388. int getNumSampleRates()
  224389. {
  224390. return internal->sampleRates.size();
  224391. }
  224392. double getSampleRate (int index)
  224393. {
  224394. return internal->sampleRates [index];
  224395. }
  224396. int getNumBufferSizesAvailable()
  224397. {
  224398. return internal->bufferSizes.size();
  224399. }
  224400. int getBufferSizeSamples (int index)
  224401. {
  224402. return internal->bufferSizes [index];
  224403. }
  224404. int getDefaultBufferSize()
  224405. {
  224406. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  224407. if (getBufferSizeSamples(i) >= 512)
  224408. return getBufferSizeSamples(i);
  224409. return 512;
  224410. }
  224411. const String open (const BitArray& inputChannels,
  224412. const BitArray& outputChannels,
  224413. double sampleRate,
  224414. int bufferSizeSamples)
  224415. {
  224416. isOpen_ = true;
  224417. if (bufferSizeSamples <= 0)
  224418. bufferSizeSamples = getDefaultBufferSize();
  224419. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  224420. lastError = internal->error;
  224421. return lastError;
  224422. }
  224423. void close()
  224424. {
  224425. isOpen_ = false;
  224426. }
  224427. bool isOpen()
  224428. {
  224429. return isOpen_;
  224430. }
  224431. int getCurrentBufferSizeSamples()
  224432. {
  224433. return internal != 0 ? internal->getBufferSize() : 512;
  224434. }
  224435. double getCurrentSampleRate()
  224436. {
  224437. return internal != 0 ? internal->getSampleRate() : 0;
  224438. }
  224439. int getCurrentBitDepth()
  224440. {
  224441. return 32; // no way to find out, so just assume it's high..
  224442. }
  224443. const BitArray getActiveOutputChannels() const
  224444. {
  224445. return internal != 0 ? internal->activeOutputChans : BitArray();
  224446. }
  224447. const BitArray getActiveInputChannels() const
  224448. {
  224449. BitArray chans;
  224450. if (internal != 0)
  224451. {
  224452. chans = internal->activeInputChans;
  224453. if (internal->inputDevice != 0)
  224454. chans.orWith (internal->inputDevice->activeInputChans);
  224455. }
  224456. return chans;
  224457. }
  224458. int getOutputLatencyInSamples()
  224459. {
  224460. if (internal == 0)
  224461. return 0;
  224462. // this seems like a good guess at getting the latency right - comparing
  224463. // this with a round-trip measurement, it gets it to within a few millisecs
  224464. // for the built-in mac soundcard
  224465. return internal->outputLatency + internal->getBufferSize() * 2;
  224466. }
  224467. int getInputLatencyInSamples()
  224468. {
  224469. if (internal == 0)
  224470. return 0;
  224471. return internal->inputLatency + internal->getBufferSize() * 2;
  224472. }
  224473. void start (AudioIODeviceCallback* callback)
  224474. {
  224475. if (internal != 0 && ! isStarted)
  224476. {
  224477. if (callback != 0)
  224478. callback->audioDeviceAboutToStart (this);
  224479. isStarted = true;
  224480. internal->start (callback);
  224481. }
  224482. }
  224483. void stop()
  224484. {
  224485. if (isStarted && internal != 0)
  224486. {
  224487. AudioIODeviceCallback* const lastCallback = internal->callback;
  224488. isStarted = false;
  224489. internal->stop (true);
  224490. if (lastCallback != 0)
  224491. lastCallback->audioDeviceStopped();
  224492. }
  224493. }
  224494. bool isPlaying()
  224495. {
  224496. if (internal->callback == 0)
  224497. isStarted = false;
  224498. return isStarted;
  224499. }
  224500. const String getLastError()
  224501. {
  224502. return lastError;
  224503. }
  224504. int inputIndex, outputIndex;
  224505. juce_UseDebuggingNewOperator
  224506. private:
  224507. CoreAudioInternal* internal;
  224508. bool isOpen_, isStarted;
  224509. String lastError;
  224510. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  224511. {
  224512. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  224513. switch (inPropertyID)
  224514. {
  224515. case kAudioHardwarePropertyDevices:
  224516. intern->deviceDetailsChanged();
  224517. break;
  224518. case kAudioHardwarePropertyDefaultOutputDevice:
  224519. case kAudioHardwarePropertyDefaultInputDevice:
  224520. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  224521. break;
  224522. }
  224523. return noErr;
  224524. }
  224525. CoreAudioIODevice (const CoreAudioIODevice&);
  224526. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  224527. };
  224528. class CoreAudioIODeviceType : public AudioIODeviceType
  224529. {
  224530. public:
  224531. CoreAudioIODeviceType()
  224532. : AudioIODeviceType (T("CoreAudio")),
  224533. hasScanned (false)
  224534. {
  224535. }
  224536. ~CoreAudioIODeviceType()
  224537. {
  224538. }
  224539. void scanForDevices()
  224540. {
  224541. hasScanned = true;
  224542. inputDeviceNames.clear();
  224543. outputDeviceNames.clear();
  224544. inputIds.clear();
  224545. outputIds.clear();
  224546. UInt32 size;
  224547. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  224548. {
  224549. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  224550. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  224551. {
  224552. static bool alreadyLogged = false;
  224553. const int num = size / sizeof (AudioDeviceID);
  224554. for (int i = 0; i < num; ++i)
  224555. {
  224556. char name[1024];
  224557. size = sizeof (name);
  224558. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  224559. {
  224560. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  224561. if (! alreadyLogged)
  224562. log (T("CoreAudio device: ") + nameString);
  224563. const int numIns = getNumChannels (devs[i], true);
  224564. const int numOuts = getNumChannels (devs[i], false);
  224565. if (numIns > 0)
  224566. {
  224567. inputDeviceNames.add (nameString);
  224568. inputIds.add (devs[i]);
  224569. }
  224570. if (numOuts > 0)
  224571. {
  224572. outputDeviceNames.add (nameString);
  224573. outputIds.add (devs[i]);
  224574. }
  224575. }
  224576. }
  224577. alreadyLogged = true;
  224578. }
  224579. juce_free (devs);
  224580. }
  224581. inputDeviceNames.appendNumbersToDuplicates (false, true);
  224582. outputDeviceNames.appendNumbersToDuplicates (false, true);
  224583. }
  224584. const StringArray getDeviceNames (const bool wantInputNames) const
  224585. {
  224586. jassert (hasScanned); // need to call scanForDevices() before doing this
  224587. if (wantInputNames)
  224588. return inputDeviceNames;
  224589. else
  224590. return outputDeviceNames;
  224591. }
  224592. int getDefaultDeviceIndex (const bool forInput) const
  224593. {
  224594. jassert (hasScanned); // need to call scanForDevices() before doing this
  224595. AudioDeviceID deviceID;
  224596. UInt32 size = sizeof (deviceID);
  224597. // if they're asking for any input channels at all, use the default input, so we
  224598. // get the built-in mic rather than the built-in output with no inputs..
  224599. if (AudioHardwareGetProperty (forInput ? kAudioHardwarePropertyDefaultInputDevice
  224600. : kAudioHardwarePropertyDefaultOutputDevice,
  224601. &size, &deviceID) == noErr)
  224602. {
  224603. if (forInput)
  224604. {
  224605. for (int i = inputIds.size(); --i >= 0;)
  224606. if (inputIds[i] == deviceID)
  224607. return i;
  224608. }
  224609. else
  224610. {
  224611. for (int i = outputIds.size(); --i >= 0;)
  224612. if (outputIds[i] == deviceID)
  224613. return i;
  224614. }
  224615. }
  224616. return 0;
  224617. }
  224618. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  224619. {
  224620. jassert (hasScanned); // need to call scanForDevices() before doing this
  224621. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  224622. if (d == 0)
  224623. return -1;
  224624. return asInput ? d->inputIndex
  224625. : d->outputIndex;
  224626. }
  224627. bool hasSeparateInputsAndOutputs() const { return true; }
  224628. AudioIODevice* createDevice (const String& outputDeviceName,
  224629. const String& inputDeviceName)
  224630. {
  224631. jassert (hasScanned); // need to call scanForDevices() before doing this
  224632. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  224633. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  224634. String deviceName (outputDeviceName);
  224635. if (deviceName.isEmpty())
  224636. deviceName = inputDeviceName;
  224637. if (index >= 0)
  224638. return new CoreAudioIODevice (deviceName,
  224639. inputIds [inputIndex],
  224640. inputIndex,
  224641. outputIds [outputIndex],
  224642. outputIndex);
  224643. return 0;
  224644. }
  224645. juce_UseDebuggingNewOperator
  224646. private:
  224647. StringArray inputDeviceNames, outputDeviceNames;
  224648. Array <AudioDeviceID> inputIds, outputIds;
  224649. bool hasScanned;
  224650. static int getNumChannels (AudioDeviceID deviceID, bool input)
  224651. {
  224652. int total = 0;
  224653. UInt32 size;
  224654. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  224655. {
  224656. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  224657. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  224658. {
  224659. const int numStreams = bufList->mNumberBuffers;
  224660. for (int i = 0; i < numStreams; ++i)
  224661. {
  224662. const AudioBuffer& b = bufList->mBuffers[i];
  224663. total += b.mNumberChannels;
  224664. }
  224665. }
  224666. juce_free (bufList);
  224667. }
  224668. return total;
  224669. }
  224670. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  224671. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  224672. };
  224673. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  224674. {
  224675. return new CoreAudioIODeviceType();
  224676. }
  224677. #undef log
  224678. #endif
  224679. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  224680. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  224681. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224682. // compiled on its own).
  224683. #ifdef JUCE_INCLUDED_FILE
  224684. #undef log
  224685. #define log(a) Logger::writeToLog(a)
  224686. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  224687. {
  224688. if (err == noErr)
  224689. return true;
  224690. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  224691. jassertfalse
  224692. return false;
  224693. }
  224694. #undef OK
  224695. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  224696. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  224697. {
  224698. String result;
  224699. CFStringRef str = 0;
  224700. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  224701. if (str != 0)
  224702. {
  224703. result = PlatformUtilities::cfStringToJuceString (str);
  224704. CFRelease (str);
  224705. str = 0;
  224706. }
  224707. MIDIEntityRef entity = 0;
  224708. MIDIEndpointGetEntity (endpoint, &entity);
  224709. if (entity == 0)
  224710. return result; // probably virtual
  224711. if (result.isEmpty())
  224712. {
  224713. // endpoint name has zero length - try the entity
  224714. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  224715. if (str != 0)
  224716. {
  224717. result += PlatformUtilities::cfStringToJuceString (str);
  224718. CFRelease (str);
  224719. str = 0;
  224720. }
  224721. }
  224722. // now consider the device's name
  224723. MIDIDeviceRef device = 0;
  224724. MIDIEntityGetDevice (entity, &device);
  224725. if (device == 0)
  224726. return result;
  224727. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  224728. if (str != 0)
  224729. {
  224730. const String s (PlatformUtilities::cfStringToJuceString (str));
  224731. CFRelease (str);
  224732. // if an external device has only one entity, throw away
  224733. // the endpoint name and just use the device name
  224734. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  224735. {
  224736. result = s;
  224737. }
  224738. else if (! result.startsWithIgnoreCase (s))
  224739. {
  224740. // prepend the device name to the entity name
  224741. result = (s + T(" ") + result).trimEnd();
  224742. }
  224743. }
  224744. return result;
  224745. }
  224746. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  224747. {
  224748. String result;
  224749. // Does the endpoint have connections?
  224750. CFDataRef connections = 0;
  224751. int numConnections = 0;
  224752. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  224753. if (connections != 0)
  224754. {
  224755. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  224756. if (numConnections > 0)
  224757. {
  224758. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  224759. for (int i = 0; i < numConnections; ++i, ++pid)
  224760. {
  224761. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  224762. MIDIObjectRef connObject;
  224763. MIDIObjectType connObjectType;
  224764. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  224765. if (err == noErr)
  224766. {
  224767. String s;
  224768. if (connObjectType == kMIDIObjectType_ExternalSource
  224769. || connObjectType == kMIDIObjectType_ExternalDestination)
  224770. {
  224771. // Connected to an external device's endpoint (10.3 and later).
  224772. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  224773. }
  224774. else
  224775. {
  224776. // Connected to an external device (10.2) (or something else, catch-all)
  224777. CFStringRef str = 0;
  224778. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  224779. if (str != 0)
  224780. {
  224781. s = PlatformUtilities::cfStringToJuceString (str);
  224782. CFRelease (str);
  224783. }
  224784. }
  224785. if (s.isNotEmpty())
  224786. {
  224787. if (result.isNotEmpty())
  224788. result += (", ");
  224789. result += s;
  224790. }
  224791. }
  224792. }
  224793. }
  224794. CFRelease (connections);
  224795. }
  224796. if (result.isNotEmpty())
  224797. return result;
  224798. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  224799. return getEndpointName (endpoint, false);
  224800. }
  224801. const StringArray MidiOutput::getDevices()
  224802. {
  224803. StringArray s;
  224804. const ItemCount num = MIDIGetNumberOfDestinations();
  224805. for (ItemCount i = 0; i < num; ++i)
  224806. {
  224807. MIDIEndpointRef dest = MIDIGetDestination (i);
  224808. if (dest != 0)
  224809. {
  224810. String name (getConnectedEndpointName (dest));
  224811. if (name.isEmpty())
  224812. name = "<error>";
  224813. s.add (name);
  224814. }
  224815. else
  224816. {
  224817. s.add ("<error>");
  224818. }
  224819. }
  224820. return s;
  224821. }
  224822. int MidiOutput::getDefaultDeviceIndex()
  224823. {
  224824. return 0;
  224825. }
  224826. static MIDIClientRef globalMidiClient;
  224827. static bool hasGlobalClientBeenCreated = false;
  224828. static bool makeSureClientExists()
  224829. {
  224830. if (! hasGlobalClientBeenCreated)
  224831. {
  224832. String name (T("JUCE"));
  224833. if (JUCEApplication::getInstance() != 0)
  224834. name = JUCEApplication::getInstance()->getApplicationName();
  224835. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  224836. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  224837. CFRelease (appName);
  224838. }
  224839. return hasGlobalClientBeenCreated;
  224840. }
  224841. struct MidiPortAndEndpoint
  224842. {
  224843. MIDIPortRef port;
  224844. MIDIEndpointRef endPoint;
  224845. };
  224846. MidiOutput* MidiOutput::openDevice (int index)
  224847. {
  224848. MidiOutput* mo = 0;
  224849. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  224850. {
  224851. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  224852. CFStringRef pname;
  224853. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  224854. {
  224855. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  224856. if (makeSureClientExists())
  224857. {
  224858. MIDIPortRef port;
  224859. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  224860. {
  224861. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  224862. mpe->port = port;
  224863. mpe->endPoint = endPoint;
  224864. mo = new MidiOutput();
  224865. mo->internal = (void*)mpe;
  224866. }
  224867. }
  224868. CFRelease (pname);
  224869. }
  224870. }
  224871. return mo;
  224872. }
  224873. MidiOutput::~MidiOutput()
  224874. {
  224875. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  224876. MIDIPortDispose (mpe->port);
  224877. delete mpe;
  224878. }
  224879. void MidiOutput::reset()
  224880. {
  224881. }
  224882. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  224883. {
  224884. return false;
  224885. }
  224886. void MidiOutput::setVolume (float leftVol, float rightVol)
  224887. {
  224888. }
  224889. void MidiOutput::sendMessageNow (const MidiMessage& message)
  224890. {
  224891. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  224892. if (message.isSysEx())
  224893. {
  224894. const int maxPacketSize = 256;
  224895. int pos = 0, bytesLeft = message.getRawDataSize();
  224896. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  224897. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 * numPackets + message.getRawDataSize());
  224898. packets->numPackets = numPackets;
  224899. MIDIPacket* p = packets->packet;
  224900. for (int i = 0; i < numPackets; ++i)
  224901. {
  224902. p->timeStamp = 0;
  224903. p->length = jmin (maxPacketSize, bytesLeft);
  224904. memcpy (p->data, message.getRawData() + pos, p->length);
  224905. pos += p->length;
  224906. bytesLeft -= p->length;
  224907. p = MIDIPacketNext (p);
  224908. }
  224909. MIDISend (mpe->port, mpe->endPoint, packets);
  224910. juce_free (packets);
  224911. }
  224912. else
  224913. {
  224914. MIDIPacketList packets;
  224915. packets.numPackets = 1;
  224916. packets.packet[0].timeStamp = 0;
  224917. packets.packet[0].length = message.getRawDataSize();
  224918. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  224919. MIDISend (mpe->port, mpe->endPoint, &packets);
  224920. }
  224921. }
  224922. const StringArray MidiInput::getDevices()
  224923. {
  224924. StringArray s;
  224925. const ItemCount num = MIDIGetNumberOfSources();
  224926. for (ItemCount i = 0; i < num; ++i)
  224927. {
  224928. MIDIEndpointRef source = MIDIGetSource (i);
  224929. if (source != 0)
  224930. {
  224931. String name (getConnectedEndpointName (source));
  224932. if (name.isEmpty())
  224933. name = "<error>";
  224934. s.add (name);
  224935. }
  224936. else
  224937. {
  224938. s.add ("<error>");
  224939. }
  224940. }
  224941. return s;
  224942. }
  224943. int MidiInput::getDefaultDeviceIndex()
  224944. {
  224945. return 0;
  224946. }
  224947. struct MidiPortAndCallback
  224948. {
  224949. MidiInput* input;
  224950. MIDIPortRef port;
  224951. MIDIEndpointRef endPoint;
  224952. MidiInputCallback* callback;
  224953. MemoryBlock pendingData;
  224954. int pendingBytes;
  224955. double pendingDataTime;
  224956. bool active;
  224957. };
  224958. static CriticalSection callbackLock;
  224959. static VoidArray activeCallbacks;
  224960. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  224961. {
  224962. if (*d == 0xf0)
  224963. {
  224964. mpe->pendingBytes = 0;
  224965. mpe->pendingDataTime = time;
  224966. }
  224967. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  224968. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  224969. uint8* dest = totalMessage + mpe->pendingBytes;
  224970. while (size > 0)
  224971. {
  224972. if (mpe->pendingBytes > 0 && *d >= 0x80)
  224973. {
  224974. if (*d >= 0xfa || *d == 0xf8)
  224975. {
  224976. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  224977. ++d;
  224978. --size;
  224979. }
  224980. else
  224981. {
  224982. if (*d == 0xf7)
  224983. {
  224984. *dest++ = *d++;
  224985. mpe->pendingBytes++;
  224986. --size;
  224987. }
  224988. break;
  224989. }
  224990. }
  224991. else
  224992. {
  224993. *dest++ = *d++;
  224994. mpe->pendingBytes++;
  224995. --size;
  224996. }
  224997. }
  224998. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  224999. {
  225000. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  225001. mpe->pendingBytes,
  225002. mpe->pendingDataTime));
  225003. mpe->pendingBytes = 0;
  225004. }
  225005. else
  225006. {
  225007. mpe->callback->handlePartialSysexMessage (mpe->input,
  225008. totalMessage,
  225009. mpe->pendingBytes,
  225010. mpe->pendingDataTime);
  225011. }
  225012. }
  225013. static void midiInputProc (const MIDIPacketList* pktlist,
  225014. void* readProcRefCon,
  225015. void* srcConnRefCon)
  225016. {
  225017. double time = Time::getMillisecondCounterHiRes() * 0.001;
  225018. const double originalTime = time;
  225019. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  225020. const ScopedLock sl (callbackLock);
  225021. if (activeCallbacks.contains (mpe) && mpe->active)
  225022. {
  225023. const MIDIPacket* packet = &pktlist->packet[0];
  225024. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  225025. {
  225026. const uint8* d = (const uint8*) (packet->data);
  225027. int size = packet->length;
  225028. while (size > 0)
  225029. {
  225030. time = originalTime;
  225031. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  225032. {
  225033. processSysex (mpe, d, size, time);
  225034. }
  225035. else
  225036. {
  225037. int used = 0;
  225038. const MidiMessage m (d, size, used, 0, time);
  225039. if (used <= 0)
  225040. {
  225041. jassertfalse // malformed midi message
  225042. break;
  225043. }
  225044. else
  225045. {
  225046. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  225047. }
  225048. size -= used;
  225049. d += used;
  225050. }
  225051. }
  225052. packet = MIDIPacketNext (packet);
  225053. }
  225054. }
  225055. }
  225056. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  225057. {
  225058. MidiInput* mi = 0;
  225059. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  225060. {
  225061. MIDIEndpointRef endPoint = MIDIGetSource (index);
  225062. if (endPoint != 0)
  225063. {
  225064. CFStringRef pname;
  225065. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225066. {
  225067. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  225068. if (makeSureClientExists())
  225069. {
  225070. MIDIPortRef port;
  225071. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  225072. mpe->active = false;
  225073. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  225074. {
  225075. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  225076. {
  225077. mpe->port = port;
  225078. mpe->endPoint = endPoint;
  225079. mpe->callback = callback;
  225080. mpe->pendingBytes = 0;
  225081. mpe->pendingData.ensureSize (128);
  225082. mi = new MidiInput (getDevices() [index]);
  225083. mpe->input = mi;
  225084. mi->internal = (void*) mpe;
  225085. const ScopedLock sl (callbackLock);
  225086. activeCallbacks.add (mpe);
  225087. }
  225088. else
  225089. {
  225090. OK (MIDIPortDispose (port));
  225091. delete mpe;
  225092. }
  225093. }
  225094. else
  225095. {
  225096. delete mpe;
  225097. }
  225098. }
  225099. }
  225100. CFRelease (pname);
  225101. }
  225102. }
  225103. return mi;
  225104. }
  225105. MidiInput::MidiInput (const String& name_)
  225106. : name (name_)
  225107. {
  225108. }
  225109. MidiInput::~MidiInput()
  225110. {
  225111. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225112. mpe->active = false;
  225113. callbackLock.enter();
  225114. activeCallbacks.removeValue (mpe);
  225115. callbackLock.exit();
  225116. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  225117. OK (MIDIPortDispose (mpe->port));
  225118. delete mpe;
  225119. }
  225120. void MidiInput::start()
  225121. {
  225122. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225123. const ScopedLock sl (callbackLock);
  225124. mpe->active = true;
  225125. }
  225126. void MidiInput::stop()
  225127. {
  225128. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225129. const ScopedLock sl (callbackLock);
  225130. mpe->active = false;
  225131. }
  225132. #undef log
  225133. #endif
  225134. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  225135. /********* Start of inlined file: juce_mac_CameraDevice.mm *********/
  225136. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225137. // compiled on its own).
  225138. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME && JUCE_USE_CAMERA
  225139. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  225140. class QTCameraDeviceInteral;
  225141. END_JUCE_NAMESPACE
  225142. @interface QTCaptureCallbackDelegate : NSObject
  225143. {
  225144. @public
  225145. CameraDevice* owner;
  225146. QTCameraDeviceInteral* internal;
  225147. Time* firstRecordedTime;
  225148. }
  225149. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  225150. - (void) dealloc;
  225151. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  225152. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  225153. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225154. fromConnection: (QTCaptureConnection*) connection;
  225155. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  225156. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225157. fromConnection: (QTCaptureConnection*) connection;
  225158. @end
  225159. BEGIN_JUCE_NAMESPACE
  225160. class QTCameraDeviceInteral
  225161. {
  225162. public:
  225163. QTCameraDeviceInteral (CameraDevice* owner, int index)
  225164. {
  225165. const ScopedAutoReleasePool pool;
  225166. session = [[QTCaptureSession alloc] init];
  225167. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  225168. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  225169. input = 0;
  225170. fileOutput = 0;
  225171. imageOutput = 0;
  225172. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  225173. internalDev: this];
  225174. NSError* err = 0;
  225175. [device retain];
  225176. [device open: &err];
  225177. if (err == 0)
  225178. {
  225179. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  225180. [session addInput: input error: &err];
  225181. if (err == 0)
  225182. {
  225183. resetFile();
  225184. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  225185. [imageOutput setDelegate: callbackDelegate];
  225186. if (err == 0)
  225187. {
  225188. [session startRunning];
  225189. return;
  225190. }
  225191. }
  225192. }
  225193. openingError = nsStringToJuce ([err description]);
  225194. DBG (openingError);
  225195. }
  225196. ~QTCameraDeviceInteral()
  225197. {
  225198. [session stopRunning];
  225199. [session removeOutput: imageOutput];
  225200. [session release];
  225201. [input release];
  225202. [device release];
  225203. [fileOutput release];
  225204. [imageOutput release];
  225205. [callbackDelegate release];
  225206. }
  225207. void resetFile()
  225208. {
  225209. [session removeOutput: fileOutput];
  225210. [fileOutput release];
  225211. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  225212. [fileOutput setDelegate: callbackDelegate];
  225213. }
  225214. void addListener (CameraImageListener* listenerToAdd)
  225215. {
  225216. const ScopedLock sl (listenerLock);
  225217. if (listeners.size() == 0)
  225218. [session addOutput: imageOutput error: nil];
  225219. listeners.addIfNotAlreadyThere (listenerToAdd);
  225220. }
  225221. void removeListener (CameraImageListener* listenerToRemove)
  225222. {
  225223. const ScopedLock sl (listenerLock);
  225224. listeners.removeValue (listenerToRemove);
  225225. if (listeners.size() == 0)
  225226. [session removeOutput: imageOutput];
  225227. }
  225228. static void drawNSBitmapIntoJuceImage (Image& dest, NSBitmapImageRep* source)
  225229. {
  225230. const ScopedAutoReleasePool pool;
  225231. int lineStride, pixelStride;
  225232. uint8* pixels = dest.lockPixelDataReadWrite (0, 0, dest.getWidth(), dest.getHeight(),
  225233. lineStride, pixelStride);
  225234. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  225235. initWithBitmapDataPlanes: &pixels
  225236. pixelsWide: dest.getWidth()
  225237. pixelsHigh: dest.getHeight()
  225238. bitsPerSample: 8
  225239. samplesPerPixel: pixelStride
  225240. hasAlpha: dest.hasAlphaChannel()
  225241. isPlanar: NO
  225242. colorSpaceName: NSCalibratedRGBColorSpace
  225243. bitmapFormat: (NSBitmapFormat) 0
  225244. bytesPerRow: lineStride
  225245. bitsPerPixel: pixelStride * 8];
  225246. [NSGraphicsContext saveGraphicsState];
  225247. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithBitmapImageRep: rep]];
  225248. [source drawAtPoint: NSZeroPoint];
  225249. [[NSGraphicsContext currentContext] flushGraphics];
  225250. [NSGraphicsContext restoreGraphicsState];
  225251. uint8* start = pixels;
  225252. for (int h = dest.getHeight(); --h >= 0;)
  225253. {
  225254. uint8* p = start;
  225255. start += lineStride;
  225256. for (int i = dest.getWidth(); --i >= 0;)
  225257. {
  225258. #if JUCE_BIG_ENDIAN
  225259. const uint8 oldp3 = p[3];
  225260. const uint8 oldp1 = p[1];
  225261. p[3] = p[0];
  225262. p[0] = oldp1;
  225263. p[1] = p[2];
  225264. p[2] = oldp3;
  225265. #else
  225266. const uint8 oldp0 = p[0];
  225267. p[0] = p[2];
  225268. p[2] = oldp0;
  225269. #endif
  225270. p += pixelStride;
  225271. }
  225272. }
  225273. dest.releasePixelDataReadWrite (pixels);
  225274. }
  225275. void callListeners (NSBitmapImageRep* bitmap)
  225276. {
  225277. Image image (Image::ARGB, [bitmap size].width, [bitmap size].height, false);
  225278. drawNSBitmapIntoJuceImage (image, bitmap);
  225279. const ScopedLock sl (listenerLock);
  225280. for (int i = listeners.size(); --i >= 0;)
  225281. {
  225282. CameraImageListener* l = (CameraImageListener*) listeners[i];
  225283. if (l != 0)
  225284. l->imageReceived (image);
  225285. }
  225286. }
  225287. QTCaptureDevice* device;
  225288. QTCaptureDeviceInput* input;
  225289. QTCaptureSession* session;
  225290. QTCaptureMovieFileOutput* fileOutput;
  225291. QTCaptureDecompressedVideoOutput* imageOutput;
  225292. QTCaptureCallbackDelegate* callbackDelegate;
  225293. String openingError;
  225294. VoidArray listeners;
  225295. CriticalSection listenerLock;
  225296. };
  225297. END_JUCE_NAMESPACE
  225298. @implementation QTCaptureCallbackDelegate
  225299. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  225300. internalDev: (QTCameraDeviceInteral*) d
  225301. {
  225302. [super init];
  225303. owner = owner_;
  225304. internal = d;
  225305. firstRecordedTime = 0;
  225306. return self;
  225307. }
  225308. - (void) dealloc
  225309. {
  225310. delete firstRecordedTime;
  225311. [super dealloc];
  225312. }
  225313. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  225314. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  225315. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225316. fromConnection: (QTCaptureConnection*) connection
  225317. {
  225318. const ScopedAutoReleasePool pool;
  225319. CIImage* image = [CIImage imageWithCVImageBuffer: videoFrame];
  225320. NSBitmapImageRep* bitmap = [[[NSBitmapImageRep alloc] initWithCIImage: image] autorelease];
  225321. internal->callListeners (bitmap);
  225322. }
  225323. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  225324. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225325. fromConnection: (QTCaptureConnection*) connection
  225326. {
  225327. if (firstRecordedTime == 0)
  225328. firstRecordedTime = new Time (Time::getCurrentTime());
  225329. }
  225330. @end
  225331. BEGIN_JUCE_NAMESPACE
  225332. class QTCaptureViewerComp : public NSViewComponent
  225333. {
  225334. public:
  225335. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  225336. {
  225337. const ScopedAutoReleasePool pool;
  225338. captureView = [[QTCaptureView alloc] init];
  225339. [captureView setCaptureSession: internal->session];
  225340. setSize (640, 480); // xxx need to somehow get the movie size - how?
  225341. setView (captureView);
  225342. }
  225343. ~QTCaptureViewerComp()
  225344. {
  225345. setView (0);
  225346. [captureView setCaptureSession: nil];
  225347. [captureView release];
  225348. }
  225349. QTCaptureView* captureView;
  225350. };
  225351. CameraDevice::CameraDevice (const String& name_, int index)
  225352. : name (name_)
  225353. {
  225354. isRecording = false;
  225355. QTCameraDeviceInteral* d = new QTCameraDeviceInteral (this, index);
  225356. internal = d;
  225357. }
  225358. CameraDevice::~CameraDevice()
  225359. {
  225360. stopRecording();
  225361. delete (QTCameraDeviceInteral*) internal;
  225362. internal = 0;
  225363. }
  225364. Component* CameraDevice::createViewerComponent()
  225365. {
  225366. return new QTCaptureViewerComp (this, (QTCameraDeviceInteral*) internal);
  225367. }
  225368. const String CameraDevice::getFileExtension()
  225369. {
  225370. return ".mov";
  225371. }
  225372. void CameraDevice::startRecordingToFile (const File& file)
  225373. {
  225374. stopRecording();
  225375. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225376. deleteAndZero (d->callbackDelegate->firstRecordedTime);
  225377. file.deleteFile();
  225378. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  225379. [d->session addOutput: d->fileOutput error: nil];
  225380. isRecording = true;
  225381. }
  225382. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  225383. {
  225384. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225385. if (d->callbackDelegate->firstRecordedTime != 0)
  225386. return *d->callbackDelegate->firstRecordedTime;
  225387. return Time();
  225388. }
  225389. void CameraDevice::stopRecording()
  225390. {
  225391. if (isRecording)
  225392. {
  225393. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225394. d->resetFile();
  225395. isRecording = false;
  225396. }
  225397. }
  225398. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  225399. {
  225400. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225401. if (listenerToAdd != 0)
  225402. d->addListener (listenerToAdd);
  225403. }
  225404. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  225405. {
  225406. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225407. if (listenerToRemove != 0)
  225408. d->removeListener (listenerToRemove);
  225409. }
  225410. const StringArray CameraDevice::getAvailableDevices()
  225411. {
  225412. const ScopedAutoReleasePool pool;
  225413. StringArray results;
  225414. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  225415. for (int i = 0; i < [devs count]; ++i)
  225416. {
  225417. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  225418. results.add (nsStringToJuce ([dev localizedDisplayName]));
  225419. }
  225420. return results;
  225421. }
  225422. CameraDevice* CameraDevice::openDevice (int index,
  225423. int minWidth, int minHeight,
  225424. int maxWidth, int maxHeight)
  225425. {
  225426. CameraDevice* d = new CameraDevice (getAvailableDevices() [index], index);
  225427. if (((QTCameraDeviceInteral*) (d->internal))->openingError.isEmpty())
  225428. return d;
  225429. delete d;
  225430. return 0;
  225431. }
  225432. #endif
  225433. /********* End of inlined file: juce_mac_CameraDevice.mm *********/
  225434. #endif
  225435. END_JUCE_NAMESPACE
  225436. /********* End of inlined file: juce_mac_NativeCode.mm *********/
  225437. #endif